content stringlengths 7 1.05M |
|---|
"""
Given a binary tree, return the zigzag level order traversal
of its nodes' values.
(ie, from left to right, then right to left
for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
"""
def zigzag_level(root):
res = []
if not root:
return res
level = [root]
flag = 1
while level:
current = []
new_level = []
for node in level:
current.append(node.val)
if node.left:
new_level.append(node.left)
if node.right:
new_level.append(node.right)
level = new_level
res.append(current[::flag])
flag *= -1
return res
|
# -*- coding: utf-8 -*-
def main():
n = int(input())
mod = 10 ** 9 + 7
ans = 0
for i in range(n):
ans += ((i + 1) ** 10 - i ** 10) * (n // (i + 1)) ** 10
ans %= mod
print(ans)
if __name__ == '__main__':
main()
|
load("//tools/bzl:maven_jar.bzl", "maven_jar")
GUAVA_VERSION = "30.1-jre"
GUAVA_BIN_SHA1 = "00d0c3ce2311c9e36e73228da25a6e99b2ab826f"
GUAVA_DOC_URL = "https://google.github.io/guava/releases/" + GUAVA_VERSION + "/api/docs/"
TESTCONTAINERS_VERSION = "1.15.3"
def declare_nongoogle_deps():
"""loads dependencies that are not used at Google.
Changes to versions are exempt from library compliance review. New
dependencies must pass through library compliance review. This is
enforced by //lib:nongoogle_test.
"""
maven_jar(
name = "j2objc",
artifact = "com.google.j2objc:j2objc-annotations:1.1",
sha1 = "ed28ded51a8b1c6b112568def5f4b455e6809019",
)
# Transitive dependency of commons-compress
maven_jar(
name = "tukaani-xz",
artifact = "org.tukaani:xz:1.8",
sha1 = "c4f7d054303948eb6a4066194253886c8af07128",
)
maven_jar(
name = "dropwizard-core",
artifact = "io.dropwizard.metrics:metrics-core:4.1.12.1",
sha1 = "cb2f351bf4463751201f43bb99865235d5ba07ca",
)
SSHD_VERS = "2.6.0"
maven_jar(
name = "sshd-osgi",
artifact = "org.apache.sshd:sshd-osgi:" + SSHD_VERS,
sha1 = "40e365bb799e1bff3d31dc858b1e59a93c123f29",
)
maven_jar(
name = "sshd-sftp",
artifact = "org.apache.sshd:sshd-sftp:" + SSHD_VERS,
sha1 = "6eddfe8fdf59a3d9a49151e4177f8c1bebeb30c9",
)
maven_jar(
name = "eddsa",
artifact = "net.i2p.crypto:eddsa:0.3.0",
sha1 = "1901c8d4d8bffb7d79027686cfb91e704217c3e1",
)
maven_jar(
name = "mina-core",
artifact = "org.apache.mina:mina-core:2.0.21",
sha1 = "e1a317689ecd438f54e863747e832f741ef8e092",
)
maven_jar(
name = "sshd-mina",
artifact = "org.apache.sshd:sshd-mina:" + SSHD_VERS,
sha1 = "d22138ba75dee95e2123f0e53a9c514b2a766da9",
)
# elasticsearch-rest-client explicitly depends on this version
maven_jar(
name = "httpasyncclient",
artifact = "org.apache.httpcomponents:httpasyncclient:4.1.4",
sha1 = "f3a3240681faae3fa46b573a4c7e50cec9db0d86",
)
# elasticsearch-rest-client explicitly depends on this version
maven_jar(
name = "httpcore-nio",
artifact = "org.apache.httpcomponents:httpcore-nio:4.4.12",
sha1 = "84cd29eca842f31db02987cfedea245af020198b",
)
maven_jar(
name = "openid-consumer",
artifact = "org.openid4java:openid4java:1.0.0",
sha1 = "541091bb49f2c0d583544c5bb1e6df7612d31e3e",
)
maven_jar(
name = "nekohtml",
artifact = "net.sourceforge.nekohtml:nekohtml:1.9.10",
sha1 = "14052461031a7054aa094f5573792feb6686d3de",
)
maven_jar(
name = "xerces",
artifact = "xerces:xercesImpl:2.8.1",
attach_source = False,
sha1 = "25101e37ec0c907db6f0612cbf106ee519c1aef1",
)
maven_jar(
name = "jruby",
artifact = "org.jruby:jruby-complete:9.1.17.0",
sha1 = "76716d529710fc03d1d429b43e3cedd4419f78d4",
)
maven_jar(
name = "jackson-core",
artifact = "com.fasterxml.jackson.core:jackson-core:2.12.0",
sha1 = "afe52c6947d9939170da7989612cef544115511a",
)
maven_jar(
name = "commons-io",
artifact = "commons-io:commons-io:2.4",
sha1 = "b1b6ea3b7e4aa4f492509a4952029cd8e48019ad",
)
# Google internal dependencies: these are developed at Google, so there is
# no concern about version skew.
FLOGGER_VERS = "0.5.1"
maven_jar(
name = "flogger",
artifact = "com.google.flogger:flogger:" + FLOGGER_VERS,
sha1 = "71d1e2cef9cc604800825583df56b8ef5c053f14",
)
maven_jar(
name = "flogger-log4j-backend",
artifact = "com.google.flogger:flogger-log4j-backend:" + FLOGGER_VERS,
sha1 = "5e2794b75c88223f263f1c1a9d7ea51e2dc45732",
)
maven_jar(
name = "flogger-system-backend",
artifact = "com.google.flogger:flogger-system-backend:" + FLOGGER_VERS,
sha1 = "b66d3bedb14da604828a8693bb24fd78e36b0e9e",
)
maven_jar(
name = "guava",
artifact = "com.google.guava:guava:" + GUAVA_VERSION,
sha1 = GUAVA_BIN_SHA1,
)
GUICE_VERS = "5.0.1"
maven_jar(
name = "guice-library",
artifact = "com.google.inject:guice:" + GUICE_VERS,
sha1 = "0dae7556b441cada2b4f0a2314eb68e1ff423429",
)
maven_jar(
name = "guice-assistedinject",
artifact = "com.google.inject.extensions:guice-assistedinject:" + GUICE_VERS,
sha1 = "62e02f2aceb7d90ba354584dacc018c1e94ff01c",
)
maven_jar(
name = "guice-servlet",
artifact = "com.google.inject.extensions:guice-servlet:" + GUICE_VERS,
sha1 = "f527009d51f172a2e6937bfb55fcb827e2e2386b",
)
# Keep this version of Soy synchronized with the version used in Gitiles.
maven_jar(
name = "soy",
artifact = "com.google.template:soy:2021-02-01",
sha1 = "8e833744832ba88059205a1e30e0898f925d8cb5",
)
# Test-only dependencies below.
maven_jar(
name = "cglib-3_2",
artifact = "cglib:cglib-nodep:3.2.6",
sha1 = "92bf48723d277d6efd1150b2f7e9e1e92cb56caf",
)
maven_jar(
name = "objenesis",
artifact = "org.objenesis:objenesis:1.3",
sha1 = "dc13ae4faca6df981fc7aeb5a522d9db446d5d50",
)
DOCKER_JAVA_VERS = "3.2.8"
maven_jar(
name = "docker-java-api",
artifact = "com.github.docker-java:docker-java-api:" + DOCKER_JAVA_VERS,
sha1 = "4ac22a72d546a9f3523cd4b5fabffa77c4a6ec7c",
)
maven_jar(
name = "docker-java-transport",
artifact = "com.github.docker-java:docker-java-transport:" + DOCKER_JAVA_VERS,
sha1 = "c3b5598c67d0a5e2e780bf48f520da26b9915eab",
)
# https://github.com/docker-java/docker-java/blob/3.2.8/pom.xml#L61
# <=> DOCKER_JAVA_VERS
maven_jar(
name = "jackson-annotations",
artifact = "com.fasterxml.jackson.core:jackson-annotations:2.10.3",
sha1 = "0f63b3b1da563767d04d2e4d3fc1ae0cdeffebe7",
)
maven_jar(
name = "testcontainers",
artifact = "org.testcontainers:testcontainers:" + TESTCONTAINERS_VERSION,
sha1 = "95c6cfde71c2209f0c29cb14e432471e0b111880",
)
maven_jar(
name = "duct-tape",
artifact = "org.rnorth.duct-tape:duct-tape:1.0.8",
sha1 = "92edc22a9ab2f3e17c9bf700aaee377d50e8b530",
)
maven_jar(
name = "visible-assertions",
artifact = "org.rnorth.visible-assertions:visible-assertions:2.1.2",
sha1 = "20d31a578030ec8e941888537267d3123c2ad1c1",
)
maven_jar(
name = "jna",
artifact = "net.java.dev.jna:jna:5.5.0",
sha1 = "0e0845217c4907822403912ad6828d8e0b256208",
)
maven_jar(
name = "jimfs",
artifact = "com.google.jimfs:jimfs:1.2",
sha1 = "48462eb319817c90c27d377341684b6b81372e08",
)
TRUTH_VERS = "1.1"
maven_jar(
name = "truth",
artifact = "com.google.truth:truth:" + TRUTH_VERS,
sha1 = "6a096a16646559c24397b03f797d0c9d75ee8720",
)
maven_jar(
name = "truth-java8-extension",
artifact = "com.google.truth.extensions:truth-java8-extension:" + TRUTH_VERS,
sha1 = "258db6eb8df61832c5c059ed2bc2e1c88683e92f",
)
maven_jar(
name = "truth-liteproto-extension",
artifact = "com.google.truth.extensions:truth-liteproto-extension:" + TRUTH_VERS,
sha1 = "bf65afa13aa03330e739bcaa5d795fe0f10fbf20",
)
maven_jar(
name = "truth-proto-extension",
artifact = "com.google.truth.extensions:truth-proto-extension:" + TRUTH_VERS,
sha1 = "64cba89cf87c1d84cb8c81d06f0b9c482f10b4dc",
)
|
# leetcode 625. Minimum Factorization
# Given a positive integer a, find the smallest positive integer b whose multiplication of each digit equals to a.
# If there is no answer or the answer is not fit in 32-bit signed integer, then return 0.
# Example 1
# Input:
# 48
# Output:
# 68
# Example 2
# Input:
# 15
# Output:
# 35
# V1
# idea :
# please notice the "each digit" term in the problem description
class Solution(object):
def smallestFactorization(self, a):
if a ==1:
return 1
for i in range(2,10):
if a%i == 0:
q = int(a/i)
ans = min((a*10+i), (i*10)+a)
if ans <= 2**31: # 2**31 or 0x7FFFFFFF : 32-bit signed integer
return ans
return 0
return 0
# V2
# http://bookshadow.com/weblog/2017/06/18/leetcode-minimum-factorization/
# https://blog.csdn.net/feifeiiong/article/details/73556747
class Solution(object):
def smallestFactorization(self, a):
"""
:type a: int
:rtype: int
"""
if a == 1: return 1
cnt = [0] * 10
for x in range(9, 1, -1):
while a % x == 0:
cnt[x] += 1
a /= x
if a > 1: return 0
ans = int(''.join(str(n) * cnt[n] for n in range(2, 10)))
return ans <= 0x7FFFFFFF and ans or 0
# V3
# Time: O(loga)
# Space: O(1)
class Solution(object):
def smallestFactorization(self, a):
"""
:type a: int
:rtype: int
"""
if a < 2:
return a
result, mul = 0, 1
for i in reversed(range(2, 10)):
while a % i == 0:
a /= i
result = mul*i + result
mul *= 10
return result if a == 1 and result < 2**31 else 0
|
'''
Last digit of number's factorial
Status: Accepted
'''
###############################################################################
def main():
"""Read input and print output"""
nonzero = {}
nonzero[1] = 1
nonzero[2] = 2
nonzero[3] = 6
nonzero[4] = 4
for _ in range(int(input())):
i = int(input())
if i in nonzero:
print(nonzero[i])
else:
print('0')
###############################################################################
if __name__ == '__main__':
main()
|
def find_metathesis_pair(filename):
"""Takes a word list as text file, returns a list of word pairs that can
be created by swapping one pair of letters"""
res = []
t = find_anagrams(filename)
for i in t:
possibles = i
for x in range(len(possibles)):
for y in range(len(possibles)):
if is_swappable(possibles[x], possibles[y]):
res.append((possibles[x], possibles[y]))
return res
def is_swappable(word1, word2):
"""Input: 2 strings of equal length
Returns True if Word2 can be formed by swapping 2 letters in Word1, else False"""
differing_letter_positions = []
index = 0
for i in word1:
if word1[index] != word2[index]:
differing_letter_positions.append(index)
index += 1
if len(differing_letter_positions) != 2:
return False
word2 = list(word2)
index1 = differing_letter_positions[0]
index2 = differing_letter_positions[1]
word2[index1], word2[index2] = word2[index2], word2[index1]
if list(word1) == (word2):
return True
return False
def make_anagram_dict(filename):
"""Takes a text file containing one word per line.
Returns a dictionary:
Key is an alphabetised duple of letters in each word,
Value is a list of all words that can be formed by those letters"""
result = {}
fin = open(filename)
for line in fin:
word = line.strip().lower()
letters_in_word = tuple(sorted(word))
if letters_in_word not in result:
result[letters_in_word] = [word]
else:
result[letters_in_word].append(word)
return result
def find_anagrams(filename):
"""Takes a text file word list, returns an alphabetised list of lists of
anagrams found in the word list"""
result = []
t = make_anagram_dict(filename)
for i in t:
anagrams = []
for word in t[i]:
anagrams.append(word)
if sorted(anagrams) not in anagrams:
result.append(sorted(anagrams))
list_of_anagrams = []
for i in range (len(result)):
if len(result[i]) > 1:
list_of_anagrams.append(result[i])
return list_of_anagrams
def sort_anagram_list(filename):
"""Takes a list of lists of anagrams
Returns a list of duples - number of letters(sorted high to low), list of anagrams
for those letters"""
t = find_anagrams('words.txt')
res = []
lengths = []
for i in t:
lengths.append((len(i), i))
for i in sorted(lengths, reverse = True):
res.append(i)
return res
t = find_metathesis_pair('words.txt')
for i in t:
print(i)
|
Import("env")
print("Extra Script (Pre): common_pre.py")
# Get build flags values from env
def get_build_flag_value(flag_name):
build_flags = env.ParseFlags(env['BUILD_FLAGS'])
flags_with_value_list = [build_flag for build_flag in build_flags.get('CPPDEFINES') if type(build_flag) == list]
defines = {k: v for (k, v) in flags_with_value_list}
return defines.get(flag_name)
# Current details
print("Device Code: %s" % get_build_flag_value("DEVICE_CODE"))
print("Build tag: %s" % get_build_flag_value("BUILD_TAG"))
# Change build file name
new_name = "%s-Pv%s" % (get_build_flag_value("DEVICE_CODE"), get_build_flag_value("BUILD_TAG"))
print("Changing build file name to: %s" % new_name)
env.Replace(PROGNAME=new_name)
|
KONSTANT = "KONSTANT"
def funktion(value):
print(value)
class Klass:
def method(self):
funktion(KONSTANT)
Klass().method()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
multiset.py -- non-recursive n multichoose k and
non-recursive multiset permutations
for python lists
author: Erik Garrison <erik.garrison@bc.edu>
last revised: 2010-07-15
Copyright (c) 2010 by Erik Garrison
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
def multichoose(k, objects):
"""n multichoose k multisets from the list of objects. n is the size of
the objects."""
j,j_1,q = k,k,k # init here for scoping
r = len(objects) - 1
a = [0 for i in range(k)] # initial multiset indexes
while True:
yield [objects[a[i]] for i in range(0,k)] # emit result
j = k - 1
while j >= 0 and a[j] == r: j -= 1
if j < 0: break # check for end condition
j_1 = j
while j_1 <= k - 1:
a[j_1] = a[j_1] + 1 # increment
q = j_1
while q < k - 1:
a[q+1] = a[q] # shift left
q += 1
q += 1
j_1 = q
"""
Permutations of a multiset:
Algorithm 1
Visits the permutations of multiset E. The permutations are stored
in a singly-linked list pointed to by head pointer h. Each node in the linked
list has a value field v and a next field n. The init(E) call creates a
singly-linked list storing the elements of E in non-increasing order with h, i,
and j pointing to its first, second-last, and last nodes, respectively. The
null pointer is given by φ. Note: If E is empty, then init(E) should exit.
Also, if E contains only one element, then init(E) does not need to provide a
value for i.
[h, i, j] ← init(E)
visit(h)
while j.n ≠ φ orj.v <h.v do
if j.n ≠ φ and i.v ≥ j.n.v then
s←j
else
s←i
end if
t←s.n
s.n ← t.n
t.n ← h
if t.v < h.v then
i←t
end if
j←i.n
h←t
visit(h)
end while
... from "Loopless Generation of Multiset Permutations using a Constant Number
of Variables by Prefix Shifts." Aaron Williams, 2009
"""
class ListElement:
def __init__(self, value, next):
self.value = value
self.next = next
def nth(self, n):
o = self
i = 0
while i < n and o.next is not None:
o = o.next
i += 1
return o
def __init(multiset):
multiset.sort() # ensures proper non-increasing order
h = ListElement(multiset[0], None)
for item in multiset[1:]:
h = ListElement(item, h)
return h, h.nth(len(multiset) - 2), h.nth(len(multiset) - 1)
def __visit(h):
"""Converts our bespoke linked list to a python list."""
o = h
l = []
while o is not None:
l.append(o.value)
o = o.next
return l
def permutations(multiset):
"""Generator providing all multiset permutations of a multiset."""
h, i, j = __init(multiset)
yield __visit(h)
while j.next is not None or j.value < h.value:
if j.next is not None and i.value >= j.next.value:
s = j
else:
s = i
t = s.next
s.next = t.next
t.next = h
if t.value < h.value:
i = t
j = i.next
h = t
yield __visit(h)
|
# -*- coding: utf-8 -*-
"""
square
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class HttpResponse(object):
"""Information about an HTTP Response including its status code, returned
headers, and raw body
Attributes:
status_code (int): The status code response from the server that
corresponds to this response.
reason_phrase (string): The reason phrase returned by the server.
headers (dict): A dictionary of headers (key : value) that were
returned with the response
text (string): The Raw body of the HTTP Response as a string
request (HttpRequest): The request that resulted in this response.
"""
def __init__(self,
status_code,
reason_phrase,
headers,
text,
request):
"""Constructor for the HttpResponse class
Args:
status_code (int): The response status code.
reason_phrase (string): The response reason phrase.
headers (dict): The response headers.
text (string): The raw body from the server.
request (HttpRequest): The request that resulted in this response.
"""
self.status_code = status_code
self.reason_phrase = reason_phrase
self.headers = headers
self.text = text
self.request = request
|
conf = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'isAccessLog': {
'()': 'utils.CustomLogFilter.AccessLogFilter'
},
'isHuntLog': {
'()': 'utils.CustomLogFilter.HuntLogFilter'
},
'isHuntResultLog': {
'()': 'utils.CustomLogFilter.HuntResultLogFilter'
},
},
# 'loggers': {
# 'elasticsearch': {
# 'level': 'INFO',
# 'handlers': [
# 'consoleHandler',
# 'logFileHandler',
# ],
# "propagate": "no",
# }
# },
'root': {
'level': 'DEBUG',
'handlers': [
'consoleHandler',
'logFileHandler',
'AccessLogFileHandler',
# 'AccessLogSysLogHandler',
'HuntLogFileHandler',
'HuntResultLogFileHandler',
]
},
'handlers': {
'consoleHandler': {
'class': 'logging.StreamHandler',
'level': 'INFO',
'formatter': 'consoleFormatter',
'stream': 'ext://sys.stdout'
},
'logFileHandler': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'level': 'DEBUG',
'formatter': 'logFileFormatter',
'filename': './log/wowhoneypot.log',
'when': 'MIDNIGHT',
'backupCount': 10,
'encoding': 'utf-8'
},
'AccessLogFileHandler': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'level': 'INFO',
'formatter': 'AccessLogFileFormatter',
'filename': './log/access.log',
'when': 'MIDNIGHT',
'backupCount': 10,
'encoding': 'utf-8',
'filters': [
'isAccessLog'
]
},
# 'AccessLogSysLogHandler': {
# 'class': 'logging.handlers.SysLogHandler',
# 'address': ('127.0.0.1', 514),
# 'facility': "local0",
# 'filters': [
# 'isAccessLog'
# ]
# },
'HuntLogFileHandler': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'level': 'INFO',
'formatter': 'HuntLogFileFormatter',
'filename': './log/hunting.log',
'when': 'MIDNIGHT',
'backupCount': 10,
'encoding': 'utf-8',
'filters': [
'isHuntLog'
]
},
'HuntResultLogFileHandler': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'level': 'INFO',
'formatter': 'HuntLogFileFormatter',
'filename': './log/hunt_result.log',
'when': 'MIDNIGHT',
'backupCount': 10,
'encoding': 'utf-8',
'filters': [
'isHuntResultLog'
]
},
},
'formatters': {
'consoleFormatter': {
'format': '%(asctime)s [%(levelname)-8s] %(funcName)s - %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S%z'
},
'logFileFormatter': {
'format': '%(asctime)s|%(levelname)-8s|%(name)s|%(funcName)s|%(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S%z'
},
'AccessLogFileFormatter': {
'format': '%(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S%z'
},
'HuntLogFileFormatter': {
'format': '[%(asctime)s] %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S%z'
},
'HuntResultLogFileFormatter': {
'format': '[%(asctime)s] %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S%z'
},
}
}
|
def isPerfectCube(num):
ans = 0
while ans**3 < abs(num):
ans += 1
if ans**3 != abs(num):
print("Not a perfect cube")
else:
if num < 0:
ans = -ans
print(ans, "is a cube root of", num)
def main():
if __name__ == "__main__":
print(isPerfectCube(8), "answer is 2")
print(isPerfectCube(-8), "answer is -2")
print(isPerfectCube(9), "answer is not perfect cube")
main() |
# -*- coding: utf-8 -*-
"""
#project: CCP_Python3
#file: CCPRest.py
#author: ceephoen
#contact: ceephoen@163.com
#time: 2019/6/13 21:43:21
#desc:
""" |
# Common data problems!!
# In this chapter, you'll learn how to overcome some of the most common dirty data problems. You'll convert data types, apply range constraints to remove future data points, and remove duplicated data points to avoid double-counting.
# Numeric data or ... ?
# In this exercise, and throughout this chapter, you'll be working with bicycle ride sharing data in San Francisco called ride_sharing. It contains information on the start and end stations, the trip duration, and some user information for a bike sharing service.
# The user_type column contains information on whether a user is taking a free ride and takes on the following values:
# 1 for free riders.
# 2 for pay per ride.
# 3 for monthly subscribers.
# In this instance, you will print the information of ride_sharing using .info() and see a firsthand example of how an incorrect data type can flaw your analysis of the dataset. The pandas package is imported as pd.
# Print the information of ride_sharing
print(ride_sharing.info())
# Print summary statistics of user_type column
print(ride_sharing['user_type'].describe())
# Summing strings and concatenating numbers
# In the previous exercise, you were able to identify that category is the correct data type for user_type and convert it in order to extract relevant statistical summaries that shed light on the distribution of user_type.
# Another common data type problem is importing what should be numerical values as strings, as mathematical operations such as summing and multiplication lead to string concatenation, not numerical outputs.
# In this exercise, you'll be converting the string column duration to the type int. Before that however, you will need to make sure to strip "minutes" from the column in order to make sure pandas reads it as numerical. The pandas package has been imported as pd.
# Strip duration of minutes
ride_sharing['duration_trim'] = ride_sharing['duration'].str.strip('minutes')
# Convert duration to integer
ride_sharing['duration_time'] = ride_sharing['duration_trim'].astype('int')
# Write an assert statement making sure of conversion
assert ride_sharing['duration_time'].dtype == 'int'
# Print formed columns and calculate average ride duration
print(ride_sharing[['duration','duration_trim','duration_time']])
print(ride_sharing['duration_time'].mean())
# Tire size constraints
# In this lesson, you're going to build on top of the work you've been doing with the ride_sharing DataFrame. You'll be working with the tire_sizes column which contains data on each bike's tire size.
# Bicycle tire sizes could be either 26″, 27″ or 29″ and are here correctly stored as a categorical value. In an effort to cut maintenance costs, the ride sharing provider decided to set the maximum tire size to be 27″.
# In this exercise, you will make sure the tire_sizes column has the correct range by first converting it to an integer, then setting and testing the new upper limit of 27″ for tire sizes.
# Convert tire_sizes to integer
ride_sharing['tire_sizes'] = ride_sharing['tire_sizes'].astype('int')
# Set all values above 27 to 27
ride_sharing.loc[ride_sharing['tire_sizes'] > 27, 'tire_sizes'] = 27
# Reconvert tire_sizes back to categorical
ride_sharing['tire_sizes'] = ride_sharing['tire_sizes'].astype('category')
# Print tire size description
print(ride_sharing['tire_sizes'].describe())
# Back to the future
# A new update to the data pipeline feeding into the ride_sharing DataFrame has been updated to register each ride's date. This information is stored in the ride_date column of the type object, which represents strings in pandas.
# A bug was discovered which was relaying rides taken today as taken next year. To fix this, you will find all instances of the ride_date column that occur anytime in the future, and set the maximum possible value of this column to today's date. Before doing so, you would need to convert ride_date to a datetime object.
# The datetime package has been imported as dt, alongside all the packages you've been using till now.
# Convert ride_date to datetime
ride_sharing['ride_dt'] = pd.to_datetime(ride_sharing['ride_date'])
# Save today's date
today = dt.date.today()
# Set all in the future to today's date
ride_sharing.loc[ride_sharing['ride_dt'] > today, 'ride_dt'] = today
# Print maximum of ride_dt column
print(ride_sharing['ride_dt'].max())
# Finding duplicates
# A new update to the data pipeline feeding into ride_sharing has added the ride_id column, which represents a unique identifier for each ride.
# The update however coincided with radically shorter average ride duration times and irregular user birth dates set in the future. Most importantly, the number of rides taken has increased by 20% overnight, leading you to think there might be both complete and incomplete duplicates in the ride_sharing DataFrame.
# In this exercise, you will confirm this suspicion by finding those duplicates. A sample of ride_sharing is in your environment, as well as all the packages you've been working with thus far.
# Find duplicates
duplicates = ride_sharing.duplicated(subset = 'ride_id', keep = False)
# Sort your duplicated rides
duplicated_rides = ride_sharing[duplicates].sort_values('ride_id')
# Print relevant columns of duplicated_rides
print(duplicated_rides[['ride_id','duration','user_birth_year']])
# Treating duplicates
# In the last exercise, you were able to verify that the new update feeding into ride_sharing contains a bug generating both complete and incomplete duplicated rows for some values of the ride_id column, with occasional discrepant values for the user_birth_year and duration columns.
# In this exercise, you will be treating those duplicated rows by first dropping complete duplicates, and then merging the incomplete duplicate rows into one while keeping the average duration, and the minimum user_birth_year for each set of incomplete duplicate rows.
# Drop complete duplicates from ride_sharing
ride_dup = ride_sharing.drop_duplicates()
# Create statistics dictionary for aggregation function
statistics = {'user_birth_year': 'min', 'duration': 'mean'}
# Group by ride_id and compute new statistics
ride_unique = ride_dup.groupby('ride_id').agg(statistics).reset_index()
# Find duplicated values again
duplicates = ride_unique.duplicated(subset = 'ride_id', keep = False)
duplicated_rides = ride_unique[duplicates == True]
# Assert duplicates are processed
assert duplicated_rides.shape[0] == 0
|
"""
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
"""
class Solution:
def getImportance(self, employees: List['Employee'], id: int) -> int:
emap = {e.id: e for e in employees}
def dfs(eid):
employee = emap[eid]
return (employee.importance +
sum(dfs(eid) for eid in employee.subordinates))
return dfs(id)
|
def detect_db(fh):
"""
Parameters
----------
fh : file-like object
Returns
-------
db_type : str
one of 'irefindex', 'string'
Notes
-----
STRING
======
head -n2 9606.protein.links.full.v10.5.txt
protein1 protein2 neighborhood neighborhood_transferred fusion cooccurence homology coexpression coexpression_transferred experiments experiments_transferred database database_transferred textmining textmining_transferred combined_score
9606.ENSP00000000233 9606.ENSP00000263431 0 0 0 0 0 0 53 0 176 0 0 0 128 260
iRefIndex
========
head -n2 9606.mitab.04072015.txt
#uidA uidB altA altB aliasA aliasB method author pmids taxa taxb interactionType sourcedb interactionIdentifier confidence expansion biological_role_A biological_role_B experimental_role_A experimental_role_B interactor_type_A interactor_type_B xrefs_A xrefs_B xrefs_Interaction Annotations_A Annotations_B Annotations_Interaction Host_organism_taxid parameters_Interaction Creation_date Update_date Checksum_A Checksum_B Checksum_Interaction Negative OriginalReferenceA OriginalReferenceB FinalReferenceA FinalReferenceB MappingScoreA MappingScoreB irogida irogidb irigid crogida crogidb crigid icrogida icrogidb icrigid imex_id edgetype numParticipants
uniprotkb:A0A024R3E3 uniprotkb:A0A024R3E3 entrezgene/locuslink:335|genbank_protein_gi:4557321|refseq:NP_000030|rogid:yEzPDeU8Uu/43dkLLOBAy6ey1vs9606|irogid:122812673 entrezgene/locuslink:335|genbank_protein_gi:4557321|refseq:NP_000030|rogid:yEzPDeU8Uu/43dkLLOBAy6ey1vs9606|irogid:122812673 hgnc:APOA1|uniprotkb:A0A024R3E3_HUMAN|uniprotkb:APOA1_HUMAN|crogid:yEzPDeU8Uu/43dkLLOBAy6ey1vs9606|icrogid:122812673 hgnc:APOA1|uniprotkb:A0A024R3E3_HUMAN|uniprotkb:APOA1_HUMAN|crogid:yEzPDeU8Uu/43dkLLOBAy6ey1vs9606|icrogid:122812673 - - pubmed:9003180|pubmed:9200714|pubmed:9356442 taxid:9606(Homo sapiens) taxid:9606(Homo sapiens) - MI:0462(bind) bind:75986|rigid:WRUQaMHXGmnC/H/BzyolIfyaa7Y|edgetype:X hpr:141818|lpr:1|np:8 none MI:0000(unspecified) MI:0000(unspecified) MI:0000(unspecified) MI:0000(unspecified) MI:0326(protein) MI:0326(protein) - - - - - - - - 2015-04-07 2015-04-07 rogid:yEzPDeU8Uu/43dkLLOBAy6ey1vs9606 rogid:yEzPDeU8Uu/43dkLLOBAy6ey1vs9606 rigid:WRUQaMHXGmnC/H/BzyolIfyaa7Y false GenBank:NP_000030 GenBank:NP_000030 refseq:NP_000030 refseq:NP_000030 PD PD 122812673 122812673 881764 yEzPDeU8Uu/43dkLLOBAy6ey1vs9606 yEzPDeU8Uu/43dkLLOBAy6ey1vs9606 WRUQaMHXGmnC/H/BzyolIfyaa7Y 122812673 122812673 881764 - X 2
"""
string_header = """protein1 protein2 neighborhood neighborhood_transferred fusion cooccurence homology coexpression coexpression_transferred experiments experiments_transferred database database_transferred textmining textmining_transferred combined_score""".split()
irefindex_header = """#uidA uidB altA altB aliasA aliasB method author pmids taxa taxb interactionType sourcedb interactionIdentifier confidence expansion biological_role_A biological_role_B experimental_role_A experimental_role_B interactor_type_A interactor_type_B xrefs_A xrefs_B xrefs_Interaction Annotations_A Annotations_B Annotations_Interaction Host_organism_taxid parameters_Interaction Creation_date Update_date Checksum_A Checksum_B Checksum_Interaction Negative OriginalReferenceA OriginalReferenceB FinalReferenceA FinalReferenceB MappingScoreA MappingScoreB irogida irogidb irigid crogida crogidb crigid icrogida icrogidb icrigid imex_id edgetype numParticipants""".split()
rv = None
fh.seek(0)
fh_header = fh.next().rstrip().split()
if fh_header == string_header:
rv = "string"
elif fh_header == irefindex_header:
rv = "irefindex"
else:
raise RuntimeError("Unrecognized database file: it is not one of iRefIndex, STRING")
fh.seek(0)
return rv
|
"""
This module contains exceptions for use throughout the L11 Colorlib.
"""
class ColorMathException(Exception):
"""
Base exception for all colormath exceptions.
"""
pass
class UndefinedConversionError(ColorMathException):
"""
Raised when the user asks for a color space conversion that does not exist.
"""
def __init__(self, cobj, cs_to):
super(UndefinedConversionError, self).__init__(cobj, cs_to)
self.message = "Conversion from %s to %s is not defined." % (cobj, cs_to)
class InvalidIlluminantError(ColorMathException):
"""
Raised when an invalid illuminant is set on a ColorObj.
"""
def __init__(self, illuminant):
super(InvalidIlluminantError, self).__init__(illuminant)
self.message = "Invalid illuminant specified: %s" % illuminant
class InvalidObserverError(ColorMathException):
"""
Raised when an invalid observer is set on a ColorObj.
"""
def __init__(self, cobj):
super(InvalidObserverError, self).__init__(cobj)
self.message = "Invalid observer angle specified: %s" % cobj.observer
|
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Modifications made by Cloudera are:
# Copyright (c) 2016 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
class AltusCLIError(Exception):
"""
The base exception class for Altus CLI exceptions.
"""
fmt = 'An unspecified error occured'
def __init__(self, **kwargs):
msg = self.fmt.format(**kwargs)
Exception.__init__(self, msg)
self.kwargs = kwargs
class ValidationError(AltusCLIError):
"""
An exception occurred validating parameters.
"""
fmt = "Invalid value ('{value}') for param {param} of type {type_name}"
class ParamValidationError(AltusCLIError):
fmt = 'Parameter validation failed:\n{report}'
class DataNotFoundError(AltusCLIError):
"""
The data associated with a particular path could not be loaded.
"""
fmt = 'Unable to load data for: {data_path}'
class ExecutableNotFoundError(AltusCLIError):
"""
The executable was not found.
"""
fmt = 'Could not find executable named: {executable_name}'
class OperationNotPageableError(AltusCLIError):
fmt = 'Operation cannot be paginated: {operation_name}'
class ClientError(Exception):
MSG_TEMPLATE = (
'An error occurred: {error_message} ('
'Status Code: {http_status_code}; '
'Error Code: {error_code}; '
'Service: {service_name}; '
'Operation: {operation_name}; '
'Request ID: {request_id};)')
def __init__(self, error_response, operation_name, service_name,
http_status_code, request_id):
msg = self.MSG_TEMPLATE.format(
error_code=error_response['error'].get('code', 'Unknown'),
error_message=error_response['error'].get('message', 'Unknown'),
operation_name=operation_name,
service_name=service_name,
http_status_code=http_status_code,
request_id=request_id)
super(ClientError, self).__init__(msg)
self.response = error_response
class UnseekableStreamError(AltusCLIError):
"""
Need to seek a stream, but stream does not support seeking.
"""
fmt = ('Need to rewind the stream {stream_object}, but stream '
'is not seekable.')
class EndpointConnectionError(AltusCLIError):
fmt = (
'Could not connect to the endpoint URL: "{endpoint_url}"')
class IncompleteReadError(AltusCLIError):
"""
HTTP response did not return expected number of bytes.
"""
fmt = ('{actual_bytes} read, but total bytes '
'expected is {expected_bytes}.')
class PaginationError(AltusCLIError):
fmt = 'Error during pagination: {message}'
class UnknownSignatureVersionError(AltusCLIError):
"""
Requested Signature Version is not known.
"""
fmt = 'Unknown Signature Version: {signature_version}.'
class UnsupportedSignatureVersionError(AltusCLIError):
"""
Error when trying to access a method on a client that does not exist.
"""
fmt = 'Signature version is not supported: {signature_version}'
class NoCredentialsError(AltusCLIError):
"""
No credentials could be found
"""
fmt = 'Unable to locate Altus credentials'
class UnknownCredentialError(AltusCLIError):
"""
Tried to insert before/after an unregistered credential type.
"""
fmt = 'Credential named {name} not found.'
class PartialCredentialsError(AltusCLIError):
"""
Only partial credentials were found.
"""
fmt = 'Partial credentials found in {provider}, missing: {cred_var}'
class BaseEndpointResolverError(AltusCLIError):
"""
Base error for endpoint resolving errors.
Should never be raised directly, but clients can catch
this exception if they want to generically handle any errors
during the endpoint resolution process.
"""
class NoRegionError(BaseEndpointResolverError):
"""
No region was specified.
"""
fmt = 'You must specify a region.'
class ProfileNotFound(AltusCLIError):
"""
The specified configuration profile was not found in the
configuration file.
"""
fmt = 'The config profile ({profile}) could not be found'
class ConfigNotFound(AltusCLIError):
"""
The specified configuration file could not be found.
"""
fmt = 'The specified config file ({path}) could not be found.'
class ConfigParseError(AltusCLIError):
"""
The configuration file could not be parsed.
"""
fmt = 'Unable to parse config file: {path}'
class ClusterTerminatingError(AltusCLIError):
"""
The cluster is terminating or has already terminated.
"""
fmt = 'Cluster {cluster_name} is terminating.'
class ClusterStartingError(AltusCLIError):
"""
The cluster is starting.
"""
fmt = 'Cluster {cluster_name} is starting.'
class ClusterFailedError(AltusCLIError):
"""
The cluster failed to start.
"""
fmt = 'Cluster {cluster_name} failed to start.'
class ClusterDoesNotExistError(AltusCLIError):
"""
Cluster with the given name does not exist.
"""
fmt = 'Cluster {cluster_name} does not exist.'
class ClusterStatusNotFound(AltusCLIError):
"""
Unable to find cluster status.
"""
fmt = 'Unable to find {cluster_name}\'s status.'
class ClusterEndpointNotFound(AltusCLIError):
"""
Unable to find cluster's Cloudera Manager Endpoint.
"""
fmt = 'Unable to find {cluster_name}\'s Cloudera Manager Endpoint.'
class MultipleClustersExist(AltusCLIError):
"""
Multiple clusters exist, expected single cluster.
"""
fmt = 'Multiple clusters exist, expected single cluster.'
class SSHNotFoundError(AltusCLIError):
"""
SSH or Putty not available.
"""
fmt = 'SSH or Putty not available.'
class WrongPuttyKeyError(AltusCLIError):
"""
A wrong key has been used with a compatible program.
"""
fmt = 'Key file file format is incorrect. Putty expects a ppk file.'
|
NORMALIZED_POWERS = {
191: ('1x127', '1.5'),
200: ('1x133', '1.5'),
330: ('1x220', '1.5'),
345: ('1x230', '1.5'),
381: ('1x127', '3'),
399: ('1x133', '3'),
445: ('1x127', '3.5'),
466: ('1x133', '3.5'),
572: ('3x220/127', '1.5'),
598: ('3x230/133', '1.5'),
635: ('1x127', '5'),
660: ('1x220', '3'),
665: ('1x133', '5'),
690: ('1x230', '3'),
770: ('1x220', '3.5'),
805: ('1x230', '3.5'),
953: ('1x127', '7.5'),
987: ('3x380/220', '1.5'),
998: ('1x133', '7.5'),
1039: ('3x400/230', '1.5'),
1100: ('1x220', '5'),
1143: ('3x220/127', '3'),
1150: ('1x230', '5'),
1195: ('3x230/133', '3'),
1270: ('1x127', '10'),
1330: ('1x133', '10'),
1334: ('3x220/127', '3.5'),
1394: ('3x230/133', '3.5'),
1650: ('1x220', '7.5'),
1725: ('1x230', '7.5'),
1905: ('1x127', '15'),
1975: ('3x380/220', '3'),
1992: ('3x230/133', '5'),
1995: ('1x133', '15'),
2078: ('3x400/230', '3'),
2200: ('1x220', '10'),
2300: ('1x230', '10'),
2304: ('3x380/220', '3.5'),
2425: ('3x400/230', '3.5'),
2540: ('1x127', '20'),
2660: ('1x133', '20'),
2858: ('3x220/127', '7.5'),
2988: ('3x230/133', '7.5'),
3175: ('1x127', '25'),
3291: ('3x380/220', '5'),
3300: ('1x220', '15'),
3325: ('1x133', '25'),
3450: ('1x230', '15'),
3464: ('3x400/230', '5'),
3810: ('1x127', '30'),
3811: ('3x220/127', '10'),
3984: ('3x230/133', '10'),
3990: ('1x133', '30'),
4400: ('1x220', '20'),
4445: ('1x127', '35'),
4600: ('1x230', '20'),
4655: ('1x133', '35'),
4936: ('3x380/220', '7.5'),
5080: ('1x127', '40'),
5196: ('3x400/230', '7.5'),
5320: ('1x133', '40'),
5500: ('1x220', '25'),
5715: ('1x127', '45'),
5716: ('3x220/127', '15'),
5750: ('1x230', '25'),
5976: ('3x230/133', '15'),
5985: ('1x133', '45'),
6350: ('1x127', '50'),
6582: ('3x380/220', '10'),
6600: ('1x220', '30'),
6650: ('1x133', '50'),
6900: ('1x230', '30'),
6928: ('3x400/230', '10'),
7621: ('3x220/127', '20'),
7700: ('1x220', '35'),
7967: ('3x230/133', '20'),
8001: ('1x127', '63'),
8050: ('1x230', '35'),
8379: ('1x133', '63'),
8800: ('1x220', '40'),
9200: ('1x230', '40'),
9526: ('3x220/127', '25'),
9873: ('3x380/220', '15'),
9900: ('1x220', '45'),
9959: ('3x230/133', '25'),
10350: ('1x230', '45'),
10392: ('3x400/230', '15'),
11000: ('1x220', '50'),
11432: ('3x220/127', '30'),
11500: ('1x230', '50'),
11951: ('3x230/133', '30'),
13164: ('3x380/220', '20'),
13337: ('3x220/127', '35'),
13856: ('3x400/230', '20'),
13860: ('1x220', '63'),
13943: ('3x230/133', '35'),
14490: ('1x230', '63'),
15242: ('3x220/127', '40'),
15935: ('3x230/133', '40'),
16454: ('3x380/220', '25'),
17147: ('3x220/127', '45'),
17321: ('3x400/230', '25'),
17927: ('3x230/133', '45'),
19053: ('3x220/127', '50'),
19745: ('3x380/220', '30'),
19919: ('3x230/133', '50'),
20785: ('3x400/230', '30'),
23036: ('3x380/220', '35'),
24006: ('3x220/127', '63'),
24249: ('3x400/230', '35'),
25097: ('3x230/133', '63'),
26327: ('3x380/220', '40'),
27713: ('3x400/230', '40'),
29618: ('3x380/220', '45'),
31177: ('3x400/230', '45'),
32909: ('3x380/220', '50'),
34641: ('3x400/230', '50'),
41465: ('3x380/220', '63'),
43648: ('3x400/230', '63')
}
NOT_NORMALIZED_100 = dict([(p, (None, None)) for p in range(100, 15001, 100)
if p not in NORMALIZED_POWERS])
ALL_POWERS = NOT_NORMALIZED_100.copy()
ALL_POWERS.update(NORMALIZED_POWERS)
class NormalizedPower(object):
def get_volt_int(self, pot):
volt_int = ALL_POWERS.get(pot, None)
if volt_int is None:
raise ValueError('The given power is not normalized')
return volt_int
def is_normalized(self, pot):
return pot in ALL_POWERS
def get_norm_powers(self, pot_min, pot_max):
for norm_pow in sorted(ALL_POWERS):
if pot_min < norm_pow <= pot_max:
yield norm_pow
elif norm_pow > pot_max:
break
|
dict_camera = {'wfpc1': 1, 'wfpc1_planetary': 2, 'wfpc1_foc_f48': 3, 'wfpc1_foc_f48': 4, 'wfpc2': 5, 'wfpc2_planetary': 6, 'wfpc2_foc_f48': 7, 'wfpc2_foc_f48': 8, 'nicmos1_precryo': 9, 'nicmos2_precryo': 10, 'nicmos3_precryo': 11, 'stis_ccd': 12, 'stis_nuv': 13, 'stis_fuv': 14, 'acs_widefield': 15, 'acs_highres': 16, 'acs_coronoffspot': 17, 'acs_solarblind': 18, 'nicmos1_cryo': 19, 'nicmos2_cryo': 20, 'nicmos3_cryo': 21, 'wfc3_uvis': 22, 'wfc3_ir': 23,}
dict_spectrum_form = {'stellar': 1, 'blackbody': 2, 'powerlaw_nu': 3, 'powerlaw_lam': 4, 'user': 5}
dict_spectrum_stellar = {'o5': 1, 'o8f': 2, 'o6': 3, 'b1v': 4, 'b3v': 5, 'b6v': 6,
'a0v': 7, 'a5v': 8, 'f6v': 9, 'f8v': 10, 'g2v': 11, 'g5v': 12, 'g8v': 13,
'k4v': 14, 'k7v': 15, 'm1.5v': 16, 'm3v': 17}
|
def log_error(error):
'''
This logging function just print a formated error message
'''
print(error)
|
class Depvar:
"""The Depvar object specifies solution-dependent state variables.
Notes
-----
This object can be accessed by:
.. code-block:: python
import material
mdb.models[name].materials[name].depvar
import odbMaterial
session.odbs[name].materials[name].depvar
The corresponding analysis keywords are:
- DEPVAR
"""
def __init__(self, deleteVar: int = 0, n: int = 0):
"""This method creates a Depvar object.
Notes
-----
This function can be accessed by:
.. code-block:: python
mdb.models[name].materials[name].Depvar
session.odbs[name].materials[name].Depvar
Parameters
----------
deleteVar
An Int specifying the state variable number controlling the element deletion flag. The
default value is 0.This argument applies only to Abaqus/Explicit analyses.
n
An Int specifying the number of solution-dependent state variables required at each
integration point. The default value is 0.
Returns
-------
A Depvar object.
Raises
------
RangeError
"""
pass
def setValues(self):
"""This method modifies the Depvar object.
Raises
------
RangeError
"""
pass
|
host = 'Your SMTP server host here'
port = 25 # Your SMTP server port here
username = 'Your SMTP server username here'
password = 'Your SMTP server password here'
encryption = 'required' # Your SMTP server security policy here. Must be one of 'required', 'optional', or 'ssl'
__all__ = ['host', 'port', 'username', 'password', 'encryption']
|
class Solution:
# @param {string} a a number
# @param {string} b a number
# @return {string} the result
def addBinary(self, a, b):
# Write your code here
alen, blen = len(a), len(b)
if alen > blen:
b = '0' * (alen - blen) + b
nlen = alen
else:
a = '0' * (blen - alen) + a
nlen = blen
res, c = '', 0
for i in range(nlen - 1, -1, -1):
at, bt = int(a[i]), int(b[i])
if at + bt + c > 1:
res = str(at + bt + c - 2) + res
c = 1
else:
res = str(at + bt + c) + res
c = 0
if c == 1:
res = '1' + res
return res
|
palettes = {
"material_design": {
"red_500": 0xF44336,
"pink_500": 0xE91E63,
"purple_500": 0x9C27B0,
"deep_purple_500": 0x673AB7,
"indigo_500": 0x3F51B5,
"blue_500": 0x2196F3,
"light_blue_500": 0x03A9F4,
"cyan_500": 0x00BCD4,
"teal_500": 0x009688,
"green_500": 0x4CAF50,
"light_green_500": 0x8BC34A,
"lime_500": 0xCDDC39,
"yellow_500": 0xFFEB3B,
"amber_500": 0xFFC107,
"orange_500": 0xFF9800,
"deep_orange_500": 0xFF5722,
"brown_500": 0x795548,
}
}
|
class Node:
"""This class represents one node of a trie tree
Parameters
----------
self.char --> str
the character it stores, i.e. one character per node
self.valid --> bool
True if the character is the end of a valid word
self.parent --> Node
the parent node, i.e. each node only has one parent, None if root node
self.children --> list of Node
a list of children nodes, i.e. each node can have multiple children, empty if leaf node
Methods
-------
get_child(self, char)
returns the child corresponding to the input char if present, otherwise return False.
sorted_children(self)
Returns the children of a node but sorted by in alphabetical order
"""
def __init__(self, char):
"""Creates the Node instance.
Parameters
----------
char : str
The character the node represents
"""
self.char = char
self.valid = False
self.parent = None
self.children = []
self.occurrence = 0 # new attribute to store occurrence when building the trie
def __repr__(self):
"""Overrides the defauly print implementation."""
return f"\n\t Node {self.char}"
def __eq__(self, other):
"""Overrides the default equality implementation."""
if isinstance(other, Node):
return self.char == other.char
if isinstance(other, str):
return self.char == other
return False
def get_child(self, char):
"""Returns the child corresponding to the input char if present in
the node's list of children. Otherwise returns False.
Parameters
----------
char : str
The character to be checked in the node's children
"""
for child in self.children:
if child == char: # this is made possible by __eq__()
return child
return False
# new method
def sorted_children(self):
"""Returns the children of a node but sorted by in alphabetical order.
Returns
----------
sorted_children : list of Nodes
the sorted children of a node
"""
# if a node doesn't have children, return empty list
if not self.children:
return []
# else sort the children with key as node.char
sorted_children = sorted(self.children, key=lambda x: x.char)
return sorted_children
class Trie:
"""This class represents the entirety of a trie tree.
Parameters
----------
self.root --> Node
the root node with an empty string
self.word_list --> list
the input list of words converted into lower-case
self.tree --> None
calls the create_trie() method so the trie is intialized upon instantiation
Methods
-------
create_trie(self, word_list)
Calls the insert() method for each word in word_list
insert(self, word)
Inserts a word into the trie, creating nodes as required.
lookup(self, word)
Determines whether a given word is present in the trie.
peek_occurrence(self, word)
Determines the occurrence of given word.
k_most_common(self, k):
Finds k words inserted into the trie most often.
"""
def __init__(self, word_list = None):
"""Creates the Trie instance, inserts initial words if provided.
Parameters
----------
word_list : list
List of strings to be inserted into the trie upon creation.
"""
self.root = Node("")
self.word_list = [word.lower() for word in word_list]
self.tree = self.create_trie()
def __repr__(self):
"""Overrides the defauly print implementation."""
return f"This trie has root: \n{self.root}"
def create_trie(self):
"""Inserts all words from the input wordbank into the trie by calling self.insert()"""
for word in self.word_list:
self.insert(word)
def insert(self, word):
"""Inserts a word into the trie, creating missing nodes on the go.
Parameters
----------
word : str
The word to be inserted into the trie.
"""
# iterate through each character of the word
current_node = self.root
for i in range(len(word)):
# check if a child with the new character already exists
new_char = word[i]
child = current_node.get_child(new_char)
# if child doesn't exist, create new node instance
if child == False:
new_node = Node(new_char)
new_node.parent = current_node # update parent attribute
current_node.children.append(new_node) # update children attribute
current_node = new_node
# if child exists, continue
else:
current_node = child
# the last char of the word means it is a valid word
current_node.valid = True
# new line: records the occurrences of the word
current_node.occurrence += 1
def lookup(self, word):
"""Determines whether a given word is present in the trie.
Parameters
----------
word : str
The word to be looked-up in the trie.
Returns
-------
bool
True if the word is present in trie; False otherwise.
Notes
-----
Your trie should ignore whether a word is capitalized.
E.g. trie.insert('Prague') should lead to trie.lookup('prague') = True
"""
# convert to lower-case, remove white spaces, replace in-word white spaces with hyphens
word = word.lower().strip().replace(" ", "-")
current_node = self.root
for i in range(len(word)):
# goes down the trie by iteratively checking if a child exist
child = current_node.get_child(word[i])
if child != False:
current_node = child
# if a child doesn't exist, immediately return False
if child == False:
return False
# return if the last character of the word is a valid word
return current_node.valid
# new method
def alphabetical_list(self):
"""Delivers the content of the trie in alphabetical order.
Returns
----------
list
List of strings, all words from the trie in alphabetical order.
"""
if not self.root:
return []
if not self.root.children:
return []
return self._alphabetical_list(self.root)
# new inner method
def _alphabetical_list(self, root):
"""Inner function to above. Recursively appends the child char to the parent.
Parameters
----------
root
The root of a trie tree, possibly an internal node for a sub trie tree
Note: having a root parameter is helpful for recursing through the trie by considering
a child node has the root of a sub trie.
"""
lst = [] # initialize empty list
# if the root has children
if root.children:
children = root.sorted_children() # sort the children list
for child in children:
# for each string accumulated from the bottom-up
for string in self._alphabetical_list(child):
# this statement appends valid words that don't end at a leaf
if child.valid and child.children and child.char not in lst:
lst.append(child.char)
# concatenate the child's character to the accumulated string
lst.append(child.char + string)
# base case: if root (leaf) has no children
else:
lst.append('')
return lst
# new method
def peek_occurrence(self, word):
"""Determines the occurrence of given word.
Parameters
----------
word : str
The word to be peeked in the trie.
Returns
-------
int / bool
Returns the occurrence of the word. If word is not valid, return False
Note: this is very similar to the lookup() method but instead of checking
self.valid it checks self.occurrence.
"""
current_node = self.root
for i in range(len(word)):
child = current_node.get_child(word[i])
if child != False:
current_node = child
if current_node.valid:
return current_node.occurrence
return False
def k_most_common(self, k):
"""Finds k words inserted into the trie most often.
Parameters
----------
k : int
Number of most common words to be returned.
Returns
----------
list
List of tuples.
Each tuple entry consists of the word and its frequency.
The entries are sorted by frequency.
Example
-------
>>> print(trie.k_most_common(3))
[(‘the’, 154), (‘a’, 122), (‘i’, 122)]
I.e. the word ‘the’ has appeared 154 times in the inserted text.
The second and third most common words both appeared 122 times.
"""
if k <= 0 or int(k) != k:
return "ERROR: k must be a positive integer"
common_words = [] # initialize empty list
unique_words = self.alphabetical_list() # find all unique words
if not unique_words:
return "ERROR: no valid words to find the k most common words"
# peek the occurrence of the word and stores in a tuple
for word in unique_words:
common_words.append((word, self.peek_occurrence(word)))
# sort all words and their occurrences
common_words.sort(key=lambda x: x[1], reverse = True)
# if k is way too large
if k > len(unique_words):
print(f"NOTE: wordbank has {len(unique_words)} < {k} unique words!!")
return common_words
# returns the first k words with most occurrences
return common_words[:k]
# new method
def most_common(self, node, prefix):
"""Finds the most common word with the given prefix.
You might want to reuse some functionality or ideas from Q4.
Parameters
----------
node: Node
the last node (char) of the prefix
prefix : str
The word part to be “autocompleted”.
Returns
----------
str
The complete, most common word with the given prefix.
"""
common_words = [] # initalize empty list
unique_words = [prefix + word for word in self._alphabetical_list(node)] # find all unique words with the prefix
if not node:
return "ERROR: no valid words with this prefix"
# if the prefix is a valid word itself
if node.valid:
unique_words.append(prefix)
# if there are no unique words with this prefix
if not unique_words:
return "ERROR: no valid words with this prefix"
# append the word and its occurrence for each unique word
for word in unique_words:
common_words.append((word, self.peek_occurrence(word)))
# sort them by occurrences
common_words.sort(key=lambda x: x[1], reverse = True)
# return the first element of the first tuple, i.e. the string of the most common word
return common_words[0][0]
# new method
def autocomplete(self, prefix):
"""Finds the most common word with the given prefix.
You might want to reuse some functionality or ideas from Q4.
Parameters
----------
prefix : str
The word part to be “autocompleted”.
Returns
----------
str
The complete, most common word with the given prefix.
Notes
----------
The return value is equal to prefix if there is no valid word in the trie.
The return value is also equal to prefix if prefix is the most common word.
"""
# convert to lower-case
prefix = prefix.lower()
# traverse down the tree to the last char of the prefix
current_node = self.root
for i in range(len(prefix)):
current_node = current_node.get_child(prefix[i])
if current_node == False:
return "ERROR: prefix does not exist in trie"
# find the most common words with the alphabetical list from this last char
return self.most_common(current_node, prefix)
|
def main(request, response):
try:
name = "recon_fail_" + request.GET.first("id")
headers = [("Content-Type", "text/event-stream")]
cookie = request.cookies.first(name, None)
state = cookie.value if cookie is not None else None
if state == 'opened':
status = (200, "RECONNECT")
response.set_cookie(name, "reconnected")
body = "data: reconnected\n\n"
elif state == 'reconnected':
status = (204, "NO CONTENT (CLOSE)")
response.delete_cookie(name)
body = "data: closed\n\n" # Will never get through
else:
status = (200, "OPEN")
response.set_cookie(name, "opened")
body = "retry: 2\ndata: opened\n\n"
return status, headers, body
except Exception as ex:
return "error"
|
chat_component = {
"video_id" : "video_id",
"timeout" : 10,
"chatdata": [
{
"addChatItemAction": {
"item": {
"liveChatTextMessageRenderer": {
"message": {
"runs": [
{
"text": "This is normal message."
}
]
},
"authorName": {
"simpleText": "author_name"
},
"authorPhoto": {
"thumbnails": [
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 32,
"height": 32
},
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 64,
"height": 64
}
]
},
"contextMenuEndpoint": {
"commandMetadata": {
"webCommandMetadata": {
"ignoreNavigation": True
}
},
"liveChatItemContextMenuEndpoint": {
"params": "___params___"
}
},
"id": "dummy_id",
"timestampUsec": 0,
"authorExternalChannelId": "http://www.youtube.com/channel/author_channel_url",
"contextMenuAccessibility": {
"accessibilityData": {
"label": "コメントの操作"
}
}
}
},
"clientId": "dummy_client_id"
}
},
{
"addChatItemAction": {
"item": {
"liveChatTextMessageRenderer": {
"message": {
"runs": [
{
"text": "This is members's message"
}
]
},
"authorName": {
"simpleText": "author_name"
},
"authorPhoto": {
"thumbnails": [
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 32,
"height": 32
},
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 64,
"height": 64
}
]
},
"contextMenuEndpoint": {
"commandMetadata": {
"webCommandMetadata": {
"ignoreNavigation": True
}
},
"liveChatItemContextMenuEndpoint": {
"params": "___params___"
}
},
"id": "dummy_id",
"timestampUsec": 0,
"authorBadges": [
{
"liveChatAuthorBadgeRenderer": {
"customThumbnail": {
"thumbnails": [
{
"url": "https://yt3.ggpht.com/X=s32-c-k"
},
{
"url": "https://yt3.ggpht.com/X=s32-c-k"
}
]
},
"tooltip": "メンバー(2 か月)",
"accessibility": {
"accessibilityData": {
"label": "メンバー(2 か月)"
}
}
}
}
],
"authorExternalChannelId": "http://www.youtube.com/channel/author_channel_url",
"contextMenuAccessibility": {
"accessibilityData": {
"label": "コメントの操作"
}
}
}
},
"clientId": "dummy_client_id"
}
},
{
"addChatItemAction": {
"item": {
"liveChatPlaceholderItemRenderer": {
"id": "dummy_id",
"timestampUsec": 0
}
},
"clientId": "dummy_client_id"
}
},
{
"addLiveChatTickerItemAction": {
"item": {
"liveChatTickerPaidMessageItemRenderer": {
"id": "dummy_id",
"amount": {
"simpleText": "¥10,000"
},
"amountTextColor": 4294967295,
"startBackgroundColor": 4293271831,
"endBackgroundColor": 4291821568,
"authorPhoto": {
"thumbnails": [
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 32,
"height": 32
},
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 64,
"height": 64
}
]
},
"durationSec": 3600,
"showItemEndpoint": {
"commandMetadata": {
"webCommandMetadata": {
"ignoreNavigation": True
}
},
"showLiveChatItemEndpoint": {
"renderer": {
"liveChatPaidMessageRenderer": {
"id": "dummy_id",
"timestampUsec": 0,
"authorName": {
"simpleText": "author_name"
},
"authorPhoto": {
"thumbnails": [
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 32,
"height": 32
},
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 64,
"height": 64
}
]
},
"purchaseAmountText": {
"simpleText": "¥10,000"
},
"message": {
"runs": [
{
"text": "This is superchat message."
}
]
},
"headerBackgroundColor": 4291821568,
"headerTextColor": 4294967295,
"bodyBackgroundColor": 4293271831,
"bodyTextColor": 4294967295,
"authorExternalChannelId": "http://www.youtube.com/channel/author_channel_url",
"authorNameTextColor": 3019898879,
"contextMenuEndpoint": {
"commandMetadata": {
"webCommandMetadata": {
"ignoreNavigation": True
}
},
"liveChatItemContextMenuEndpoint": {
"params": "___params___"
}
},
"timestampColor": 2164260863,
"contextMenuAccessibility": {
"accessibilityData": {
"label": "コメントの操作"
}
}
}
}
}
},
"authorExternalChannelId": "http://www.youtube.com/channel/author_channel_url",
"fullDurationSec": 3600
}
},
"durationSec": "3600"
}
},
{
"addChatItemAction": {
"item": {
"liveChatPaidMessageRenderer": {
"id": "dummy_id",
"timestampUsec": 0,
"authorName": {
"simpleText": "author_name"
},
"authorPhoto": {
"thumbnails": [
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 32,
"height": 32
},
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 64,
"height": 64
}
]
},
"purchaseAmountText": {
"simpleText": "¥10,800"
},
"message": {
"runs": [
{
"text": "This is superchat message."
}
]
},
"headerBackgroundColor": 4291821568,
"headerTextColor": 4294967295,
"bodyBackgroundColor": 4293271831,
"bodyTextColor": 4294967295,
"authorExternalChannelId": "http://www.youtube.com/channel/author_channel_url",
"authorNameTextColor": 3019898879,
"contextMenuEndpoint": {
"commandMetadata": {
"webCommandMetadata": {
"ignoreNavigation": True
}
},
"liveChatItemContextMenuEndpoint": {
"params": "___params___"
}
},
"timestampColor": 2164260863,
"contextMenuAccessibility": {
"accessibilityData": {
"label": "コメントの操作"
}
}
}
}
}
},
{
"addChatItemAction": {
"item": {
"liveChatPaidStickerRenderer": {
"id": "dummy_id",
"contextMenuEndpoint": {
"clickTrackingParams": "___clickTrackingParams___",
"commandMetadata": {
"webCommandMetadata": {
"ignoreNavigation": True
}
},
"liveChatItemContextMenuEndpoint": {
"params": "___params___"
}
},
"contextMenuAccessibility": {
"accessibilityData": {
"label": "コメントの操作"
}
},
"timestampUsec": 0,
"authorPhoto": {
"thumbnails": [
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 32,
"height": 32
},
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 64,
"height": 64
}
]
},
"authorName": {
"simpleText": "author_name"
},
"authorExternalChannelId": "http://www.youtube.com/channel/author_channel_url",
"sticker": {
"thumbnails": [
{
"url": "//lh3.googleusercontent.com/param_s=s40-rp",
"width": 40,
"height": 40
},
{
"url": "//lh3.googleusercontent.com/param_s=s80-rp",
"width": 80,
"height": 80
}
],
"accessibility": {
"accessibilityData": {
"label": "___sticker_label___"
}
}
},
"moneyChipBackgroundColor": 4280191205,
"moneyChipTextColor": 4294967295,
"purchaseAmountText": {
"simpleText": "¥150"
},
"stickerDisplayWidth": 40,
"stickerDisplayHeight": 40,
"backgroundColor": 4279592384,
"authorNameTextColor": 3019898879,
"trackingParams": "___trackingParams___"
}
}
}
},
{
"addLiveChatTickerItemAction": {
"item": {
"liveChatTickerSponsorItemRenderer": {
"id": "dummy_id",
"detailText": {
"runs": [
{
"text": "メンバー"
}
]
},
"detailTextColor": 4294967295,
"startBackgroundColor": 4279213400,
"endBackgroundColor": 4278943811,
"sponsorPhoto": {
"thumbnails": [
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 32,
"height": 32
},
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 64,
"height": 64
}
]
},
"durationSec": 300,
"showItemEndpoint": {
"commandMetadata": {
"webCommandMetadata": {
"ignoreNavigation": True
}
},
"showLiveChatItemEndpoint": {
"renderer": {
"liveChatMembershipItemRenderer": {
"id": "dummy_id",
"timestampUsec": 0,
"authorExternalChannelId": "http://www.youtube.com/channel/author_channel_url",
"headerSubtext": {
"runs": [
{
"text": "メンバーシップ"
},
{
"text": " へようこそ!"
}
]
},
"authorName": {
"simpleText": "author_name"
},
"authorPhoto": {
"thumbnails": [
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 32,
"height": 32
},
{
"url": "https://yt3.ggpht.com/------------/AAAAAAAAAAA/AAAAAAAAAAA/xxxxxxxxxxxx/s32-x-x-xx-xx-xx-c0xffffff/photo.jpg",
"width": 64,
"height": 64
}
]
},
"authorBadges": [
{
"liveChatAuthorBadgeRenderer": {
"customThumbnail": {
"thumbnails": [
{
"url": "https://yt3.ggpht.com/X=s32-c-k"
},
{
"url": "https://yt3.ggpht.com/X=s32-c-k"
}
]
},
"tooltip": "新規メンバー",
"accessibility": {
"accessibilityData": {
"label": "新規メンバー"
}
}
}
}
],
"contextMenuEndpoint": {
"commandMetadata": {
"webCommandMetadata": {
"ignoreNavigation": True
}
},
"liveChatItemContextMenuEndpoint": {
"params": "___params___"
}
},
"contextMenuAccessibility": {
"accessibilityData": {
"label": "コメントの操作"
}
}
}
}
}
},
"authorExternalChannelId": "http://www.youtube.com/channel/author_channel_url",
"fullDurationSec": 300
}
},
"durationSec": "300"
}
}
]
}
|
#! python3
# __author__ = "YangJiaHao"
# date: 2018/2/14
class Solution:
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
if words == []:
return []
word_length = len(words[0])
words_length = word_length * len(words)
dic = {}
for word in words:
dic[word] = dic[word] + 1 if word in dic else 1
res = []
def find(s, l, r, curr):
if l >= r:
return True
word = s[l:l + word_length]
if word in dic:
curr[word] = curr[word] + 1 if word in curr else 1
if curr[word] > dic[word]:
return False
else:
return find(s, l + word_length, r, curr)
else:
return False
for i in range(len(s) - words_length + 1):
if find(s, i, i + words_length, {}):
res.append(i)
return res
class Solution2:
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
if words == []:
return []
word_length = len(words[0])
words_length = word_length * len(words)
if len(s) < words_length:
return []
res = []
def find(s, words):
if len(words) == 0:
return True
if s[:word_length] in words:
words.remove(s[:word_length])
return find(s[word_length:], words)
else:
return False
for i in range(len(s) - words_length + 1):
if find(s[i:i + words_length], words[:]):
res.append(i)
return res
if __name__ == '__main__':
s = "aabbaacbbaacdyangacbabc"
words = ['aa', 'bb']
so = Solution()
res = so.findSubstring(s, words)
print(res)
|
# Python - 3.6.0
paradise = God()
test.assert_equals(isinstance(paradise[0], Man), True, 'First object are a man')
|
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: disable=unused-argument
# EXAMPLE: /RedisEnterprise/put/RedisEnterpriseCreate
# NOTE: Functions will always first be looked up in manual/custom.py followed by generated/custom.py
def step_create(test, checks=None, cache_num=1):
if checks is None:
checks = []
if test.kwargs.get('no_database'):
test.cmd('az redisenterprise create '
'--cluster-name "{cluster}" '
'--sku "EnterpriseFlash_F300" '
'--tags tag1="value1" '
'--no-database '
'--resource-group "{rg}"',
checks=checks)
elif test.kwargs.get('geo-replication'):
if cache_num == 1:
test.cmd('az redisenterprise create '
'--cluster-name "{cluster31}" '
'--sku "EnterpriseFlash_F300" '
'--tags tag1="value1" '
'--no-database '
'--resource-group "{rg31}"',
checks=checks)
elif cache_num == 2:
test.cmd('az redisenterprise create '
'--location "West US" '
'--cluster-name "{cluster32}" '
'--sku "EnterpriseFlash_F300" '
'--client-protocol "Encrypted" '
'--clustering-policy "EnterpriseCluster" '
'--eviction-policy "NoEviction" '
'--group-nickname "groupName" '
'--linked-databases id="/subscriptions/{subscription}/resourceGroups/{rg31}/providers/Microsoft.Cache/redisEnterprise/{cluster31}/databases/{database}" '
'--linked-databases id="/subscriptions/{subscription}/resourceGroups/{rg32}/providers/Microsoft.Cache/redisEnterprise/{cluster32}/databases/{database}" '
'--port 10000 '
'--resource-group "{rg32}"',
checks=checks)
else:
test.cmd('az redisenterprise create '
'--cluster-name "{cluster}" '
'--sku "Enterprise_E20" '
'--capacity 4 '
'--tags tag1="value1" '
'--zones "1" "2" "3" '
'--minimum-tls-version "1.2" '
'--client-protocol "Encrypted" '
'--clustering-policy "EnterpriseCluster" '
'--eviction-policy "NoEviction" '
'--modules name="RedisBloom" '
'--modules name="RedisTimeSeries" '
'--modules name="RediSearch" '
'--port 10000 '
'--resource-group "{rg}"',
checks=checks)
# EXAMPLE: /Databases/post/RedisEnterpriseDatabasesForceUnlink - unlinking a database during a regional outage
def step_database_force_unlink(test, checks=None):
if checks is None:
checks = []
test.cmd('az redisenterprise database force-unlink '
'--cluster-name "{cluster32}" '
'--unlink-ids "/subscriptions/{subscription}/resourceGroups/{rg31}/providers/Microsoft.Cache/redisEnterprise/{'
'myRedisEnterprise2}/databases/{database}" '
'--resource-group "{rg32}"',
checks=checks)
# EXAMPLE: /RedisEnterprise/get/RedisEnterpriseGet
def step_show(test, checks=None):
if checks is None:
checks = []
if test.kwargs.get('geo-replication'):
test.cmd('az redisenterprise show '
'--cluster-name "{cluster32}" '
'--resource-group "{rg32}"',
checks=checks)
else:
test.cmd('az redisenterprise show '
'--cluster-name "{cluster}" '
'--resource-group "{rg}"',
checks=checks)
# EXAMPLE: /RedisEnterprise/delete/RedisEnterpriseDelete
def step_delete(test, checks=None):
if checks is None:
checks = []
if test.kwargs.get('geo-replication'):
test.cmd('az redisenterprise delete -y '
'--cluster-name "{cluster31}" '
'--resource-group "{rg31}"',
checks=checks)
test.cmd('az redisenterprise delete -y '
'--cluster-name "{cluster32}" '
'--resource-group "{rg32}"',
checks=checks)
else:
test.cmd('az redisenterprise delete -y '
'--cluster-name "{cluster}" '
'--resource-group "{rg}"',
checks=checks)
# EXAMPLE: /Databases/put/RedisEnterpriseDatabasesCreate
def step_database_create(test, checks=None):
if checks is None:
checks = []
if test.kwargs.get('geo-replication'):
test.cmd('az redisenterprise database create '
'--cluster-name "{cluster31}" '
'--client-protocol "Encrypted" '
'--clustering-policy "EnterpriseCluster" '
'--eviction-policy "NoEviction" '
'--group-nickname "groupName" '
'--linked-databases id="/subscriptions/{subscription}/resourceGroups/{rg31}/providers/Microsoft.Cache/redisEnterprise/{cluster31}/databases/{database}" '
'--port 10000 '
'--resource-group "{rg31}"',
checks=checks)
else:
test.cmd('az redisenterprise database create '
'--cluster-name "{cluster}" '
'--client-protocol "Plaintext" '
'--clustering-policy "OSSCluster" '
'--eviction-policy "AllKeysLRU" '
'--port 10000 '
'--resource-group "{rg}"',
checks=checks)
def step_database_force_unlink(test, checks=None):
if checks is None:
checks = []
test.cmd('az redisenterprise database force-unlink '
'--cluster-name "{cluster32}" '
'--unlink-ids "/subscriptions/{subscription}/resourceGroups/{rg31}/providers/Microsoft.Cache/redisEnterprise/{'
'cluster31}/databases/{database}" '
'--resource-group "{rg32}"',
checks=checks)
# EXAMPLE: /Databases/get/RedisEnterpriseDatabasesGet
def step_database_show(test, checks=None):
if checks is None:
checks = []
test.cmd('az redisenterprise database show '
'--cluster-name "{cluster}" '
'--resource-group "{rg}"',
checks=checks)
# EXAMPLE: /Databases/get/RedisEnterpriseDatabasesListByCluster
def step_database_list(test, checks=None):
if checks is None:
checks = []
test.cmd('az redisenterprise database list '
'--cluster-name "{cluster}" '
'--resource-group "{rg}"',
checks=checks)
# EXAMPLE: /Databases/post/RedisEnterpriseDatabasesListKeys
def step_database_list_keys(test, checks=None):
if checks is None:
checks = []
test.cmd('az redisenterprise database list-keys '
'--cluster-name "{cluster}" '
'--resource-group "{rg}"',
checks=checks)
# EXAMPLE: /Databases/post/RedisEnterpriseDatabasesRegenerateKey
def step_database_regenerate_key(test, checks=None):
if checks is None:
checks = []
test.cmd('az redisenterprise database regenerate-key '
'--cluster-name "{cluster}" '
'--key-type "Primary" '
'--resource-group "{rg}"',
checks=checks)
# EXAMPLE: /Databases/delete/RedisEnterpriseDatabasesDelete
def step_database_delete(test, checks=None):
if checks is None:
checks = []
if test.kwargs.get('geo-replication'):
test.cmd('az redisenterprise database delete -y '
'--cluster-name "{cluster31}" '
'--resource-group "{rg31}"',
checks=checks)
test.cmd('az redisenterprise database delete -y '
'--cluster-name "{cluster32}" '
'--resource-group "{rg32}"',
checks=checks)
else:
test.cmd('az redisenterprise database delete -y '
'--cluster-name "{cluster}" '
'--resource-group "{rg}"',
checks=checks)
|
#input
# 15
# 2 4 3 6 7 9 1 5 8
# 9 3 7 8 6 1 5 2 4
# 1 4 9 5 6 3 2 8 7
# 1 6 8 3 4 2 9 7 5
# 7 4 6 5 1 9 3 8 2
# 8 1 7 5 6 3 9 2 4
# 2 4 3 9 7 8 5 1 6
# 6 3 1 9 2 7 4 5 8
# 1 4 7 6 8 9 5 3 2
# 7 9 1 8 5 6 3 2 4
# 1 3 9 6 8 2 5 7 4
# 8 5 4 6 3 7 2 1 9
# 7 2 4 5 8 1 9 3 6
# 5 2 6 1 8 4 9 3 7
# 4 8 5 3 2 6 1 7 9
class Game:
board = []
def initialize(self):
self.board = []
for i in range(0, 3):
self.board.append([None, None, None])
def mark(self, pos, p):
self.board[pos // 3][pos % 3] = p
def is_game_over(self):
##check rows
for i in range(0, 3):
if (self.board[i][0] == None):
continue
if (self.board[i][0] == self.board[i][1]
and self.board[i][1] == self.board[i][2]):
return True
##check columns
for i in range(0, 3):
if (self.board[0][i] == None):
continue
if (self.board[0][i] == self.board[1][i]
and self.board[1][i] == self.board[2][i]):
return True
##check diagonals
if self.board[1][1] == None:
return False
if self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2]:
return True
if self.board[2][0] == self.board[1][1] and self.board[1][1] == self.board[0][2]:
return True
return False
game = Game()
n = int(input())
for i in range(0, n):
game.initialize()
moves = [int(x) for x in input().split()]
for j in range(0, len(moves)):
player = None
if j % 2 == 0:
player = 'x'
else:
player = 'o'
game.mark(moves[j] - 1, player)
if game.is_game_over():
print(str(j+1), "", end="")
break
if j == len(moves) - 1:
print(0, "", end="") |
#!/usr/bin/env python3
# Write a program that prints the reverse-complement of a DNA sequence
# You must use a loop and conditional
dna = 'ACTGAAAAAAAAAAA'
rvdna = ''
for i in range(len(dna) -1, -1, -1) :
nt = dna[i]
if nt == 'A' : rvdna += 'T'
elif nt == 'T': rvdna += 'A'
elif nt == 'C': rvdna += 'G'
elif nt == 'G': rvdna += 'C'
print(rvdna)
"""
python3 anti.py
TTTTTTTTTTTCAGT
"""
|
load(
"//ruby/private/tools:deps.bzl",
_transitive_deps = "transitive_deps",
)
load(
"//ruby/private:providers.bzl",
"RubyGem",
"RubyLibrary",
)
def _get_transitive_srcs(srcs, deps):
return depset(
srcs,
transitive = [dep[RubyLibrary].transitive_ruby_srcs for dep in deps],
)
def _rb_gem_impl(ctx):
gemspec = ctx.actions.declare_file("{}.gemspec".format(ctx.attr.gem_name))
metadata_file = ctx.actions.declare_file("{}_metadata".format(ctx.attr.gem_name))
_ruby_files = []
file_deps = _get_transitive_srcs([], ctx.attr.deps).to_list()
for f in file_deps:
# For some files the src_path and dest_path will be the same, but
# for othrs the src_path will be in bazel)out while the dest_path
# will be from the workspace root.
_ruby_files.append({
"src_path": f.path,
"dest_path": f.short_path,
})
ctx.actions.write(
output = metadata_file,
content = struct(
name = ctx.attr.gem_name,
raw_srcs = _ruby_files,
authors = ctx.attr.authors,
version = ctx.attr.version,
licenses = ctx.attr.licenses,
require_paths = ctx.attr.require_paths,
).to_json(),
)
ctx.actions.run(
inputs = [
ctx.file._gemspec_template,
ctx.file._gemspec_builder,
metadata_file,
] + file_deps,
executable = ctx.attr.ruby_interpreter.files_to_run.executable,
arguments = [
ctx.file._gemspec_builder.path,
"--output",
gemspec.path,
"--metadata",
metadata_file.path,
"--template",
ctx.file._gemspec_template.path,
],
outputs = [gemspec],
execution_requirements = {
"no-sandbox": "1",
},
)
return [
DefaultInfo(files = _get_transitive_srcs([gemspec], ctx.attr.deps)),
RubyGem(
ctx = ctx,
version = ctx.attr.version,
gemspec = gemspec,
),
]
_ATTRS = {
"version": attr.string(
default = "0.0.1",
),
"authors": attr.string_list(),
"licenses": attr.string_list(),
"deps": attr.label_list(
allow_files = True,
),
"data": attr.label_list(
allow_files = True,
),
"gem_name": attr.string(),
"srcs": attr.label_list(
allow_files = True,
default = [],
),
"gem_deps": attr.label_list(
allow_files = True,
),
"require_paths": attr.string_list(),
"_gemspec_template": attr.label(
allow_single_file = True,
default = "gemspec_template.tpl",
),
"ruby_sdk": attr.string(
default = "@org_ruby_lang_ruby_toolchain",
),
"ruby_interpreter": attr.label(
default = "@org_ruby_lang_ruby_toolchain//:ruby_bin",
allow_files = True,
executable = True,
cfg = "host",
),
"_gemspec_builder": attr.label(
default = Label("@coinbase_rules_ruby//ruby/private/gem:gemspec_builder.rb"),
allow_single_file = True,
),
}
rb_gemspec = rule(
implementation = _rb_gem_impl,
attrs = _ATTRS,
provides = [DefaultInfo, RubyGem],
)
|
def average_price_per_year(dates,prices):
year = ''
counter = 0
accumulator = 0
average_year_years = []
average_year_prices = []
# for every date in the date list
# do the following
for index in range(len(dates)):
# Set the first year.
if year == '':
year = dates[index][6:10]
accumulator += float(prices[index])
counter += 1
# Continue with the rest dates.
# if we are still in the same year then
elif dates[index][6:10] == year:
# add the price to the accumulator
accumulator += float(prices[index])
counter += 1
# if the year changed, caclculate the average for the year
# and continue with the next year.
else:
average = accumulator / counter
average_year_years.append(year)
average_year_prices.append(average)
year = dates[index][6:10]
counter = 1
accumulator = float(prices[index])
print('Average Price Per Year')
print('----------------------')
print()
print('Year\t\tPrice')
print('----\t\t-----')
for index in range(len(average_year_years)):
print(average_year_years[index],'\t--->\t',format(average_year_prices[index],',.3f'))
def average_price_per_month(dates,prices):
month = ''
year = ''
counter = 0
accumulator = 0
average_price_months = []
average_price_prices = []
for index in range(len(dates)):
if year == '':
year = dates[index][6:10]
elif month == '':
month = dates[index][0:2]
elif dates[index][0:2] == month and dates[index][6:10] == year:
accumulator += float(prices[index])
counter += 1
else:
average = accumulator / counter
average_price_months.append(year + '-' + month)
average_price_prices.append(average)
counter = 1
accumulator = float(prices[index])
year = dates[index][6:10]
month = dates[index][0:2]
print('Average Price Per Month')
print('-----------------------')
print()
print('Month\t\tPrice')
print('-----\t\t-----')
for index in range(len(average_price_months)):
print(average_price_months[index],'----->\t',format(average_price_prices[index],',.3f'))
def highest_lowest_price_per_year(dates,prices):
year = ''
year_list = []
highest_per_year = []
lowest_per_year = []
find_max_min_price = []
for index in range(len(prices)):
prices[index] = float(prices[index])
for index in range(len(dates)):
if year == '':
year = dates[index][6:10]
find_max_min_price.append(prices[index])
elif dates[index][6:10] == year:
find_max_min_price.append(prices[index])
else:
year_list.append(year)
highest_per_year.append(max(find_max_min_price))
lowest_per_year.append(min(find_max_min_price))
year = dates[index][6:10]
find_max_min_price = [prices[index]]
print('Highest and Lowest Prices Per Year')
print('----------------------------------')
print()
print('Year\tHigh\tLow')
print('----\t----\t---')
for index in range(len(year_list)):
print(year_list[index],'\t',format(highest_per_year[index],',.3f'),'\t',format(lowest_per_year[index],',.3f'))
def list_of_prices_lowest_to_highest(dates,prices):
min_to_max_prices = []
min_to_max_dates = []
price_list_ = []
date_list = dates[:]
outfile = open('LowToHigh.txt','w')
for index in range(len(prices)):
price_list_.append(float(prices[index]))
for count in range(len(price_list_)):
min_to_max_prices.append(min(price_list_))
min_to_max_dates.append(dates[price_list_.index(min(price_list_))])
del date_list[price_list_.index(min(price_list_))]
del price_list_[price_list_.index(min(price_list_))]
print('List of Prices, Lowest to Highest')
print('---------------------------------')
print()
print('Date\t\tPrice')
print('----\t-----')
for index in range(len(min_to_max_prices)):
print(min_to_max_dates[index],'\t',min_to_max_prices[index])
outfile.write(str(min_to_max_dates[index]) + ':' + str(min_to_max_prices[index]) + '\n')
outfile.close()
def list_of_prices_highest_to_lowest(dates,prices):
max_to_min_prices = []
max_to_min_dates = []
price_list_ = []
date_list = dates[:]
outfile = open('HighToLow.txt', 'w')
for index in range(len(prices)):
price_list_.append(float(prices[index]))
for count in range(len(price_list_)):
max_to_min_prices.append(max(price_list_))
max_to_min_dates.append(date_list[price_list_.index(max(price_list_))])
del date_list[price_list_.index(max(price_list_))]
del price_list_[price_list_.index(max(price_list_))]
print('List of Prices, Highest to Lowest')
print('---------------------------------')
print()
print('Date\t\tPrice')
print('----\t\t-----')
for index in range(len(max_to_min_prices)):
print(max_to_min_dates[index],'\t',max_to_min_prices[index])
outfile.write(str(max_to_min_dates[index]) + ':' + str(max_to_min_prices[index]) + '\n')
def main():
infile = open('GasPrices.txt', 'r')
infile_list = infile.readlines()
date_list = []
price_lists = []
for line in infile_list:
date_list.append(line[0:10])
price_lists.append(line[11:].rstrip('\n'))
infile.close()
average_price_per_year(date_list,price_lists)
average_price_per_month(date_list,price_lists)
highest_lowest_price_per_year(date_list,price_lists)
list_of_prices_lowest_to_highest(date_list,price_lists)
list_of_prices_highest_to_lowest(date_list,price_lists)
main()
|
# The maximum size of a WebSocket message that can be sent or received
# by the Determined agent and trial-runner. The master uses a different limit,
# because it uses the uwsgi WebSocket implementation; see
# `websocket-max-size` in `uwsgi.ini`.
MAX_WEBSOCKET_MSG_SIZE = 128 * 1024 * 1024
# The maximum HTTP request size that will be accepted by the master. This
# is intended as a safeguard to quickly drop overly large HTTP requests.
MAX_HTTP_REQUEST_SIZE = 128 * 1024 * 1024
# The maximum size of a model (the sum of the model definition plus any
# additional package dependencies). Models are created via HTTP and sent
# to agents via WebSockets; we also have to account for the overhead of
# base64 encoding. Models are also stored in Postgres but the max
# Postgres field size is 1GB, so we ignore that here.
MAX_ENCODED_SIZE = (min(MAX_WEBSOCKET_MSG_SIZE, MAX_HTTP_REQUEST_SIZE) // 8) * 6
# We subtract one megabyte to account for any message envelope size we may have.
MAX_CONTEXT_SIZE = MAX_ENCODED_SIZE - (1 * 1024 * 1024)
# The username and password for the default user.
DEFAULT_DETERMINED_USER = "determined"
DEFAULT_DETERMINED_PASSWORD = ""
DEFAULT_CHECKPOINT_PATH = "checkpoints"
ACTIVE = "ACTIVE"
CANCELED = "CANCELED"
COMPLETED = "COMPLETED"
DELETED = "DELETED"
ERROR = "ERROR"
TERMINAL_STATES = {COMPLETED, CANCELED, ERROR}
SHARED_FS_CONTAINER_PATH = "/determined_shared_fs"
# By default, we ignore:
# - all byte-compiled Python files to ignore a potential stale compilation
# - terraform files generated by `det deploy gcp`, e.g. when user creates
# a cluster from the (tutorial) model def directory.
# - .git and IDE-related content
# Users may also define custom .detignore files to ignore arbitrary paths.
DEFAULT_DETIGNORE = [
"__pycache__/",
"*.py[co]",
"*$py.class",
"terraform",
"terraform_data",
"terraform.tfstate*",
"terraform.tfvars*",
".terraform*",
".git/",
".vscode/",
".idea/",
".mypy_cache/",
]
|
"""
@author Wildo Monges
Grid was provided as an initial skeleton of the project.
Note:
This was a project that I did for the course of Artificial Intelligence in Edx.org
To run it, just execute GameManager.py
"""
class BaseAI:
def get_move(self, grid):
pass
|
"""
defined:
_exec(cmd, input="", pipe_from_memory=False) : executes a command and returns output
_absrelerr(actual, expected, eps=1e-6): check if floating point absrel error is below epsilon
tmp_path : temporary file the problem definition may use (e.g. input file for other program)
verbose : if verbose mode activated (could print out more information)
imported:
sys, random, math
"""
SOLN_PATH = "~/C"
cases = []
solns = {}
def set_up_cases(num_cases):
""" Initialize the checker/generator """
for i in range(num_cases):
n = random.randint(1, 100000)
m = random.randint(1, 100000)
case_str = str(n) + " " + str(m) + "\n"
for j in range(m):
xi = random.randint(-1000, 1000)
di = random.randint(-1000, 1000)
case_str += str(xi) + " " + str(di) + "\n"
cases.append(case_str)
solns[case_str] = float(_exec(SOLN_PATH, case_str, True))
def retrieve_case(case_id):
"""
Retrieve a test case for the current problem. Must return a string with the properly formatted input data.
case_id is an integer [0, \infty)
"""
return cases[case_id]
def check_output_correct(input, output):
""" checks if the output is correct, given the input. Returns True if correct, False else. """
expected = solns[input]
got = float(output)
return _absrelerr(got, expected, 1e-6)
|
"""
Define the ChangeEvent class
"""
class ChangeEvent:
""" A class to represents a change in the website """
def __init__(self, did_change=False, whitelisted_words=[], blacklisted_words=[]):
"""Hold information about the change in a site
Args:
did_change (bool, optional): Did the site changed from last time. Defaults to False.
whitelisted_words (list, optional): Whitelisted words in the HTML. Defaults to [].
blacklisted_words (list, optional): Blacklisted words in the HTML. Defaults to [].
"""
self.did_change = did_change
self.new_whitelisted = whitelisted_words
self.new_blacklisted = blacklisted_words
|
# -*- coding: utf-8 -*-
"""
The models in directory default have been added as a pure convenience and for demonstration
purpose. Whenever there is a need to use a modified version, copy one of these models into
the projects model directory and adopt it to your needs. Otherwise just import the model
into your own models.py file without using it. The latter is important to materialize the
model.
Each model is declared in its own file. This is to prevent model validation errors on related
fields if a file containing this definition is imported without using the model.
""" |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class LogoData(object):
def __init__(self, name=None, x=None, y=None, w=None, h=None):
"""
:param name: (Optional) 识别出的logo名称
:param x: (Optional) 以图片左上角为坐标原点,logo区域左上角到y轴距离
:param y: (Optional) 以图片左上角为坐标原点,logo区域左上角到x轴距离
:param w: (Optional) logo区域宽度
:param h: (Optional) logo区域高度
"""
self.name = name
self.x = x
self.y = y
self.w = w
self.h = h
|
#
# @lc app=leetcode id=7 lang=python
#
# [7] Reverse Integer
#
# https://leetcode.com/problems/reverse-integer/description/
#
# algorithms
# Easy (25.07%)
# Total Accepted: 593.7K
# Total Submissions: 2.4M
# Testcase Example: '123'
#
# Given a 32-bit signed integer, reverse digits of an integer.
#
# Example 1:
#
#
# Input: 123
# Output: 321
#
#
# Example 2:
#
#
# Input: -123
# Output: -321
#
#
# Example 3:
#
#
# Input: 120
# Output: 21
#
#
# Note:
# Assume we are dealing with an environment which could only store integers
# within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of
# this problem, assume that your function returns 0 when the reversed integer
# overflows.
#
#
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
flag = False
if x < 0:
flag = True
b = list(str(abs(x)))
b.reverse()
c = int(''.join(b))
if c > 2**31-1 or c < -2**31:
return 0
return -c if flag else c
|
"""
This function is intended to wrap the rewards returned by the CityLearn RL environment, and is meant to
be modified by the participants of The CityLearn Challenge.
CityLearn returns the energy consumption of each building as a reward.
This reward_function takes all the electrical demands of all the buildings and turns them into one or multiple rewards for the agent(s)
The current code computes a virtual (made-up) electricity price proportional to the total demand for electricity in the neighborhood, and multiplies every
reward by that price. Then it returns the new rewards, which should be used by the agent. Participants of the CityLearn Challenge are encouraged to completely modify this function
in order to minimize the 5 proposed metrics.
"""
# Reward function for the multi-agent (decentralized) agents
def reward_function_ma(electricity_demand):
total_energy_demand = 0
for e in electricity_demand:
total_energy_demand += -e
price = max(total_energy_demand*0.01, 0)
for i in range(len(electricity_demand)):
electricity_demand[i] = min(price*electricity_demand[i], 0)
return electricity_demand
# Reward function for the single-agent (centralized) agent
def reward_function_sa(electricity_demand):
total_energy_demand = 0
for e in electricity_demand:
total_energy_demand += -e
price = max(total_energy_demand*0.005, 0)
for i in range(len(electricity_demand)):
electricity_demand[i] = min(price*electricity_demand[i], 0)
return sum(electricity_demand)
|
def avaliarSituacao(media):
if media >= 6:
print('aprovado')
else:
print('reprovado')
def calcularMedia(p1, p2):
media = (p1 + p2) / 2
avaliarSituacao(media)
def main():
p1 = float(input('Digite a primeira nota: '))
p2 = float(input('Digite a segunda nota: '))
calcularMedia(p1, p2)
main()
|
#######################
# Dennis MUD #
# list_users.py #
# Copyright 2018-2020 #
# Michael D. Reiley #
#######################
# **********
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# **********
NAME = "list users"
CATEGORIES = ["users"]
ALIASES = ["who"]
USAGE = "list users"
DESCRIPTION = """List all online users in the world.
If you are a wizard, you will see a list of all registered users, including offline users."""
def COMMAND(console, args):
# Perform initial checks.
if not COMMON.check(NAME, console, args, argc=0):
return False
# Sort all users in the database by username.
allusers = sorted(console.database.users.all(), key=lambda k: k["name"])
# Iterate through the users, checking whether each one is online or offline,
# and keeping track of how many were online vs offline.
online_count = 0
offline_count = 0
if len(allusers):
for thisuser in allusers:
# Everyone can see which users are online. List them out and keep count.
if console.database.online(thisuser["name"]):
console.msg("{0} ({1})".format(thisuser["nick"], thisuser["name"]))
online_count += 1
# If we are a wizard, iterate through again and list out the offline users this time, and keep count.
if console.user["wizard"]:
for thisuser in allusers:
if not console.database.online(thisuser["name"]):
console.msg("{0} ({1}) [offline]".format(thisuser["nick"], thisuser["name"]))
offline_count += 1
# Format the count of online and offline users for wizards.
console.msg("{0}: Total users online: {1}; offline: {2}".format(NAME, online_count, offline_count))
else:
# Format the count of just online users for regular players.
console.msg("{0}: Total users online: {1}".format(NAME, online_count))
# This shouldn't ever happen.
else:
console.log.error("No users returned from list users command.")
console.msg("{0}: ERROR: No users returned from list users command.".format(NAME))
# Finished.
return True
|
"""
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
click to show clarification.
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
"""
__author__ = 'Danyang'
class Solution:
def reverseWords(self, s):
"""
Notice: ask how to deal with punctuations
:param s: a string
:return: a string
"""
words_lst = s.split() # not s.split(" ")
words_lst = reversed(words_lst)
return ' '.join(words_lst) |
#!/usr/bin/env python
# coding=utf-8
"""
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为
数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转
数组的最小元素。例如,数组[3,4,5,1,2]为[1,2,3,4,5]的一个旋转,
该数组的最小值为1.
"""
class Solution(object):
def min(self, data):
if not data:
return
length = len(data)
index_mid = index1 = 0
index2 = length - 1
while data[index1] >= data[index2]:
if index2 - index1 == 1:
index_mid = index2
break
index_mid = (index1 + index2) / 2
# 如果三者相同,没法判断中间的数字是位于前面的子数组还是后面的子数组
if data[index1] == data[index2] == data[index_mid]:
return self.min_in_data(data, index1, index2)
if data[index_mid] >= data[index1]:
index1 = index_mid
elif data[index_mid] <= data[index2]:
index2 = index_mid
return data[index_mid]
def min_in_data(self, data, index1, index2):
result = data[index1]
for i in range(index1+1, index2+1):
if result > data[i]:
result = data[i]
return result
if __name__ == '__main__':
solution = Solution()
# data = [3, 4, 5, 1, 2]
# min_number = solution.min(data)
data = [1, 0, 1, 1, 1]
min_number = solution.min(data)
print(min_number)
|
def extractEuricetteWordpressCom(item):
'''
Parser for 'euricette.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Greatest Alchemist', 'Someday Will I Be The Greatest Alchemist?', 'translated'),
('The Elf is a Freeloader', 'The Elf is a Freeloader', 'translated'),
('Stepmother', 'I Obtained a Stepmother. I Obtained a Little Brother. It Appears That Little Brother Is Not Father\'s Child, but a Scum King\'s Child, However, Don\'t Mind It Please ( ´_ゝ`)', 'translated'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return []
n = len(nums)
res = []
nums.sort()
# 思路1
def helper1(idx, n, temp_list):
if temp_list not in res:
res.append(temp_list)
for i in range(idx, n):
helper1(i + 1, n, temp_list + [nums[i]])
# 思路2
def helper2(idx, n, temp_list):
res.append(temp_list)
for i in range(idx, n):
if i > idx and nums[i] == nums[i - 1]:
continue
helper2(i + 1, n, temp_list + [nums[i]])
helper2(0, n, [])
return res
|
# i = 4, tallest library building
''' Nearly complete
building_coordinations = [[(-0.126585027793863,16.8195412372661),
(-1.26360571382314,26.9366491540346),
(-15.8471949722061,25.2976587627339),
(-14.7101742861769,15.1805508459654)],
[(-23.0767794626376,16.8481382394501),
(-15.1990122585185,17.6638842108194),
(-16.2936205373624,28.2346617605499),
(-24.1713877414815,27.4189157891806)],
[(-24.6491019813129,-2.8185334334924),
(-14.101147340091,-2.84946701921701),
(-14.0468980186871,15.6488534334924),
(-24.594852659909,15.679787019217)],
[(-21.5000842110591,-9.44961399824389),
(-14.0429792391866,-9.28372083691639),
(-14.1765157889409,-3.28108600175611),
(-21.6336207608134,-3.44697916308361)],
[(3.94535013848411,-3.36623865637194),
(14.493304779706,-3.39717224209654),
(14.5540698615159,17.3229386563719),
(4.00611522029401,17.3538722420965)],
[(8.04858173555005,-30.4958667788278),
(12.4781226874434,-30.5088571252425),
(12.53001826445,-12.8131332211722),
(8.10047731255663,-12.8001428747575)],
[(16.1178588413269,-32.2262223173032),
(20.5473997932202,-32.2392126637179),
(20.5917411586731,-17.1193776826968),
(16.1622002067798,-17.1063873362821)],
[(20.5041475657755,-32.1942704687495),
(24.9336885176689,-32.2072608151642),
(24.9464524342245,-27.8549295312505),
(20.5169114823311,-27.8419391848358)],
[(19.5743191710178,-16.0103447371203),
(25.002585828147,-16.0262640084564),
(25.0170808289822,-11.0836552628797),
(19.588814171853,-11.0677359915436)]]
'''
# The last one is the tallest building i = 6
building_coordinations = [[(-0.126585027793863,16.8195412372661),
(-1.26360571382314,26.9366491540346),
(-15.8471949722061,25.2976587627339),
(-14.7101742861769,15.1805508459654)],
[(-23.0767794626376,16.8481382394501),
(-15.1990122585185,17.6638842108194),
(-16.2936205373624,28.2346617605499),
(-24.1713877414815,27.4189157891806)],
[(-24.6491019813129,-2.8185334334924),
(-14.101147340091,-2.84946701921701),
(-14.0468980186871,15.6488534334924),
(-24.594852659909,15.679787019217)],
[(-21.5000842110591,-9.44961399824389),
(-14.0429792391866,-9.28372083691639),
(-14.1765157889409,-3.28108600175611),
(-21.6336207608134,-3.44697916308361)],
[(3.94535013848411,-3.36623865637194),
(14.493304779706,-3.39717224209654),
(14.5540698615159,17.3229386563719),
(4.00611522029401,17.3538722420965)],
[(2.57209348808029,-3.26004248341449),
(3.79342823604293,-3.26362424541571),
(3.81202651191971,3.07814848341449),
(2.59069176395707,3.08173024541571)],
[(-3.2169746262757,-5.0930349504193),
(2.44827101178602,-5.1096492010069),
(2.4795386262757,5.5522049504193),
(-3.18570701178602,5.5688192010069)]]
''' # Complete
lawn_coordinations = [[(-19.0,-14.0),
(2.0,-14.0),
(-4.5,-24.0),
(-11.0,-24.0)],
[(-19.5,-20.0),
(-14.5,-25.5),
(-14.5,-30.5),
(-19.5,-37.0)],
[(-1.0,-24.5),
(4.5,-18.5),
(4.5,-36.5),
(-1.0,-30.5)],
[(-11.0,-32.5),
(-4.5,-32.5),
(2.0,-42.0),
(-19.0,-42.0)],
[(-8.5,1.0),
(-3.0,1.0),
(-3.0,-4.5),
(-8.5,-4.5)],
[(14.5,11.0),
(27.0,8.0),
(15.5,-4.5)],
[(28.0,2.0),
(27.5,-11.0),
(17.5,-10.0)]]
'''
lawn_coordinations = [[(-10.5,1.0),
(-5.0,1.0),
(-5.0,-4.5),
(-10.5,-4.5)],
[(14.5,11.0),
(27.0,8.0),
(15.5,-4.5)],
[(28.0,2.0),
(27.5,-11.0),
(17.5,-10.0)]]
forest_coordinations = [[(1.0,21.5),
(18.0,36.0),
(4.0,40.0)],
[(7.0,17.5),
(27.5,17.5),
(24.5,30.5)]]
food_coordinations = [[-14.5,39.0],[-7.0,10.0],[15.0,30.0]]
red_chaser_init_pos = [[-8.0,0.0],[-10.0,30.0],[15.0,29.0]]
green_escaper_init_pos = [[-5.0,-5.0],[-2.0,-9.5],[-10.0,34.0],[20.0,4.5],[17.5,17.0],[-15.0,28.5],[15.5,35.0],[18.0,26.0]]
init_plaza = [-10.0,-5.0]
init_forest_1 = [4.0,37.0]
init_forest_2 = [20.0,24.0]
escaper_starter_range = [[[-14.0,25.0],[-10.0,-7.0]],
[[-13.0,-5.0],[-7.0,14.0]],
[[-5.0,3.0],[7.0,29.0]],
[[4.0,25.0],[19.0,29.0]],
[[15.0,25.0],[-7.0,18.0]],
[[-25.0,25.0],[30.0,40.0]]]
|
# Created by MechAviv
# ID :: [4000022]
# Maple Road : Adventurer Training Center 1
sm.showFieldEffect("maplemap/enter/1010100", 0) |
# simplify_fraction.py
def validate_input_simplify(fraction):
if type(fraction) is not tuple:
raise Exception('Argument can only be of type "tuple".')
if len(fraction) != 2:
raise Exception('Tuple can only contain 2 elements.')
if type(fraction[0]) != int or type(fraction[1]) != int:
raise Exception('Tuple can only contain integers.')
if fraction[1] == 0:
raise Exception('Cannot devide by zero.')
def gcd(nominator, denominator):
if nominator == denominator:
return nominator
elif nominator > denominator:
return gcd(nominator - denominator, denominator)
else:
return gcd(nominator, denominator - nominator)
def simplify_fraction(fraction):
validate_input_simplify(fraction)
nominator = fraction[0]
denominator = fraction[1]
if nominator == 0:
return (nominator, 1)
res = gcd(nominator, denominator)
while res != 1:
nominator //= res
denominator //= res
res = gcd(nominator, denominator)
return (nominator, denominator)
def main():
print(simplify_fraction((3,9)))
# Expected output: (1,3)
print(simplify_fraction((1,7)))
# Expected output: (1,7)
print(simplify_fraction((4,10)))
# Expected output: (2,5)
print(simplify_fraction((462,63)))
# Expected output: (22,3)
if __name__ == '__main__':
main() |
items3 = ["Mic", "Phone", 323.12, 3123.123, "Justin", "Bag", "Cliff Bars", 134]
def my_sum_and_count(my_num_list):
total = 0
count = 0
for i in my_num_list:
if isinstance(i, float) or isinstance(i, int):
total += i
count += 1
return total, count
def my_avg(my_num_list):
the_sum, num_of_items = my_sum_and_count(my_num_list)
return the_sum / (num_of_items * 1.0)
my_avg(items3)
|
# coding: utf-8
PI = [58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7]
CP_1 = [57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4]
CP_2 = [14, 17, 11, 24, 1, 5, 3, 28,
15, 6, 21, 10, 23, 19, 12, 4,
26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40,
51, 45, 33, 48, 44, 49, 39, 56,
34, 53, 46, 42, 50, 36, 29, 32]
E = [32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1]
S_BOX = [
[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
],
[[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
[3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
[0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
],
[[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
[13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
[13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
[1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
],
[[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
[13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
[10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
[3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
],
[[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
[14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
[4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
[11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
],
[[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
[10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
[9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
[4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
],
[[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
[13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
[1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
[6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
],
[[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
[1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
[7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
[2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
]
]
P = [16, 7, 20, 21, 29, 12, 28, 17,
1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9,
19, 13, 30, 6, 22, 11, 4, 25]
PI_1 = [40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25]
SHIFT = [1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1]
def string_to_bit_array(text):
array = list()
for char in text:
binval = binvalue(char, 8)
array.extend([int(x) for x in list(binval)])
return array
def bit_array_to_string(array):
res = ''.join([chr(int(y,2)) for y in [''.join([str(x) for x in _bytes]) for _bytes in nsplit(array,8)]])
return res
def binvalue(val, bitsize):
binval = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:]
if len(binval) > bitsize:
raise "binary value larger than the expected size"
while len(binval) < bitsize:
binval = "0"+binval
return binval
def nsplit(s, n):
return [s[k:k+n] for k in range(0, len(s), n)]
ENCRYPT=1
DECRYPT=0
class des():
def __init__(self):
self.password = None
self.text = None
self.keys = list()
def run(self, key, text, action=ENCRYPT, padding=False):
if len(key) < 8:
raise "Key Should be 8 bytes long"
elif len(key) > 8:
key = key[:8]
self.password = key
self.text = text
if padding and action==ENCRYPT:
self.addPadding()
elif len(self.text) % 8 != 0:
raise "Data size should be multiple of 8"
self.generatekeys()
text_blocks = nsplit(self.text, 8)
result = list()
for block in text_blocks:
block = string_to_bit_array(block)
block = self.permut(block,PI)
g, d = nsplit(block, 32)
tmp = None
for i in range(16):
d_e = self.expand(d, E)
if action == ENCRYPT:
tmp = self.xor(self.keys[i], d_e)
else:
tmp = self.xor(self.keys[15-i], d_e)
tmp = self.substitute(tmp)
tmp = self.permut(tmp, P)
tmp = self.xor(g, tmp)
g = d
d = tmp
result += self.permut(d+g, PI_1)
final_res = bit_array_to_string(result)
if padding and action==DECRYPT:
return self.removePadding(final_res)
else:
return final_res
def substitute(self, d_e):
subblocks = nsplit(d_e, 6)
result = list()
for i in range(len(subblocks)):
block = subblocks[i]
row = int(str(block[0])+str(block[5]),2)
column = int(''.join([str(x) for x in block[1:][:-1]]),2)
val = S_BOX[i][row][column]
bin = binvalue(val, 4)
result += [int(x) for x in bin]
return result
def permut(self, block, table):
return [block[x-1] for x in table]
def expand(self, block, table):
return [block[x-1] for x in table]
def xor(self, t1, t2):
return [x^y for x,y in zip(t1,t2)]
def generatekeys(self):
self.keys = []
key = string_to_bit_array(self.password)
key = self.permut(key, CP_1)
g, d = nsplit(key, 28)
for i in range(16):
g, d = self.shift(g, d, SHIFT[i])
tmp = g + d
self.keys.append(self.permut(tmp, CP_2))
def shift(self, g, d, n):
return g[n:] + g[:n], d[n:] + d[:n]
def addPadding(self):
pad_len = 8 - (len(self.text) % 8)
self.text += pad_len * chr(pad_len)
def removePadding(self, data):
pad_len = ord(data[-1])
return data[:-pad_len]
def encrypt(self, key, text, padding=False):
return self.run(key, text, ENCRYPT, padding)
def decrypt(self, key, text, padding=False):
return self.run(key, text, DECRYPT, padding)
if __name__ == '__main__':
key = "secret_k"
text= "Hello wo"
d = des()
r = d.encrypt(key,text)
r2 = d.decrypt(key,r)
print("Ciphered: r", r)
print("Deciphered: ", r2) |
"""D."""
def fun(a, b, name):
print(a, b , name)
x = (1, 2)
fun(*x, 'fuck')
print(F) |
"""Errors specific to this library"""
class ScreenConnectError(Exception):
""" Base class for ScreenConnect errors """
@property
def message(self):
""" Returns provided message to construct error """
return self.args[0]
|
# -*- coding: utf-8 -*-
"""
pagarmeapisdk
This file was automatically generated by APIMATIC v3.0 (
https://www.apimatic.io ).
"""
class CreateBankAccountRequest(object):
"""Implementation of the 'CreateBankAccountRequest' model.
Request for creating a bank account
Attributes:
holder_name (string): Bank account holder name
holder_type (string): Bank account holder type
holder_document (string): Bank account holder document
bank (string): Bank
branch_number (string): Branch number
branch_check_digit (string): Branch check digit
account_number (string): Account number
account_check_digit (string): Account check digit
mtype (string): Bank account type
metadata (dict): Metadata
pix_key (string): Pix key
"""
# Create a mapping from Model property names to API property names
_names = {
"holder_name": 'holder_name',
"holder_type": 'holder_type',
"holder_document": 'holder_document',
"bank": 'bank',
"branch_number": 'branch_number',
"branch_check_digit": 'branch_check_digit',
"account_number": 'account_number',
"account_check_digit": 'account_check_digit',
"mtype": 'type',
"metadata": 'metadata',
"pix_key": 'pix_key'
}
def __init__(self,
holder_name=None,
holder_type=None,
holder_document=None,
bank=None,
branch_number=None,
branch_check_digit=None,
account_number=None,
account_check_digit=None,
mtype=None,
metadata=None,
pix_key=None):
"""Constructor for the CreateBankAccountRequest class"""
# Initialize members of the class
self.holder_name = holder_name
self.holder_type = holder_type
self.holder_document = holder_document
self.bank = bank
self.branch_number = branch_number
self.branch_check_digit = branch_check_digit
self.account_number = account_number
self.account_check_digit = account_check_digit
self.mtype = mtype
self.metadata = metadata
self.pix_key = pix_key
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object
as obtained from the deserialization of the server's response. The
keys MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
holder_name = dictionary.get('holder_name')
holder_type = dictionary.get('holder_type')
holder_document = dictionary.get('holder_document')
bank = dictionary.get('bank')
branch_number = dictionary.get('branch_number')
branch_check_digit = dictionary.get('branch_check_digit')
account_number = dictionary.get('account_number')
account_check_digit = dictionary.get('account_check_digit')
mtype = dictionary.get('type')
metadata = dictionary.get('metadata')
pix_key = dictionary.get('pix_key')
# Return an object of this model
return cls(holder_name,
holder_type,
holder_document,
bank,
branch_number,
branch_check_digit,
account_number,
account_check_digit,
mtype,
metadata,
pix_key)
|
# Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista composta.
# No final, mostre um boletim contendo a média de cada um e permita que
# o usuário possa mostrar as notas de cada aluno individualemte.
ficha = list()
while True:
nome = str(input('Nome: '))
nota1 = float(input('Nota 1: '))
nota2 = float(input('Nota 2: '))
media = (nota1 + nota2)/2
ficha.append([nome, [nota1, nota2], media])
resposta = str(input('Quer continuar? [S/N] ')).strip().upper()
if resposta in 'Nn':
break
print('-=' * 30)
print(f'{"No.":<4}{"NOME":<10}{"MÉDIA:":>8}')
print('-=' * 26)
for i, a in enumerate(ficha):
print(f'{i:<4}{a[0]:<10}{a[2]:>8.1f}')
while True:
print('-' * 35)
opc = int(input('Mostrar notas de qual aluno? (999 interrompe): '))
if opc == 999:
print('FINALIZANDO...')
break
if opc <= len(ficha):
print(f'Notas de {ficha[opc][0]} são {ficha[opc][1]}')
print('<<< VOLTE SEMPRE >>>')
|
"""Python implementations of built-in fprime types
This package provides the modules necessary for the representation of fprime types (Fw/Types) package in a Python
context. These standard types are represented as Python classes representing each individual type.
Example:
U32 is represented by fprime.common.modules.serialize.numerical_types.U32Type
Special autocoded types are represented by configurable classes: ArrayType, SerializableType, and EnumType. These
represent a generic version of these classes whose designed properties are set as dynamic properties on the python
class itself.
Example:
Serializables are represented by fprime.common.modules.serialize.serializable_type.SerializableType
SerializableType(typename="MySerializable") is used to specify the Ai serializable's name
"""
|
# Instructions: The following code example would print the data type of x, what data type would that be?
x = 20.5
print(type(x))
'''
Solution:
float
The inexact numbers are float type. Read more here: https://www.w3schools.com/python/python_datatypes.asp
''' |
seg1 = float(input('Primeiro segmento:'))
seg2 = float(input('Segundo segmento:'))
seg3 = float(input('Terceiro Segmento:'))
print('\033[1;33;04m Verificando os segmentos do seu triangulo...\033[m ')
if seg1 < seg2 + seg3 and seg2 < seg1 + seg3 and seg3 < seg1 +seg2:
print('\033[1;30;45mOs segmentos acima PODEM FORMAR um Triângulo\033[m')
if seg1 == seg2 and seg1 == seg3 and seg2 == seg3:
print('\033[1;30;45m É um triangulo EQUILATERO! \033[m')
elif seg1 != seg2 and seg2 != seg3 and seg3 != seg1:
print('\033[1;30;43m É um triangulo ESCALENO! \033[m')
else:
print('\033[1;36;40m É um triângulo ISÓSCELES!\033[m')
else:
print('Os segmentos não podem Formar um triângulo.')
|
def print_sth(s):
print('print from module2: {}'.format(s))
if __name__ == "__main__":
s = 'test in main'
print_sth(s) |
#
# PySNMP MIB module FC-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FC-MGMT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:05:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, transmission, NotificationType, Integer32, Counter64, Counter32, ModuleIdentity, Unsigned32, iso, MibIdentifier, Gauge32, Bits, IpAddress, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "transmission", "NotificationType", "Integer32", "Counter64", "Counter32", "ModuleIdentity", "Unsigned32", "iso", "MibIdentifier", "Gauge32", "Bits", "IpAddress", "TimeTicks")
DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TruthValue", "TextualConvention")
fcMgmtMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 10, 56))
fcMgmtMIB.setRevisions(('2005-04-26 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: fcMgmtMIB.setRevisionsDescriptions(('Initial version of the Fibre Channel Mgmt MIB module.',))
if mibBuilder.loadTexts: fcMgmtMIB.setLastUpdated('200504260000Z')
if mibBuilder.loadTexts: fcMgmtMIB.setOrganization('IETF IPS (IP-Storage) Working Group')
if mibBuilder.loadTexts: fcMgmtMIB.setContactInfo(' Keith McCloghrie Cisco Systems, Inc. Tel: +1 408 526-5260 E-mail: kzm@cisco.com Postal: 170 West Tasman Drive San Jose, CA USA 95134 ')
if mibBuilder.loadTexts: fcMgmtMIB.setDescription('This module defines management information specific to Fibre Channel-attached devices. Copyright (C) The Internet Society (2005). This version of this MIB module is part of RFC 4044; see the RFC itself for full legal notices.')
fcmgmtObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 56, 1))
fcmgmtNotifications = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 56, 2))
fcmgmtNotifPrefix = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 56, 2, 0))
fcmgmtConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 56, 3))
class FcNameIdOrZero(TextualConvention, OctetString):
description = 'The World Wide Name (WWN) associated with a Fibre Channel (FC) entity. WWNs were initially defined as 64-bits in length. The latest definition (for future use) is 128-bits long. The zero-length string value is used in circumstances in which the WWN is unassigned/unknown.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(0, 0), ValueSizeConstraint(8, 8), ValueSizeConstraint(16, 16), )
class FcAddressIdOrZero(TextualConvention, OctetString):
description = 'A Fibre Channel Address ID, a 24-bit value unique within the address space of a Fabric. The zero-length string value is used in circumstances in which the WWN is unassigned/unknown.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(0, 0), ValueSizeConstraint(3, 3), )
class FcDomainIdOrZero(TextualConvention, Integer32):
description = 'The Domain Id (of an FC switch), or zero if the no Domain Id has been assigned.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 239)
class FcPortType(TextualConvention, Unsigned32):
reference = 'The IANA-maintained registry for Fibre Channel port types (http://www.iana.org/).'
description = 'The type of a Fibre Channel port, as indicated by the use of the appropriate value assigned by IANA.'
status = 'current'
class FcClasses(TextualConvention, Bits):
reference = 'Classes of service are described in FC-FS Section 13.'
description = 'A set of Fibre Channel classes of service.'
status = 'current'
namedValues = NamedValues(("classF", 0), ("class1", 1), ("class2", 2), ("class3", 3), ("class4", 4), ("class5", 5), ("class6", 6))
class FcBbCredit(TextualConvention, Integer32):
description = 'The buffer-to-buffer credit of an FC port.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 32767)
class FcBbCreditModel(TextualConvention, Integer32):
description = 'The buffer-to-buffer credit model of an Fx_Port.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("regular", 1), ("alternate", 2))
class FcDataFieldSize(TextualConvention, Integer32):
description = 'The Receive Data Field Size associated with an FC port.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(128, 2112)
class FcUnitFunctions(TextualConvention, Bits):
description = "A set of functions that a Fibre Channel Interconnect Element or Platform might perform. A value with no bits set indicates the function(s) are unknown. The individual bits have the following meanings: other - none of the following. hub - a device that interconnects L_Ports, but does not operate as an FL_Port. switch - a fabric element conforming to the Fibre Channel switch fabric set of standards (e.g., [FC-SW-3]). bridge - a device that encapsulates Fibre Channel frames within another protocol (e.g., [FC-BB], FC-BB-2). gateway - a device that converts an FC-4 to another protocol (e.g., FCP to iSCSI). host - a computer system that provides end users with services such as computation and storage access. storageSubsys - an integrated collection of storage controllers, storage devices, and necessary software that provides storage services to one or more hosts. storageAccessDev - a device that provides storage management and access for heterogeneous hosts and heterogeneous devices (e.g., medium changer). nas - a device that connects to a network and provides file access services. wdmux - a device that modulates/demodulates each of several data streams (e.g., Fibre Channel protocol data streams) onto/from a different part of the light spectrum in an optical fiber. storageDevice - a disk/tape/etc. device (without the controller and/or software required for it to be a 'storageSubsys')."
status = 'current'
namedValues = NamedValues(("other", 0), ("hub", 1), ("switch", 2), ("bridge", 3), ("gateway", 4), ("host", 5), ("storageSubsys", 6), ("storageAccessDev", 7), ("nas", 8), ("wdmux", 9), ("storageDevice", 10))
fcmInstanceTable = MibTable((1, 3, 6, 1, 2, 1, 10, 56, 1, 1), )
if mibBuilder.loadTexts: fcmInstanceTable.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceTable.setDescription('Information about the local Fibre Channel management instances.')
fcmInstanceEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 56, 1, 1, 1), ).setIndexNames((0, "FC-MGMT-MIB", "fcmInstanceIndex"))
if mibBuilder.loadTexts: fcmInstanceEntry.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceEntry.setDescription('A list of attributes for a particular local Fibre Channel management instance.')
fcmInstanceIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: fcmInstanceIndex.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceIndex.setDescription('An arbitrary integer value that uniquely identifies this instance amongst all local Fibre Channel management instances. It is mandatory to keep this value constant between restarts of the agent, and to make every possible effort to keep it constant across restarts (but note, it is unrealistic to expect it to remain constant across all re-configurations of the local system, e.g., across the replacement of all non- volatile storage).')
fcmInstanceWwn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 1, 1, 2), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmInstanceWwn.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceWwn.setDescription('If the instance has one (or more) WWN(s), then this object contains that (or one of those) WWN(s). If the instance does not have a WWN associated with it, then this object contains the zero-length string.')
fcmInstanceFunctions = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 1, 1, 3), FcUnitFunctions()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmInstanceFunctions.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceFunctions.setDescription('One (or more) Fibre Channel unit functions being performed by this instance.')
fcmInstancePhysicalIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmInstancePhysicalIndex.setReference('entPhysicalIndex is defined in the Entity MIB, RFC 2737.')
if mibBuilder.loadTexts: fcmInstancePhysicalIndex.setStatus('current')
if mibBuilder.loadTexts: fcmInstancePhysicalIndex.setDescription("If this management instance corresponds to a physical component (or to a hierarchy of physical components) identified by the Entity-MIB, then this object's value is the value of the entPhysicalIndex of that component (or of the component at the root of that hierarchy). If there is no correspondence to a physical component (or no component that has an entPhysicalIndex value), then the value of this object is zero.")
fcmInstanceSoftwareIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmInstanceSoftwareIndex.setReference('hrSWInstalledIndex is defined in the Host Resources MIB, RFC 2790')
if mibBuilder.loadTexts: fcmInstanceSoftwareIndex.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceSoftwareIndex.setDescription("If this management instance corresponds to an installed software module identified in the Host Resources MIB, then this object's value is the value of the hrSWInstalledIndex of that module. If there is no correspondence to an installed software module (or no module that has a hrSWInstalledIndex value), then the value of this object is zero.")
fcmInstanceStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("unknown", 1), ("ok", 2), ("warning", 3), ("failed", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmInstanceStatus.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceStatus.setDescription('Overall status of the Fibre Channel entity/entities managed by this management instance. The value should reflect the most serious status of such entities.')
fcmInstanceTextName = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 1, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 79))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fcmInstanceTextName.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceTextName.setDescription('A textual name for this management instance and the Fibre Channel entity/entities that it is managing.')
fcmInstanceDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 1, 1, 8), SnmpAdminString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fcmInstanceDescr.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceDescr.setDescription('A textual description of this management instance and the Fibre Channel entity/entities that it is managing.')
fcmInstanceFabricId = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 1, 1, 9), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmInstanceFabricId.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceFabricId.setDescription('The globally unique Fabric Identifier that identifies the fabric to which the Fibre Channel entity/entities managed by this management instance are connected, or, of which they are a part. This is typically the Node WWN of the principal switch of a Fibre Channel fabric. The zero-length string indicates that the fabric identifier is unknown (or not applicable). In the event that the Fibre Channel entity/entities managed by this management instance is/are connected to multiple fabrics, then this object records the first (known) one.')
fcmSwitchTable = MibTable((1, 3, 6, 1, 2, 1, 10, 56, 1, 2), )
if mibBuilder.loadTexts: fcmSwitchTable.setStatus('current')
if mibBuilder.loadTexts: fcmSwitchTable.setDescription('A table of information about Fibre Channel switches that are managed by Fibre Channel management instances. Each Fibre Channel management instance can manage one or more Fibre Channel switches.')
fcmSwitchEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 56, 1, 2, 1), ).setIndexNames((0, "FC-MGMT-MIB", "fcmInstanceIndex"), (0, "FC-MGMT-MIB", "fcmSwitchIndex"))
if mibBuilder.loadTexts: fcmSwitchEntry.setStatus('current')
if mibBuilder.loadTexts: fcmSwitchEntry.setDescription('Information about a particular Fibre Channel switch that is managed by the management instance given by fcmInstanceIndex.')
fcmSwitchIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: fcmSwitchIndex.setStatus('current')
if mibBuilder.loadTexts: fcmSwitchIndex.setDescription('An arbitrary integer that uniquely identifies a Fibre Channel switch amongst those managed by one Fibre Channel management instance. It is mandatory to keep this value constant between restarts of the agent, and to make every possible effort to keep it constant across restarts.')
fcmSwitchDomainId = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 2, 1, 2), FcDomainIdOrZero()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fcmSwitchDomainId.setStatus('current')
if mibBuilder.loadTexts: fcmSwitchDomainId.setDescription('The Domain Id of this switch. A value of zero indicates that a switch has not (yet) been assigned a Domain Id.')
fcmSwitchPrincipal = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 2, 1, 3), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmSwitchPrincipal.setStatus('current')
if mibBuilder.loadTexts: fcmSwitchPrincipal.setDescription('An indication of whether this switch is the principal switch within its fabric.')
fcmSwitchWWN = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 2, 1, 4), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmSwitchWWN.setStatus('current')
if mibBuilder.loadTexts: fcmSwitchWWN.setDescription('The World Wide Name of this switch.')
fcmPortTable = MibTable((1, 3, 6, 1, 2, 1, 10, 56, 1, 3), )
if mibBuilder.loadTexts: fcmPortTable.setReference('RFC 2863, The Interfaces Group MIB, June 2000.')
if mibBuilder.loadTexts: fcmPortTable.setStatus('current')
if mibBuilder.loadTexts: fcmPortTable.setDescription("Information about Fibre Channel ports. Each Fibre Channel port is represented by one entry in the IF-MIB's ifTable.")
fcmPortEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: fcmPortEntry.setStatus('current')
if mibBuilder.loadTexts: fcmPortEntry.setDescription('Each entry contains information about a specific port.')
fcmPortInstanceIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortInstanceIndex.setStatus('current')
if mibBuilder.loadTexts: fcmPortInstanceIndex.setDescription('The value of fcmInstanceIndex by which the Fibre Channel management instance, which manages this port, is identified in the fcmInstanceTable.')
fcmPortWwn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 2), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortWwn.setStatus('current')
if mibBuilder.loadTexts: fcmPortWwn.setDescription('The World Wide Name of the port, or the zero-length string if the port does not have a WWN.')
fcmPortNodeWwn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 3), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortNodeWwn.setStatus('current')
if mibBuilder.loadTexts: fcmPortNodeWwn.setDescription('The World Wide Name of the Node that contains this port, or the zero-length string if the port does not have a node WWN.')
fcmPortAdminType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 4), FcPortType()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fcmPortAdminType.setStatus('current')
if mibBuilder.loadTexts: fcmPortAdminType.setDescription('The administratively desired type of this port.')
fcmPortOperType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 5), FcPortType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortOperType.setStatus('current')
if mibBuilder.loadTexts: fcmPortOperType.setDescription('The current operational type of this port.')
fcmPortFcCapClass = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 6), FcClasses()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortFcCapClass.setStatus('current')
if mibBuilder.loadTexts: fcmPortFcCapClass.setDescription('The classes of service capability of this port.')
fcmPortFcOperClass = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 7), FcClasses()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortFcOperClass.setStatus('current')
if mibBuilder.loadTexts: fcmPortFcOperClass.setDescription('The classes of service that are currently operational on this port. For an FL_Port, this is the union of the classes being supported across all attached NL_Ports.')
fcmPortTransmitterType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("unknown", 1), ("other", 2), ("shortwave850nm", 3), ("longwave1550nm", 4), ("longwave1310nm", 5), ("electrical", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortTransmitterType.setReference('FC-GS-3, section 6.1.2.2.3')
if mibBuilder.loadTexts: fcmPortTransmitterType.setStatus('current')
if mibBuilder.loadTexts: fcmPortTransmitterType.setDescription('The technology of the port transceiver.')
fcmPortConnectorType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("unknown", 1), ("other", 2), ("gbic", 3), ("embedded", 4), ("glm", 5), ("gbicSerialId", 6), ("gbicNoSerialId", 7), ("sfpSerialId", 8), ("sfpNoSerialId", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortConnectorType.setReference('FC-GS-3, section 6.1.2.2.4')
if mibBuilder.loadTexts: fcmPortConnectorType.setStatus('current')
if mibBuilder.loadTexts: fcmPortConnectorType.setDescription("The module type of the port connector. This object refers to the hardware implementation of the port. It will be 'embedded' if the hardware equivalent to Gigabit interface card (GBIC) is part of the line card and is unremovable. It will be 'glm' if it's a gigabit link module (GLM). It will be 'gbicSerialId' if the GBIC serial id can be read, else it will be 'gbicNoSerialId'. It will be 'sfpSerialId' if the small form factor (SFP) pluggable GBICs serial id can be read, else it will be 'sfpNoSerialId'.")
fcmPortSerialNumber = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 10), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortSerialNumber.setReference('FC-GS-3, section 6.1.2.2.4')
if mibBuilder.loadTexts: fcmPortSerialNumber.setStatus('current')
if mibBuilder.loadTexts: fcmPortSerialNumber.setDescription("The serial number associated with the port (e.g., for a GBIC). If not applicable, the object's value is a zero- length string.")
fcmPortPhysicalNumber = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 11), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortPhysicalNumber.setReference('FC-GS-3, section 6.1.2.2.5')
if mibBuilder.loadTexts: fcmPortPhysicalNumber.setStatus('current')
if mibBuilder.loadTexts: fcmPortPhysicalNumber.setDescription("This is the port's 'Physical Port Number' as defined by GS-3.")
fcmPortAdminSpeed = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("auto", 1), ("eighthGbs", 2), ("quarterGbs", 3), ("halfGbs", 4), ("oneGbs", 5), ("twoGbs", 6), ("fourGbs", 7), ("tenGbs", 8)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fcmPortAdminSpeed.setStatus('current')
if mibBuilder.loadTexts: fcmPortAdminSpeed.setDescription("The speed of the interface: 'auto' - auto-negotiation 'tenGbs' - 10Gbs 'fourGbs' - 4Gbs 'twoGbs' - 2Gbs 'oneGbs' - 1Gbs 'halfGbs' - 500Mbs 'quarterGbs' - 250Mbs 'eighthGbs' - 125Mbs")
fcmPortCapProtocols = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 13), Bits().clone(namedValues=NamedValues(("unknown", 0), ("loop", 1), ("fabric", 2), ("scsi", 3), ("tcpIp", 4), ("vi", 5), ("ficon", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortCapProtocols.setStatus('current')
if mibBuilder.loadTexts: fcmPortCapProtocols.setDescription('A bit mask specifying the higher level protocols that are capable of running over this port. Note that for generic Fx_Ports, E_Ports, and B_Ports, this object will indicate all protocols.')
fcmPortOperProtocols = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 3, 1, 14), Bits().clone(namedValues=NamedValues(("unknown", 0), ("loop", 1), ("fabric", 2), ("scsi", 3), ("tcpIp", 4), ("vi", 5), ("ficon", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortOperProtocols.setStatus('current')
if mibBuilder.loadTexts: fcmPortOperProtocols.setDescription("A bit mask specifying the higher level protocols that are currently operational on this port. For Fx_Ports, E_Ports, and B_Ports, this object will typically have the value 'unknown'.")
fcmPortStatsTable = MibTable((1, 3, 6, 1, 2, 1, 10, 56, 1, 4), )
if mibBuilder.loadTexts: fcmPortStatsTable.setStatus('current')
if mibBuilder.loadTexts: fcmPortStatsTable.setDescription('A list of statistics for Fibre Channel ports.')
fcmPortStatsEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1), )
if mibBuilder.loadTexts: fcmPortStatsEntry.setReference('The Interfaces Group MIB, RFC 2863, June 2000.')
fcmPortEntry.registerAugmentions(("FC-MGMT-MIB", "fcmPortStatsEntry"))
fcmPortStatsEntry.setIndexNames(*fcmPortEntry.getIndexNames())
if mibBuilder.loadTexts: fcmPortStatsEntry.setStatus('current')
if mibBuilder.loadTexts: fcmPortStatsEntry.setDescription('An entry containing statistics for a Fibre Channel port. If any counter in this table suffers a discontinuity, the value of ifCounterDiscontinuityTime (defined in the IF-MIB) must be updated.')
fcmPortBBCreditZeros = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 1), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortBBCreditZeros.setStatus('current')
if mibBuilder.loadTexts: fcmPortBBCreditZeros.setDescription('The number of transitions in/out of the buffer-to-buffer credit zero state. The other side is not providing any credit.')
fcmPortFullInputBuffers = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 2), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortFullInputBuffers.setStatus('current')
if mibBuilder.loadTexts: fcmPortFullInputBuffers.setDescription('The number of occurrences when all input buffers of a port were full and outbound buffer-to-buffer credit transitioned to zero, i.e., there became no credit to provide to other side.')
fcmPortClass2RxFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 3), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2RxFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2RxFrames.setDescription('The number of Class 2 frames received at this port.')
fcmPortClass2RxOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 4), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2RxOctets.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2RxOctets.setDescription('The number of octets contained in Class 2 frames received at this port.')
fcmPortClass2TxFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 5), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2TxFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2TxFrames.setDescription('The number of Class 2 frames transmitted out of this port.')
fcmPortClass2TxOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 6), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2TxOctets.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2TxOctets.setDescription('The number of octets contained in Class 2 frames transmitted out of this port.')
fcmPortClass2Discards = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 7), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2Discards.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2Discards.setDescription('The number of Class 2 frames that were discarded upon reception at this port.')
fcmPortClass2RxFbsyFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 8), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2RxFbsyFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2RxFbsyFrames.setDescription('The number of times that F_BSY was returned to this port as a result of a Class 2 frame that could not be delivered to the other end of the link. This can occur when either the fabric or the destination port is temporarily busy. Note that this counter will never increment for an F_Port.')
fcmPortClass2RxPbsyFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 9), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2RxPbsyFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2RxPbsyFrames.setDescription('The number of times that P_BSY was returned to this port as a result of a Class 2 frame that could not be delivered to the other end of the link. This can occur when the destination port is temporarily busy.')
fcmPortClass2RxFrjtFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 10), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2RxFrjtFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2RxFrjtFrames.setDescription('The number of times that F_RJT was returned to this port as a result of a Class 2 frame that was rejected by the fabric. Note that this counter will never increment for an F_Port.')
fcmPortClass2RxPrjtFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 11), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2RxPrjtFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2RxPrjtFrames.setDescription('The number of times that P_RJT was returned to this port as a result of a Class 2 frame that was rejected at the destination N_Port.')
fcmPortClass2TxFbsyFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 12), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2TxFbsyFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2TxFbsyFrames.setDescription('The number of times that F_BSY was generated by this port as a result of a Class 2 frame that could not be delivered because either the Fabric or the destination port was temporarily busy. Note that this counter will never increment for an N_Port.')
fcmPortClass2TxPbsyFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 13), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2TxPbsyFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2TxPbsyFrames.setDescription('The number of times that P_BSY was generated by this port as a result of a Class 2 frame that could not be delivered because the destination port was temporarily busy. Note that this counter will never increment for an F_Port.')
fcmPortClass2TxFrjtFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 14), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2TxFrjtFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2TxFrjtFrames.setDescription('The number of times that F_RJT was generated by this port as a result of a Class 2 frame being rejected by the fabric. Note that this counter will never increment for an N_Port.')
fcmPortClass2TxPrjtFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 15), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass2TxPrjtFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass2TxPrjtFrames.setDescription('The number of times that P_RJT was generated by this port as a result of a Class 2 frame being rejected at the destination N_Port. Note that this counter will never increment for an F_Port.')
fcmPortClass3RxFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 16), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass3RxFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass3RxFrames.setDescription('The number of Class 3 frames received at this port.')
fcmPortClass3RxOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 17), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass3RxOctets.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass3RxOctets.setDescription('The number of octets contained in Class 3 frames received at this port.')
fcmPortClass3TxFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 18), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass3TxFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass3TxFrames.setDescription('The number of Class 3 frames transmitted out of this port.')
fcmPortClass3TxOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 19), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass3TxOctets.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass3TxOctets.setDescription('The number of octets contained in Class 3 frames transmitted out of this port.')
fcmPortClass3Discards = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 20), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClass3Discards.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass3Discards.setDescription('The number of Class 3 frames that were discarded upon reception at this port.')
fcmPortClassFRxFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 21), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClassFRxFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClassFRxFrames.setDescription('The number of Class F frames received at this port.')
fcmPortClassFRxOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 22), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClassFRxOctets.setStatus('current')
if mibBuilder.loadTexts: fcmPortClassFRxOctets.setDescription('The number of octets contained in Class F frames received at this port.')
fcmPortClassFTxFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 23), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClassFTxFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortClassFTxFrames.setDescription('The number of Class F frames transmitted out of this port.')
fcmPortClassFTxOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 24), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClassFTxOctets.setStatus('current')
if mibBuilder.loadTexts: fcmPortClassFTxOctets.setDescription('The number of octets contained in Class F frames transmitted out of this port.')
fcmPortClassFDiscards = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 4, 1, 25), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortClassFDiscards.setStatus('current')
if mibBuilder.loadTexts: fcmPortClassFDiscards.setDescription('The number of Class F frames that were discarded upon reception at this port.')
fcmPortLcStatsTable = MibTable((1, 3, 6, 1, 2, 1, 10, 56, 1, 5), )
if mibBuilder.loadTexts: fcmPortLcStatsTable.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcStatsTable.setDescription('A list of Counter32-based statistics for systems that do not support Counter64.')
fcmPortLcStatsEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1), )
if mibBuilder.loadTexts: fcmPortLcStatsEntry.setReference('The Interfaces Group MIB, RFC 2863, June 2000.')
fcmPortEntry.registerAugmentions(("FC-MGMT-MIB", "fcmPortLcStatsEntry"))
fcmPortLcStatsEntry.setIndexNames(*fcmPortEntry.getIndexNames())
if mibBuilder.loadTexts: fcmPortLcStatsEntry.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcStatsEntry.setDescription('An entry containing low-capacity (i.e., based on Counter32) statistics for a Fibre Channel port. If any counter in this table suffers a discontinuity, the value of ifCounterDiscontinuityTime (defined in the IF-MIB) must be updated.')
fcmPortLcBBCreditZeros = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcBBCreditZeros.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcBBCreditZeros.setDescription('The number of transitions in/out of the buffer-to-buffer credit zero state. The other side is not providing any credit.')
fcmPortLcFullInputBuffers = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcFullInputBuffers.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcFullInputBuffers.setDescription('The number of occurrences when all input buffers of a port were full and outbound buffer-to-buffer credit transitioned to zero, i.e., there became no credit to provide to other side.')
fcmPortLcClass2RxFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2RxFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2RxFrames.setDescription('The number of Class 2 frames received at this port.')
fcmPortLcClass2RxOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2RxOctets.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2RxOctets.setDescription('The number of octets contained in Class 2 frames received at this port.')
fcmPortLcClass2TxFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2TxFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2TxFrames.setDescription('The number of Class 2 frames transmitted out of this port.')
fcmPortLcClass2TxOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2TxOctets.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2TxOctets.setDescription('The number of octets contained in Class 2 frames transmitted out of this port.')
fcmPortLcClass2Discards = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2Discards.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2Discards.setDescription('The number of Class 2 frames that were discarded upon reception at this port.')
fcmPortLcClass2RxFbsyFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2RxFbsyFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2RxFbsyFrames.setDescription('The number of times that F_BSY was returned to this port as a result of a Class 2 frame that could not be delivered to the other end of the link. This can occur when either the fabric or the destination port is temporarily busy. Note that this counter will never increment for an F_Port.')
fcmPortLcClass2RxPbsyFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2RxPbsyFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2RxPbsyFrames.setDescription('The number of times that P_BSY was returned to this port as a result of a Class 2 frame that could not be delivered to the other end of the link. This can occur when the destination port is temporarily busy.')
fcmPortLcClass2RxFrjtFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2RxFrjtFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2RxFrjtFrames.setDescription('The number of times that F_RJT was returned to this port as a result of a Class 2 frame that was rejected by the fabric. Note that this counter will never increment for an F_Port.')
fcmPortLcClass2RxPrjtFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2RxPrjtFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2RxPrjtFrames.setDescription('The number of times that P_RJT was returned to this port as a result of a Class 2 frame that was rejected at the destination N_Port.')
fcmPortLcClass2TxFbsyFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2TxFbsyFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2TxFbsyFrames.setDescription('The number of times that F_BSY was generated by this port as a result of a Class 2 frame that could not be delivered because either the Fabric or the destination port was temporarily busy. Note that this counter will never increment for an N_Port.')
fcmPortLcClass2TxPbsyFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2TxPbsyFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2TxPbsyFrames.setDescription('The number of times that P_BSY was generated by this port as a result of a Class 2 frame that could not be delivered because the destination port was temporarily busy. Note that this counter will never increment for an F_Port.')
fcmPortLcClass2TxFrjtFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2TxFrjtFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2TxFrjtFrames.setDescription('The number of times that F_RJT was generated by this port as a result of a Class 2 frame being rejected by the fabric. Note that this counter will never increment for an N_Port.')
fcmPortLcClass2TxPrjtFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass2TxPrjtFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass2TxPrjtFrames.setDescription('The number of times that P_RJT was generated by this port as a result of a Class 2 frame being rejected at the destination N_Port. Note that this counter will never increment for an F_Port.')
fcmPortLcClass3RxFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass3RxFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass3RxFrames.setDescription('The number of Class 3 frames received at this port.')
fcmPortLcClass3RxOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass3RxOctets.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass3RxOctets.setDescription('The number of octets contained in Class 3 frames received at this port.')
fcmPortLcClass3TxFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass3TxFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass3TxFrames.setDescription('The number of Class 3 frames transmitted out of this port.')
fcmPortLcClass3TxOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 19), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass3TxOctets.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass3TxOctets.setDescription('The number of octets contained in Class 3 frames transmitted out of this port.')
fcmPortLcClass3Discards = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 5, 1, 20), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLcClass3Discards.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcClass3Discards.setDescription('The number of Class 3 frames that were discarded upon reception at this port.')
fcmPortErrorsTable = MibTable((1, 3, 6, 1, 2, 1, 10, 56, 1, 6), )
if mibBuilder.loadTexts: fcmPortErrorsTable.setStatus('current')
if mibBuilder.loadTexts: fcmPortErrorsTable.setDescription('Error counters for Fibre Channel ports.')
fcmPortErrorsEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1), )
if mibBuilder.loadTexts: fcmPortErrorsEntry.setReference('The Interfaces Group MIB, RFC 2863, June 2000.')
fcmPortEntry.registerAugmentions(("FC-MGMT-MIB", "fcmPortErrorsEntry"))
fcmPortErrorsEntry.setIndexNames(*fcmPortEntry.getIndexNames())
if mibBuilder.loadTexts: fcmPortErrorsEntry.setStatus('current')
if mibBuilder.loadTexts: fcmPortErrorsEntry.setDescription('Error counters for a Fibre Channel port. If any counter in this table suffers a discontinuity, the value of ifCounterDiscontinuityTime (defined in the IF-MIB) must be updated.')
fcmPortRxLinkResets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortRxLinkResets.setStatus('current')
if mibBuilder.loadTexts: fcmPortRxLinkResets.setDescription('The number of Link Reset (LR) Primitive Sequences received.')
fcmPortTxLinkResets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortTxLinkResets.setStatus('current')
if mibBuilder.loadTexts: fcmPortTxLinkResets.setDescription('The number of Link Reset (LR) Primitive Sequences transmitted.')
fcmPortLinkResets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLinkResets.setStatus('current')
if mibBuilder.loadTexts: fcmPortLinkResets.setDescription('The number of times the reset link protocol was initiated on this port. This includes the number of Loop Initialization Primitive (LIP) events on an arbitrated loop port.')
fcmPortRxOfflineSequences = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortRxOfflineSequences.setStatus('current')
if mibBuilder.loadTexts: fcmPortRxOfflineSequences.setDescription('The number of Offline (OLS) Primitive Sequences received at this port.')
fcmPortTxOfflineSequences = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortTxOfflineSequences.setStatus('current')
if mibBuilder.loadTexts: fcmPortTxOfflineSequences.setDescription('The number of Offline (OLS) Primitive Sequences transmitted by this port.')
fcmPortLinkFailures = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLinkFailures.setReference('FC-PH, rev 4.3, 1 June 1994, section 29.8 [FC-PH].')
if mibBuilder.loadTexts: fcmPortLinkFailures.setStatus('current')
if mibBuilder.loadTexts: fcmPortLinkFailures.setDescription("The number of link failures. This count is part of FC-PH's Link Error Status Block (LESB).")
fcmPortLossofSynchs = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLossofSynchs.setReference('FC-PH, rev 4.3, 1 June 1994, section 29.8.')
if mibBuilder.loadTexts: fcmPortLossofSynchs.setStatus('current')
if mibBuilder.loadTexts: fcmPortLossofSynchs.setDescription("The number of instances of synchronization loss detected at this port. This count is part of FC-PH's Link Error Status Block (LESB).")
fcmPortLossofSignals = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortLossofSignals.setReference('FC-PH, rev 4.3, 1 June 1994, section 29.8.')
if mibBuilder.loadTexts: fcmPortLossofSignals.setStatus('current')
if mibBuilder.loadTexts: fcmPortLossofSignals.setDescription("The number of instances of signal loss detected at this port. This count is part of FC-PH's Link Error Status Block (LESB).")
fcmPortPrimSeqProtocolErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortPrimSeqProtocolErrors.setReference('FC-PH, rev 4.3, 1 June 1994, section 29.8.')
if mibBuilder.loadTexts: fcmPortPrimSeqProtocolErrors.setStatus('current')
if mibBuilder.loadTexts: fcmPortPrimSeqProtocolErrors.setDescription("The number of primitive sequence protocol errors detected at this port. This count is part of FC-PH's Link Error Status Block (LESB).")
fcmPortInvalidTxWords = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortInvalidTxWords.setReference('FC-PH, rev 4.3, 1 June 1994, section 29.8.')
if mibBuilder.loadTexts: fcmPortInvalidTxWords.setStatus('current')
if mibBuilder.loadTexts: fcmPortInvalidTxWords.setDescription("The number of invalid transmission words received at this port. This count is part of FC-PH's Link Error Status Block (LESB).")
fcmPortInvalidCRCs = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortInvalidCRCs.setReference('FC-PH, rev 4.3, 1 June 1994, section 29.8.')
if mibBuilder.loadTexts: fcmPortInvalidCRCs.setStatus('current')
if mibBuilder.loadTexts: fcmPortInvalidCRCs.setDescription("The number of frames received with an invalid CRC. This count is part of FC-PH's Link Error Status Block (LESB).")
fcmPortInvalidOrderedSets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortInvalidOrderedSets.setStatus('current')
if mibBuilder.loadTexts: fcmPortInvalidOrderedSets.setDescription('The number of invalid ordered sets received at this port.')
fcmPortFrameTooLongs = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortFrameTooLongs.setStatus('current')
if mibBuilder.loadTexts: fcmPortFrameTooLongs.setDescription('The number of frames received at this port for which the frame length was greater than what was agreed to in FLOGI/PLOGI. This could be caused by losing the end of frame delimiter.')
fcmPortTruncatedFrames = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortTruncatedFrames.setStatus('current')
if mibBuilder.loadTexts: fcmPortTruncatedFrames.setDescription('The number of frames received at this port for which the frame length was less than the minimum indicated by the frame header - normally 24 bytes, but it could be more if the DFCTL field indicates an optional header should have been present.')
fcmPortAddressErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortAddressErrors.setStatus('current')
if mibBuilder.loadTexts: fcmPortAddressErrors.setDescription('The number of frames received with unknown addressing; for example, an unknown SID or DID.')
fcmPortDelimiterErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortDelimiterErrors.setStatus('current')
if mibBuilder.loadTexts: fcmPortDelimiterErrors.setDescription('The number of invalid frame delimiters received at this port. An example is a frame with a class 2 start and a class 3 at the end.')
fcmPortEncodingDisparityErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortEncodingDisparityErrors.setStatus('current')
if mibBuilder.loadTexts: fcmPortEncodingDisparityErrors.setDescription('The number of encoding disparity errors received at this port.')
fcmPortOtherErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 6, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmPortOtherErrors.setStatus('current')
if mibBuilder.loadTexts: fcmPortOtherErrors.setDescription('The number of errors that were detected on this port but not counted by any other error counter in this row.')
fcmFxPortTable = MibTable((1, 3, 6, 1, 2, 1, 10, 56, 1, 7), )
if mibBuilder.loadTexts: fcmFxPortTable.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortTable.setDescription('Additional information about Fibre Channel ports that is specific to Fx_Ports. This table will contain one entry for each fcmPortTable entry that represents an Fx_Port.')
fcmFxPortEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: fcmFxPortEntry.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortEntry.setDescription('Each entry contains information about a specific Fx_Port.')
fcmFxPortRatov = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 1), Unsigned32()).setUnits('milliseconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortRatov.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortRatov.setDescription('The Resource_Allocation_Timeout Value configured for this Fx_Port. This is used as the timeout value for determining when to reuse an Nx_Port resource such as a Recovery_Qualifier. It represents the Error_Detect_Timeout value (see fcmFxPortEdtov) plus twice the maximum time that a frame may be delayed within the Fabric and still be delivered.')
fcmFxPortEdtov = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 2), Unsigned32()).setUnits('milliseconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortEdtov.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortEdtov.setDescription('The Error_Detect_Timeout value configured for this Fx_Port. This is used as the timeout value for detecting an error condition.')
fcmFxPortRttov = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 3), Unsigned32()).setUnits('milliseconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortRttov.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortRttov.setDescription('The Receiver_Transmitter_Timeout value of this Fx_Port. This is used by the receiver logic to detect a Loss of Synchronization.')
fcmFxPortHoldTime = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 4), Unsigned32()).setUnits('microseconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortHoldTime.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortHoldTime.setDescription('The maximum time that this Fx_Port shall hold a frame before discarding the frame if it is unable to deliver the frame. The value 0 means that this Fx_Port does not support this parameter.')
fcmFxPortCapBbCreditMax = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 5), FcBbCredit()).setUnits('buffers').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortCapBbCreditMax.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortCapBbCreditMax.setDescription('The maximum number of receive buffers that this port is capable of making available for holding frames from attached Nx_Port(s).')
fcmFxPortCapBbCreditMin = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 6), FcBbCredit()).setUnits('buffers').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortCapBbCreditMin.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortCapBbCreditMin.setDescription('The minimum number of receive buffers that this port is capable of making available for holding frames from attached Nx_Port(s).')
fcmFxPortCapDataFieldSizeMax = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 7), FcDataFieldSize()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortCapDataFieldSizeMax.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortCapDataFieldSizeMax.setDescription('The maximum size in bytes of the Data Field in a frame that this Fx_Port is capable of receiving from an attached Nx_Port.')
fcmFxPortCapDataFieldSizeMin = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 8), FcDataFieldSize()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortCapDataFieldSizeMin.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortCapDataFieldSizeMin.setDescription('The minimum size in bytes of the Data Field in a frame that this Fx_Port is capable of receiving from an attached Nx_Port.')
fcmFxPortCapClass2SeqDeliv = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 9), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortCapClass2SeqDeliv.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortCapClass2SeqDeliv.setDescription('An indication of whether this Fx_Port is capable of supporting Class 2 Sequential Delivery.')
fcmFxPortCapClass3SeqDeliv = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 10), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortCapClass3SeqDeliv.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortCapClass3SeqDeliv.setDescription('An indication of whether this Fx_Port is capable of supporting Class 3 Sequential Delivery.')
fcmFxPortCapHoldTimeMax = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 11), Unsigned32()).setUnits('microseconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortCapHoldTimeMax.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortCapHoldTimeMax.setDescription('The maximum holding time that this Fx_Port is capable of supporting.')
fcmFxPortCapHoldTimeMin = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 7, 1, 12), Unsigned32()).setUnits('microseconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFxPortCapHoldTimeMin.setStatus('current')
if mibBuilder.loadTexts: fcmFxPortCapHoldTimeMin.setDescription('The minimum holding time that this Fx_Port is capable of supporting.')
fcmISPortTable = MibTable((1, 3, 6, 1, 2, 1, 10, 56, 1, 8), )
if mibBuilder.loadTexts: fcmISPortTable.setStatus('current')
if mibBuilder.loadTexts: fcmISPortTable.setDescription('Additional information about E_Ports, B_Ports, and any other type of Fibre Channel port to which inter-switch links can be connected. This table will contain one entry for each fcmPortTable entry that represents such a port.')
fcmISPortEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 56, 1, 8, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: fcmISPortEntry.setStatus('current')
if mibBuilder.loadTexts: fcmISPortEntry.setDescription('Each entry contains information about a specific port connected to an inter-switch link.')
fcmISPortClassFCredit = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 8, 1, 1), FcBbCredit()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fcmISPortClassFCredit.setStatus('current')
if mibBuilder.loadTexts: fcmISPortClassFCredit.setDescription('The maximum number of Class F data frames that can be transmitted by the inter-switch port without receipt of ACK or Link_Response frames.')
fcmISPortClassFDataFieldSize = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 8, 1, 2), FcDataFieldSize()).setUnits('bytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmISPortClassFDataFieldSize.setStatus('current')
if mibBuilder.loadTexts: fcmISPortClassFDataFieldSize.setDescription('The Receive Data Field Size that the inter-switch port has agreed to support for Class F frames to/from this port. The size specifies the largest Data Field Size for an FT_1 frame.')
fcmFLoginTable = MibTable((1, 3, 6, 1, 2, 1, 10, 56, 1, 9), )
if mibBuilder.loadTexts: fcmFLoginTable.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginTable.setDescription('A table that contains one entry for each Nx_Port logged- in/attached to a particular Fx_Port in the switch. Each entry contains the services parameters established during the most recent Fabric Login, explicit or implicit. Note that an Fx_Port may have one or more Nx_Ports attached to it.')
fcmFLoginEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "FC-MGMT-MIB", "fcmFLoginNxPortIndex"))
if mibBuilder.loadTexts: fcmFLoginEntry.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginEntry.setDescription('An entry containing service parameters established from a successful Fabric Login.')
fcmFLoginNxPortIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: fcmFLoginNxPortIndex.setReference('The Interfaces Group MIB, RFC 2863, June 2000.')
if mibBuilder.loadTexts: fcmFLoginNxPortIndex.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginNxPortIndex.setDescription('An arbitrary integer that uniquely identifies an Nx_Port amongst all those attached to the Fx_Port indicated by ifIndex. After a value of this object is assigned to a particular Nx_Port, that value can be re-used when and only when it is assigned to the same Nx_Port, or, after a reset of the value of the relevant instance of ifCounterDiscontinuityTime.')
fcmFLoginPortWwn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1, 2), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFLoginPortWwn.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginPortWwn.setDescription('The port name of the attached Nx_Port, or the zero-length string if unknown.')
fcmFLoginNodeWwn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1, 3), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFLoginNodeWwn.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginNodeWwn.setDescription('The node name of the attached Nx_Port, or the zero-length string if unknown.')
fcmFLoginBbCreditModel = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1, 4), FcBbCreditModel()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFLoginBbCreditModel.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginBbCreditModel.setDescription('The buffer-to-buffer credit model in use by the Fx_Port.')
fcmFLoginBbCredit = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1, 5), FcBbCredit()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFLoginBbCredit.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginBbCredit.setDescription('The number of buffers available for holding frames to be transmitted to the attached Nx_Port. These buffers are for buffer-to-buffer flow control in the direction from Fx_Port to Nx_Port.')
fcmFLoginClassesAgreed = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1, 6), FcClasses()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFLoginClassesAgreed.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginClassesAgreed.setDescription('The Classes of Service that the Fx_Port has agreed to support for this Nx_Port.')
fcmFLoginClass2SeqDelivAgreed = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1, 7), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFLoginClass2SeqDelivAgreed.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginClass2SeqDelivAgreed.setDescription('An indication of whether the Fx_Port has agreed to support Class 2 sequential delivery for this Nx_Port. This is only meaningful if Class 2 service has been agreed upon.')
fcmFLoginClass2DataFieldSize = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1, 8), FcDataFieldSize()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFLoginClass2DataFieldSize.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginClass2DataFieldSize.setDescription('The Receive Data Field Size that the Fx_Port has agreed to support for Class 2 frames to/from this Nx_Port. The size specifies the largest Data Field Size for an FT_1 frame. This is only meaningful if Class 2 service has been agreed upon.')
fcmFLoginClass3SeqDelivAgreed = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1, 9), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFLoginClass3SeqDelivAgreed.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginClass3SeqDelivAgreed.setDescription('An indication of whether the Fx_Port has agreed to support Class 3 sequential delivery for this Nx_Port. This is only meaningful if Class 3 service has been agreed upon.')
fcmFLoginClass3DataFieldSize = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 9, 1, 10), FcDataFieldSize()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmFLoginClass3DataFieldSize.setStatus('current')
if mibBuilder.loadTexts: fcmFLoginClass3DataFieldSize.setDescription('The Receive Data Field Size that the Fx_Port has agreed to support for Class 3 frames to/from this Nx_Port. The size specifies the largest Data Field Size for an FT_1 frame. This is only meaningful if Class 3 service has been agreed upon.')
fcmLinkTable = MibTable((1, 3, 6, 1, 2, 1, 10, 56, 1, 10), )
if mibBuilder.loadTexts: fcmLinkTable.setStatus('current')
if mibBuilder.loadTexts: fcmLinkTable.setDescription("A table containing any Fibre Channel link information that is known to local Fibre Channel managed instances. One end of such a link is typically at a local port, but the table can also contain information on links for which neither end is a local port. If one end of a link terminates locally, then that end is termed 'end1'; the other end is termed 'end2'.")
fcmLinkEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1), ).setIndexNames((0, "FC-MGMT-MIB", "fcmInstanceIndex"), (0, "FC-MGMT-MIB", "fcmLinkIndex"))
if mibBuilder.loadTexts: fcmLinkEntry.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEntry.setDescription("An entry containing information that a particular Fibre Channel managed instance has about a Fibre Channel link. The two ends of the link are called 'end1' and 'end2'.")
fcmLinkIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: fcmLinkIndex.setStatus('current')
if mibBuilder.loadTexts: fcmLinkIndex.setDescription('An arbitrary integer that uniquely identifies one link within the set of links about which a particular managed instance has information.')
fcmLinkEnd1NodeWwn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 2), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmLinkEnd1NodeWwn.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEnd1NodeWwn.setDescription('The node name of end1, or the zero-length string if unknown.')
fcmLinkEnd1PhysPortNumber = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmLinkEnd1PhysPortNumber.setReference('FC-GS-3, section 6.1.2.2.5')
if mibBuilder.loadTexts: fcmLinkEnd1PhysPortNumber.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEnd1PhysPortNumber.setDescription('The physical port number of end1, or zero if unknown.')
fcmLinkEnd1PortWwn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 4), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmLinkEnd1PortWwn.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEnd1PortWwn.setDescription("The port WWN of end1, or the zero-length string if unknown. ('end1' is local if this value is equal to the value of fcmPortWwn in one of the rows of the fcmPortTable.)")
fcmLinkEnd2NodeWwn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 5), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmLinkEnd2NodeWwn.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEnd2NodeWwn.setDescription('The node name of end2, or the zero-length string if unknown.')
fcmLinkEnd2PhysPortNumber = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmLinkEnd2PhysPortNumber.setReference('FC-GS-3, section 6.1.2.2.5')
if mibBuilder.loadTexts: fcmLinkEnd2PhysPortNumber.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEnd2PhysPortNumber.setDescription('The physical port number of end2, or zero if unknown.')
fcmLinkEnd2PortWwn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 7), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmLinkEnd2PortWwn.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEnd2PortWwn.setDescription('The port WWN of end2, or the zero-length string if unknown.')
fcmLinkEnd2AgentAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 8), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmLinkEnd2AgentAddress.setReference('FC-GS-3, section 6.1.2.1.7')
if mibBuilder.loadTexts: fcmLinkEnd2AgentAddress.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEnd2AgentAddress.setDescription('The address of the management agent for the Fibre Channel Interconnect Element or Platform of which end2 is a part. The GS-4 specification provides some information about management agents. If the address is unknown, the value of this object is the zero-length string.')
fcmLinkEnd2PortType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 9), FcPortType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmLinkEnd2PortType.setReference('FC-GS-3, section 6.1.2.2.2')
if mibBuilder.loadTexts: fcmLinkEnd2PortType.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEnd2PortType.setDescription('The port type of end2.')
fcmLinkEnd2UnitType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 10), FcUnitFunctions()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmLinkEnd2UnitType.setReference('FC-GS-3, sections 6.1.2.1.2 and 6.1.2.3.2')
if mibBuilder.loadTexts: fcmLinkEnd2UnitType.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEnd2UnitType.setDescription('The type of/function(s) performed by the Fibre Channel Interconnect Element or Platform of which end2 is a part.')
fcmLinkEnd2FcAddressId = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 56, 1, 10, 1, 11), FcAddressIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fcmLinkEnd2FcAddressId.setStatus('current')
if mibBuilder.loadTexts: fcmLinkEnd2FcAddressId.setDescription('The Fibre Channel Address ID of end2, or the zero-length string if unknown.')
fcmgmtCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 56, 3, 1))
fcmgmtGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 56, 3, 2))
fcmgmtCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 10, 56, 3, 1, 1)).setObjects(("FC-MGMT-MIB", "fcmInstanceBasicGroup"), ("FC-MGMT-MIB", "fcmPortBasicGroup"), ("FC-MGMT-MIB", "fcmPortErrorsGroup"), ("FC-MGMT-MIB", "fcmPortStatsGroup"), ("FC-MGMT-MIB", "fcmPortClass23StatsGroup"), ("FC-MGMT-MIB", "fcmPortClassFStatsGroup"), ("FC-MGMT-MIB", "fcmPortLcStatsGroup"), ("FC-MGMT-MIB", "fcmSwitchBasicGroup"), ("FC-MGMT-MIB", "fcmSwitchPortGroup"), ("FC-MGMT-MIB", "fcmSwitchLoginGroup"), ("FC-MGMT-MIB", "fcmLinkBasicGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmgmtCompliance = fcmgmtCompliance.setStatus('current')
if mibBuilder.loadTexts: fcmgmtCompliance.setDescription('Describes the requirements for compliance to this Fibre Channel Management MIB.')
fcmInstanceBasicGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 1)).setObjects(("FC-MGMT-MIB", "fcmInstanceWwn"), ("FC-MGMT-MIB", "fcmInstanceFunctions"), ("FC-MGMT-MIB", "fcmInstancePhysicalIndex"), ("FC-MGMT-MIB", "fcmInstanceSoftwareIndex"), ("FC-MGMT-MIB", "fcmInstanceStatus"), ("FC-MGMT-MIB", "fcmInstanceTextName"), ("FC-MGMT-MIB", "fcmInstanceDescr"), ("FC-MGMT-MIB", "fcmInstanceFabricId"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmInstanceBasicGroup = fcmInstanceBasicGroup.setStatus('current')
if mibBuilder.loadTexts: fcmInstanceBasicGroup.setDescription('Basic information about Fibre Channel managed instances.')
fcmSwitchBasicGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 2)).setObjects(("FC-MGMT-MIB", "fcmSwitchDomainId"), ("FC-MGMT-MIB", "fcmSwitchPrincipal"), ("FC-MGMT-MIB", "fcmSwitchWWN"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmSwitchBasicGroup = fcmSwitchBasicGroup.setStatus('current')
if mibBuilder.loadTexts: fcmSwitchBasicGroup.setDescription('Basic information about Fibre Channel switches.')
fcmPortBasicGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 3)).setObjects(("FC-MGMT-MIB", "fcmPortInstanceIndex"), ("FC-MGMT-MIB", "fcmPortWwn"), ("FC-MGMT-MIB", "fcmPortNodeWwn"), ("FC-MGMT-MIB", "fcmPortAdminType"), ("FC-MGMT-MIB", "fcmPortOperType"), ("FC-MGMT-MIB", "fcmPortFcCapClass"), ("FC-MGMT-MIB", "fcmPortFcOperClass"), ("FC-MGMT-MIB", "fcmPortTransmitterType"), ("FC-MGMT-MIB", "fcmPortConnectorType"), ("FC-MGMT-MIB", "fcmPortSerialNumber"), ("FC-MGMT-MIB", "fcmPortPhysicalNumber"), ("FC-MGMT-MIB", "fcmPortAdminSpeed"), ("FC-MGMT-MIB", "fcmPortCapProtocols"), ("FC-MGMT-MIB", "fcmPortOperProtocols"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmPortBasicGroup = fcmPortBasicGroup.setStatus('current')
if mibBuilder.loadTexts: fcmPortBasicGroup.setDescription('Basic information about Fibre Channel ports.')
fcmPortStatsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 4)).setObjects(("FC-MGMT-MIB", "fcmPortBBCreditZeros"), ("FC-MGMT-MIB", "fcmPortFullInputBuffers"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmPortStatsGroup = fcmPortStatsGroup.setStatus('current')
if mibBuilder.loadTexts: fcmPortStatsGroup.setDescription('Traffic statistics, which are not specific to any one class of service, for Fibre Channel ports.')
fcmPortClass23StatsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 5)).setObjects(("FC-MGMT-MIB", "fcmPortClass2RxFrames"), ("FC-MGMT-MIB", "fcmPortClass2RxOctets"), ("FC-MGMT-MIB", "fcmPortClass2TxFrames"), ("FC-MGMT-MIB", "fcmPortClass2TxOctets"), ("FC-MGMT-MIB", "fcmPortClass2Discards"), ("FC-MGMT-MIB", "fcmPortClass2RxFbsyFrames"), ("FC-MGMT-MIB", "fcmPortClass2RxPbsyFrames"), ("FC-MGMT-MIB", "fcmPortClass2RxFrjtFrames"), ("FC-MGMT-MIB", "fcmPortClass2RxPrjtFrames"), ("FC-MGMT-MIB", "fcmPortClass2TxFbsyFrames"), ("FC-MGMT-MIB", "fcmPortClass2TxPbsyFrames"), ("FC-MGMT-MIB", "fcmPortClass2TxFrjtFrames"), ("FC-MGMT-MIB", "fcmPortClass2TxPrjtFrames"), ("FC-MGMT-MIB", "fcmPortClass3RxFrames"), ("FC-MGMT-MIB", "fcmPortClass3RxOctets"), ("FC-MGMT-MIB", "fcmPortClass3TxFrames"), ("FC-MGMT-MIB", "fcmPortClass3TxOctets"), ("FC-MGMT-MIB", "fcmPortClass3Discards"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmPortClass23StatsGroup = fcmPortClass23StatsGroup.setStatus('current')
if mibBuilder.loadTexts: fcmPortClass23StatsGroup.setDescription('Traffic statistics for Class 2 and Class 3 traffic on Fibre Channel ports.')
fcmPortClassFStatsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 6)).setObjects(("FC-MGMT-MIB", "fcmPortClassFRxFrames"), ("FC-MGMT-MIB", "fcmPortClassFRxOctets"), ("FC-MGMT-MIB", "fcmPortClassFTxFrames"), ("FC-MGMT-MIB", "fcmPortClassFTxOctets"), ("FC-MGMT-MIB", "fcmPortClassFDiscards"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmPortClassFStatsGroup = fcmPortClassFStatsGroup.setStatus('current')
if mibBuilder.loadTexts: fcmPortClassFStatsGroup.setDescription('Traffic statistics for Class F traffic on Fibre Channel ports.')
fcmPortLcStatsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 7)).setObjects(("FC-MGMT-MIB", "fcmPortLcBBCreditZeros"), ("FC-MGMT-MIB", "fcmPortLcFullInputBuffers"), ("FC-MGMT-MIB", "fcmPortLcClass2RxFrames"), ("FC-MGMT-MIB", "fcmPortLcClass2RxOctets"), ("FC-MGMT-MIB", "fcmPortLcClass2TxFrames"), ("FC-MGMT-MIB", "fcmPortLcClass2TxOctets"), ("FC-MGMT-MIB", "fcmPortLcClass2Discards"), ("FC-MGMT-MIB", "fcmPortLcClass3Discards"), ("FC-MGMT-MIB", "fcmPortLcClass3RxFrames"), ("FC-MGMT-MIB", "fcmPortLcClass3RxOctets"), ("FC-MGMT-MIB", "fcmPortLcClass3TxFrames"), ("FC-MGMT-MIB", "fcmPortLcClass3TxOctets"), ("FC-MGMT-MIB", "fcmPortLcClass2RxFbsyFrames"), ("FC-MGMT-MIB", "fcmPortLcClass2RxPbsyFrames"), ("FC-MGMT-MIB", "fcmPortLcClass2RxFrjtFrames"), ("FC-MGMT-MIB", "fcmPortLcClass2RxPrjtFrames"), ("FC-MGMT-MIB", "fcmPortLcClass2TxFbsyFrames"), ("FC-MGMT-MIB", "fcmPortLcClass2TxPbsyFrames"), ("FC-MGMT-MIB", "fcmPortLcClass2TxFrjtFrames"), ("FC-MGMT-MIB", "fcmPortLcClass2TxPrjtFrames"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmPortLcStatsGroup = fcmPortLcStatsGroup.setStatus('current')
if mibBuilder.loadTexts: fcmPortLcStatsGroup.setDescription('Low-capacity (32-bit) statistics for Fibre Channel ports.')
fcmPortErrorsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 8)).setObjects(("FC-MGMT-MIB", "fcmPortRxLinkResets"), ("FC-MGMT-MIB", "fcmPortTxLinkResets"), ("FC-MGMT-MIB", "fcmPortLinkResets"), ("FC-MGMT-MIB", "fcmPortRxOfflineSequences"), ("FC-MGMT-MIB", "fcmPortTxOfflineSequences"), ("FC-MGMT-MIB", "fcmPortLinkFailures"), ("FC-MGMT-MIB", "fcmPortLossofSynchs"), ("FC-MGMT-MIB", "fcmPortLossofSignals"), ("FC-MGMT-MIB", "fcmPortPrimSeqProtocolErrors"), ("FC-MGMT-MIB", "fcmPortInvalidTxWords"), ("FC-MGMT-MIB", "fcmPortInvalidCRCs"), ("FC-MGMT-MIB", "fcmPortInvalidOrderedSets"), ("FC-MGMT-MIB", "fcmPortFrameTooLongs"), ("FC-MGMT-MIB", "fcmPortTruncatedFrames"), ("FC-MGMT-MIB", "fcmPortAddressErrors"), ("FC-MGMT-MIB", "fcmPortDelimiterErrors"), ("FC-MGMT-MIB", "fcmPortEncodingDisparityErrors"), ("FC-MGMT-MIB", "fcmPortOtherErrors"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmPortErrorsGroup = fcmPortErrorsGroup.setStatus('current')
if mibBuilder.loadTexts: fcmPortErrorsGroup.setDescription('Error statistics for Fibre Channel ports.')
fcmSwitchPortGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 9)).setObjects(("FC-MGMT-MIB", "fcmFxPortRatov"), ("FC-MGMT-MIB", "fcmFxPortEdtov"), ("FC-MGMT-MIB", "fcmFxPortRttov"), ("FC-MGMT-MIB", "fcmFxPortHoldTime"), ("FC-MGMT-MIB", "fcmFxPortCapBbCreditMax"), ("FC-MGMT-MIB", "fcmFxPortCapBbCreditMin"), ("FC-MGMT-MIB", "fcmFxPortCapDataFieldSizeMax"), ("FC-MGMT-MIB", "fcmFxPortCapDataFieldSizeMin"), ("FC-MGMT-MIB", "fcmFxPortCapClass2SeqDeliv"), ("FC-MGMT-MIB", "fcmFxPortCapClass3SeqDeliv"), ("FC-MGMT-MIB", "fcmFxPortCapHoldTimeMax"), ("FC-MGMT-MIB", "fcmFxPortCapHoldTimeMin"), ("FC-MGMT-MIB", "fcmISPortClassFCredit"), ("FC-MGMT-MIB", "fcmISPortClassFDataFieldSize"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmSwitchPortGroup = fcmSwitchPortGroup.setStatus('current')
if mibBuilder.loadTexts: fcmSwitchPortGroup.setDescription('Information about ports on a Fibre Channel switch.')
fcmSwitchLoginGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 10)).setObjects(("FC-MGMT-MIB", "fcmFLoginPortWwn"), ("FC-MGMT-MIB", "fcmFLoginNodeWwn"), ("FC-MGMT-MIB", "fcmFLoginBbCreditModel"), ("FC-MGMT-MIB", "fcmFLoginBbCredit"), ("FC-MGMT-MIB", "fcmFLoginClassesAgreed"), ("FC-MGMT-MIB", "fcmFLoginClass2SeqDelivAgreed"), ("FC-MGMT-MIB", "fcmFLoginClass2DataFieldSize"), ("FC-MGMT-MIB", "fcmFLoginClass3SeqDelivAgreed"), ("FC-MGMT-MIB", "fcmFLoginClass3DataFieldSize"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmSwitchLoginGroup = fcmSwitchLoginGroup.setStatus('current')
if mibBuilder.loadTexts: fcmSwitchLoginGroup.setDescription('Information known to a Fibre Channel switch about attached/logged-in Nx_Ports.')
fcmLinkBasicGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 56, 3, 2, 11)).setObjects(("FC-MGMT-MIB", "fcmLinkEnd1NodeWwn"), ("FC-MGMT-MIB", "fcmLinkEnd1PhysPortNumber"), ("FC-MGMT-MIB", "fcmLinkEnd1PortWwn"), ("FC-MGMT-MIB", "fcmLinkEnd2NodeWwn"), ("FC-MGMT-MIB", "fcmLinkEnd2PhysPortNumber"), ("FC-MGMT-MIB", "fcmLinkEnd2PortWwn"), ("FC-MGMT-MIB", "fcmLinkEnd2AgentAddress"), ("FC-MGMT-MIB", "fcmLinkEnd2PortType"), ("FC-MGMT-MIB", "fcmLinkEnd2UnitType"), ("FC-MGMT-MIB", "fcmLinkEnd2FcAddressId"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
fcmLinkBasicGroup = fcmLinkBasicGroup.setStatus('current')
if mibBuilder.loadTexts: fcmLinkBasicGroup.setDescription('Information about Fibre Channel links.')
mibBuilder.exportSymbols("FC-MGMT-MIB", fcmPortOtherErrors=fcmPortOtherErrors, fcmLinkEnd1PhysPortNumber=fcmLinkEnd1PhysPortNumber, FcClasses=FcClasses, fcmFxPortTable=fcmFxPortTable, fcmgmtConformance=fcmgmtConformance, fcmFLoginPortWwn=fcmFLoginPortWwn, fcmPortClass3RxOctets=fcmPortClass3RxOctets, fcmInstanceEntry=fcmInstanceEntry, FcBbCreditModel=FcBbCreditModel, fcmFLoginNxPortIndex=fcmFLoginNxPortIndex, fcmFLoginBbCredit=fcmFLoginBbCredit, fcmPortEntry=fcmPortEntry, fcmLinkEnd2PhysPortNumber=fcmLinkEnd2PhysPortNumber, FcAddressIdOrZero=FcAddressIdOrZero, fcmPortClass2RxFrames=fcmPortClass2RxFrames, fcmPortClass2RxPbsyFrames=fcmPortClass2RxPbsyFrames, fcmPortPhysicalNumber=fcmPortPhysicalNumber, fcmPortLossofSynchs=fcmPortLossofSynchs, fcmPortOperProtocols=fcmPortOperProtocols, fcmPortClass3TxFrames=fcmPortClass3TxFrames, fcmPortLinkResets=fcmPortLinkResets, fcmPortStatsGroup=fcmPortStatsGroup, fcmgmtNotifications=fcmgmtNotifications, fcmFxPortCapClass3SeqDeliv=fcmFxPortCapClass3SeqDeliv, fcmPortClassFDiscards=fcmPortClassFDiscards, fcmInstancePhysicalIndex=fcmInstancePhysicalIndex, fcmSwitchTable=fcmSwitchTable, fcmPortLcClass2RxOctets=fcmPortLcClass2RxOctets, fcmPortClass3TxOctets=fcmPortClass3TxOctets, fcmPortLcClass2TxFrames=fcmPortLcClass2TxFrames, fcmFxPortEdtov=fcmFxPortEdtov, fcmSwitchEntry=fcmSwitchEntry, fcmLinkEnd2PortWwn=fcmLinkEnd2PortWwn, fcmPortLcBBCreditZeros=fcmPortLcBBCreditZeros, fcmSwitchBasicGroup=fcmSwitchBasicGroup, fcmInstanceFunctions=fcmInstanceFunctions, fcmPortLcStatsGroup=fcmPortLcStatsGroup, fcmPortNodeWwn=fcmPortNodeWwn, fcmPortClassFStatsGroup=fcmPortClassFStatsGroup, fcmLinkTable=fcmLinkTable, fcmPortClass3Discards=fcmPortClass3Discards, fcmPortLcClass3TxFrames=fcmPortLcClass3TxFrames, fcmFLoginBbCreditModel=fcmFLoginBbCreditModel, fcmPortLcClass2RxFbsyFrames=fcmPortLcClass2RxFbsyFrames, fcmLinkIndex=fcmLinkIndex, fcmPortClassFTxFrames=fcmPortClassFTxFrames, fcmLinkEntry=fcmLinkEntry, fcmPortLcClass2TxPrjtFrames=fcmPortLcClass2TxPrjtFrames, fcmSwitchLoginGroup=fcmSwitchLoginGroup, fcmPortLinkFailures=fcmPortLinkFailures, fcmPortConnectorType=fcmPortConnectorType, fcmPortLcClass2TxFbsyFrames=fcmPortLcClass2TxFbsyFrames, fcmFLoginClass3DataFieldSize=fcmFLoginClass3DataFieldSize, fcmPortFrameTooLongs=fcmPortFrameTooLongs, fcmPortClass2RxFbsyFrames=fcmPortClass2RxFbsyFrames, fcmPortTxOfflineSequences=fcmPortTxOfflineSequences, fcmInstanceFabricId=fcmInstanceFabricId, fcmSwitchWWN=fcmSwitchWWN, fcmFLoginClass2DataFieldSize=fcmFLoginClass2DataFieldSize, fcmPortLcClass2Discards=fcmPortLcClass2Discards, fcmPortBasicGroup=fcmPortBasicGroup, fcmPortClassFTxOctets=fcmPortClassFTxOctets, fcmPortClass2TxFrjtFrames=fcmPortClass2TxFrjtFrames, fcmLinkEnd2NodeWwn=fcmLinkEnd2NodeWwn, fcmLinkEnd2PortType=fcmLinkEnd2PortType, fcmPortCapProtocols=fcmPortCapProtocols, fcmPortClass2TxFbsyFrames=fcmPortClass2TxFbsyFrames, fcmPortClass2TxFrames=fcmPortClass2TxFrames, fcmPortLcStatsTable=fcmPortLcStatsTable, fcmISPortTable=fcmISPortTable, fcMgmtMIB=fcMgmtMIB, fcmSwitchPortGroup=fcmSwitchPortGroup, FcNameIdOrZero=FcNameIdOrZero, fcmPortFcCapClass=fcmPortFcCapClass, fcmInstanceIndex=fcmInstanceIndex, fcmPortClass3RxFrames=fcmPortClass3RxFrames, fcmFLoginClassesAgreed=fcmFLoginClassesAgreed, fcmFLoginTable=fcmFLoginTable, fcmFLoginNodeWwn=fcmFLoginNodeWwn, fcmInstanceStatus=fcmInstanceStatus, fcmInstanceBasicGroup=fcmInstanceBasicGroup, fcmLinkEnd2FcAddressId=fcmLinkEnd2FcAddressId, fcmSwitchDomainId=fcmSwitchDomainId, fcmPortAdminSpeed=fcmPortAdminSpeed, fcmPortLcClass2RxPbsyFrames=fcmPortLcClass2RxPbsyFrames, fcmPortEncodingDisparityErrors=fcmPortEncodingDisparityErrors, fcmPortTransmitterType=fcmPortTransmitterType, fcmFxPortRttov=fcmFxPortRttov, fcmPortLcClass2TxFrjtFrames=fcmPortLcClass2TxFrjtFrames, fcmFxPortCapDataFieldSizeMax=fcmFxPortCapDataFieldSizeMax, fcmPortInvalidTxWords=fcmPortInvalidTxWords, fcmFxPortCapDataFieldSizeMin=fcmFxPortCapDataFieldSizeMin, fcmgmtCompliance=fcmgmtCompliance, fcmPortClass2TxPbsyFrames=fcmPortClass2TxPbsyFrames, fcmInstanceSoftwareIndex=fcmInstanceSoftwareIndex, PYSNMP_MODULE_ID=fcMgmtMIB, fcmFLoginClass2SeqDelivAgreed=fcmFLoginClass2SeqDelivAgreed, fcmPortClass2RxOctets=fcmPortClass2RxOctets, fcmPortLcClass3RxFrames=fcmPortLcClass3RxFrames, fcmInstanceWwn=fcmInstanceWwn, fcmISPortEntry=fcmISPortEntry, fcmPortTable=fcmPortTable, FcUnitFunctions=FcUnitFunctions, fcmPortAdminType=fcmPortAdminType, fcmFxPortHoldTime=fcmFxPortHoldTime, fcmPortFcOperClass=fcmPortFcOperClass, fcmPortClass2TxOctets=fcmPortClass2TxOctets, fcmPortClassFRxOctets=fcmPortClassFRxOctets, fcmFLoginClass3SeqDelivAgreed=fcmFLoginClass3SeqDelivAgreed, FcPortType=FcPortType, fcmPortTxLinkResets=fcmPortTxLinkResets, fcmPortLcClass2TxOctets=fcmPortLcClass2TxOctets, fcmPortInvalidOrderedSets=fcmPortInvalidOrderedSets, fcmLinkEnd1PortWwn=fcmLinkEnd1PortWwn, fcmPortErrorsGroup=fcmPortErrorsGroup, fcmPortLcClass3RxOctets=fcmPortLcClass3RxOctets, fcmPortLcFullInputBuffers=fcmPortLcFullInputBuffers, fcmPortErrorsEntry=fcmPortErrorsEntry, fcmPortLossofSignals=fcmPortLossofSignals, fcmFxPortCapBbCreditMax=fcmFxPortCapBbCreditMax, fcmFxPortCapBbCreditMin=fcmFxPortCapBbCreditMin, fcmPortLcClass2RxFrames=fcmPortLcClass2RxFrames, fcmFLoginEntry=fcmFLoginEntry, fcmPortOperType=fcmPortOperType, fcmInstanceTable=fcmInstanceTable, fcmLinkBasicGroup=fcmLinkBasicGroup, fcmInstanceDescr=fcmInstanceDescr, fcmPortInvalidCRCs=fcmPortInvalidCRCs, fcmgmtObjects=fcmgmtObjects, fcmPortBBCreditZeros=fcmPortBBCreditZeros, fcmPortFullInputBuffers=fcmPortFullInputBuffers, fcmSwitchIndex=fcmSwitchIndex, fcmPortSerialNumber=fcmPortSerialNumber, fcmPortErrorsTable=fcmPortErrorsTable, fcmPortLcClass3TxOctets=fcmPortLcClass3TxOctets, fcmPortWwn=fcmPortWwn, fcmPortRxOfflineSequences=fcmPortRxOfflineSequences, FcBbCredit=FcBbCredit, fcmInstanceTextName=fcmInstanceTextName, fcmPortInstanceIndex=fcmPortInstanceIndex, fcmFxPortCapClass2SeqDeliv=fcmFxPortCapClass2SeqDeliv, fcmPortClass2TxPrjtFrames=fcmPortClass2TxPrjtFrames, fcmgmtGroups=fcmgmtGroups, fcmPortLcClass2RxFrjtFrames=fcmPortLcClass2RxFrjtFrames, fcmLinkEnd2AgentAddress=fcmLinkEnd2AgentAddress, fcmgmtCompliances=fcmgmtCompliances, fcmPortClassFRxFrames=fcmPortClassFRxFrames, fcmPortStatsEntry=fcmPortStatsEntry, fcmgmtNotifPrefix=fcmgmtNotifPrefix, fcmPortClass2RxFrjtFrames=fcmPortClass2RxFrjtFrames, fcmPortClass2Discards=fcmPortClass2Discards, fcmISPortClassFDataFieldSize=fcmISPortClassFDataFieldSize, FcDataFieldSize=FcDataFieldSize, fcmPortLcClass3Discards=fcmPortLcClass3Discards, fcmFxPortEntry=fcmFxPortEntry, fcmPortTruncatedFrames=fcmPortTruncatedFrames, fcmFxPortCapHoldTimeMin=fcmFxPortCapHoldTimeMin, fcmFxPortRatov=fcmFxPortRatov, FcDomainIdOrZero=FcDomainIdOrZero, fcmPortClass2RxPrjtFrames=fcmPortClass2RxPrjtFrames, fcmPortRxLinkResets=fcmPortRxLinkResets, fcmPortAddressErrors=fcmPortAddressErrors, fcmSwitchPrincipal=fcmSwitchPrincipal, fcmPortPrimSeqProtocolErrors=fcmPortPrimSeqProtocolErrors, fcmLinkEnd2UnitType=fcmLinkEnd2UnitType, fcmISPortClassFCredit=fcmISPortClassFCredit, fcmLinkEnd1NodeWwn=fcmLinkEnd1NodeWwn, fcmPortLcClass2RxPrjtFrames=fcmPortLcClass2RxPrjtFrames, fcmPortClass23StatsGroup=fcmPortClass23StatsGroup, fcmPortDelimiterErrors=fcmPortDelimiterErrors, fcmPortLcClass2TxPbsyFrames=fcmPortLcClass2TxPbsyFrames, fcmFxPortCapHoldTimeMax=fcmFxPortCapHoldTimeMax, fcmPortLcStatsEntry=fcmPortLcStatsEntry, fcmPortStatsTable=fcmPortStatsTable)
|
EXPOSED_CRED_POLICY = 'AWSExposedCredentialPolicy_DO_NOT_REMOVE'
def rule(event):
request_params = event.get('requestParameters', {})
if request_params:
return (event['eventName'] == 'PutUserPolicy' and
request_params.get('policyName') == EXPOSED_CRED_POLICY)
return False
def dedup(event):
return event['userIdentity'].get('userName')
def title(event):
message = '{username}\'s access key ID [{key}] was uploaded to a public GitHub repo'
return message.format(username=dedup(event),
key=event['userIdentity'].get('accessKeyId'))
|
"""462. Total Occurrence of Target
"""
class Solution:
"""
@param A: A an integer array sorted in ascending order
@param target: An integer
@return: An integer
"""
def totalOccurrence(self, A, target):
# write your code here
### Practice:
if not A:
return 0
index = self.binarySearch(A, target)
if index == None:
return 0
cnt = 0
for i in range(index, len(A)):
if A[i] == target:
cnt += 1
return cnt
def binarySearch(self, nums, target):
start = 0
end = len(nums) - 1
while start + 1 < end:
mid = (start + end) // 2
if nums[mid] < target:
start = mid
else:
end = mid
if nums[start] == target:
return start
if nums[end] == target:
return end
return None
######
if not A:
return 0
start = 0
end = len(A) - 1
count = 0
while start + 1 < end:
mid = (start + end) // 2
if A[mid] < target:
start = mid
else:
end = mid
occur = 0
if A[start] == target:
occur = start
elif A[end] == target:
occur = end
else:
return 0
for i in range(occur, len(A)):
if A[i] != target:
break
count += 1
return count
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
result = []
depth = -1
def backtrack(root, curr):
nonlocal depth
if not root:
return
if curr > depth:
result.append([])
depth = curr
result[curr].append(root.val)
backtrack(root.left, curr+1)
backtrack(root.right, curr+1)
backtrack(root, 0)
return result[::-1] |
"""
LJM library error codes.
"""
# Success
NOERROR = 0
# Warnings:
WARNINGS_BEGIN = 200
WARNINGS_END = 399
FRAMES_OMITTED_DUE_TO_PACKET_SIZE = 201
DEBUG_LOG_FAILURE = 202
USING_DEFAULT_CALIBRATION = 203
DEBUG_LOG_FILE_NOT_OPEN = 204
# Modbus Errors:
MODBUS_ERRORS_BEGIN = 1200
MODBUS_ERRORS_END = 1216
MBE1_ILLEGAL_FUNCTION = 1201
MBE2_ILLEGAL_DATA_ADDRESS = 1202
MBE3_ILLEGAL_DATA_VALUE = 1203
MBE4_SLAVE_DEVICE_FAILURE = 1204
MBE5_ACKNOWLEDGE = 1205
MBE6_SLAVE_DEVICE_BUSY = 1206
MBE8_MEMORY_PARITY_ERROR = 1208
MBE10_GATEWAY_PATH_UNAVAILABLE = 1210
MBE11_GATEWAY_TARGET_NO_RESPONSE = 1211
# Library Errors:
LIBRARY_ERRORS_BEGIN = 1220
LIBRARY_ERRORS_END = 1399
UNKNOWN_ERROR = 1221
INVALID_DEVICE_TYPE = 1222
INVALID_HANDLE = 1223
DEVICE_NOT_OPEN = 1224
STREAM_NOT_INITIALIZED = 1225
DEVICE_DISCONNECTED = 1226
DEVICE_NOT_FOUND = 1227
DEVICE_ALREADY_OPEN = 1229
DEVICE_CURRENTLY_CLAIMED_BY_ANOTHER_PROCESS = 1230
CANNOT_CONNECT = 1231
SOCKET_LEVEL_ERROR = 1233
CANNOT_OPEN_DEVICE = 1236
CANNOT_DISCONNECT = 1237
WINSOCK_FAILURE = 1238
RECONNECT_FAILED = 1239
CONNECTION_HAS_YIELDED_RECONNECT_FAILED = 1240
USB_FAILURE = 1241
# LJM does not support U3, U6, UE9, or U12 devices
U3_NOT_SUPPORTED_BY_LJM = 1243
U6_NOT_SUPPORTED_BY_LJM = 1246
UE9_NOT_SUPPORTED_BY_LJM = 1249
INVALID_ADDRESS = 1250
INVALID_CONNECTION_TYPE = 1251
INVALID_DIRECTION = 1252
INVALID_FUNCTION = 1253
INVALID_NUM_REGISTERS = 1254
INVALID_PARAMETER = 1255
INVALID_PROTOCOL_ID = 1256
INVALID_TRANSACTION_ID = 1257
UNKNOWN_VALUE_TYPE = 1259
MEMORY_ALLOCATION_FAILURE = 1260
NO_COMMAND_BYTES_SENT = 1261
INCORRECT_NUM_COMMAND_BYTES_SENT = 1262
NO_RESPONSE_BYTES_RECEIVED = 1263
INCORRECT_NUM_RESPONSE_BYTES_RECEIVED = 1264
MIXED_FORMAT_IP_ADDRESS = 1265
UNKNOWN_IDENTIFIER = 1266
NOT_IMPLEMENTED = 1267
INVALID_INDEX = 1268
INVALID_LENGTH = 1269
ERROR_BIT_SET = 1270
INVALID_MAXBYTESPERMBFB = 1271
NULL_POINTER = 1272
NULL_OBJ = 1273
RESERVED_NAME = 1274
UNPARSABLE_DEVICE_TYPE = 1275
UNPARSABLE_CONNECTION_TYPE = 1276
UNPARSABLE_IDENTIFIER = 1277
PACKET_SIZE_TOO_LARGE = 1278
TRANSACTION_ID_ERR = 1279
PROTOCOL_ID_ERR = 1280
LENGTH_ERR = 1281
UNIT_ID_ERR = 1282
FUNCTION_ERR = 1283
STARTING_REG_ERR = 1284
NUM_REGS_ERR = 1285
NUM_BYTES_ERR = 1286
CONFIG_FILE_NOT_FOUND = 1289
CONFIG_PARSING_ERROR = 1290
INVALID_NUM_VALUES = 1291
MODBUS_CONSTANTS_FILE_NOT_FOUND = 1292
INVALID_MODBUS_CONSTANTS_FILE = 1293
INVALID_NAME = 1294
OVERSPECIFIED_PORT = 1296
INTENT_NOT_READY = 1297
ATTR_LOAD_COMM_FAILURE = 1298
INVALID_CONFIG_NAME = 1299
ERROR_RETRIEVAL_FAILURE = 1300
LJM_BUFFER_FULL = 1301
COULD_NOT_START_STREAM = 1302
STREAM_NOT_RUNNING = 1303
UNABLE_TO_STOP_STREAM = 1304
INVALID_VALUE = 1305
SYNCHRONIZATION_TIMEOUT = 1306
OLD_FIRMWARE = 1307
CANNOT_READ_OUT_ONLY_STREAM = 1308
NO_SCANS_RETURNED = 1309
TEMPERATURE_OUT_OF_RANGE = 1310
VOLTAGE_OUT_OF_RANGE = 1311
FUNCTION_DOES_NOT_SUPPORT_THIS_TYPE = 1312
INVALID_INFO_HANDLE = 1313
NO_DEVICES_FOUND = 1314
AUTO_IPS_FILE_NOT_FOUND = 1316
AUTO_IPS_FILE_INVALID = 1317
INVALID_INTERVAL_HANDLE = 1318
NAMED_MUTEX_PERMISSION_DENIED = 1319
DIGITAL_AUTO_RECOVERY_ERROR_DETECTED = 1320
NEGATIVE_RECEIVE_BUFFER_SIZE = 1321
COULD_NOT_CLAIM_DEVICE = 1230 # Deprecated - use DEVICE_CURRENTLY_CLAIMED_BY_ANOTHER_PROCESS instead
U3_CANNOT_BE_OPENED_BY_LJM = 1243 # Deprecated - use U3_NOT_SUPPORTED_BY_LJM instead
U6_CANNOT_BE_OPENED_BY_LJM = 1246 # Deprecated - use U6_NOT_SUPPORTED_BY_LJM instead
UE9_CANNOT_BE_OPENED_BY_LJM = 1249 # Deprecated- use UE9_NOT_SUPPORTED_BY_LJM instead
INVALID_VALUE_TYPE = 1259 # Deprecated - use UNKNOWN_VALUE_TYPE instead
|
#
# Copyright (C) 2019 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ofthe License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specificlanguage governing permissions and
# limitations under the License.
#
class PacketInjection(object):
"""
Definition of a Skydive packet injection.
"""
def __init__(self, uuid="", src="", dst="", srcip="", dstip="", srcmac="",
dstmac="", srcport=0, dstport=0, type="icmp4", payload="",
trackingid="", icmpid=0, count=1, interval=0,
mode="unique", starttime="", ttl=64):
self.uuid = uuid
self.src = src
self.dst = dst
self.srcip = srcip
self.dstip = dstip
self.srcmac = srcmac
self.dstmac = dstmac
self.srcport = srcport
self.dstport = dstport
self.type = type
self.payload = payload
self.trackingid = trackingid
self.icmpid = icmpid
self.count = count
self.interval = interval
self.mode = mode
self.starttime = starttime
self.ttl = ttl
def repr_json(self):
obj = {}
if self.uuid:
obj["UUID"] = self.uuid
if self.src:
obj["Src"] = self.src
if self.dst:
obj["Dst"] = self.dst
if self.srcip:
obj["SrcIP"] = self.srcip
if self.dstip:
obj["DstIP"] = self.dstip
if self.srcmac:
obj["SrcMAC"] = self.srcmac
if self.dstmac:
obj["DstMAC"] = self.dstmac
if self.srcport:
obj["SrcPort"] = self.srcport
if self.dstport:
obj["DstPort"] = self.dstport
if self.type:
obj["Type"] = self.type
if self.payload:
obj["Payload"] = self.payload
if self.trackingid:
obj["TrackingID"] = self.trackingid
if self.icmpid:
obj["ICMPID"] = self.icmpid
if self.count:
obj["Count"] = self.count
if self.interval:
obj["Interval"] = self.interval
if self.mode:
obj["Mode"] = self.mode
if self.ttl:
obj["TTL"] = self.ttl
return obj
@classmethod
def from_object(self, obj):
return self(uuid=obj.get("UUID"),
src=obj.get("Src"),
dst=obj.get("Dst"),
srcip=obj.get("SrcIP"),
dstip=obj.get("DstIP"),
srcmac=obj.get("SrcMAC"),
dstmac=obj.get("DstMAC"),
srcport=obj.get("SrcPort"),
dstport=obj.get("DstPort"),
type=obj.get("Type"),
payload=obj.get("Payload"),
trackingid=obj.get("TrackingID"),
icmpid=obj.get("ICMPID"),
count=obj.get("Count"),
interval=obj.get("Interval"),
mode=obj.get("Mode"),
ttl=obj.get("TTL"))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {string[]}
def binaryTreePaths(self, root):
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
return map(lambda x:str(root.val)+'->'+x, self.binaryTreePaths(root.left)) + \
map(lambda x:str(root.val)+'->'+x, self.binaryTreePaths(root.right)) |
def inc(x):
return x + 1
def dec(x):
return x - 1
def floor(par):
x = 0
y = 1
for i in par:
x = inc(x) if i == "(" else dec(x)
if x == -1:
return y
y += 1
return x
print(floor(
"((((()(()(((((((()))(((()((((()())(())()(((()((((((()((()(()(((()(()((())))()((()()())))))))))()((((((())((()))(((((()(((((((((()()))((()(())()((())((()(()))((()))()))()(((((()(((()()))()())((()((((())()())()((((())()(()(()(((()(())(()(())(((((((())()()(((())(()(()(()(())))(()((((())((()))(((()(()()(((((()()(()(((()(((((())()))()((()(()))()((()((((())((((())(()(((())()()(()()()()()(())((((())((())(()()))()((((())))((((()())()((((())((()())((())(())(((((()((((()(((()((((())(()(((()()))()))((((((()((())()())))(((()(()))(()()(()(((()(()))((()()()())((()()()(((())())()())())())((()))(()(()))(((((()(()(())((()(())(())()((((()())()))((((())(())((())())((((()(((())(())((()()((((()((((((()(())()()(()(()()((((()))(())()())()))(())))(())))())()()(())(()))()((()(()(())()()))(()())))))(()))(()()))(())(((((()(()(()()((())()())))))((())())((())(()(())((()))(())(((()((((((((()()()(()))()()(((()))()((()()(())(())())()(()(())))(((((()(())(())(()))))())()))(()))()(()(((((((()((((())))())())())())()((((((((((((((()()((((((()()()())())()())())())(())(())))())((()())((()(()))))))()))))))))))))))))())((())((())()()))))))(((()((()(()()))((())(()()))()()())))(())))))))(()(((())))())()())))()()(())()))()(()))())((()()))))(()))))()))(()()(())))))))()(((()))))()(()))(())())))))()))((()))((()))())(())))))))))((((())()))()))()))())(())()()(())))())))(()())()))((()()(())))(())((((((()(())((()(((()(()()(())))()))))))()))()(()((()))()(()))(()(((())((((())())(())(()))))))))())))))))())())))))())))))()()(((())()(()))))))))())))))(())()()()))()))()))(()(())()()())())))))))())()(()(()))))()()()))))())(()))))()()))))()())))))(((())()()))(()))))))))))()()))))()()()))))(()())())()()())()(()))))()(()))(())))))))(((((())(())())()()))()()))(())))))()(()))))(())(()()))()())()))()))()))()))))())()()))())())))(()))(()))))))())()(((())()))))))))()))()())))())))())))()))))))))))()()))(()()))))))(())()(()))))())(()))))(()))))(()())))))())())()()))))())()))))))))(()))))()))))))()(()())))))))()))())))())))())))())))))))())(()()))))))(()())())))()())()))))))))))))))())))()(())))()))())()()(())(()()))(())))())()())(()(()(()))))())))))))))))())(()))()))()))))(())()())()())))))))))))()()))))))))))))())())))))(()())))))))))))())(())))()))))))))())())(()))()))(())))()))()()(())()))))))()((((())()))())())))))()))()))))((()())()))))())))(())))))))))))))))))()))))()()())()))()()))))())()))((()())))())))(()))(()())))))))()))()))))(())))))))(())))))())()()(()))())()))()()))))())()()))))())()))())))))))(()))))()())()))))))))(()))())))(()))()))))(())()))())())(())())())))))))((((())))))()))()))()())()(())))()))()))()())(()())()()(()())()))))())())))))(()))()))))())(()()(())))))(())()()((())())))))(())(())))))))())))))))))()(())))))))()())())())()(()))))))))(()))))))))())()()))()(()))))))()))))))())))))))(())))()()(())()())))))(((())))()((())()))())))(()()))())(())())))()(((()())))))()(()()())))()()(()()(()()))())()(()()()))())()()))()())(()))))())))))())))(())()()))))(()))))(())(()))(())))))()()))()))))())()))()()(())())))((()))())()))))))()()))))((()(()))))()()))))))())))))())(()((()())))))))))))()())())))()))(()))))))(()))(())()())))(()))))))))())()()()()))))(()())))))))((())))()))(()))(())(())()())()))))))))(())))())))(()))()()))(()()))(()))())))()(())))())((()((()(())))((())))()))))((((())())()())))(())))()))))))())(()()((())))())()(()())))))(()())()))())))))))((())())))))))(()(()))())()()(()()(((()(((()())))))()))))))()(())(()()((()()(())()()))())()())()))()())())())))))))(((())))))))()()))))))(((())()))(()()))(()()))))(()(()()((((())()())((()()))))(()(())))))()((()()()())()()((()((()()))(()))(((()()()))(((())))()(((())()))))))((()(())())))(()())(((((()(()))(()((()))(()())()))))(()(()))()(()))(())(((())(()()))))()()))(((()))))(()()()()))())))((()()()(())()))()))))()()))()))))))((((((()()()))))())((()()(((()))))(()(())(()()())())())))()(((()()))(())((())))(()))(()()()())((())())())(()))))()))()((()(())()(()()(())(()))(())()))(())(()))))(())(())())(()()(()((()()((())))((()))()((())))(((()()()()((((()))(()()))()()()(((())((())())(()()(()()()))()((())(())()))())(((()()(())))()((()()())()())(()(())())(((())(())())((())(())()(((()()))(())))((())(()())())(())((()()()((((((())))((()(((((())()))()))(())(()()))()))(())()()))(())((()()())()()(()))())()((())))()((()()())((((()())((())())())((()((()))()))((())((()()(()((()()(((())(()()))))((()((())()(((())(()((())())((())(()((((((())())()(()())()(())(((())((((((()(())(()((()()()((()()(()()()())))()()(((((()()))()((((((()))()(()(()(()(((()())((()))())()((()))(())))()))()()))())()()))())((((())(()(()))(((((((())(((()(((((()(((()()((((())(((())())))(()()()(()(()))()))((((((()))((()(((()(())((()((((()((((((())(((((())))(((()(()))))(((()(((())()((())(()((()))(((()()(((())((((()(()(((((()))(((()(((((((()(()()()(()(()(()()())(())(((((()(())())()())(()(()(()))()(()()()())(()()(()((()))()((())())()(()))((())(()))()(()))()(((()(()(()((((((()()()()())()(((((()()(((()()()((()(((((()))((((((((()()()(((((()))))))(()()()(())(()))(()()))))(())()))(((((()(((((()()(()(()())(((()))((((()((()(()(()((()(()((())))()(((()((()))((()))(((((((((()((()((()(())))()((((()((()()))((())(((()(((((()()(()(()()((()(()()()(((((((())())()())))))((((()()(()))()))(()((())()(()(((((((((()()(((()(()())(()((()())((())())((((()(((()(((()((((()((()((((()(()((((((())((((((((((((()()(()()((((((((((((((()((()()))()((((((((((((())((((()(()())((()(()(()))()(((((()()(((()()))()())(())((()(((((()((())(((((()((()(((((()))()()((((())()((((())(((((((((()(())(()(())))())(()((())(((())(())(())())(()(()(())()()((()((())()(((()(((((()(())))()(((()((())))((()()()(((()(((()((()(()(())(()((()())(()(()(((()(((((((((())(()((((()()))(()((((()()()()(((()((((((((()(()()((((((()(()()(()((()((((((((((()()(((((((()())(())))(((()()))(((((()((()()())(()()((((())((()((((()))))(())((()(()()(((()(()(((()((((()(((((()))())())(()((())()))(((()())((())((())((((()((()((((((())(()((((()()))((((((())()(()))((()(((())((((((((((()()(((((()(((((()((()()()((((())))(()))()((()(())()()((()((((((((((()((())(())(((((()(()(()()))((((()((((()()((()(((()(((((((((()(()((()((()))((((((()(((())()()((()(((((((()())))()()(()((()((()()(((()(()()()()((((()((())((((()(((((((((()(((()()(((()(()(((()(((()((())()(()((()(()(()(()))()(((()))(()((((()((())((((())((((((())(()))(()((((())((()(()((((((((()()((((((()(()(()()()(())((()((()()(((()(((((((()()((()(((((((()))(((((()(((()(()()()(()(((()((()()((())(()(((((((((()(()((()((((((()()((())()))(((((()((())()())()(((((((((((()))((((()()()()())(()()(()(()()))()))(()))(()(((()()))())(()(()))()()((())(()())()())()(()))()))(()()(()((((((())((()(((((((((((()(())()((()(()((()((()(()((()((((((((((()()())((())()(())))((())()())()(((((()(()())((((()((()(())(()))(((())()((()))(((((())(()))()()(()))(((())((((()((((()(())))(((((((()))))())()())(())((())()(()()((()(()))()(()()(()()((()())((())((()()))((((()))()()))(()()(())()()(((((()(())((()((((()))()))(()())())(((()()(()()))(())))))(()))((())(((((()((((()))()((((()))()((())(((())))(((()())))((()(()()(("))
|
"""
https://www.hackerrank.com/challenges/no-idea
There is an array of integers. There are also disjoint sets, and , each containing integers. You like all the integers in set and dislike all the integers in set . Your initial happiness is . For each integer in the array, if , you add to your happiness. If , you add to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end.
Note: Since and are sets, they have no repeated elements. However, the array might contain duplicate elements.
Constraints
Input Format
The first line contains integers and separated by a space.
The second line contains integers, the elements of the array.
The third and fourth lines contain integers, and , respectively.
Output Format
Output a single integer, your total happiness.
Sample Input
3 2
1 5 3
3 1
5 7
Sample Output
1
Explanation
You gain unit of happiness for elements and in set . You lose unit for in set . The element in set does not exist in the array so it is not included in the calculation.
Hence, the total happiness is .
"""
#!/bin/python3
# Enter your code here. Read input from STDIN. Print output to STDOUT
def get_points(array, like_list, dislike_list):
points = 0
for number in array:
if number in like_list:
points += 1
if number in dislike_list:
points -= 1
return points
if __name__ == "__main__":
n,m = tuple(map(int, input().split()))
array = tuple(map(int, input().split()))
like_list = set(map(int, input().split()))
dislike_list = set(map(int, input().split()))
print(get_points(array, like_list, dislike_list))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def get_input(path):
with open(path) as infile:
return [line.rstrip('\n') for line in infile]
|
#
# PySNMP MIB module JUNIPER-SMI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-SMI
# Produced by pysmi-0.3.4 at Wed May 1 11:37:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
enterprises, Counter64, IpAddress, Counter32, Integer32, iso, TimeTicks, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, MibIdentifier, Gauge32, Bits, ObjectIdentity, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "Counter64", "IpAddress", "Counter32", "Integer32", "iso", "TimeTicks", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "MibIdentifier", "Gauge32", "Bits", "ObjectIdentity", "ModuleIdentity")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
juniperMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 2636))
juniperMIB.setRevisions(('2010-07-09 00:00', '2009-10-29 00:00', '2010-06-18 00:00', '2003-04-17 01:00', '2005-08-17 01:00', '2006-12-14 01:00', '2007-01-01 00:00', '2007-10-09 00:00', '2009-12-31 00:00', '2010-07-14 00:00', '2011-01-26 00:00', '2012-02-10 00:00', '2012-08-01 00:00', '2012-11-01 00:00', '2012-12-07 00:00', '2013-01-25 00:00', '2013-11-26 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: juniperMIB.setRevisionsDescriptions(('Added jnxLicenseMibRoot branch.', 'Added jnxCosNotifications branch.', 'Added jnxLicenseMibRoot branch.', 'Added jnxExperiment branch.', 'Added jnxNsm branch.', 'Added jnxCA branch.', 'Added jnxUtilMibRoot branch.', 'Added jnxAdvancedInsightMgr branch.', 'Added jnxBxMibRoot branch.', 'Added jnxSubscriberMibRoot branch.', 'Added jnxDcfMibRoot branch.', 'Added jnxMediaFlow branch.', 'Added jnxSDKApplicationsRoot branch.', 'Added jnxJVAEMibRoot branch.', 'Added jnxStrm branch.', 'Added jnxIfOtnMibRoot branch. Added jnxOpticsMibRoot branch. Added jnxAlarmExtMibRoot branch. Added jnxoptIfMibRoot branch. Added jnxIfOtnNotifications branch. Added jnxOpticsNotifications branch.', ' Added jnxSnmpSetMibRoot branch',))
if mibBuilder.loadTexts: juniperMIB.setLastUpdated('201007090000Z')
if mibBuilder.loadTexts: juniperMIB.setOrganization('Juniper Networks, Inc.')
if mibBuilder.loadTexts: juniperMIB.setContactInfo(' Juniper Technical Assistance Center Juniper Networks, Inc. 1194 N. Mathilda Avenue Sunnyvale, CA 94089 E-mail: support@juniper.net')
if mibBuilder.loadTexts: juniperMIB.setDescription('The Structure of Management Information for Juniper Networks.')
jnxProducts = ObjectIdentity((1, 3, 6, 1, 4, 1, 2636, 1))
if mibBuilder.loadTexts: jnxProducts.setStatus('current')
if mibBuilder.loadTexts: jnxProducts.setDescription("The root of Juniper's Product OIDs.")
jnxMediaFlow = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 1, 2))
jnxJunosSpace = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 1, 3))
jnxReservedProducts3 = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 1, 4))
jnxReservedProducts4 = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 1, 5))
jnxReservedProducts5 = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 1, 6))
jnxSDKApplicationsRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 1, 7))
jnxJAB = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 1, 8))
jnxStrm = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 1, 9))
jnxServices = ObjectIdentity((1, 3, 6, 1, 4, 1, 2636, 2))
if mibBuilder.loadTexts: jnxServices.setStatus('current')
if mibBuilder.loadTexts: jnxServices.setDescription("The root of Juniper's Services OIDs.")
jnxMibs = ObjectIdentity((1, 3, 6, 1, 4, 1, 2636, 3))
if mibBuilder.loadTexts: jnxMibs.setStatus('current')
if mibBuilder.loadTexts: jnxMibs.setDescription("The root of Juniper's MIB objects.")
jnxJsMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 39))
jnxExMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 40))
jnxWxMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 41))
jnxDcfMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 42))
jnxReservedMibs5 = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 43))
jnxPfeMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 44))
jnxBfdMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 45))
jnxXstpMibs = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 46))
jnxUtilMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 47))
jnxl2aldMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 48))
jnxL2tpMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 49))
jnxRpmMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 50))
jnxUserAAAMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 51))
jnxIpSecMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 52))
jnxL2cpMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 53))
jnxPwTdmMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 54))
jnxPwTCMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 55))
jnxOtnMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 56))
jnxPsuMIBRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 58))
jnxSvcsMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 59))
jnxDomMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 60))
jnxJdhcpMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 61))
jnxJdhcpv6MibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 62))
jnxLicenseMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 63))
jnxSubscriberMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 64))
jnxMagMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 65))
jnxMobileGatewayMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 66))
jnxPppoeMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 67))
jnxPppMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 68))
jnxJVAEMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 69))
jnxIfOtnMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 70))
jnxOpticsMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 71))
jnxAlarmExtMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 72))
jnxoptIfMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 73))
jnxFruMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 74))
jnxTimingNotfnsMIBRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 75))
jnxSnmpSetMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 76))
jnxTraps = ObjectIdentity((1, 3, 6, 1, 4, 1, 2636, 4))
if mibBuilder.loadTexts: jnxTraps.setStatus('current')
if mibBuilder.loadTexts: jnxTraps.setDescription("The root of Juniper's Trap OIDs.")
jnxChassisTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 1))
jnxChassisOKTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 2))
jnxRmonTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 3))
jnxLdpTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 4))
jnxCmNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 5))
jnxSonetNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 6))
jnxPMonNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 7))
jnxCollectorNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 8))
jnxPingNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 9))
jnxSpNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 10))
jnxDfcNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 11))
jnxSyslogNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 12))
jnxEventNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 13))
jnxVccpNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 14))
jnxOtnNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 15))
jnxSAIDPNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 16))
jnxCosNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 17))
jnxDomNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 18))
jnxFabricChassisTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 19))
jnxFabricChassisOKTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 20))
jnxIfOtnNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 21))
jnxOpticsNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 22))
jnxFruTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 23))
jnxSnmpSetTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 4, 24))
jnxExperiment = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 5))
jnxNsm = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 6))
jnxCA = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 7))
jnxAAA = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 8))
jnxAdvancedInsightMgr = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 9))
jnxBxMibRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 10))
mibBuilder.exportSymbols("JUNIPER-SMI", jnxFabricChassisOKTraps=jnxFabricChassisOKTraps, jnxReservedProducts4=jnxReservedProducts4, jnxJsMibRoot=jnxJsMibRoot, jnxEventNotifications=jnxEventNotifications, jnxPingNotifications=jnxPingNotifications, jnxPppMibRoot=jnxPppMibRoot, jnxL2cpMibRoot=jnxL2cpMibRoot, jnxServices=jnxServices, jnxJVAEMibRoot=jnxJVAEMibRoot, jnxAAA=jnxAAA, jnxXstpMibs=jnxXstpMibs, jnxReservedMibs5=jnxReservedMibs5, jnxIfOtnNotifications=jnxIfOtnNotifications, jnxRmonTraps=jnxRmonTraps, jnxLdpTraps=jnxLdpTraps, jnxFruTraps=jnxFruTraps, jnxDomMibRoot=jnxDomMibRoot, jnxSonetNotifications=jnxSonetNotifications, jnxoptIfMibRoot=jnxoptIfMibRoot, jnxChassisTraps=jnxChassisTraps, jnxBfdMibRoot=jnxBfdMibRoot, jnxPwTdmMibRoot=jnxPwTdmMibRoot, jnxOpticsNotifications=jnxOpticsNotifications, jnxAdvancedInsightMgr=jnxAdvancedInsightMgr, jnxMediaFlow=jnxMediaFlow, jnxLicenseMibRoot=jnxLicenseMibRoot, jnxBxMibRoot=jnxBxMibRoot, jnxCA=jnxCA, jnxAlarmExtMibRoot=jnxAlarmExtMibRoot, jnxOtnMibRoot=jnxOtnMibRoot, jnxPsuMIBRoot=jnxPsuMIBRoot, jnxPMonNotifications=jnxPMonNotifications, jnxL2tpMibRoot=jnxL2tpMibRoot, jnxCmNotifications=jnxCmNotifications, jnxFabricChassisTraps=jnxFabricChassisTraps, jnxRpmMibRoot=jnxRpmMibRoot, jnxOpticsMibRoot=jnxOpticsMibRoot, jnxChassisOKTraps=jnxChassisOKTraps, jnxWxMibRoot=jnxWxMibRoot, jnxPwTCMibRoot=jnxPwTCMibRoot, jnxJdhcpMibRoot=jnxJdhcpMibRoot, jnxSnmpSetMibRoot=jnxSnmpSetMibRoot, jnxl2aldMibRoot=jnxl2aldMibRoot, jnxExperiment=jnxExperiment, jnxReservedProducts3=jnxReservedProducts3, jnxExMibRoot=jnxExMibRoot, jnxIfOtnMibRoot=jnxIfOtnMibRoot, jnxDomNotifications=jnxDomNotifications, jnxSDKApplicationsRoot=jnxSDKApplicationsRoot, jnxJdhcpv6MibRoot=jnxJdhcpv6MibRoot, jnxDfcNotifications=jnxDfcNotifications, jnxDcfMibRoot=jnxDcfMibRoot, jnxOtnNotifications=jnxOtnNotifications, PYSNMP_MODULE_ID=juniperMIB, jnxMagMibRoot=jnxMagMibRoot, jnxCosNotifications=jnxCosNotifications, jnxUserAAAMibRoot=jnxUserAAAMibRoot, jnxCollectorNotifications=jnxCollectorNotifications, juniperMIB=juniperMIB, jnxFruMibRoot=jnxFruMibRoot, jnxSvcsMibRoot=jnxSvcsMibRoot, jnxTimingNotfnsMIBRoot=jnxTimingNotfnsMIBRoot, jnxSpNotifications=jnxSpNotifications, jnxStrm=jnxStrm, jnxUtilMibRoot=jnxUtilMibRoot, jnxProducts=jnxProducts, jnxSubscriberMibRoot=jnxSubscriberMibRoot, jnxPfeMibRoot=jnxPfeMibRoot, jnxSAIDPNotifications=jnxSAIDPNotifications, jnxTraps=jnxTraps, jnxJunosSpace=jnxJunosSpace, jnxNsm=jnxNsm, jnxMibs=jnxMibs, jnxJAB=jnxJAB, jnxMobileGatewayMibRoot=jnxMobileGatewayMibRoot, jnxSyslogNotifications=jnxSyslogNotifications, jnxSnmpSetTraps=jnxSnmpSetTraps, jnxVccpNotifications=jnxVccpNotifications, jnxReservedProducts5=jnxReservedProducts5, jnxPppoeMibRoot=jnxPppoeMibRoot, jnxIpSecMibRoot=jnxIpSecMibRoot)
|
class TcpUtils:
"""
Stores constants related to TCP protocol and utility methods
"""
TCP_HEADER_LENGTH = 5
TCP_HEADER_LENGTH_BYTES = TCP_HEADER_LENGTH * 4
TCP_OPTIONS_MAX_LENGTH_BYTES = 40
@staticmethod
def validate_options_length(options):
length = len(options)
if length > TcpUtils.TCP_OPTIONS_MAX_LENGTH_BYTES:
raise ValueError(f"Max options length is "
f"{TcpUtils.TCP_OPTIONS_MAX_LENGTH_BYTES} "
f"got {length}")
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 19 13:26:07 2020
@author: admin
"""
#Fibonacci last digit
n=int(input())
n1=0
n2=1
for i in range(2,n+1):
nex=n1+n2
n1=n2
n2=nex
print(nex%10) |
"""
This test makes sure that the implicit rule dependencies are discoverable by
an IDE. We stuff all dependencies into _scala_toolchain so we just need to make
sure the targets we expect are there.
"""
attr_aspects = ["_scala_toolchain", "deps"]
def _aspect_impl(target, ctx):
visited = [str(target.label)]
for attr_name in attr_aspects:
if hasattr(ctx.rule.attr, attr_name):
for dep in getattr(ctx.rule.attr, attr_name):
if hasattr(dep, "visited"):
visited += dep.visited
return struct(visited = visited)
test_aspect = aspect(
attr_aspects = attr_aspects,
implementation = _aspect_impl,
)
def _rule_impl(ctx):
expected_deps = {
"scala_library": [
"//test/aspect:scala_library",
"//scala/private/toolchain_deps:scala_library_classpath",
],
"scala_test": [
"//test/aspect:scala_test",
"//scala/private/toolchain_deps:scala_library_classpath",
"//testing/toolchain:scalatest_classpath",
],
"scala_junit_test": [
"//test/aspect:scala_junit_test",
"//scala/private/toolchain_deps:scala_library_classpath",
"//testing/toolchain:junit_classpath",
],
"scala_specs2_junit_test": [
"//scala/private/toolchain_deps:scala_library_classpath",
"//test/aspect:scala_specs2_junit_test",
"//testing/toolchain:junit_classpath",
# From specs2/specs2.bzl:specs2_dependencies()
"@io_bazel_rules_scala//specs2:specs2",
"@io_bazel_rules_scala_org_specs2_specs2_common//:io_bazel_rules_scala_org_specs2_specs2_common",
"@io_bazel_rules_scala_org_specs2_specs2_core//:io_bazel_rules_scala_org_specs2_specs2_core",
"@io_bazel_rules_scala_org_specs2_specs2_fp//:io_bazel_rules_scala_org_specs2_specs2_fp",
"@io_bazel_rules_scala_org_specs2_specs2_matcher//:io_bazel_rules_scala_org_specs2_specs2_matcher",
"@io_bazel_rules_scala//scala/private/toolchain_deps:scala_xml",
"@io_bazel_rules_scala//scala/private/toolchain_deps:scala_library_classpath",
# From specs2/specs2_junit.bzl:specs2_junit_dependencies()
"@io_bazel_rules_scala_org_specs2_specs2_junit//:io_bazel_rules_scala_org_specs2_specs2_junit",
],
}
content = ""
for target in ctx.attr.targets:
visited = depset(sorted(target.visited)).to_list()
expected = depset(sorted(expected_deps[target.label.name])).to_list()
if visited != expected:
content += """
echo Expected these deps from {name}: 1>&2
echo {expected}, 1>&2
echo but got these instead: 1>&2
echo {visited} 1>&2
false # test returns 1 (and fails) if this is the final line
""".format(
name = target.label.name,
expected = ", ".join(expected),
visited = ", ".join(visited),
)
ctx.actions.write(
output = ctx.outputs.executable,
content = content,
)
return struct()
aspect_test = rule(
implementation = _rule_impl,
attrs = {
# The targets whose dependencies we want to verify.
"targets": attr.label_list(aspects = [test_aspect]),
},
test = True,
)
|
# Hexadecimal
print(hex(12))
print(hex(512))
# Binary
print(bin(128))
print(bin(512))
# Exponential
print(pow(2, 4))
print(pow(2, 4, 3))
# Absolute value
print(abs(2))
# Round
print(round(3.6)) # Round up
print(round(3.4)) # Round down
print(round(3.4, 2)) # Round down
|
def evaluate_list(list):
list.sort()
pairs_list = []
for i in range(len(list)-1):
for e in list[i+1::]:
if abs(list[i] - e) == 2:
pairs_list.append([list[i], e])
for pair in pairs_list:
print("{},{}".format(pair[0], pair[1]))
def main():
custom_list = []
try:
num = int(input('Introduce la cantidad de elementos del arreglo: '))
for _ in range(num):
num = int(input('Introduce un numero: '))
if num not in custom_list:
custom_list.append(num)
except:
raise Exception("Valor introducido no válido.")
evaluate_list(custom_list)
if __name__ == "__main__":
main() |
print("Vou advinhar se é par ou impar")
x = int(input('Digite um numero: '))
y = x % 2
if y <= 0:
print("o numero é par")
else:
print("o numero é impar")
|
def update_matches(matches, nubank_month_data, mobills_month_data):
"""
Changes done in place. NuBank and Mobills expenses with match will be removed from original object.
"""
# Filter matches to only items that still exist
matches_cleaned = []
for match in matches:
[nubank_ids, mobills_ids] = match['nubank'], match['mobills']
nubank_ids_filtered = []
for nu_id in nubank_ids:
if nu_id in nubank_month_data:
nubank_ids_filtered.append(nu_id)
mobills_ids_filtered = []
for mo_id in mobills_ids:
if mo_id in mobills_month_data:
mobills_ids_filtered.append(mo_id)
if len(nubank_ids_filtered) > 0 and len(mobills_ids_filtered) > 0:
matches_cleaned.append([nubank_ids_filtered, mobills_ids_filtered])
for nu_id in nubank_ids_filtered:
del nubank_month_data[nu_id]
for mo_id in mobills_ids_filtered:
mobills_month_data[mo_id]['count'] -= 1
if mobills_month_data[mo_id]['count'] == 0:
del mobills_month_data[mo_id]
matches = matches_cleaned
|
def long(x):
separado=x.split(" ")
ultima=separado[-1]
a=len(ultima)
print(f"La longitud de {ultima} es {a}")
oracion=input("Escriba una oración: ")
long(oracion)
|
def nonConstructibleChange(coins):
if len(coins) == 0:
return 1
coins.sort()
change = 0
for coin in coins:
if coin > change + 1:
return change + 1
change += coin
return change + 1 |
# -*- coding: utf-8 -*-
"""The-lost-planet.py: A text-based interactive game."""
__author__ = "Razique Mahroua"
__copyright__ = "Copyright 20459, Planet GC-1450"
class ParseError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
self.subject = subject[1]
self.verb = verb[1]
self.object = object[1]
def __eq__(self, other):
return self.__dict__ == other.__dict__
def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
def match(word_list, expecting):
if word_list:
word = word_list.pop(0)
if word[0] == expecting:
return word
else:
return None
else:
return None
def skip(word_list, word_type):
while peek(word_list) == word_type:
match(word_list, word_type)
def parse_verb(word_list):
skip(word_list, 'stop')
if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParseError("Expected a verb next.")
def parse_object(word_list):
skip(word_list, 'stop')
next = peek(word_list)
if next == 'noun':
return match(word_list, 'noun')
if next == 'direction':
return match(word_list, 'direction')
else:
raise ParseError("Expected a noun or direction next")
def parse_subject(word_list, subj):
verb = parse_verb(word_list)
obj = parse_object(word_list)
return Sentence(subj, verb, obj)
def parse_sentence(word_list):
skip(word_list, 'stop')
start = peek(word_list)
if start == 'noun':
subj = match(word_list, 'noun')
return parse_subject(word_list, subj)
elif start == 'verb':
return parse_subject(word_list, ('noun', 'player'))
else:
raise ParseError("Must start with subject, object, or verb not %s" % start)
|
for i in range(int(input())):
n = int(input())
a = []
for j in range(n):
l,r = [int(k) for k in input().split()]
a.append((l,0))
a.append((r,1))
a.sort()
c = 0
f = 0
m = 1e5
for j in a:
if(j[1]):
f=1
c-=1
else:
if(f==1):
m=min(m,c)
c+=1
if(m==int(1e5)):
print(-1)
else:
print(m)
|
class MyData:
def __del__(self):
print('test __del__ OK')
data = MyData()
|
def validate_dog_age(letter):
"""this function takes a letter as age
and returns a tuple or range of ages"""
if "b" or "y" or "a" or "s" in letter:
return (1, 97)
elif "b" or "y" in letter:
return (1, 26)
elif "a" or "s" in letter:
return (25, 97)
elif 'b' in letter:
return (1, 13)
elif 'y' in letter:
return (13, 26)
elif 'a' in letter:
return (25, 38)
else:
return (37, 97)
|
map_sokoban = {
"x" : 5,
"y" : 5
}
player = {
"x" : 0,
"y" : 4
}
boxes = [
{"x" : 1, "y" : 1},
{"x" : 2, "y" : 2},
{"x" : 3, "y" : 3}
]
destinations = [
{"x" : 2, "y" : 1},
{"x" : 3, "y" : 2},
{"x" : 4, "y" : 3}
]
while True:
for y in range(map_sokoban["y"]):
for x in range(map_sokoban["x"]):
box_is_here = False
des_is_here = False
player_is_here = False
for box in boxes:
if box["x"] == x and box["y"] == y:
box_is_here = True
for des in destinations:
if des["x"] == x and des["y"] == y:
des_is_here = True
if x == player["x"] and y == player["y"]:
player_is_here = True
if box_is_here:
print("B",end=" ")
elif des_is_here:
print("D",end=" ")
elif player_is_here:
print("P",end=" ")
else:
print("-",end=" ")
print()
is_win = True
for box in boxes:
if box not in destinations:
is_win = False
if is_win:
print("WIN")
break
move = input("Your move? ").upper()
dx = 0
dy = 0
if move == "W":
dy = -1
elif move == "S":
dy = 1
elif move == "A":
dx = -1
elif move == "D":
dx = 1
if (player["x"] + dx) in range(0,map_sokoban["x"]) and \
(player["y"] + dy) in range(0,map_sokoban["y"]):
player["x"] += dx
player["y"] += dy
for box in boxes:
if box["x"] == player["x"] and box["y"] == player["y"]:
box["x"] += dx
box["y"] += dy
|
input = """
edge(a,b,1).
edge(a,c,3).
edge(c,b,2).
edge(b,d,3).
edge(b,c,1).
edge(c,d,3).
town(T) :- edge(T,_,_).
town(T) :- edge(_,T,_).
"""
output = """
edge(a,b,1).
edge(a,c,3).
edge(c,b,2).
edge(b,d,3).
edge(b,c,1).
edge(c,d,3).
town(T) :- edge(T,_,_).
town(T) :- edge(_,T,_).
"""
|
"""
Leia a hora inicial, minuto inicial, hora final e minuto final de um jogo. A seguir calcule a duração do jogo.
OBS: O jogo tem duração mínima de um (1) minuto e duração máxima de 24 horas.
"""
entrada = input().split()
hora1 = int(entrada[0])
minuto1 = int(entrada[1])
hora2 = int(entrada[2])
minuto2 = int(entrada[3])
start = hora1*60 + minuto1
end = hora2*60 + minuto2
duracao = 0
if hora1 <= hora2:
duracao = end - start
if duracao == 0:
print(f'O JOGO DUROU {24} HORA(S) E {0} MINUTO(S)')
else:
print(f'O JOGO DUROU {int((duracao - (duracao%60)) / 60)} HORA(S) E {duracao%60} MINUTO(S)')
else:
duracao = end - (start + 60)
print(f'O JOGO DUROU {int((duracao - (duracao%60)) / 60)} HORA(S) E {duracao%60} MINUTO(S)')
|
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.insert(0, item)
def dequeue(self):
return self.queue.pop()
def size(self):
return len(self.queue)
def is_empty(self):
return self.queue == [] |
class Solution:
def addToArrayForm(self, A, K):
for i in range(len(A))[::-1]:
A[i], K = (A[i] + K) % 10, (A[i] + K) // 10
return [int(i) for i in str(K)] + A if K else A |
# use a func to create the matrix
def create_matrix(rows):
result = []
for _ in range(rows):
result.append(list(int(el) for el in input().split()))
return result
#read input
rows, columns = [int(el) for el in input().split()]
matrix = create_matrix(rows)
max_sum_square = -9999999999999
#create for loop to check sums of 3x3 squares
for r in range(rows - 2):
for c in range(columns - 2):
sum_square = sum(matrix[r][c:c + 3]) + sum(matrix[r+1][c:c + 3]) + sum(matrix[r+2][c:c + 3])
if sum_square > max_sum_square:
max_sum_square = sum_square
max_square = [matrix[r][c:c + 3], matrix[r+1][c:c + 3], matrix[r+2][c:c + 3]]
print(f"Sum = {max_sum_square}")
for el in max_square:
print(*el, sep=" ") |
def gnome_sort(a):
i, j, size = 1, 2, len(a)
while i < size:
if a[i-1] <= a[i]:
i, j = j, j+1
else:
a[i-1], a[i] = a[i], a[i-1]
i -= 1
if i == 0:
i, j = j, j+1
return a
|
'''VARIÁVEIS COMPOSTAS, LISTAS (parte 1)'''
print('No Python, igualar duas listas significa ligar uma a outra, alterando a segunda, a primeira também se altera')
a = [1, 2, 3, 4]
b = a #igualando-as
b[2] = 9 #modificando-a para demonstração
print(f'Lista A: {a}')
print(f'Lista B: {b}')
print('\nMas é possível fazer uma cópia')
c = [1, 2, 3, 4]
d = c[:] #copiando os valores de outra lista sem ligar uma a outra
d[2] = 9 #modificando-a para demonstração
print(f'Lista C: {c}')
print(f'Lista D: {d}') |
# iteracyjne obliczanie silni
def silnia(n):
s = 1
for i in range(2,n+1):
s = s*i
return s
silnia(20)
|
"""
Entradas:
Capital -> flotador -> cap
tiempo -> int -> Tiem
tasa -> flotar -> Tasa
Salidas:
Interes -> flotar -> Interes
Promedio -> flotar -> prom
"""
Cap = float ( input ( "Insertar capital:" ))
Tiem = int ( input ( "Insertar el tiempo de inversión:" ))
Tasa = float ( input ( "Insertar la tasa de interes:" ))
Interes = (( Cap * Tasa * Tiem ) / 100 )
Prom = ( Interes / Tiem )
print ( "El valor total de ineteres es:" + str ( Interes ), "El porcentaje de interes por año es:" + str ( Prom ), "%" ) |
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x == 0:
return True
if x < 0 or x % 10 == 0:
return False
l = len(str(x))
i = 1
x1 = x2 = x
while i <= l / 2:
left = x1 / (10 ** (l - i))
x1 = x1 % (10 ** (l - i))
right = x2 % 10
x2 = x2 / 10
if left != right:
return False
i += 1
return True
|
'''
@description 【Python】单例设计模式 2019/10/04 16:55
'''
# TODO:单例模式
# 某个类或者模型在整个程序运行中最多只能有个对象被创建
# 我们可以判断,如果User这个类没有创建对象,那么久创建一个对象保存在某个地方
# 以后如果要创建对象,我会去判断,如果之前已经创建了一个对象,那么就不再创建
# 而是直接把之前那个对象返回回去
class User(object):
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super().__new__(cls)
return cls.__instance
def __init__(self, name):
self.name = name
user1 = User('zhiliao')
user2 = User('ketang')
print(user1.name)
print(user2.name)
print(id(user1))
print(id(user2)) |
def is_primel_4(n):
if n == 2:
return True # 2 is prime
if n % 2 == 0:
print(n, "is divisible by 2")
return False # all even numbers except 2 are not prime
if n < 2:
return False # numbers less then 2 are not prime
prime = True
m = n // 2 + 1
for x in range(3, m, 2):
if n % x == 0:
print(n, "is divisible by", x)
prime = False
break
return prime
while True:
number = int(input("Please enter a number (enter 0 to exit): "))
prime = is_primel_4(number)
if number is 0:
break
elif prime is True:
print(number, "is a prime number.")
else:
print(number, "is not a prime number")
|
#
# PySNMP MIB module NETSCREEN-RESOURCE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETSCREEN-RESOURCE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:20:16 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, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint")
netscreenResource, = mibBuilder.importSymbols("NETSCREEN-SMI", "netscreenResource")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Unsigned32, iso, Counter64, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Bits, TimeTicks, Counter32, ObjectIdentity, Integer32, NotificationType, MibIdentifier, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "iso", "Counter64", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Bits", "TimeTicks", "Counter32", "ObjectIdentity", "Integer32", "NotificationType", "MibIdentifier", "Gauge32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
netscreenResourceMibModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 3224, 16, 0))
netscreenResourceMibModule.setRevisions(('2004-05-03 00:00', '2004-03-03 00:00', '2003-11-10 00:00', '2002-05-05 00:00', '2001-04-30 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: netscreenResourceMibModule.setRevisionsDescriptions(('Modified copyright and contact information', 'Converted to SMIv2 by Longview Software', 'Correct spelling mistake', 'Remove active session', 'Creation Date',))
if mibBuilder.loadTexts: netscreenResourceMibModule.setLastUpdated('200405032022Z')
if mibBuilder.loadTexts: netscreenResourceMibModule.setOrganization('Juniper Networks, Inc.')
if mibBuilder.loadTexts: netscreenResourceMibModule.setContactInfo('Customer Support 1194 North Mathilda Avenue Sunnyvale, California 94089-1206 USA Tel: 1-800-638-8296 E-mail: customerservice@juniper.net HTTP://www.juniper.net')
if mibBuilder.loadTexts: netscreenResourceMibModule.setDescription('This module defines the object that are used to monitor resource in netscreen box')
nsResCPU = MibIdentifier((1, 3, 6, 1, 4, 1, 3224, 16, 1))
nsResCpuAvg = MibScalar((1, 3, 6, 1, 4, 1, 3224, 16, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsResCpuAvg.setStatus('current')
if mibBuilder.loadTexts: nsResCpuAvg.setDescription('Average System CPU utilization in percentage.')
nsResCpuLast1Min = MibScalar((1, 3, 6, 1, 4, 1, 3224, 16, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsResCpuLast1Min.setStatus('current')
if mibBuilder.loadTexts: nsResCpuLast1Min.setDescription('Last one minute CPU utilization in percentage.')
nsResCpuLast5Min = MibScalar((1, 3, 6, 1, 4, 1, 3224, 16, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsResCpuLast5Min.setStatus('current')
if mibBuilder.loadTexts: nsResCpuLast5Min.setDescription('Last five minutes CPU utilization in percentage.')
nsResCpuLast15Min = MibScalar((1, 3, 6, 1, 4, 1, 3224, 16, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsResCpuLast15Min.setStatus('current')
if mibBuilder.loadTexts: nsResCpuLast15Min.setDescription('Last fifteen minutes CPU utilization in percentage.')
nsResMem = MibIdentifier((1, 3, 6, 1, 4, 1, 3224, 16, 2))
nsResMemAllocate = MibScalar((1, 3, 6, 1, 4, 1, 3224, 16, 2, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsResMemAllocate.setStatus('current')
if mibBuilder.loadTexts: nsResMemAllocate.setDescription('Memory allocated.')
nsResMemLeft = MibScalar((1, 3, 6, 1, 4, 1, 3224, 16, 2, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsResMemLeft.setStatus('current')
if mibBuilder.loadTexts: nsResMemLeft.setDescription('Memory left.')
nsResMemFrag = MibScalar((1, 3, 6, 1, 4, 1, 3224, 16, 2, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsResMemFrag.setStatus('current')
if mibBuilder.loadTexts: nsResMemFrag.setDescription('Memory fragment.')
nsResSession = MibIdentifier((1, 3, 6, 1, 4, 1, 3224, 16, 3))
nsResSessAllocate = MibScalar((1, 3, 6, 1, 4, 1, 3224, 16, 3, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsResSessAllocate.setStatus('current')
if mibBuilder.loadTexts: nsResSessAllocate.setDescription('Allocate session number.')
nsResSessMaxium = MibScalar((1, 3, 6, 1, 4, 1, 3224, 16, 3, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsResSessMaxium.setStatus('current')
if mibBuilder.loadTexts: nsResSessMaxium.setDescription('Maxium session number system can afford.')
nsResSessFailed = MibScalar((1, 3, 6, 1, 4, 1, 3224, 16, 3, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nsResSessFailed.setStatus('current')
if mibBuilder.loadTexts: nsResSessFailed.setDescription('Failed session allocation counters.')
mibBuilder.exportSymbols("NETSCREEN-RESOURCE-MIB", nsResSession=nsResSession, nsResCpuAvg=nsResCpuAvg, nsResCpuLast5Min=nsResCpuLast5Min, nsResMemFrag=nsResMemFrag, nsResSessFailed=nsResSessFailed, netscreenResourceMibModule=netscreenResourceMibModule, nsResCPU=nsResCPU, nsResMemAllocate=nsResMemAllocate, nsResCpuLast1Min=nsResCpuLast1Min, nsResSessAllocate=nsResSessAllocate, nsResCpuLast15Min=nsResCpuLast15Min, nsResMem=nsResMem, PYSNMP_MODULE_ID=netscreenResourceMibModule, nsResMemLeft=nsResMemLeft, nsResSessMaxium=nsResSessMaxium)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.