content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class RuleCollection(object):
def __init__(self, name, ruleset_list, result_on_match):
self.name = name
self.ruleset_list = ruleset_list
self.result_on_match = result_on_match
def check(self, data):
results = []
for ruleset in self.ruleset_list:
results.append(ruleset.check(data))
if True in results and False not in results:
return self.result_on_match
else:
return None
| class Rulecollection(object):
def __init__(self, name, ruleset_list, result_on_match):
self.name = name
self.ruleset_list = ruleset_list
self.result_on_match = result_on_match
def check(self, data):
results = []
for ruleset in self.ruleset_list:
results.append(ruleset.check(data))
if True in results and False not in results:
return self.result_on_match
else:
return None |
class A:
def __init__(self):
self.nr=int(input())
self.nc=int(input())
self.matrix=[]
for i in range(self.nr):
self.col=[]
for j in range(self.nc):
self.element=int(input())
self.col.append(self.element)
self.matrix.append(self.col)
def printMatrix(self):
for i in range(0,self.nr):
for j in range(0,self.nc):
print(self.matrix[i][j],end=" ")
print()
#def sumMat(self,A,B):
a=A()
b=A()
#a.printMatrix()
| class A:
def __init__(self):
self.nr = int(input())
self.nc = int(input())
self.matrix = []
for i in range(self.nr):
self.col = []
for j in range(self.nc):
self.element = int(input())
self.col.append(self.element)
self.matrix.append(self.col)
def print_matrix(self):
for i in range(0, self.nr):
for j in range(0, self.nc):
print(self.matrix[i][j], end=' ')
print()
a = a()
b = a() |
poesia = list()
poesia = input().split(" ")
while "*" not in poesia[0]:
aux = poesia[0]
aux = aux[0].lower()
tam = 0
for i in poesia:
if i[0].lower() == aux:
tam+=1
if tam == len(poesia):
print("Y")
else:
print("N")
poesia.clear()
poesia = input().split(" ")
| poesia = list()
poesia = input().split(' ')
while '*' not in poesia[0]:
aux = poesia[0]
aux = aux[0].lower()
tam = 0
for i in poesia:
if i[0].lower() == aux:
tam += 1
if tam == len(poesia):
print('Y')
else:
print('N')
poesia.clear()
poesia = input().split(' ') |
# Time: O(n^2)
# Space: O(n^2)
# On an N x N grid, each square grid[i][j] represents the elevation at that point (i,j).
#
# Now rain starts to fall. At time t, the depth of the water everywhere is t.
# You can swim from a square to another 4-directionally adjacent square
# if and only if the elevation of both squares individually are at most t.
# You can swim infinite distance in zero time. Of course,
# you must stay within the boundaries of the grid during your swim.
#
# You start at the top left square (0, 0).
# What is the least time until you can reach the bottom right square (N-1, N-1)?
#
# Example 1:
# Input: [[0,2],[1,3]]
# Output: 3
# Explanation:
# At time 0, you are in grid location (0, 0).
# You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
#
# You cannot reach point (1, 1) until time 3.
# When the depth of water is 3, we can swim anywhere inside the grid.
# Example 2:
#
# Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
# Output: 16
# Explanation:
# 0 1 2 3 4
# 24 23 22 21 5
# 12 13 14 15 16
# 11 17 18 19 20
# 10 9 8 7 6
#
# The final route is marked in bold.
# We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
#
# Note:
# - 2 <= N <= 50.
# - grid[i][j] is a permutation of [0, ..., N*N - 1].
class UnionFind(object):
def __init__(self, n):
self.set = range(n)
def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x]) # path compression.
return self.set[x]
def union_set(self, x, y):
x_root, y_root = map(self.find_set, (x, y))
if x_root == y_root:
return False
self.set[min(x_root, y_root)] = max(x_root, y_root)
return True
class Solution(object):
def swimInWater(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
positions = [None] * (n**2)
for i in xrange(n):
for j in xrange(n):
positions[grid[i][j]] = (i, j)
directions = ((-1, 0), (1, 0), (0, -1), (0, 1))
union_find = UnionFind(n**2)
for elevation in xrange(n**2):
i, j = positions[elevation]
for direction in directions:
x, y = i+direction[0], j+direction[1]
if 0 <= x < n and 0 <= y < n and grid[x][y] <= elevation:
union_find.union_set(i*n+j, x*n+y)
if union_find.find_set(0) == union_find.find_set(n**2-1):
return elevation
return n**2-1
| class Unionfind(object):
def __init__(self, n):
self.set = range(n)
def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x])
return self.set[x]
def union_set(self, x, y):
(x_root, y_root) = map(self.find_set, (x, y))
if x_root == y_root:
return False
self.set[min(x_root, y_root)] = max(x_root, y_root)
return True
class Solution(object):
def swim_in_water(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
positions = [None] * n ** 2
for i in xrange(n):
for j in xrange(n):
positions[grid[i][j]] = (i, j)
directions = ((-1, 0), (1, 0), (0, -1), (0, 1))
union_find = union_find(n ** 2)
for elevation in xrange(n ** 2):
(i, j) = positions[elevation]
for direction in directions:
(x, y) = (i + direction[0], j + direction[1])
if 0 <= x < n and 0 <= y < n and (grid[x][y] <= elevation):
union_find.union_set(i * n + j, x * n + y)
if union_find.find_set(0) == union_find.find_set(n ** 2 - 1):
return elevation
return n ** 2 - 1 |
class CommonWriter:
"""
Writer interface
"""
def write(self, dictionary):
raise Exception("unimplemented") | class Commonwriter:
"""
Writer interface
"""
def write(self, dictionary):
raise exception('unimplemented') |
#
# PySNMP MIB module ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH
# Produced by pysmi-0.3.4 at Wed May 1 13:06:37 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, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint")
ecExperimental, = mibBuilder.importSymbols("ESSENTIAL-COMMUNICATIONS-GLOBAL-REG", "ecExperimental")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter32, enterprises, Bits, iso, Integer32, ObjectIdentity, MibIdentifier, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, NotificationType, Counter64, TimeTicks, IpAddress, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "enterprises", "Bits", "iso", "Integer32", "ObjectIdentity", "MibIdentifier", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "NotificationType", "Counter64", "TimeTicks", "IpAddress", "Unsigned32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
essentialCommunications = MibIdentifier((1, 3, 6, 1, 4, 1, 2159))
ecRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1))
ecProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1, 3))
ecExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1, 6))
hippiSwitchMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1, 6, 1))
hippiSwitchMIBv103 = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1))
switchObjs = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1))
switchDescription = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 1), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: switchDescription.setStatus('mandatory')
if mibBuilder.loadTexts: switchDescription.setDescription('Returns the description, vendor, and version numbers of the switch.')
switchNumOfPorts = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 2), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: switchNumOfPorts.setStatus('mandatory')
if mibBuilder.loadTexts: switchNumOfPorts.setDescription('The number of slots in this switch. (Max number of media access cards).')
sccDescription = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sccDescription.setStatus('mandatory')
if mibBuilder.loadTexts: sccDescription.setDescription('The model, vendor, and version number of the switch control card.')
sccDateTime = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 4), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: sccDateTime.setStatus('mandatory')
if mibBuilder.loadTexts: sccDateTime.setDescription('The date/time in the real time clock. Format: yyyymmddhhmmss.')
sccAdminStatus = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("reset", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: sccAdminStatus.setStatus('mandatory')
if mibBuilder.loadTexts: sccAdminStatus.setDescription('The desired state of the switch.')
sccOperStatus = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("up", 1), ("reseting", 2), ("busy", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: sccOperStatus.setStatus('mandatory')
if mibBuilder.loadTexts: sccOperStatus.setDescription('The current state of the switch. SNMP operations can not occur when the switch is busy. SNMP operations can not occur when the switch is resetting.')
backPlaneTable = MibTable((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7), )
if mibBuilder.loadTexts: backPlaneTable.setStatus('mandatory')
if mibBuilder.loadTexts: backPlaneTable.setDescription('This table represent all of the slots in a HIPPI switch. None of the rows can be added to or deleted by the user.')
backPlaneEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1), ).setIndexNames((0, "ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", "backPlaneIndex"))
if mibBuilder.loadTexts: backPlaneEntry.setStatus('mandatory')
if mibBuilder.loadTexts: backPlaneEntry.setDescription('A row in the table describing one slot in the switch backplane. ')
backPlaneIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 1), Gauge32())
if mibBuilder.loadTexts: backPlaneIndex.setStatus('mandatory')
if mibBuilder.loadTexts: backPlaneIndex.setDescription('The table index for this slot on the backplane.')
backPlaneNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 2), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: backPlaneNumber.setStatus('mandatory')
if mibBuilder.loadTexts: backPlaneNumber.setDescription('The slot number as seen printed on the switch (backPlaneIndex + 1)')
backPlaneCard = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("unknown", 1), ("parallel", 2), ("serial", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: backPlaneCard.setStatus('mandatory')
if mibBuilder.loadTexts: backPlaneCard.setDescription('The type of MIC present in this slot of the backplane on the switch')
mICPowerUpInitError = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICPowerUpInitError.setStatus('mandatory')
if mibBuilder.loadTexts: mICPowerUpInitError.setDescription('True if error detected by MIC on start-up.')
mICHippiParityBurstError = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 5), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICHippiParityBurstError.setStatus('mandatory')
if mibBuilder.loadTexts: mICHippiParityBurstError.setDescription('Valid the SMIC only. Type of parity error.')
mICLinkReady = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 6), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICLinkReady.setStatus('mandatory')
if mibBuilder.loadTexts: mICLinkReady.setDescription('Valid the SMIC only. True if link ready asserted.')
mICSourceInterconnect = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 7), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICSourceInterconnect.setStatus('mandatory')
if mibBuilder.loadTexts: mICSourceInterconnect.setDescription('Source interconnect is valid for the PMIC only.')
mICSourceRequest = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 8), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICSourceRequest.setStatus('mandatory')
if mibBuilder.loadTexts: mICSourceRequest.setDescription('True if source request is asserted.')
mICSourceConnect = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 9), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICSourceConnect.setStatus('mandatory')
if mibBuilder.loadTexts: mICSourceConnect.setDescription('True if source connect is asserted.')
mICSourceLastConnectAttempt = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 10), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICSourceLastConnectAttempt.setStatus('mandatory')
if mibBuilder.loadTexts: mICSourceLastConnectAttempt.setDescription('True if last source request was successful.')
mICDestinationInterconnect = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 11), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICDestinationInterconnect.setStatus('mandatory')
if mibBuilder.loadTexts: mICDestinationInterconnect.setDescription('True if destination interconnect is asserted.')
mICDestinationRequest = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 12), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICDestinationRequest.setStatus('mandatory')
if mibBuilder.loadTexts: mICDestinationRequest.setDescription('True if destination request is asserted.')
mICDestinationConnect = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 13), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICDestinationConnect.setStatus('mandatory')
if mibBuilder.loadTexts: mICDestinationConnect.setDescription('True if destination connect is asserted.')
mICByteCounterOverflow = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 14), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICByteCounterOverflow.setStatus('mandatory')
if mibBuilder.loadTexts: mICByteCounterOverflow.setDescription('The number of times the byte counter has over-flowed.')
mICNumberOfBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 15), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICNumberOfBytes.setStatus('mandatory')
if mibBuilder.loadTexts: mICNumberOfBytes.setDescription('The number of bytes that have passed through the MIC.')
mICNumberOfPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 16), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICNumberOfPackets.setStatus('mandatory')
if mibBuilder.loadTexts: mICNumberOfPackets.setDescription('The number of times packets has been asserted.')
mICConnectsSuccessful = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 17), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mICConnectsSuccessful.setStatus('mandatory')
if mibBuilder.loadTexts: mICConnectsSuccessful.setDescription('The number of times this MIC has connected since reset.')
sourceRouteTable = MibTable((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8), )
if mibBuilder.loadTexts: sourceRouteTable.setStatus('mandatory')
if mibBuilder.loadTexts: sourceRouteTable.setDescription('This table holds all of the source routes for this switch. FORMAT: OutputPort InputPortList Status. Output port is 0 to 15 Input port is 0 to 15 List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2. Status is 0 (disabled) or 1 (enabled)')
sourceRouteEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8, 1), ).setIndexNames((0, "ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", "srcIndex"))
if mibBuilder.loadTexts: sourceRouteEntry.setStatus('mandatory')
if mibBuilder.loadTexts: sourceRouteEntry.setDescription('One row in the source route table.')
srcIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8, 1, 1), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: srcIndex.setStatus('mandatory')
if mibBuilder.loadTexts: srcIndex.setDescription('The row number for this row of the table.')
srcRoute = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: srcRoute.setStatus('mandatory')
if mibBuilder.loadTexts: srcRoute.setDescription('One source route. FORMAT: OutputPort InputPortList Status. Output port is 0 to 15 Input port is 0 to 15 List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2. Status is 0 (disabled) or 1 (enabled)')
srcWriteRow = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 9), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: srcWriteRow.setStatus('mandatory')
if mibBuilder.loadTexts: srcWriteRow.setDescription('Setting this variable alters source routes. FORMAT: OutputPortList InputPortList Status. Output port is 0 to 15 Input port is 0 to 15 List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2. Status is 0 (disabled) or 1 (enabled)')
destRouteTable = MibTable((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10), )
if mibBuilder.loadTexts: destRouteTable.setStatus('mandatory')
if mibBuilder.loadTexts: destRouteTable.setDescription('This table holds all of destination routes (logical address routes) for this switch. FORMAT: LogicalAddress InputPortList Huntgroup. LogicalAddress is 0 to 4095. Input port is 0 to 15 Huntgroup is 0 to 31. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.')
destRouteEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10, 1), ).setIndexNames((0, "ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", "destIndex"))
if mibBuilder.loadTexts: destRouteEntry.setStatus('mandatory')
if mibBuilder.loadTexts: destRouteEntry.setDescription('A row in the destination route table.')
destIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10, 1, 1), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: destIndex.setStatus('mandatory')
if mibBuilder.loadTexts: destIndex.setDescription('The index for this row of the table.')
destRoute = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: destRoute.setStatus('mandatory')
if mibBuilder.loadTexts: destRoute.setDescription('One Destination Route. FORMAT: LogicalAddress InputPortList Huntgroup. LogicalAddress is 0 to 4095. Input port is 0 to 15. Huntgroup is 0 to 31. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.')
destWriteRow = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 11), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: destWriteRow.setStatus('mandatory')
if mibBuilder.loadTexts: destWriteRow.setDescription('Setting this variable will alter the desitination routes. FORMAT: LogicalAddressList Huntgroup InputPortList. LogicalAddress is 0 to 4095. Huntgroup is 0 to 31. 31 will disable this route. Input port is 0 to 15. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.')
huntGroupTable = MibTable((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12), )
if mibBuilder.loadTexts: huntGroupTable.setStatus('mandatory')
if mibBuilder.loadTexts: huntGroupTable.setDescription('This table holds all of the huntgroups for this switch. FORMAT: Huntgroup ( OutportList ) Huntgroup is 0 to 31. OutportList is an orderd list of output ports in Huntgroup.')
huntGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12, 1), ).setIndexNames((0, "ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", "hg"))
if mibBuilder.loadTexts: huntGroupEntry.setStatus('mandatory')
if mibBuilder.loadTexts: huntGroupEntry.setDescription('A row in the huntgroup table.')
hg = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12, 1, 1), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hg.setStatus('mandatory')
if mibBuilder.loadTexts: hg.setDescription('The huntgroup number.')
hgOutPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hgOutPortList.setStatus('mandatory')
if mibBuilder.loadTexts: hgOutPortList.setDescription('The definition of one Huntgroup. FORMAT: Huntgroup ( OutportList ) Huntgroup is 0 to 31. OutportList is an orderd list of output ports in Huntgroup.')
hgLWriteRow = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 13), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hgLWriteRow.setStatus('mandatory')
if mibBuilder.loadTexts: hgLWriteRow.setDescription('Setting this variable will alter the huntgroup table by setting every huntgroup in list to include outPortList. FORMAT: HuntgroupList OutportList Huntgroup is 0 to 31. Outport is 0 to 15 and 16. 16 will clear the huntgroup. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.')
huntGroupOrderTable = MibTable((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14), )
if mibBuilder.loadTexts: huntGroupOrderTable.setStatus('mandatory')
if mibBuilder.loadTexts: huntGroupOrderTable.setDescription('This table holds all of the huntgroup order information for this switch. i.e. The order huntgroups are processed in when more than one huntgroup contends for the same output port. FORMAT: OutputPort HuntGroupList OutputPort is 0 to 15. Huntgroup is 0 to 31. List is an ordered list of huntgroups.')
huntGroupOrderEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14, 1), ).setIndexNames((0, "ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", "hg"))
if mibBuilder.loadTexts: huntGroupOrderEntry.setStatus('mandatory')
if mibBuilder.loadTexts: huntGroupOrderEntry.setDescription("One record on an output port's huntgroup priority.")
hgOrderIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14, 1, 1), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hgOrderIndex.setStatus('mandatory')
if mibBuilder.loadTexts: hgOrderIndex.setDescription('The backplane slot number containing output port.')
hgOrderList = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hgOrderList.setStatus('mandatory')
if mibBuilder.loadTexts: hgOrderList.setDescription("An ordered list of an output port's huntgroup priority. FORMAT: OutputPort HuntGroupList OutputPort is 0 to 15. Huntgroup is 0 to 31. List is an ordered list of huntgroups.")
hgOWriteRow = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 15), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hgOWriteRow.setStatus('mandatory')
if mibBuilder.loadTexts: hgOWriteRow.setDescription('Setting this variable will alter the huntgroup order table. FORMAT: OutputPort HuntGroupList Output port is 0 to 15. Huntgroup is 0 to 31. Huntgroup must contain output port in its output port list. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.')
hgSaveRestore = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("save", 1), ("restore", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hgSaveRestore.setStatus('mandatory')
if mibBuilder.loadTexts: hgSaveRestore.setDescription(' Writting a 1 saves all hunt group information on the switch. Writting a 2 restores all hunt group information on the switch.')
routesSaveRestore = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("save", 1), ("restore", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: routesSaveRestore.setStatus('mandatory')
if mibBuilder.loadTexts: routesSaveRestore.setDescription(' Writting a 1 saves all source/destination routes on the switch. Writting a 2 restores all source/destination routes on the switch.')
mibBuilder.exportSymbols("ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", srcWriteRow=srcWriteRow, hg=hg, hippiSwitchMIBv103=hippiSwitchMIBv103, switchDescription=switchDescription, backPlaneTable=backPlaneTable, mICNumberOfPackets=mICNumberOfPackets, backPlaneNumber=backPlaneNumber, hgLWriteRow=hgLWriteRow, mICPowerUpInitError=mICPowerUpInitError, sccAdminStatus=sccAdminStatus, huntGroupOrderEntry=huntGroupOrderEntry, sccDescription=sccDescription, backPlaneCard=backPlaneCard, huntGroupTable=huntGroupTable, ecProducts=ecProducts, mICHippiParityBurstError=mICHippiParityBurstError, srcRoute=srcRoute, destWriteRow=destWriteRow, switchNumOfPorts=switchNumOfPorts, destRoute=destRoute, sourceRouteTable=sourceRouteTable, destIndex=destIndex, hgOWriteRow=hgOWriteRow, mICSourceRequest=mICSourceRequest, mICDestinationInterconnect=mICDestinationInterconnect, hgOrderIndex=hgOrderIndex, ecRoot=ecRoot, destRouteTable=destRouteTable, hgSaveRestore=hgSaveRestore, sccOperStatus=sccOperStatus, ecExperimental=ecExperimental, mICSourceLastConnectAttempt=mICSourceLastConnectAttempt, backPlaneIndex=backPlaneIndex, sccDateTime=sccDateTime, hgOutPortList=hgOutPortList, mICSourceConnect=mICSourceConnect, mICDestinationConnect=mICDestinationConnect, mICByteCounterOverflow=mICByteCounterOverflow, srcIndex=srcIndex, mICLinkReady=mICLinkReady, switchObjs=switchObjs, mICSourceInterconnect=mICSourceInterconnect, backPlaneEntry=backPlaneEntry, huntGroupEntry=huntGroupEntry, routesSaveRestore=routesSaveRestore, sourceRouteEntry=sourceRouteEntry, hgOrderList=hgOrderList, mICDestinationRequest=mICDestinationRequest, huntGroupOrderTable=huntGroupOrderTable, hippiSwitchMIB=hippiSwitchMIB, mICConnectsSuccessful=mICConnectsSuccessful, mICNumberOfBytes=mICNumberOfBytes, essentialCommunications=essentialCommunications, destRouteEntry=destRouteEntry)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, constraints_intersection, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint')
(ec_experimental,) = mibBuilder.importSymbols('ESSENTIAL-COMMUNICATIONS-GLOBAL-REG', 'ecExperimental')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(counter32, enterprises, bits, iso, integer32, object_identity, mib_identifier, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, notification_type, counter64, time_ticks, ip_address, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'enterprises', 'Bits', 'iso', 'Integer32', 'ObjectIdentity', 'MibIdentifier', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'NotificationType', 'Counter64', 'TimeTicks', 'IpAddress', 'Unsigned32')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
essential_communications = mib_identifier((1, 3, 6, 1, 4, 1, 2159))
ec_root = mib_identifier((1, 3, 6, 1, 4, 1, 2159, 1))
ec_products = mib_identifier((1, 3, 6, 1, 4, 1, 2159, 1, 3))
ec_experimental = mib_identifier((1, 3, 6, 1, 4, 1, 2159, 1, 6))
hippi_switch_mib = mib_identifier((1, 3, 6, 1, 4, 1, 2159, 1, 6, 1))
hippi_switch_mi_bv103 = mib_identifier((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1))
switch_objs = mib_identifier((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1))
switch_description = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 1), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
switchDescription.setStatus('mandatory')
if mibBuilder.loadTexts:
switchDescription.setDescription('Returns the description, vendor, and version numbers of the switch.')
switch_num_of_ports = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 2), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
switchNumOfPorts.setStatus('mandatory')
if mibBuilder.loadTexts:
switchNumOfPorts.setDescription('The number of slots in this switch. (Max number of media access cards).')
scc_description = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 3), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sccDescription.setStatus('mandatory')
if mibBuilder.loadTexts:
sccDescription.setDescription('The model, vendor, and version number of the switch control card.')
scc_date_time = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 4), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
sccDateTime.setStatus('mandatory')
if mibBuilder.loadTexts:
sccDateTime.setDescription('The date/time in the real time clock. Format: yyyymmddhhmmss.')
scc_admin_status = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('up', 1), ('reset', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
sccAdminStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
sccAdminStatus.setDescription('The desired state of the switch.')
scc_oper_status = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('up', 1), ('reseting', 2), ('busy', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sccOperStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
sccOperStatus.setDescription('The current state of the switch. SNMP operations can not occur when the switch is busy. SNMP operations can not occur when the switch is resetting.')
back_plane_table = mib_table((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7))
if mibBuilder.loadTexts:
backPlaneTable.setStatus('mandatory')
if mibBuilder.loadTexts:
backPlaneTable.setDescription('This table represent all of the slots in a HIPPI switch. None of the rows can be added to or deleted by the user.')
back_plane_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1)).setIndexNames((0, 'ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH', 'backPlaneIndex'))
if mibBuilder.loadTexts:
backPlaneEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
backPlaneEntry.setDescription('A row in the table describing one slot in the switch backplane. ')
back_plane_index = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 1), gauge32())
if mibBuilder.loadTexts:
backPlaneIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
backPlaneIndex.setDescription('The table index for this slot on the backplane.')
back_plane_number = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 2), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
backPlaneNumber.setStatus('mandatory')
if mibBuilder.loadTexts:
backPlaneNumber.setDescription('The slot number as seen printed on the switch (backPlaneIndex + 1)')
back_plane_card = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3))).clone(namedValues=named_values(('none', 0), ('unknown', 1), ('parallel', 2), ('serial', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
backPlaneCard.setStatus('mandatory')
if mibBuilder.loadTexts:
backPlaneCard.setDescription('The type of MIC present in this slot of the backplane on the switch')
m_ic_power_up_init_error = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 4), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICPowerUpInitError.setStatus('mandatory')
if mibBuilder.loadTexts:
mICPowerUpInitError.setDescription('True if error detected by MIC on start-up.')
m_ic_hippi_parity_burst_error = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 5), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICHippiParityBurstError.setStatus('mandatory')
if mibBuilder.loadTexts:
mICHippiParityBurstError.setDescription('Valid the SMIC only. Type of parity error.')
m_ic_link_ready = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 6), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICLinkReady.setStatus('mandatory')
if mibBuilder.loadTexts:
mICLinkReady.setDescription('Valid the SMIC only. True if link ready asserted.')
m_ic_source_interconnect = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 7), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICSourceInterconnect.setStatus('mandatory')
if mibBuilder.loadTexts:
mICSourceInterconnect.setDescription('Source interconnect is valid for the PMIC only.')
m_ic_source_request = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 8), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICSourceRequest.setStatus('mandatory')
if mibBuilder.loadTexts:
mICSourceRequest.setDescription('True if source request is asserted.')
m_ic_source_connect = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 9), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICSourceConnect.setStatus('mandatory')
if mibBuilder.loadTexts:
mICSourceConnect.setDescription('True if source connect is asserted.')
m_ic_source_last_connect_attempt = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 10), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICSourceLastConnectAttempt.setStatus('mandatory')
if mibBuilder.loadTexts:
mICSourceLastConnectAttempt.setDescription('True if last source request was successful.')
m_ic_destination_interconnect = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 11), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICDestinationInterconnect.setStatus('mandatory')
if mibBuilder.loadTexts:
mICDestinationInterconnect.setDescription('True if destination interconnect is asserted.')
m_ic_destination_request = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 12), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICDestinationRequest.setStatus('mandatory')
if mibBuilder.loadTexts:
mICDestinationRequest.setDescription('True if destination request is asserted.')
m_ic_destination_connect = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 13), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICDestinationConnect.setStatus('mandatory')
if mibBuilder.loadTexts:
mICDestinationConnect.setDescription('True if destination connect is asserted.')
m_ic_byte_counter_overflow = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 14), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICByteCounterOverflow.setStatus('mandatory')
if mibBuilder.loadTexts:
mICByteCounterOverflow.setDescription('The number of times the byte counter has over-flowed.')
m_ic_number_of_bytes = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 15), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICNumberOfBytes.setStatus('mandatory')
if mibBuilder.loadTexts:
mICNumberOfBytes.setDescription('The number of bytes that have passed through the MIC.')
m_ic_number_of_packets = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 16), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICNumberOfPackets.setStatus('mandatory')
if mibBuilder.loadTexts:
mICNumberOfPackets.setDescription('The number of times packets has been asserted.')
m_ic_connects_successful = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 17), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mICConnectsSuccessful.setStatus('mandatory')
if mibBuilder.loadTexts:
mICConnectsSuccessful.setDescription('The number of times this MIC has connected since reset.')
source_route_table = mib_table((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8))
if mibBuilder.loadTexts:
sourceRouteTable.setStatus('mandatory')
if mibBuilder.loadTexts:
sourceRouteTable.setDescription('This table holds all of the source routes for this switch. FORMAT: OutputPort InputPortList Status. Output port is 0 to 15 Input port is 0 to 15 List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2. Status is 0 (disabled) or 1 (enabled)')
source_route_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8, 1)).setIndexNames((0, 'ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH', 'srcIndex'))
if mibBuilder.loadTexts:
sourceRouteEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
sourceRouteEntry.setDescription('One row in the source route table.')
src_index = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8, 1, 1), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
srcIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
srcIndex.setDescription('The row number for this row of the table.')
src_route = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
srcRoute.setStatus('mandatory')
if mibBuilder.loadTexts:
srcRoute.setDescription('One source route. FORMAT: OutputPort InputPortList Status. Output port is 0 to 15 Input port is 0 to 15 List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2. Status is 0 (disabled) or 1 (enabled)')
src_write_row = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 9), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
srcWriteRow.setStatus('mandatory')
if mibBuilder.loadTexts:
srcWriteRow.setDescription('Setting this variable alters source routes. FORMAT: OutputPortList InputPortList Status. Output port is 0 to 15 Input port is 0 to 15 List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2. Status is 0 (disabled) or 1 (enabled)')
dest_route_table = mib_table((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10))
if mibBuilder.loadTexts:
destRouteTable.setStatus('mandatory')
if mibBuilder.loadTexts:
destRouteTable.setDescription('This table holds all of destination routes (logical address routes) for this switch. FORMAT: LogicalAddress InputPortList Huntgroup. LogicalAddress is 0 to 4095. Input port is 0 to 15 Huntgroup is 0 to 31. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.')
dest_route_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10, 1)).setIndexNames((0, 'ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH', 'destIndex'))
if mibBuilder.loadTexts:
destRouteEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
destRouteEntry.setDescription('A row in the destination route table.')
dest_index = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10, 1, 1), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
destIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
destIndex.setDescription('The index for this row of the table.')
dest_route = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
destRoute.setStatus('mandatory')
if mibBuilder.loadTexts:
destRoute.setDescription('One Destination Route. FORMAT: LogicalAddress InputPortList Huntgroup. LogicalAddress is 0 to 4095. Input port is 0 to 15. Huntgroup is 0 to 31. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.')
dest_write_row = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 11), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
destWriteRow.setStatus('mandatory')
if mibBuilder.loadTexts:
destWriteRow.setDescription('Setting this variable will alter the desitination routes. FORMAT: LogicalAddressList Huntgroup InputPortList. LogicalAddress is 0 to 4095. Huntgroup is 0 to 31. 31 will disable this route. Input port is 0 to 15. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.')
hunt_group_table = mib_table((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12))
if mibBuilder.loadTexts:
huntGroupTable.setStatus('mandatory')
if mibBuilder.loadTexts:
huntGroupTable.setDescription('This table holds all of the huntgroups for this switch. FORMAT: Huntgroup ( OutportList ) Huntgroup is 0 to 31. OutportList is an orderd list of output ports in Huntgroup.')
hunt_group_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12, 1)).setIndexNames((0, 'ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH', 'hg'))
if mibBuilder.loadTexts:
huntGroupEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
huntGroupEntry.setDescription('A row in the huntgroup table.')
hg = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12, 1, 1), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hg.setStatus('mandatory')
if mibBuilder.loadTexts:
hg.setDescription('The huntgroup number.')
hg_out_port_list = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hgOutPortList.setStatus('mandatory')
if mibBuilder.loadTexts:
hgOutPortList.setDescription('The definition of one Huntgroup. FORMAT: Huntgroup ( OutportList ) Huntgroup is 0 to 31. OutportList is an orderd list of output ports in Huntgroup.')
hg_l_write_row = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 13), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hgLWriteRow.setStatus('mandatory')
if mibBuilder.loadTexts:
hgLWriteRow.setDescription('Setting this variable will alter the huntgroup table by setting every huntgroup in list to include outPortList. FORMAT: HuntgroupList OutportList Huntgroup is 0 to 31. Outport is 0 to 15 and 16. 16 will clear the huntgroup. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.')
hunt_group_order_table = mib_table((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14))
if mibBuilder.loadTexts:
huntGroupOrderTable.setStatus('mandatory')
if mibBuilder.loadTexts:
huntGroupOrderTable.setDescription('This table holds all of the huntgroup order information for this switch. i.e. The order huntgroups are processed in when more than one huntgroup contends for the same output port. FORMAT: OutputPort HuntGroupList OutputPort is 0 to 15. Huntgroup is 0 to 31. List is an ordered list of huntgroups.')
hunt_group_order_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14, 1)).setIndexNames((0, 'ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH', 'hg'))
if mibBuilder.loadTexts:
huntGroupOrderEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
huntGroupOrderEntry.setDescription("One record on an output port's huntgroup priority.")
hg_order_index = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14, 1, 1), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hgOrderIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
hgOrderIndex.setDescription('The backplane slot number containing output port.')
hg_order_list = mib_table_column((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hgOrderList.setStatus('mandatory')
if mibBuilder.loadTexts:
hgOrderList.setDescription("An ordered list of an output port's huntgroup priority. FORMAT: OutputPort HuntGroupList OutputPort is 0 to 15. Huntgroup is 0 to 31. List is an ordered list of huntgroups.")
hg_o_write_row = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 15), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hgOWriteRow.setStatus('mandatory')
if mibBuilder.loadTexts:
hgOWriteRow.setDescription('Setting this variable will alter the huntgroup order table. FORMAT: OutputPort HuntGroupList Output port is 0 to 15. Huntgroup is 0 to 31. Huntgroup must contain output port in its output port list. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.')
hg_save_restore = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 16), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('save', 1), ('restore', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hgSaveRestore.setStatus('mandatory')
if mibBuilder.loadTexts:
hgSaveRestore.setDescription(' Writting a 1 saves all hunt group information on the switch. Writting a 2 restores all hunt group information on the switch.')
routes_save_restore = mib_scalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 17), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('save', 1), ('restore', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
routesSaveRestore.setStatus('mandatory')
if mibBuilder.loadTexts:
routesSaveRestore.setDescription(' Writting a 1 saves all source/destination routes on the switch. Writting a 2 restores all source/destination routes on the switch.')
mibBuilder.exportSymbols('ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH', srcWriteRow=srcWriteRow, hg=hg, hippiSwitchMIBv103=hippiSwitchMIBv103, switchDescription=switchDescription, backPlaneTable=backPlaneTable, mICNumberOfPackets=mICNumberOfPackets, backPlaneNumber=backPlaneNumber, hgLWriteRow=hgLWriteRow, mICPowerUpInitError=mICPowerUpInitError, sccAdminStatus=sccAdminStatus, huntGroupOrderEntry=huntGroupOrderEntry, sccDescription=sccDescription, backPlaneCard=backPlaneCard, huntGroupTable=huntGroupTable, ecProducts=ecProducts, mICHippiParityBurstError=mICHippiParityBurstError, srcRoute=srcRoute, destWriteRow=destWriteRow, switchNumOfPorts=switchNumOfPorts, destRoute=destRoute, sourceRouteTable=sourceRouteTable, destIndex=destIndex, hgOWriteRow=hgOWriteRow, mICSourceRequest=mICSourceRequest, mICDestinationInterconnect=mICDestinationInterconnect, hgOrderIndex=hgOrderIndex, ecRoot=ecRoot, destRouteTable=destRouteTable, hgSaveRestore=hgSaveRestore, sccOperStatus=sccOperStatus, ecExperimental=ecExperimental, mICSourceLastConnectAttempt=mICSourceLastConnectAttempt, backPlaneIndex=backPlaneIndex, sccDateTime=sccDateTime, hgOutPortList=hgOutPortList, mICSourceConnect=mICSourceConnect, mICDestinationConnect=mICDestinationConnect, mICByteCounterOverflow=mICByteCounterOverflow, srcIndex=srcIndex, mICLinkReady=mICLinkReady, switchObjs=switchObjs, mICSourceInterconnect=mICSourceInterconnect, backPlaneEntry=backPlaneEntry, huntGroupEntry=huntGroupEntry, routesSaveRestore=routesSaveRestore, sourceRouteEntry=sourceRouteEntry, hgOrderList=hgOrderList, mICDestinationRequest=mICDestinationRequest, huntGroupOrderTable=huntGroupOrderTable, hippiSwitchMIB=hippiSwitchMIB, mICConnectsSuccessful=mICConnectsSuccessful, mICNumberOfBytes=mICNumberOfBytes, essentialCommunications=essentialCommunications, destRouteEntry=destRouteEntry) |
def ordenada(lista):
ordem = True
for index in range(len(lista)-1):
if lista[index] > lista[index + 1]:
ordem = False
return ordem
| def ordenada(lista):
ordem = True
for index in range(len(lista) - 1):
if lista[index] > lista[index + 1]:
ordem = False
return ordem |
DATA = '../data/articles/'
BUILDINGS = "../data/buildings/"
OUTPUT = '../output/'
PHOTO_LOC = '/Users/elisabethsilver/Box/SIB/photos/'
DATA_FNAME = f"{DATA}uni_data.xlsx"
FMTD_DATA_FNAME = f"{DATA}uni_data_year_formatted.xlsx"
LINK_FNAME = f"{DATA}uni_links.csv"
YEAR_LINK_FNAME = f"{DATA}uni_links_year.csv"
GDRIVE = "/Users/elisabethsilver/Google Drive/Seeing is believing/News article study/2019 Data/"
| data = '../data/articles/'
buildings = '../data/buildings/'
output = '../output/'
photo_loc = '/Users/elisabethsilver/Box/SIB/photos/'
data_fname = f'{DATA}uni_data.xlsx'
fmtd_data_fname = f'{DATA}uni_data_year_formatted.xlsx'
link_fname = f'{DATA}uni_links.csv'
year_link_fname = f'{DATA}uni_links_year.csv'
gdrive = '/Users/elisabethsilver/Google Drive/Seeing is believing/News article study/2019 Data/' |
def generate(env):
env.Replace(
MODE='Release'
)
env.Append(
CPPDEFINES={'RELEASE': None},
CCFLAGS=[
'-O3',
],
)
def exists(env):
return 1
| def generate(env):
env.Replace(MODE='Release')
env.Append(CPPDEFINES={'RELEASE': None}, CCFLAGS=['-O3'])
def exists(env):
return 1 |
def binomial( k, n ):
if n < k or n < 0 or k < 0:
raise ValueError("n > k > 0")
if k == 1 or k == (n-1):
return n
elif k == 0 or k == n:
return 1
return binomial( k, n - 1 ) + binomial( k-1, n-1)
print("( a nad b )")
a = int(input("A = "))
b = int(input("B = "))
print( binomial( b, a ) )
| def binomial(k, n):
if n < k or n < 0 or k < 0:
raise value_error('n > k > 0')
if k == 1 or k == n - 1:
return n
elif k == 0 or k == n:
return 1
return binomial(k, n - 1) + binomial(k - 1, n - 1)
print('( a nad b )')
a = int(input('A = '))
b = int(input('B = '))
print(binomial(b, a)) |
__all__ = ['merge_lists']
# HELPER FUNCTION FOR MERGING LISTS
def merge_lists(*args, **kwargs):
merged = []
for seq in args:
for element in seq:
merged.append(element)
return merged | __all__ = ['merge_lists']
def merge_lists(*args, **kwargs):
merged = []
for seq in args:
for element in seq:
merged.append(element)
return merged |
def tablefy(data, column=None, gutter=1, width=79):
"""
Convert a list of strings into being a table, displaying in a left-to-right
and top-to-bottom pattern. This does not sort the values.
:param data: list of strings
:param column: width of column, if None, detected
:param gutter: width of gutter
:param width: width of entire table to fill
:returns: newline separated string
"""
if not data:
return ""
lines = []
if column is None:
column = max([len(s) for s in data])
per_line = max(int(width / column), 1)
gutter_chars = " " * gutter
items = []
for entry in data:
items.append(entry.ljust(column))
if len(items) == per_line:
lines.append(gutter_chars.join(items))
items = []
if items:
lines.append(gutter_chars.join(items))
return "\n".join(lines)
| def tablefy(data, column=None, gutter=1, width=79):
"""
Convert a list of strings into being a table, displaying in a left-to-right
and top-to-bottom pattern. This does not sort the values.
:param data: list of strings
:param column: width of column, if None, detected
:param gutter: width of gutter
:param width: width of entire table to fill
:returns: newline separated string
"""
if not data:
return ''
lines = []
if column is None:
column = max([len(s) for s in data])
per_line = max(int(width / column), 1)
gutter_chars = ' ' * gutter
items = []
for entry in data:
items.append(entry.ljust(column))
if len(items) == per_line:
lines.append(gutter_chars.join(items))
items = []
if items:
lines.append(gutter_chars.join(items))
return '\n'.join(lines) |
def sockMerchant(n, ar):
ar_no_duplicates = dict.fromkeys(ar)
pairs = 0
for sock in ar_no_duplicates:
ocurrences = ar.count(sock)
print("ocurrences of {} in {} -> {}".format(sock, ar, ocurrences))
if ocurrences % 2 == 0:
pairs += ocurrences / 2
elif ocurrences % 2 == 1 and ocurrences > 2:
pairs += (ocurrences - 1) / 2
return int(pairs)
n = 9
ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
print(sockMerchant(n, ar)) | def sock_merchant(n, ar):
ar_no_duplicates = dict.fromkeys(ar)
pairs = 0
for sock in ar_no_duplicates:
ocurrences = ar.count(sock)
print('ocurrences of {} in {} -> {}'.format(sock, ar, ocurrences))
if ocurrences % 2 == 0:
pairs += ocurrences / 2
elif ocurrences % 2 == 1 and ocurrences > 2:
pairs += (ocurrences - 1) / 2
return int(pairs)
n = 9
ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
print(sock_merchant(n, ar)) |
nome = input()
salfixo = float(input())
qtdvendas = float(input())
bonus = float(qtdvendas * (15/100))
total = salfixo + bonus
print ('TOTAL = R$ %0.2f' %total)
| nome = input()
salfixo = float(input())
qtdvendas = float(input())
bonus = float(qtdvendas * (15 / 100))
total = salfixo + bonus
print('TOTAL = R$ %0.2f' % total) |
def gcd(a,b):
if b==0:
return a
return gcd(b,a%b)
print(gcd(5,20))
| def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(gcd(5, 20)) |
#!/usr/bin/env python
if __name__== '__main__':
#set help message
help = """
Usage: help
TOOLS:
=== Help ===
./help.py [[this file]]
=== Generate results and plot ===
./run_1.py [[Do 1 run. Input conf file. Output rundir w/ csv and dbs.]]
./plot_1.py [[Plot results from 1 run. Input csv. Output pngs.]]
./showstats.py [[Show performance statistics for a run]]
Example flow: see bottom
=== Running tests ===
pytest [[run all tests]]
pytest engine/ [[run all tests in engine/ directory]]
pytest tests/test_foo.py [[run a single pytest-based test file]]
pytest tests/test_foo.py::test_foobar [[run a single pytest-based test]]
=== Config files, with params to change ===
-System parameters: ~/tokenspice.conf
-Logging: ./logging.conf
== Example flow ==
rm -rf outdir_csv; ./run_1.py 10 outdir_csv 1>out.txt 2>&1 &
tail -f out.txt
rm -rf outdir_png; ./plot_1.py outdir_csv outdir_png
eog outdir_png
"""
print(help)
| if __name__ == '__main__':
help = '\nUsage: help \n\nTOOLS: \n\n === Help ===\n ./help.py [[this file]]\n\n === Generate results and plot ===\n ./run_1.py [[Do 1 run. Input conf file. Output rundir w/ csv and dbs.]]\n ./plot_1.py [[Plot results from 1 run. Input csv. Output pngs.]]\n ./showstats.py [[Show performance statistics for a run]]\n Example flow: see bottom\n\n === Running tests === \n pytest [[run all tests]]\n pytest engine/ [[run all tests in engine/ directory]]\n pytest tests/test_foo.py [[run a single pytest-based test file]]\n pytest tests/test_foo.py::test_foobar [[run a single pytest-based test]]\n\n === Config files, with params to change === \n -System parameters: ~/tokenspice.conf\n -Logging: ./logging.conf\n\n == Example flow ==\n rm -rf outdir_csv; ./run_1.py 10 outdir_csv 1>out.txt 2>&1 &\n tail -f out.txt\n rm -rf outdir_png; ./plot_1.py outdir_csv outdir_png\n eog outdir_png\n'
print(help) |
class Lift:
def __init__(self, name, lift_type, status, sector):
self.name = name
self.lift_type = lift_type
self.status = status
self.sector = sector
def __str__(self):
return self.name + " " + self.lift_type + " " + self.status + " " + self.sector
| class Lift:
def __init__(self, name, lift_type, status, sector):
self.name = name
self.lift_type = lift_type
self.status = status
self.sector = sector
def __str__(self):
return self.name + ' ' + self.lift_type + ' ' + self.status + ' ' + self.sector |
class Constants:
j_title_list = [
'Journal of Academy of Marketing Science',
'Journal of Marketing',
'Journal of Marketing Research',
'Marketing Science',
'Management Science',
'Administrative Science Quarterly',
'Academy of Management Journal',
'Academy of Management Review']
journal_keys = [
'-JAMS-',
'-JM-',
'-JMR-',
'-MKTSC-',
'-MGMTSC-',
'-ASQ-',
'-AOMJ-',
'-AOMR-']
journal_abbrv_list = [
'jams',
'jm',
'jmr',
'mktsc',
'mgmtsc',
'asq',
'aomj',
'aomr']
j_title_dict = {
# marketing journals
'jams': 'Journal of Academy of Marketing Science',
'jm': 'Journal of Marketing',
'jmr': 'Journal of Marketing Research',
'mktsc': 'Marketing Science',
'mgmtsc': 'Management Science',
# management journals
'asq':'Administrative Science Quarterly',
'aomj':'Academy of Management Journal',
'aomr':'Academy of Management Review'}
base_url_dict = {
# marketing journals
'jm': 'https://journals.sagepub.com/action/doSearch?&publication=jmxa',
'jmr': 'https://journals.sagepub.com/action/doSearch?&publication=mrja',
'mktsc': 'https://pubsonline.informs.org/action/doSearch?&publication[]=mksc',
'mgmtsc': 'https://pubsonline.informs.org/action/doSearch?&publication[]=mnsc',
'jams': 'https://link.springer.com/search?search-within=Journal&facet-journal-id=11747',
# management journals
'aomj': 'https://journals.aom.org/action/doSearch?&publication[]=amj',
'aomr': 'https://journals.aom.org/action/doSearch?&publication[]=amr',
'asq': 'https://journals.sagepub.com/action/doSearch?&publication=asqa'} | class Constants:
j_title_list = ['Journal of Academy of Marketing Science', 'Journal of Marketing', 'Journal of Marketing Research', 'Marketing Science', 'Management Science', 'Administrative Science Quarterly', 'Academy of Management Journal', 'Academy of Management Review']
journal_keys = ['-JAMS-', '-JM-', '-JMR-', '-MKTSC-', '-MGMTSC-', '-ASQ-', '-AOMJ-', '-AOMR-']
journal_abbrv_list = ['jams', 'jm', 'jmr', 'mktsc', 'mgmtsc', 'asq', 'aomj', 'aomr']
j_title_dict = {'jams': 'Journal of Academy of Marketing Science', 'jm': 'Journal of Marketing', 'jmr': 'Journal of Marketing Research', 'mktsc': 'Marketing Science', 'mgmtsc': 'Management Science', 'asq': 'Administrative Science Quarterly', 'aomj': 'Academy of Management Journal', 'aomr': 'Academy of Management Review'}
base_url_dict = {'jm': 'https://journals.sagepub.com/action/doSearch?&publication=jmxa', 'jmr': 'https://journals.sagepub.com/action/doSearch?&publication=mrja', 'mktsc': 'https://pubsonline.informs.org/action/doSearch?&publication[]=mksc', 'mgmtsc': 'https://pubsonline.informs.org/action/doSearch?&publication[]=mnsc', 'jams': 'https://link.springer.com/search?search-within=Journal&facet-journal-id=11747', 'aomj': 'https://journals.aom.org/action/doSearch?&publication[]=amj', 'aomr': 'https://journals.aom.org/action/doSearch?&publication[]=amr', 'asq': 'https://journals.sagepub.com/action/doSearch?&publication=asqa'} |
def factorial(n):
if n==1 or n==0:
return 1
return n*factorial(n-1)
| def factorial(n):
if n == 1 or n == 0:
return 1
return n * factorial(n - 1) |
# Code listing #10
""" Module A (a.py) - Implement functions that operate on series of numbers """
# Note this is version 1 of a.py so called a1.py
def squares(narray):
""" Return array of squares of numbers """
return pow_n(narray, 2)
def cubes(narray):
""" Return array of cubes of numbers """
return pow_n(narray, 3)
def pow_n(narray, n):
""" Return array of numbers raised to arbitrary power n each """
return [pow(x, n) for x in narray]
def frequency(string, word):
""" Find the frequency of occurrences of word in string
as percentage """
word_l = word.lower()
string_l = string.lower()
# Words in string
count = string_l.count(word_l)
# Return frequency as percentage
return 100.0*count/len(string_l)
| """ Module A (a.py) - Implement functions that operate on series of numbers """
def squares(narray):
""" Return array of squares of numbers """
return pow_n(narray, 2)
def cubes(narray):
""" Return array of cubes of numbers """
return pow_n(narray, 3)
def pow_n(narray, n):
""" Return array of numbers raised to arbitrary power n each """
return [pow(x, n) for x in narray]
def frequency(string, word):
""" Find the frequency of occurrences of word in string
as percentage """
word_l = word.lower()
string_l = string.lower()
count = string_l.count(word_l)
return 100.0 * count / len(string_l) |
app = Flask(__name__)
api = Api(app)
index = RetrievalIndex()
class BuildIndex(Resource):
def post(self):
request_body = json.loads(request.data)
user_id = request_body["user_id"]
image_hashes = request_body["image_hashes"]
image_embeddings = request_body["image_embeddings"]
index.build_index_for_user(user_id, image_hashes, image_embeddings)
return jsonify({"status": True, "index_size": index.indices[user_id].ntotal})
class SearchIndex(Resource):
def post(self):
try:
request_body = json.loads(request.data)
user_id = request_body["user_id"]
image_embedding = request_body["image_embedding"]
if "n" in request_body.keys():
n = int(request_body["n"])
else:
n = 100
res = index.search_similar(user_id, image_embedding, n)
return jsonify({"status": True, "result": res})
except BaseException as e:
logger.error(str(e))
return jsonify({"status": False, "result": []}, status=500)
api.add_resource(BuildIndex, "/build/")
api.add_resource(SearchIndex, "/search/")
if __name__ == "__main__":
logger.info("starting server")
server = WSGIServer(("0.0.0.0", 8002), app)
server_thread = gevent.spawn(server.serve_forever)
gevent.joinall([server_thread]) | app = flask(__name__)
api = api(app)
index = retrieval_index()
class Buildindex(Resource):
def post(self):
request_body = json.loads(request.data)
user_id = request_body['user_id']
image_hashes = request_body['image_hashes']
image_embeddings = request_body['image_embeddings']
index.build_index_for_user(user_id, image_hashes, image_embeddings)
return jsonify({'status': True, 'index_size': index.indices[user_id].ntotal})
class Searchindex(Resource):
def post(self):
try:
request_body = json.loads(request.data)
user_id = request_body['user_id']
image_embedding = request_body['image_embedding']
if 'n' in request_body.keys():
n = int(request_body['n'])
else:
n = 100
res = index.search_similar(user_id, image_embedding, n)
return jsonify({'status': True, 'result': res})
except BaseException as e:
logger.error(str(e))
return jsonify({'status': False, 'result': []}, status=500)
api.add_resource(BuildIndex, '/build/')
api.add_resource(SearchIndex, '/search/')
if __name__ == '__main__':
logger.info('starting server')
server = wsgi_server(('0.0.0.0', 8002), app)
server_thread = gevent.spawn(server.serve_forever)
gevent.joinall([server_thread]) |
# ###########################################################
# ## generate menu
# ###########################################################
_a = request.application
_c = request.controller
_f = request.function
response.title = '%s %s' % (_f, '/'.join(request.args))
response.subtitle = 'admin'
response.menu = [(T('Site'), _f == 'site', URL(_a, 'default', 'site'))]
if request.vars.app or request.args:
_t = request.vars.app or request.args[0]
response.menu.append((T('Edit'), _c == 'default' and _f == 'design',
URL(_a, 'default', 'design', args=_t)))
response.menu.append((T('About'), _c == 'default' and _f == 'about',
URL(_a, 'default', 'about', args=_t, )))
response.menu.append((T('Errors'), _c == 'default' and _f == 'errors',
URL(_a, 'default', 'errors', args=_t)))
response.menu.append((T('Versioning'),
_c == 'mercurial' and _f == 'commit',
URL(_a, 'mercurial', 'commit', args=_t)))
if os.path.exists('applications/examples'):
response.menu.append(
(T('Help'), False, URL('examples', 'default', 'documentation')))
else:
response.menu.append((T('Help'), False, 'http://web2py.com/examples/default/documentation'))
if not session.authorized:
response.menu = [(T('Login'), True, URL('site'))]
else:
response.menu.append((T('Logout'), False,
URL(_a, 'default', f='logout')))
response.menu.append((T('Debug'), False,
URL(_a, 'debug', 'interact')))
| _a = request.application
_c = request.controller
_f = request.function
response.title = '%s %s' % (_f, '/'.join(request.args))
response.subtitle = 'admin'
response.menu = [(t('Site'), _f == 'site', url(_a, 'default', 'site'))]
if request.vars.app or request.args:
_t = request.vars.app or request.args[0]
response.menu.append((t('Edit'), _c == 'default' and _f == 'design', url(_a, 'default', 'design', args=_t)))
response.menu.append((t('About'), _c == 'default' and _f == 'about', url(_a, 'default', 'about', args=_t)))
response.menu.append((t('Errors'), _c == 'default' and _f == 'errors', url(_a, 'default', 'errors', args=_t)))
response.menu.append((t('Versioning'), _c == 'mercurial' and _f == 'commit', url(_a, 'mercurial', 'commit', args=_t)))
if os.path.exists('applications/examples'):
response.menu.append((t('Help'), False, url('examples', 'default', 'documentation')))
else:
response.menu.append((t('Help'), False, 'http://web2py.com/examples/default/documentation'))
if not session.authorized:
response.menu = [(t('Login'), True, url('site'))]
else:
response.menu.append((t('Logout'), False, url(_a, 'default', f='logout')))
response.menu.append((t('Debug'), False, url(_a, 'debug', 'interact'))) |
BASE = r"""Export of Github issues for [{repo_name}]({repo_url}).{datestring}
{issues}
"""
ISSUE = r"""# [\#{number}]({url}) `{state}`: {title}
{labels}
#### [{author}]({author_url}) opened issue at [{date}]({url}):
{body}
{comments}
<div style="page-break-after: always;"></div>
"""
COMMENT = r"""#### [{author}]({author_url}) commented at [{date}]({url}):
{body}
"""
ISSUE_FILE_FOOTNOTE = r"""
[Export of Github issue for [{repo_name}]({repo_url}).{datestring}]
"""
| base = 'Export of Github issues for [{repo_name}]({repo_url}).{datestring}\n\n{issues}\n'
issue = '# [\\#{number}]({url}) `{state}`: {title}\n{labels}\n#### [{author}]({author_url}) opened issue at [{date}]({url}):\n\n{body}\n\n{comments}\n<div style="page-break-after: always;"></div>\n'
comment = '#### [{author}]({author_url}) commented at [{date}]({url}):\n\n{body}\n'
issue_file_footnote = '\n\n[Export of Github issue for [{repo_name}]({repo_url}).{datestring}]\n' |
"""Base
Base Package
more description
"""
| """Base
Base Package
more description
""" |
class ReverseProxied(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
print(environ)
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
environ['SCRIPT_NAME'] = script_name
path_info = environ['PATH_INFO']
if path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):]
scheme = environ.get('HTTP_X_SCHEME', '')
if scheme:
environ['wsgi.url_scheme'] = scheme
return self.app(environ, start_response) | class Reverseproxied(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
print(environ)
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
environ['SCRIPT_NAME'] = script_name
path_info = environ['PATH_INFO']
if path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):]
scheme = environ.get('HTTP_X_SCHEME', '')
if scheme:
environ['wsgi.url_scheme'] = scheme
return self.app(environ, start_response) |
"""
Package for the application.
"""
#from .graficoLinhaTempo import PlotGraphTimeLineBar
#from .DataFrameUtil import SumRows
#from .DataFrameUtil import RenameCols | """
Package for the application.
""" |
print("first string" + ", " + "second string")
print(str(1) + "2" + "3" + "4")
print("spam" * 3)
print(4 * "2")
print("Love" * 0)
print("7" * 3)
# 1 + "2" + 3 -- TypeError
# "4" * "2" -- TypeError
# "Python is fun" * 7.0 -- TypeError
| print('first string' + ', ' + 'second string')
print(str(1) + '2' + '3' + '4')
print('spam' * 3)
print(4 * '2')
print('Love' * 0)
print('7' * 3) |
f = open("all.txt")
s = f.readlines();
f.close()
fout = open("allout1.txt", 'w')
o = []
outPath = 'S:\\BACKUP!!!\\WD\\L\\Canon\\All\\'
quote = "\""
for x in s:
#x.replace('\\', '\\\\')
#print(x)
#if x.rfind('MVI') > -1: ix = x.rindex('MVI');
x = x.strip();
if x.rfind('MVI') > -1: ix = x.rindex('MVI');
else: ix = -1
if x.rfind('THM') > -1: ix = -1
fn = x[ix:]
#if ix != None: fn = x[ix:]
#else: fn = "NONE"
#if (x.rfind("avi")): o = o + ["VirtualDub.Open(" + x + "); " + "VirtualDub.SaveAVI(" + outPath + fn + ");\n" ]
if ix != -1:
#if (x.rfind("avi")): so = "VirtualDub.Open(\"" + x + "\"" + "); VirtualDub.SaveAVI(" + quote + outPath + fn + quote + ");"
if (x.rfind("avi")): so = "VirtualDub.Open(" + quote + x + quote + "); VirtualDub.SaveAVI(" + quote + outPath + fn + quote + ");" + "\r\n";
print(so)
fout.write(so)
fout.close();
#print(o)
| f = open('all.txt')
s = f.readlines()
f.close()
fout = open('allout1.txt', 'w')
o = []
out_path = 'S:\\BACKUP!!!\\WD\\L\\Canon\\All\\'
quote = '"'
for x in s:
x = x.strip()
if x.rfind('MVI') > -1:
ix = x.rindex('MVI')
else:
ix = -1
if x.rfind('THM') > -1:
ix = -1
fn = x[ix:]
if ix != -1:
if x.rfind('avi'):
so = 'VirtualDub.Open(' + quote + x + quote + '); VirtualDub.SaveAVI(' + quote + outPath + fn + quote + ');' + '\r\n'
print(so)
fout.write(so)
fout.close() |
class Solution:
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0:
return 0
count = 0
n = len(nums)
d = {}
for i in range(n):
d[nums[i]] = i
for i in range(n):
if nums[i] + k in d.keys() and d[nums[i] + k] != i:
count += 1
d.pop(nums[i] + k, 0)
return count
if __name__ == '__main__':
solution = Solution()
print(solution.findPairs([3, 1, 4, 1, 5], 2))
print(solution.findPairs([2, 3, 4, 5, 1], 1))
print(solution.findPairs([1, 3, 1, 5, 4], 0))
print(solution.findPairs([1, 1, 1, 2, 1], 1))
print(solution.findPairs([1, 1, 1, 2, 2], 0))
print(solution.findPairs([-1, -2, -3], 1))
else:
pass
| class Solution:
def find_pairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0:
return 0
count = 0
n = len(nums)
d = {}
for i in range(n):
d[nums[i]] = i
for i in range(n):
if nums[i] + k in d.keys() and d[nums[i] + k] != i:
count += 1
d.pop(nums[i] + k, 0)
return count
if __name__ == '__main__':
solution = solution()
print(solution.findPairs([3, 1, 4, 1, 5], 2))
print(solution.findPairs([2, 3, 4, 5, 1], 1))
print(solution.findPairs([1, 3, 1, 5, 4], 0))
print(solution.findPairs([1, 1, 1, 2, 1], 1))
print(solution.findPairs([1, 1, 1, 2, 2], 0))
print(solution.findPairs([-1, -2, -3], 1))
else:
pass |
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
class weakdict(dict): # noqa: D101
__slots__ = ("__weakref__",)
def optional_square(number: int = 5) -> int: # noqa
"""
Square `number`.
The function from Modin.
Parameters
----------
number : int
Some number.
Notes
-----
The `optional_square` Modin function from modin/scripts/examples.py.
"""
return number ** 2
def optional_square_empty_parameters(number: int = 5) -> int:
"""
Parameters
----------
"""
return number ** 2
def square_summary(number: int) -> int: # noqa: D103, GL08
"""
Square `number`.
Examples
--------
The function that will never be used in modin.pandas.DataFrame same as in
Pandas or Numpy.
"""
return number ** 2
| class Weakdict(dict):
__slots__ = ('__weakref__',)
def optional_square(number: int=5) -> int:
"""
Square `number`.
The function from Modin.
Parameters
----------
number : int
Some number.
Notes
-----
The `optional_square` Modin function from modin/scripts/examples.py.
"""
return number ** 2
def optional_square_empty_parameters(number: int=5) -> int:
"""
Parameters
----------
"""
return number ** 2
def square_summary(number: int) -> int:
"""
Square `number`.
Examples
--------
The function that will never be used in modin.pandas.DataFrame same as in
Pandas or Numpy.
"""
return number ** 2 |
class _FieldInfo:
""" Exposes the public members of the System.Reflection.FieldInfo class to unmanaged code. """
def Equals(self,other):
"""
Equals(self: _FieldInfo,other: object) -> bool
Provides COM objects with version-independent access to the System.Object.Equals(System.Object)
method.
other: The System.Object to compare with the current System.Object.
Returns: true if the specified System.Object is equal to the current System.Object; otherwise,false.
"""
pass
def GetCustomAttributes(self,*__args):
"""
GetCustomAttributes(self: _FieldInfo,inherit: bool) -> Array[object]
Provides COM objects with version-independent access to the
System.Reflection.MemberInfo.GetCustomAttributes(System.Boolean) method.
inherit: Specifies whether to search this member's inheritance chain to find the attributes.
Returns: An array that contains all the custom attributes,or an array with zero elements if no
attributes are defined.
GetCustomAttributes(self: _FieldInfo,attributeType: Type,inherit: bool) -> Array[object]
Provides COM objects with version-independent access to the
System.Reflection.MemberInfo.GetCustomAttributes(System.Type,System.Boolean) method.
attributeType: The type of attribute to search for. Only attributes that are assignable to this type are
returned.
inherit: Specifies whether to search this member's inheritance chain to find the attributes.
Returns: An array of custom attributes applied to this member,or an array with zero (0) elements if no
attributes have been applied.
"""
pass
def GetHashCode(self):
"""
GetHashCode(self: _FieldInfo) -> int
Provides COM objects with version-independent access to the System.Object.GetHashCode method.
Returns: The hash code for the current instance.
"""
pass
def GetIDsOfNames(self,riid,rgszNames,cNames,lcid,rgDispId):
"""
GetIDsOfNames(self: _FieldInfo,riid: Guid,rgszNames: IntPtr,cNames: UInt32,lcid: UInt32,rgDispId: IntPtr) -> Guid
Maps a set of names to a corresponding set of dispatch identifiers.
riid: Reserved for future use. Must be IID_NULL.
rgszNames: Passed-in array of names to be mapped.
cNames: Count of the names to be mapped.
lcid: The locale context in which to interpret the names.
rgDispId: Caller-allocated array that receives the IDs corresponding to the names.
"""
pass
def GetType(self):
"""
GetType(self: _FieldInfo) -> Type
Provides COM objects with version-independent access to the System.Object.GetType method.
Returns: A System.Type object.
"""
pass
def GetTypeInfo(self,iTInfo,lcid,ppTInfo):
"""
GetTypeInfo(self: _FieldInfo,iTInfo: UInt32,lcid: UInt32,ppTInfo: IntPtr)
Retrieves the type information for an object,which can then be used to get the type information
for an interface.
iTInfo: The type information to return.
lcid: The locale identifier for the type information.
ppTInfo: Receives a pointer to the requested type information object.
"""
pass
def GetTypeInfoCount(self,pcTInfo):
"""
GetTypeInfoCount(self: _FieldInfo) -> UInt32
Retrieves the number of type information interfaces that an object provides (either 0 or 1).
"""
pass
def GetValue(self,obj):
"""
GetValue(self: _FieldInfo,obj: object) -> object
Provides COM objects with version-independent access to the
System.Reflection.FieldInfo.GetValue(System.Object) method.
obj: The object whose field value will be returned.
Returns: An object containing the value of the field reflected by this instance.
"""
pass
def GetValueDirect(self,obj):
"""
GetValueDirect(self: _FieldInfo,obj: TypedReference) -> object
Provides COM objects with version-independent access to the
System.Reflection.FieldInfo.GetValueDirect(System.TypedReference) method.
obj: A System.TypedReference structure that encapsulates a managed pointer to a location and a
runtime representation of the type that might be stored at that location.
Returns: An System.Object containing a field value.
"""
pass
def Invoke(self,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr):
"""
Invoke(self: _FieldInfo,dispIdMember: UInt32,riid: Guid,lcid: UInt32,wFlags: Int16,pDispParams: IntPtr,pVarResult: IntPtr,pExcepInfo: IntPtr,puArgErr: IntPtr) -> Guid
Provides access to properties and methods exposed by an object.
dispIdMember: Identifies the member.
riid: Reserved for future use. Must be IID_NULL.
lcid: The locale context in which to interpret arguments.
wFlags: Flags describing the context of the call.
pDispParams: Pointer to a structure containing an array of arguments,an array of argument DISPIDs for named
arguments,and counts for the number of elements in the arrays.
pVarResult: Pointer to the location where the result is to be stored.
pExcepInfo: Pointer to a structure that contains exception information.
puArgErr: The index of the first argument that has an error.
"""
pass
def IsDefined(self,attributeType,inherit):
"""
IsDefined(self: _FieldInfo,attributeType: Type,inherit: bool) -> bool
Provides COM objects with version-independent access to the
System.Reflection.MemberInfo.IsDefined(System.Type,System.Boolean) method.
attributeType: The System.Type object to which the custom attributes are applied.
inherit: Specifies whether to search this member's inheritance chain to find the attributes.
Returns: true if one or more instance of attributeType is applied to this member; otherwise,false.
"""
pass
def SetValue(self,obj,value,invokeAttr=None,binder=None,culture=None):
"""
SetValue(self: _FieldInfo,obj: object,value: object)
Provides COM objects with version-independent access to the
System.Reflection.FieldInfo.SetValue(System.Object,System.Object) method.
obj: The object whose field value will be set.
value: The value to assign to the field.
SetValue(self: _FieldInfo,obj: object,value: object,invokeAttr: BindingFlags,binder: Binder,culture: CultureInfo)
Provides COM objects with version-independent access to the
System.Reflection.PropertyInfo.SetValue(System.Object,System.Object,System.Reflection.BindingFlag
s,System.Reflection.Binder,System.Object[],System.Globalization.CultureInfo) method.
obj: The object whose field value will be set.
value: The value to assign to the field.
invokeAttr: A field of System.Reflection.Binder that specifies the type of binding that is desired (for
example,Binder.CreateInstance or Binder.ExactBinding).
binder: A set of properties that enables the binding,coercion of argument types,and invocation of
members through reflection. If binder is null,then Binder.DefaultBinding is used.
culture: The software preferences of a particular culture.
"""
pass
def SetValueDirect(self,obj,value):
"""
SetValueDirect(self: _FieldInfo,obj: TypedReference,value: object)
Provides COM objects with version-independent access to the
System.Reflection.FieldInfo.SetValueDirect(System.TypedReference,System.Object) method.
obj: The object whose field value will be set.
value: The value to assign to the field.
"""
pass
def ToString(self):
"""
ToString(self: _FieldInfo) -> str
Provides COM objects with version-independent access to the System.Object.ToString method.
Returns: A string that represents the current System.Object.
"""
pass
def __eq__(self,*args):
""" x.__eq__(y) <==> x==y """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __str__(self,*args):
pass
Attributes=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.Attributes property.
Get: Attributes(self: _FieldInfo) -> FieldAttributes
"""
DeclaringType=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.MemberInfo.DeclaringType property.
Get: DeclaringType(self: _FieldInfo) -> Type
"""
FieldHandle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.FieldHandle property.
Get: FieldHandle(self: _FieldInfo) -> RuntimeFieldHandle
"""
FieldType=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.FieldType property.
Get: FieldType(self: _FieldInfo) -> Type
"""
IsAssembly=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsAssembly property.
Get: IsAssembly(self: _FieldInfo) -> bool
"""
IsFamily=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsFamily property.
Get: IsFamily(self: _FieldInfo) -> bool
"""
IsFamilyAndAssembly=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsFamilyAndAssembly property.
Get: IsFamilyAndAssembly(self: _FieldInfo) -> bool
"""
IsFamilyOrAssembly=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsFamilyOrAssembly property.
Get: IsFamilyOrAssembly(self: _FieldInfo) -> bool
"""
IsInitOnly=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsInitOnly property.
Get: IsInitOnly(self: _FieldInfo) -> bool
"""
IsLiteral=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsLiteral property.
Get: IsLiteral(self: _FieldInfo) -> bool
"""
IsNotSerialized=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsNotSerialized property.
Get: IsNotSerialized(self: _FieldInfo) -> bool
"""
IsPinvokeImpl=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsPinvokeImpl property.
Get: IsPinvokeImpl(self: _FieldInfo) -> bool
"""
IsPrivate=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsPrivate property.
Get: IsPrivate(self: _FieldInfo) -> bool
"""
IsPublic=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsPublic property.
Get: IsPublic(self: _FieldInfo) -> bool
"""
IsSpecialName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsSpecialName property.
Get: IsSpecialName(self: _FieldInfo) -> bool
"""
IsStatic=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsStatic property.
Get: IsStatic(self: _FieldInfo) -> bool
"""
MemberType=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.FieldInfo.MemberType property.
Get: MemberType(self: _FieldInfo) -> MemberTypes
"""
Name=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.MemberInfo.Name property.
Get: Name(self: _FieldInfo) -> str
"""
ReflectedType=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Provides COM objects with version-independent access to the System.Reflection.MemberInfo.ReflectedType property.
Get: ReflectedType(self: _FieldInfo) -> Type
"""
| class _Fieldinfo:
""" Exposes the public members of the System.Reflection.FieldInfo class to unmanaged code. """
def equals(self, other):
"""
Equals(self: _FieldInfo,other: object) -> bool
Provides COM objects with version-independent access to the System.Object.Equals(System.Object)
method.
other: The System.Object to compare with the current System.Object.
Returns: true if the specified System.Object is equal to the current System.Object; otherwise,false.
"""
pass
def get_custom_attributes(self, *__args):
"""
GetCustomAttributes(self: _FieldInfo,inherit: bool) -> Array[object]
Provides COM objects with version-independent access to the
System.Reflection.MemberInfo.GetCustomAttributes(System.Boolean) method.
inherit: Specifies whether to search this member's inheritance chain to find the attributes.
Returns: An array that contains all the custom attributes,or an array with zero elements if no
attributes are defined.
GetCustomAttributes(self: _FieldInfo,attributeType: Type,inherit: bool) -> Array[object]
Provides COM objects with version-independent access to the
System.Reflection.MemberInfo.GetCustomAttributes(System.Type,System.Boolean) method.
attributeType: The type of attribute to search for. Only attributes that are assignable to this type are
returned.
inherit: Specifies whether to search this member's inheritance chain to find the attributes.
Returns: An array of custom attributes applied to this member,or an array with zero (0) elements if no
attributes have been applied.
"""
pass
def get_hash_code(self):
"""
GetHashCode(self: _FieldInfo) -> int
Provides COM objects with version-independent access to the System.Object.GetHashCode method.
Returns: The hash code for the current instance.
"""
pass
def get_i_ds_of_names(self, riid, rgszNames, cNames, lcid, rgDispId):
"""
GetIDsOfNames(self: _FieldInfo,riid: Guid,rgszNames: IntPtr,cNames: UInt32,lcid: UInt32,rgDispId: IntPtr) -> Guid
Maps a set of names to a corresponding set of dispatch identifiers.
riid: Reserved for future use. Must be IID_NULL.
rgszNames: Passed-in array of names to be mapped.
cNames: Count of the names to be mapped.
lcid: The locale context in which to interpret the names.
rgDispId: Caller-allocated array that receives the IDs corresponding to the names.
"""
pass
def get_type(self):
"""
GetType(self: _FieldInfo) -> Type
Provides COM objects with version-independent access to the System.Object.GetType method.
Returns: A System.Type object.
"""
pass
def get_type_info(self, iTInfo, lcid, ppTInfo):
"""
GetTypeInfo(self: _FieldInfo,iTInfo: UInt32,lcid: UInt32,ppTInfo: IntPtr)
Retrieves the type information for an object,which can then be used to get the type information
for an interface.
iTInfo: The type information to return.
lcid: The locale identifier for the type information.
ppTInfo: Receives a pointer to the requested type information object.
"""
pass
def get_type_info_count(self, pcTInfo):
"""
GetTypeInfoCount(self: _FieldInfo) -> UInt32
Retrieves the number of type information interfaces that an object provides (either 0 or 1).
"""
pass
def get_value(self, obj):
"""
GetValue(self: _FieldInfo,obj: object) -> object
Provides COM objects with version-independent access to the
System.Reflection.FieldInfo.GetValue(System.Object) method.
obj: The object whose field value will be returned.
Returns: An object containing the value of the field reflected by this instance.
"""
pass
def get_value_direct(self, obj):
"""
GetValueDirect(self: _FieldInfo,obj: TypedReference) -> object
Provides COM objects with version-independent access to the
System.Reflection.FieldInfo.GetValueDirect(System.TypedReference) method.
obj: A System.TypedReference structure that encapsulates a managed pointer to a location and a
runtime representation of the type that might be stored at that location.
Returns: An System.Object containing a field value.
"""
pass
def invoke(self, dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr):
"""
Invoke(self: _FieldInfo,dispIdMember: UInt32,riid: Guid,lcid: UInt32,wFlags: Int16,pDispParams: IntPtr,pVarResult: IntPtr,pExcepInfo: IntPtr,puArgErr: IntPtr) -> Guid
Provides access to properties and methods exposed by an object.
dispIdMember: Identifies the member.
riid: Reserved for future use. Must be IID_NULL.
lcid: The locale context in which to interpret arguments.
wFlags: Flags describing the context of the call.
pDispParams: Pointer to a structure containing an array of arguments,an array of argument DISPIDs for named
arguments,and counts for the number of elements in the arrays.
pVarResult: Pointer to the location where the result is to be stored.
pExcepInfo: Pointer to a structure that contains exception information.
puArgErr: The index of the first argument that has an error.
"""
pass
def is_defined(self, attributeType, inherit):
"""
IsDefined(self: _FieldInfo,attributeType: Type,inherit: bool) -> bool
Provides COM objects with version-independent access to the
System.Reflection.MemberInfo.IsDefined(System.Type,System.Boolean) method.
attributeType: The System.Type object to which the custom attributes are applied.
inherit: Specifies whether to search this member's inheritance chain to find the attributes.
Returns: true if one or more instance of attributeType is applied to this member; otherwise,false.
"""
pass
def set_value(self, obj, value, invokeAttr=None, binder=None, culture=None):
"""
SetValue(self: _FieldInfo,obj: object,value: object)
Provides COM objects with version-independent access to the
System.Reflection.FieldInfo.SetValue(System.Object,System.Object) method.
obj: The object whose field value will be set.
value: The value to assign to the field.
SetValue(self: _FieldInfo,obj: object,value: object,invokeAttr: BindingFlags,binder: Binder,culture: CultureInfo)
Provides COM objects with version-independent access to the
System.Reflection.PropertyInfo.SetValue(System.Object,System.Object,System.Reflection.BindingFlag
s,System.Reflection.Binder,System.Object[],System.Globalization.CultureInfo) method.
obj: The object whose field value will be set.
value: The value to assign to the field.
invokeAttr: A field of System.Reflection.Binder that specifies the type of binding that is desired (for
example,Binder.CreateInstance or Binder.ExactBinding).
binder: A set of properties that enables the binding,coercion of argument types,and invocation of
members through reflection. If binder is null,then Binder.DefaultBinding is used.
culture: The software preferences of a particular culture.
"""
pass
def set_value_direct(self, obj, value):
"""
SetValueDirect(self: _FieldInfo,obj: TypedReference,value: object)
Provides COM objects with version-independent access to the
System.Reflection.FieldInfo.SetValueDirect(System.TypedReference,System.Object) method.
obj: The object whose field value will be set.
value: The value to assign to the field.
"""
pass
def to_string(self):
"""
ToString(self: _FieldInfo) -> str
Provides COM objects with version-independent access to the System.Object.ToString method.
Returns: A string that represents the current System.Object.
"""
pass
def __eq__(self, *args):
""" x.__eq__(y) <==> x==y """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __str__(self, *args):
pass
attributes = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.Attributes property.\n\n\n\nGet: Attributes(self: _FieldInfo) -> FieldAttributes\n\n\n\n'
declaring_type = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.MemberInfo.DeclaringType property.\n\n\n\nGet: DeclaringType(self: _FieldInfo) -> Type\n\n\n\n'
field_handle = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.FieldHandle property.\n\n\n\nGet: FieldHandle(self: _FieldInfo) -> RuntimeFieldHandle\n\n\n\n'
field_type = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.FieldType property.\n\n\n\nGet: FieldType(self: _FieldInfo) -> Type\n\n\n\n'
is_assembly = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsAssembly property.\n\n\n\nGet: IsAssembly(self: _FieldInfo) -> bool\n\n\n\n'
is_family = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsFamily property.\n\n\n\nGet: IsFamily(self: _FieldInfo) -> bool\n\n\n\n'
is_family_and_assembly = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsFamilyAndAssembly property.\n\n\n\nGet: IsFamilyAndAssembly(self: _FieldInfo) -> bool\n\n\n\n'
is_family_or_assembly = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsFamilyOrAssembly property.\n\n\n\nGet: IsFamilyOrAssembly(self: _FieldInfo) -> bool\n\n\n\n'
is_init_only = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsInitOnly property.\n\n\n\nGet: IsInitOnly(self: _FieldInfo) -> bool\n\n\n\n'
is_literal = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsLiteral property.\n\n\n\nGet: IsLiteral(self: _FieldInfo) -> bool\n\n\n\n'
is_not_serialized = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsNotSerialized property.\n\n\n\nGet: IsNotSerialized(self: _FieldInfo) -> bool\n\n\n\n'
is_pinvoke_impl = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsPinvokeImpl property.\n\n\n\nGet: IsPinvokeImpl(self: _FieldInfo) -> bool\n\n\n\n'
is_private = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsPrivate property.\n\n\n\nGet: IsPrivate(self: _FieldInfo) -> bool\n\n\n\n'
is_public = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsPublic property.\n\n\n\nGet: IsPublic(self: _FieldInfo) -> bool\n\n\n\n'
is_special_name = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsSpecialName property.\n\n\n\nGet: IsSpecialName(self: _FieldInfo) -> bool\n\n\n\n'
is_static = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsStatic property.\n\n\n\nGet: IsStatic(self: _FieldInfo) -> bool\n\n\n\n'
member_type = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.FieldInfo.MemberType property.\n\n\n\nGet: MemberType(self: _FieldInfo) -> MemberTypes\n\n\n\n'
name = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.MemberInfo.Name property.\n\n\n\nGet: Name(self: _FieldInfo) -> str\n\n\n\n'
reflected_type = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Provides COM objects with version-independent access to the System.Reflection.MemberInfo.ReflectedType property.\n\n\n\nGet: ReflectedType(self: _FieldInfo) -> Type\n\n\n\n' |
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""
Simple calculator that determines the
price of a meal after tax and tip
Author: Alexander A. Laurence
Last modified: January 2019
Website: www.celestial.tokyo
"""
# pricing
meal = 44.5
tax = 6.75/100
tip = 15.0/100
# logic
meal = meal + (meal*tax)
total = meal+(meal*tip)
# print
print(total) | """
Simple calculator that determines the
price of a meal after tax and tip
Author: Alexander A. Laurence
Last modified: January 2019
Website: www.celestial.tokyo
"""
meal = 44.5
tax = 6.75 / 100
tip = 15.0 / 100
meal = meal + meal * tax
total = meal + meal * tip
print(total) |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"ROOT_DIR": "00_core.ipynb",
"DOWNLOAD_DIR_BASE": "00_core.ipynb",
"PROCESSED_DIR_BASE": "00_core.ipynb",
"DATASET_DIR": "00_core.ipynb",
"create_country_dirs": "00_core.ipynb",
"gen_weekdates": "00_core.ipynb",
"STANDARD_WEEK": "00_core.ipynb",
"STANDARD_WEEK.columns": "00_core.ipynb",
"LAST_MODIFIED": "020_Netherlands.ipynb",
"COUNTRIES": "03_collect.ipynb",
"SUMMARY": "03_collect.ipynb"}
modules = ["core.py",
"countries/uk.py",
"countries/netherlands.py",
"collect.py"]
doc_url = "https://kk1694.github.io/weekly_mort/"
git_url = "https://github.com/kk1694/weekly_mort/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'ROOT_DIR': '00_core.ipynb', 'DOWNLOAD_DIR_BASE': '00_core.ipynb', 'PROCESSED_DIR_BASE': '00_core.ipynb', 'DATASET_DIR': '00_core.ipynb', 'create_country_dirs': '00_core.ipynb', 'gen_weekdates': '00_core.ipynb', 'STANDARD_WEEK': '00_core.ipynb', 'STANDARD_WEEK.columns': '00_core.ipynb', 'LAST_MODIFIED': '020_Netherlands.ipynb', 'COUNTRIES': '03_collect.ipynb', 'SUMMARY': '03_collect.ipynb'}
modules = ['core.py', 'countries/uk.py', 'countries/netherlands.py', 'collect.py']
doc_url = 'https://kk1694.github.io/weekly_mort/'
git_url = 'https://github.com/kk1694/weekly_mort/tree/master/'
def custom_doc_links(name):
return None |
class Quark:
""" An :class:`src.ops.ElementalOperator` is a product of quark fields and
other commuting objects.
:param barred: Specifies if quark or anti-quark
:type barred: bool
:param flavor: Quark flavor
:type flavor: char
:param spin: Quark spin
:type spin: str
:param color: Quark color
:type color: str
:param time: Quark time
:type time: str
:param position: Quark position
:type position: str
"""
def __init__(self, barred, flavor, spin, color, time, position):
"""Constructor
"""
self.barred=barred
self.flavor=flavor
self.spin=spin
self.color=color
self.time=time
self.position=position
def __str__(self):
"""Printer to string
"""
if self.barred:
return "\\bar{" + str(self.flavor) + "}" + "_{" + self.spin + " " \
+ self.color + "}(" + self.position + ", " + self.time + ")"
else:
return str(self.flavor) + "_{" + self.spin + " " + self.color \
+ "}(" + self.position + ", " + self.time + ")"
def __eq__(self, other):
"""Check if two quarks are equal
:param other: Another quark
:type other: :class:`src.ops.Quark`
"""
return (self.barred==other.barred) and (self.flavor==other.flavor) and \
(self.spin==other.spin) and (self.color==other.color) and \
(self.time==other.time) and (self.position==other.position)
#TODO Implement this for the wick_contraction part.
class ShortQuark:
""" A more efficient implementation of :class:`src.ops.Quark` for use
within LINK_TO_WICK_CONTRACTION.
:param barred: Quark or anti-quark
:type barred: bool
:param flavor: Quark flavor
:type flavor: char
:param label: Single label for the quark
:type lavel: str
"""
def __init__(self, barred, flavor, label):
"""Constructor
"""
self.barred=barred
self.flavor=flavor
self.label=label
def __str__(self):
"""Printer to string
"""
if(self.barred):
return "\\bar{" + str(self.flavor) + "}_{" + self.label + "}"
else:
return str(self.flavor) + "_{" + self.label + "}"
def __eq__(self, other):
"""Check if two short quarks are equal
:param other: Another short quark
:type other: :class:`src.ops.ShortQuark`
"""
return (self.barred==other.barred) and (self.flavor==other.flavor) \
and (self.label==other.label)
| class Quark:
""" An :class:`src.ops.ElementalOperator` is a product of quark fields and
other commuting objects.
:param barred: Specifies if quark or anti-quark
:type barred: bool
:param flavor: Quark flavor
:type flavor: char
:param spin: Quark spin
:type spin: str
:param color: Quark color
:type color: str
:param time: Quark time
:type time: str
:param position: Quark position
:type position: str
"""
def __init__(self, barred, flavor, spin, color, time, position):
"""Constructor
"""
self.barred = barred
self.flavor = flavor
self.spin = spin
self.color = color
self.time = time
self.position = position
def __str__(self):
"""Printer to string
"""
if self.barred:
return '\\bar{' + str(self.flavor) + '}' + '_{' + self.spin + ' ' + self.color + '}(' + self.position + ', ' + self.time + ')'
else:
return str(self.flavor) + '_{' + self.spin + ' ' + self.color + '}(' + self.position + ', ' + self.time + ')'
def __eq__(self, other):
"""Check if two quarks are equal
:param other: Another quark
:type other: :class:`src.ops.Quark`
"""
return self.barred == other.barred and self.flavor == other.flavor and (self.spin == other.spin) and (self.color == other.color) and (self.time == other.time) and (self.position == other.position)
class Shortquark:
""" A more efficient implementation of :class:`src.ops.Quark` for use
within LINK_TO_WICK_CONTRACTION.
:param barred: Quark or anti-quark
:type barred: bool
:param flavor: Quark flavor
:type flavor: char
:param label: Single label for the quark
:type lavel: str
"""
def __init__(self, barred, flavor, label):
"""Constructor
"""
self.barred = barred
self.flavor = flavor
self.label = label
def __str__(self):
"""Printer to string
"""
if self.barred:
return '\\bar{' + str(self.flavor) + '}_{' + self.label + '}'
else:
return str(self.flavor) + '_{' + self.label + '}'
def __eq__(self, other):
"""Check if two short quarks are equal
:param other: Another short quark
:type other: :class:`src.ops.ShortQuark`
"""
return self.barred == other.barred and self.flavor == other.flavor and (self.label == other.label) |
server='tcp:mkgsupport.database.windows.net'
database='mkgsupport'
username='mkguser'
password='Usersqlmkg123!'
driver='/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.6.so.1.1'
| server = 'tcp:mkgsupport.database.windows.net'
database = 'mkgsupport'
username = 'mkguser'
password = 'Usersqlmkg123!'
driver = '/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.6.so.1.1' |
# _create_empty_dict.py
__module_name__ = "_create_empty_dict.py"
__author__ = ", ".join(["Michael E. Vinyard"])
__email__ = ", ".join(["vinyard@g.harvard.edu",])
def _create_empty_dict(keys):
"""
Create an empty python Dictionary given a set of keys.
Parameters:
-----------
keys
Returns:
--------
Dict
"""
Dict = {}
for key in keys:
Dict[key] = {}
return Dict | __module_name__ = '_create_empty_dict.py'
__author__ = ', '.join(['Michael E. Vinyard'])
__email__ = ', '.join(['vinyard@g.harvard.edu'])
def _create_empty_dict(keys):
"""
Create an empty python Dictionary given a set of keys.
Parameters:
-----------
keys
Returns:
--------
Dict
"""
dict = {}
for key in keys:
Dict[key] = {}
return Dict |
"""
========================================================================
Bits.py
========================================================================
Pure-Python implementation of fixed-bitwidth data type.
Author : Shunning Jiang
Date : Oct 31, 2017
"""
class Bits:
__slots__ = ( "nbits", "value" )
def __init__( self, nbits=32, value=0 ):
self.nbits = nbits
self.value = int(value) & ((1 << nbits) - 1)
def __ilshift__( self, x ):
try:
assert x.nbits == self.nbits, "Bitwidth mismatch during <<="
except AttributeError:
raise TypeError(f"Assign {type(x)} to Bits")
self._next = x.value
return self
def _flip( self ):
self.value = self._next
def __call__( self ):
return Bits( self.nbits )
# Arithmetics
def __getitem__( self, idx ):
sv = int(self.value)
if isinstance( idx, slice ):
start, stop = int(idx.start), int(idx.stop)
assert not idx.step and start < stop and start >= 0 and stop <= self.nbits, \
"Invalid access: [{}:{}] in a Bits{} instance".format( start, stop, self.nbits )
return Bits( stop-start, (sv & ((1 << stop) - 1)) >> start )
i = int(idx)
assert 0 <= i < self.nbits
return Bits( 1, (sv >> i) & 1 )
def __setitem__( self, idx, v ):
sv = int(self.value)
if isinstance( idx, slice ):
start, stop = int(idx.start), int(idx.stop)
assert not idx.step and start < stop and start >= 0 and stop <= self.nbits, \
"Invalid access: [{}:{}] in a Bits{} instance".format( start, stop, self.nbits )
self.value = (sv & (~((1 << stop) - (1 << start)))) | \
((int(v) & ((1 << (stop - start)) - 1)) << start)
return
i = int(idx)
assert 0 <= i < self.nbits
self.value = (sv & ~(1 << i)) | ((int(v) & 1) << i)
def __add__( self, other ):
try: return Bits( max(self.nbits, other.nbits), int(self.value) + int(other) )
except: return Bits( self.nbits, int(self.value) + int(other) )
def __radd__( self, other ):
return self.__add__( other )
def __sub__( self, other ):
try: return Bits( max(self.nbits, other.nbits), int(self.value) - int(other) )
except: return Bits( self.nbits, int(self.value) - int(other) )
def __rsub__( self, other ):
return Bits( self.nbits, other ) - self
def __mul__( self, other ):
try: return Bits( max(self.nbits, other.nbits), int(self.value) * int(other) )
except: return Bits( self.nbits, int(self.value) * int(other) )
def __rmul__( self, other ):
return self.__mul__( other )
def __and__( self, other ):
try: return Bits( max(self.nbits, other.nbits), int(self.value) & int(other) )
except: return Bits( self.nbits, int(self.value) & int(other) )
def __rand__( self, other ):
return self.__and__( other )
def __or__( self, other ):
try: return Bits( max(self.nbits, other.nbits), int(self.value) | int(other) )
except: return Bits( self.nbits, int(self.value) | int(other) )
def __ror__( self, other ):
return self.__or__( other )
def __xor__( self, other ):
try: return Bits( max(self.nbits, other.nbits), int(self.value) ^ int(other) )
except: return Bits( self.nbits, int(self.value) ^ int(other) )
def __rxor__( self, other ):
return self.__xor__( other )
def __div__( self, other ):
try: return Bits( max(self.nbits, other.nbits), int(self.value) / int(other) )
except: return Bits( self.nbits, int(self.value) / int(other) )
def __floordiv__( self, other ):
try: return Bits( max(self.nbits, other.nbits), int(self.value) / int(other) )
except: return Bits( self.nbits, int(self.value) / int(other) )
def __mod__( self, other ):
try: return Bits( max(self.nbits, other.nbits), int(self.value) % int(other) )
except: return Bits( self.nbits, int(self.value) % int(other) )
def __invert__( self ):
return Bits( self.nbits, ~int(self.value) )
def __lshift__( self, other ):
nb = int(self.nbits)
# TODO this doesn't work perfectly. We need a really smart
# optimization that avoids the guard totally
if int(other) >= nb: return Bits( nb )
return Bits( nb, int(self.value) << int(other) )
def __rshift__( self, other ):
return Bits( self.nbits, int(self.value) >> int(other) )
def __eq__( self, other ):
try:
other = int(other)
except ValueError:
return False
return Bits( 1, int(self.value) == other )
def __hash__( self ):
return hash((self.nbits, self.value))
def __ne__( self, other ):
try:
other = int(other)
except ValueError:
return True
return Bits( 1, int(self.value) != other )
def __lt__( self, other ):
return Bits( 1, int(self.value) < int(other) )
def __le__( self, other ):
return Bits( 1, int(self.value) <= int(other) )
def __gt__( self, other ):
return Bits( 1, int(self.value) > int(other) )
def __ge__( self, other ):
return Bits( 1, int(self.value) >= int(other) )
def __bool__( self ):
return int(self.value) != 0
def __int__( self ):
return int(self.value)
def int( self ):
if self.value >> (self.nbits - 1):
return -int(~self + 1)
return int(self.value)
def uint( self ):
return int(self.value)
def __index__( self ):
return int(self.value)
# Print
def __repr__(self):
return "Bits{}( {} )".format( self.nbits, self.hex() )
def __str__(self):
str = "{:x}".format(int(self.value)).zfill(((self.nbits-1)>>2)+1)
return str
def __oct__( self ):
# print("DEPRECATED: Please use .oct()!")
return self.oct()
def __hex__( self ):
# print("DEPRECATED: Please use .hex()!")
return self.hex()
def bin(self):
str = "{:b}".format(int(self.value)).zfill(self.nbits)
return "0b"+str
def oct( self ):
str = "{:o}".format(int(self.value)).zfill(((self.nbits-1)>>1)+1)
return "0o"+str
def hex( self ):
str = "{:x}".format(int(self.value)).zfill(((self.nbits-1)>>2)+1)
return "0x"+str
| """
========================================================================
Bits.py
========================================================================
Pure-Python implementation of fixed-bitwidth data type.
Author : Shunning Jiang
Date : Oct 31, 2017
"""
class Bits:
__slots__ = ('nbits', 'value')
def __init__(self, nbits=32, value=0):
self.nbits = nbits
self.value = int(value) & (1 << nbits) - 1
def __ilshift__(self, x):
try:
assert x.nbits == self.nbits, 'Bitwidth mismatch during <<='
except AttributeError:
raise type_error(f'Assign {type(x)} to Bits')
self._next = x.value
return self
def _flip(self):
self.value = self._next
def __call__(self):
return bits(self.nbits)
def __getitem__(self, idx):
sv = int(self.value)
if isinstance(idx, slice):
(start, stop) = (int(idx.start), int(idx.stop))
assert not idx.step and start < stop and (start >= 0) and (stop <= self.nbits), 'Invalid access: [{}:{}] in a Bits{} instance'.format(start, stop, self.nbits)
return bits(stop - start, (sv & (1 << stop) - 1) >> start)
i = int(idx)
assert 0 <= i < self.nbits
return bits(1, sv >> i & 1)
def __setitem__(self, idx, v):
sv = int(self.value)
if isinstance(idx, slice):
(start, stop) = (int(idx.start), int(idx.stop))
assert not idx.step and start < stop and (start >= 0) and (stop <= self.nbits), 'Invalid access: [{}:{}] in a Bits{} instance'.format(start, stop, self.nbits)
self.value = sv & ~((1 << stop) - (1 << start)) | (int(v) & (1 << stop - start) - 1) << start
return
i = int(idx)
assert 0 <= i < self.nbits
self.value = sv & ~(1 << i) | (int(v) & 1) << i
def __add__(self, other):
try:
return bits(max(self.nbits, other.nbits), int(self.value) + int(other))
except:
return bits(self.nbits, int(self.value) + int(other))
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
try:
return bits(max(self.nbits, other.nbits), int(self.value) - int(other))
except:
return bits(self.nbits, int(self.value) - int(other))
def __rsub__(self, other):
return bits(self.nbits, other) - self
def __mul__(self, other):
try:
return bits(max(self.nbits, other.nbits), int(self.value) * int(other))
except:
return bits(self.nbits, int(self.value) * int(other))
def __rmul__(self, other):
return self.__mul__(other)
def __and__(self, other):
try:
return bits(max(self.nbits, other.nbits), int(self.value) & int(other))
except:
return bits(self.nbits, int(self.value) & int(other))
def __rand__(self, other):
return self.__and__(other)
def __or__(self, other):
try:
return bits(max(self.nbits, other.nbits), int(self.value) | int(other))
except:
return bits(self.nbits, int(self.value) | int(other))
def __ror__(self, other):
return self.__or__(other)
def __xor__(self, other):
try:
return bits(max(self.nbits, other.nbits), int(self.value) ^ int(other))
except:
return bits(self.nbits, int(self.value) ^ int(other))
def __rxor__(self, other):
return self.__xor__(other)
def __div__(self, other):
try:
return bits(max(self.nbits, other.nbits), int(self.value) / int(other))
except:
return bits(self.nbits, int(self.value) / int(other))
def __floordiv__(self, other):
try:
return bits(max(self.nbits, other.nbits), int(self.value) / int(other))
except:
return bits(self.nbits, int(self.value) / int(other))
def __mod__(self, other):
try:
return bits(max(self.nbits, other.nbits), int(self.value) % int(other))
except:
return bits(self.nbits, int(self.value) % int(other))
def __invert__(self):
return bits(self.nbits, ~int(self.value))
def __lshift__(self, other):
nb = int(self.nbits)
if int(other) >= nb:
return bits(nb)
return bits(nb, int(self.value) << int(other))
def __rshift__(self, other):
return bits(self.nbits, int(self.value) >> int(other))
def __eq__(self, other):
try:
other = int(other)
except ValueError:
return False
return bits(1, int(self.value) == other)
def __hash__(self):
return hash((self.nbits, self.value))
def __ne__(self, other):
try:
other = int(other)
except ValueError:
return True
return bits(1, int(self.value) != other)
def __lt__(self, other):
return bits(1, int(self.value) < int(other))
def __le__(self, other):
return bits(1, int(self.value) <= int(other))
def __gt__(self, other):
return bits(1, int(self.value) > int(other))
def __ge__(self, other):
return bits(1, int(self.value) >= int(other))
def __bool__(self):
return int(self.value) != 0
def __int__(self):
return int(self.value)
def int(self):
if self.value >> self.nbits - 1:
return -int(~self + 1)
return int(self.value)
def uint(self):
return int(self.value)
def __index__(self):
return int(self.value)
def __repr__(self):
return 'Bits{}( {} )'.format(self.nbits, self.hex())
def __str__(self):
str = '{:x}'.format(int(self.value)).zfill((self.nbits - 1 >> 2) + 1)
return str
def __oct__(self):
return self.oct()
def __hex__(self):
return self.hex()
def bin(self):
str = '{:b}'.format(int(self.value)).zfill(self.nbits)
return '0b' + str
def oct(self):
str = '{:o}'.format(int(self.value)).zfill((self.nbits - 1 >> 1) + 1)
return '0o' + str
def hex(self):
str = '{:x}'.format(int(self.value)).zfill((self.nbits - 1 >> 2) + 1)
return '0x' + str |
"""This module contains exceptions that power Injectify."""
class ClassFoundException(Exception):
pass
| """This module contains exceptions that power Injectify."""
class Classfoundexception(Exception):
pass |
a = 1
b = 0
c = 128
d = 0
f = 836 + c #964
if a == 1:
c = 10550400
f = f + c #10551364
a = 0
for b in range(1, f+1):
if (f % b) == 0:
a += b
print(a) | a = 1
b = 0
c = 128
d = 0
f = 836 + c
if a == 1:
c = 10550400
f = f + c
a = 0
for b in range(1, f + 1):
if f % b == 0:
a += b
print(a) |
class GoodreadsClientException(Exception):
pass
class NetworkError(GoodreadsClientException):
pass
| class Goodreadsclientexception(Exception):
pass
class Networkerror(GoodreadsClientException):
pass |
def show_words(**kwargs):
print(kwargs['pies'], kwargs['kot'])
for key, value in kwargs.items():
print(key + "->" + value)
show_words(pies="Dog", kot="Cat", sowa="Owl", mysz="Mouse")
| def show_words(**kwargs):
print(kwargs['pies'], kwargs['kot'])
for (key, value) in kwargs.items():
print(key + '->' + value)
show_words(pies='Dog', kot='Cat', sowa='Owl', mysz='Mouse') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Shashi Bhushan (sbhushan1 @ outlook dot com)'
class GameObject(object):
pass
| __author__ = 'Shashi Bhushan (sbhushan1 @ outlook dot com)'
class Gameobject(object):
pass |
debian_os = ['debian', 'ubuntu']
rhel_os = ['redhat', 'centos']
def test_distribution(host):
assert host.system_info.distribution.lower() in debian_os + rhel_os
def test_conf_dir(host):
f = host.file('/etc/pgbouncer_exporter')
assert f.exists
assert f.is_directory
def test_log_dir(host):
f = host.file('/var/log/pgbouncer_exporter')
assert f.exists
assert f.is_directory
def test_service(host):
s = host.service('pgbouncer_exporter')
assert s.is_enabled
assert s.is_running
def test_user(host):
u = host.user('postgres')
assert u.exists
def test_group(host):
g = host.group('postgres')
assert g.exists
def test_socket(host):
s = host.socket("tcp://127.0.0.1:9127")
assert s.is_listening
def test_version(host):
g = host.pip_package.get_packages(pip_path='pip3')
for k, v in g.items():
if k == "prometheus-pgbouncer-exporter":
version = v['version']
break
assert version == "2.0.1"
| debian_os = ['debian', 'ubuntu']
rhel_os = ['redhat', 'centos']
def test_distribution(host):
assert host.system_info.distribution.lower() in debian_os + rhel_os
def test_conf_dir(host):
f = host.file('/etc/pgbouncer_exporter')
assert f.exists
assert f.is_directory
def test_log_dir(host):
f = host.file('/var/log/pgbouncer_exporter')
assert f.exists
assert f.is_directory
def test_service(host):
s = host.service('pgbouncer_exporter')
assert s.is_enabled
assert s.is_running
def test_user(host):
u = host.user('postgres')
assert u.exists
def test_group(host):
g = host.group('postgres')
assert g.exists
def test_socket(host):
s = host.socket('tcp://127.0.0.1:9127')
assert s.is_listening
def test_version(host):
g = host.pip_package.get_packages(pip_path='pip3')
for (k, v) in g.items():
if k == 'prometheus-pgbouncer-exporter':
version = v['version']
break
assert version == '2.0.1' |
#!/usr/bin/env python3
"""
linear_search.py - Linear Search Implementation
Author: Hoanh An (hoanhan@bennington.edu)
Date: 10/18/2017
"""
def linear_search(arr, x):
for i in arr:
if i == x:
return True
return False
if __name__ == '__main__':
test_array = [1, 2, 3]
if linear_search(test_array, 3):
print("PASSED test_item_in_list")
if linear_search(test_array, 5) == False:
print("PASSED test_item_NOT_in_list") | """
linear_search.py - Linear Search Implementation
Author: Hoanh An (hoanhan@bennington.edu)
Date: 10/18/2017
"""
def linear_search(arr, x):
for i in arr:
if i == x:
return True
return False
if __name__ == '__main__':
test_array = [1, 2, 3]
if linear_search(test_array, 3):
print('PASSED test_item_in_list')
if linear_search(test_array, 5) == False:
print('PASSED test_item_NOT_in_list') |
a = 1
b = 2
c = 3
d = 4
e = 5
f = 6 | a = 1
b = 2
c = 3
d = 4
e = 5
f = 6 |
# --- Day 15: Rambunctious Recitation ---
# You catch the airport shuttle and try to book a new flight to your vacation island. Due to the storm, all direct flights have been cancelled, but a route is available to get around the storm. You take it.
# While you wait for your flight, you decide to check in with the Elves back at the North Pole. They're playing a memory game and are ever so excited to explain the rules!
# In this game, the players take turns saying numbers. They begin by taking turns reading from a list of starting numbers (your puzzle input). Then, each turn consists of considering the most recently spoken number:
# If that was the first time the number has been spoken, the current player says 0.
# Otherwise, the number had been spoken before; the current player announces how many turns apart the number is from when it was previously spoken.
# So, after the starting numbers, each turn results in that player speaking aloud either 0 (if the last number is new) or an age (if the last number is a repeat).
# For example, suppose the starting numbers are 0,3,6:
# Turn 1: The 1st number spoken is a starting number, 0.
# Turn 2: The 2nd number spoken is a starting number, 3.
# Turn 3: The 3rd number spoken is a starting number, 6.
# Turn 4: Now, consider the last number spoken, 6. Since that was the first time the number had been spoken, the 4th number spoken is 0.
# Turn 5: Next, again consider the last number spoken, 0. Since it had been spoken before, the next number to speak is the difference between the turn number when it was last spoken (the previous turn, 4) and the turn number of the time it was most recently spoken before then (turn 1). Thus, the 5th number spoken is 4 - 1, 3.
# Turn 6: The last number spoken, 3 had also been spoken before, most recently on turns 5 and 2. So, the 6th number spoken is 5 - 2, 3.
# Turn 7: Since 3 was just spoken twice in a row, and the last two turns are 1 turn apart, the 7th number spoken is 1.
# Turn 8: Since 1 is new, the 8th number spoken is 0.
# Turn 9: 0 was last spoken on turns 8 and 4, so the 9th number spoken is the difference between them, 4.
# Turn 10: 4 is new, so the 10th number spoken is 0.
# (The game ends when the Elves get sick of playing or dinner is ready, whichever comes first.)
# Their question for you is: what will be the 2020th number spoken? In the example above, the 2020th number spoken will be 436.
# Here are a few more examples:
# Given the starting numbers 1,3,2, the 2020th number spoken is 1.
# Given the starting numbers 2,1,3, the 2020th number spoken is 10.
# Given the starting numbers 1,2,3, the 2020th number spoken is 27.
# Given the starting numbers 2,3,1, the 2020th number spoken is 78.
# Given the starting numbers 3,2,1, the 2020th number spoken is 438.
# Given the starting numbers 3,1,2, the 2020th number spoken is 1836.
# Given your starting numbers, what will be the 2020th number spoken?
def fileInput():
f = open(inputFile, 'r')
with open(inputFile) as f:
read_data = f.read().split(',')
f.close()
return read_data
def dictTransform(data):
turn_count = 0
dict_data = {}
for num in data:
turn_count += 1 #turn starts on count 1, so do it before and add extra count at the end
dict_data.update({int(num):[0,turn_count]})
prev_num = num
dict_data.update({int(prev_num):[turn_count]})
return dict_data,turn_count
def memGameTurn(dict_data,prev_num,turn_count):
# print('-----------')
# print('#',turn_count,prev_num, '->',dict_data,end=" ")
if dict_data.get(prev_num) is None:
dict_data.update({prev_num:[turn_count]})
prev_num = 0
elif len(dict_data.get(prev_num)) == 1:
dict_data.update({prev_num:[dict_data.get(prev_num)[0],turn_count]})
prev_num = dict_data.get(prev_num)[1]-dict_data.get(prev_num)[0]
else:
dict_data.update({prev_num:[dict_data.get(prev_num)[1],turn_count]})
prev_num = dict_data.get(prev_num)[1]-dict_data.get(prev_num)[0]
return dict_data,prev_num
def memGame(data):
turn_end = 2020
prev_num = 0 #first turn after data is always new number
dict_data,turn_start = dictTransform(data)
for i in range(turn_start+1,turn_end):
dict_data,prev_num = memGameTurn(dict_data,prev_num,i)
return prev_num
#///////////////////////////////////////////////////
inputFile = 'day15-input.txt'
if __name__ == "__main__":
data = fileInput()
print(memGame(data))
| def file_input():
f = open(inputFile, 'r')
with open(inputFile) as f:
read_data = f.read().split(',')
f.close()
return read_data
def dict_transform(data):
turn_count = 0
dict_data = {}
for num in data:
turn_count += 1
dict_data.update({int(num): [0, turn_count]})
prev_num = num
dict_data.update({int(prev_num): [turn_count]})
return (dict_data, turn_count)
def mem_game_turn(dict_data, prev_num, turn_count):
if dict_data.get(prev_num) is None:
dict_data.update({prev_num: [turn_count]})
prev_num = 0
elif len(dict_data.get(prev_num)) == 1:
dict_data.update({prev_num: [dict_data.get(prev_num)[0], turn_count]})
prev_num = dict_data.get(prev_num)[1] - dict_data.get(prev_num)[0]
else:
dict_data.update({prev_num: [dict_data.get(prev_num)[1], turn_count]})
prev_num = dict_data.get(prev_num)[1] - dict_data.get(prev_num)[0]
return (dict_data, prev_num)
def mem_game(data):
turn_end = 2020
prev_num = 0
(dict_data, turn_start) = dict_transform(data)
for i in range(turn_start + 1, turn_end):
(dict_data, prev_num) = mem_game_turn(dict_data, prev_num, i)
return prev_num
input_file = 'day15-input.txt'
if __name__ == '__main__':
data = file_input()
print(mem_game(data)) |
# -*- coding: utf-8 -*-
# in VTK, the header file is the same as the classname
def get_include_file(classname,filename):
incfile = '#include "{0}"'.format(filename)
#print "including class {0} from file {1}".format(classname,incfile)
if classname.startswith("itk::DefaultConvertPixelTraits"):
incfile = '#include "itkMatrix.h"\n'+incfile
if classname.startswith("std::set"):
incfile = '#include <set>\n'+incfile
return incfile
#return "{0}.h".format(classname)
def get_var_filter():
return "(itk::|vnl_|itkAmi|gdcm::|std::).*"
def wrap_public_fields(classname):
return False
def deleter_includefile():
return ""
def implement_deleter(classname):
# no deleter for the moment unless for smart pointers?
# or only in case of protected deleter?
return ", smartpointer_nodeleter<{0} >()".format(classname) | def get_include_file(classname, filename):
incfile = '#include "{0}"'.format(filename)
if classname.startswith('itk::DefaultConvertPixelTraits'):
incfile = '#include "itkMatrix.h"\n' + incfile
if classname.startswith('std::set'):
incfile = '#include <set>\n' + incfile
return incfile
def get_var_filter():
return '(itk::|vnl_|itkAmi|gdcm::|std::).*'
def wrap_public_fields(classname):
return False
def deleter_includefile():
return ''
def implement_deleter(classname):
return ', smartpointer_nodeleter<{0} >()'.format(classname) |
class Calculadora:
def soma(self, valor_a, valor_b):
return valor_a + valor_b
def subtracao(self, valor_a, valor_b):
return valor_a - valor_b
def multiplacacao(self, valor_a, valor_b):
return valor_a * valor_b
def divisao(self, valor_a, valor_b):
return valor_a / valor_b
calculadora = Calculadora()
print(calculadora.soma(10, 2))
print(calculadora.subtracao(5, 3))
print(calculadora.divisao(100, 2))
print(calculadora.multiplacacao(10, 5)) | class Calculadora:
def soma(self, valor_a, valor_b):
return valor_a + valor_b
def subtracao(self, valor_a, valor_b):
return valor_a - valor_b
def multiplacacao(self, valor_a, valor_b):
return valor_a * valor_b
def divisao(self, valor_a, valor_b):
return valor_a / valor_b
calculadora = calculadora()
print(calculadora.soma(10, 2))
print(calculadora.subtracao(5, 3))
print(calculadora.divisao(100, 2))
print(calculadora.multiplacacao(10, 5)) |
#!/usr/bin/python
#Excercise 1 from Chapter 4
spam = ['apples','bananas','tofu','cats']
def structlist(lists):
sstring = ""
for i in range(len(lists)):
if i == len(lists)-1:
sstring +="and "+lists[i]
print(sstring)
break
else:
sstring += lists[i]+", "
structlist(spam)
spam.append("lions")
#This should prove that the size of the list wont matter.
structlist(spam)
| spam = ['apples', 'bananas', 'tofu', 'cats']
def structlist(lists):
sstring = ''
for i in range(len(lists)):
if i == len(lists) - 1:
sstring += 'and ' + lists[i]
print(sstring)
break
else:
sstring += lists[i] + ', '
structlist(spam)
spam.append('lions')
structlist(spam) |
# Configuration file for ipcontroller.
c = get_config()
#------------------------------------------------------------------------------
# IPControllerApp configuration
#------------------------------------------------------------------------------
# IPControllerApp will inherit config from: BaseParallelApplication,
# BaseIPythonApplication, Application
# Use threads instead of processes for the schedulers
# c.IPControllerApp.use_threads = False
# Create a massive crash report when IPython encounters what may be an internal
# error. The default is to append a short message to the usual traceback
# c.IPControllerApp.verbose_crash = False
# JSON filename where client connection info will be stored.
# c.IPControllerApp.client_json_file = 'ipcontroller-client.json'
# String id to add to runtime files, to prevent name collisions when using
# multiple clusters with a single profile simultaneously.
#
# When set, files will be named like: 'ipcontroller-<cluster_id>-engine.json'
#
# Since this is text inserted into filenames, typical recommendations apply:
# Simple character strings are ideal, and spaces are not recommended (but should
# generally work).
# c.IPControllerApp.cluster_id = ''
# The date format used by logging formatters for %(asctime)s
# c.IPControllerApp.log_datefmt = '%Y-%m-%d %H:%M:%S'
# Whether to overwrite existing config files when copying
# c.IPControllerApp.overwrite = False
# Set the log level by value or name.
# c.IPControllerApp.log_level = 30
# Set the working dir for the process.
# c.IPControllerApp.work_dir = u'/fusion/gpfs/home/scollis'
# ssh url for engines to use when connecting to the Controller processes. It
# should be of the form: [user@]server[:port]. The Controller's listening
# addresses must be accessible from the ssh server
# c.IPControllerApp.engine_ssh_server = u''
# Path to an extra config file to load.
#
# If specified, load this config file in addition to any other IPython config.
# c.IPControllerApp.extra_config_file = u''
# Whether to create profile dir if it doesn't exist.
# c.IPControllerApp.auto_create = True
# The external IP or domain name of the Controller, used for disambiguating
# engine and client connections.
# c.IPControllerApp.location = u''
# ssh url for clients to use when connecting to the Controller processes. It
# should be of the form: [user@]server[:port]. The Controller's listening
# addresses must be accessible from the ssh server
# c.IPControllerApp.ssh_server = u''
# The IPython profile to use.
# c.IPControllerApp.profile = u'default'
# The ZMQ URL of the iplogger to aggregate logging.
# c.IPControllerApp.log_url = ''
# whether to log to a file
# c.IPControllerApp.log_to_file = False
# The name of the IPython directory. This directory is used for logging
# configuration (through profiles), history storage, etc. The default is usually
# $HOME/.ipython. This option can also be specified through the environment
# variable IPYTHONDIR.
# c.IPControllerApp.ipython_dir = u''
# Whether to install the default config files into the profile dir. If a new
# profile is being created, and IPython contains config files for that profile,
# then they will be staged into the new directory. Otherwise, default config
# files will be automatically generated.
# c.IPControllerApp.copy_config_files = False
# import statements to be run at startup. Necessary in some environments
# c.IPControllerApp.import_statements = []
# Whether to reuse existing json connection files. If False, connection files
# will be removed on a clean exit.
# c.IPControllerApp.reuse_files = False
# Reload engine state from JSON file
# c.IPControllerApp.restore_engines = False
# JSON filename where engine connection info will be stored.
# c.IPControllerApp.engine_json_file = 'ipcontroller-engine.json'
# whether to cleanup old logfiles before starting
# c.IPControllerApp.clean_logs = False
# The Logging format template
# c.IPControllerApp.log_format = '[%(name)s]%(highlevel)s %(message)s'
#------------------------------------------------------------------------------
# ProfileDir configuration
#------------------------------------------------------------------------------
# An object to manage the profile directory and its resources.
#
# The profile directory is used by all IPython applications, to manage
# configuration, logging and security.
#
# This object knows how to find, create and manage these directories. This
# should be used by any code that wants to handle profiles.
# Set the profile location directly. This overrides the logic used by the
# `profile` option.
# c.ProfileDir.location = u''
#------------------------------------------------------------------------------
# Session configuration
#------------------------------------------------------------------------------
# Object for handling serialization and sending of messages.
#
# The Session object handles building messages and sending them with ZMQ sockets
# or ZMQStream objects. Objects can communicate with each other over the
# network via Session objects, and only need to work with the dict-based IPython
# message spec. The Session will handle serialization/deserialization, security,
# and metadata.
#
# Sessions support configurable serialization via packer/unpacker traits, and
# signing with HMAC digests via the key/keyfile traits.
#
# Parameters ----------
#
# debug : bool
# whether to trigger extra debugging statements
# packer/unpacker : str : 'json', 'pickle' or import_string
# importstrings for methods to serialize message parts. If just
# 'json' or 'pickle', predefined JSON and pickle packers will be used.
# Otherwise, the entire importstring must be used.
#
# The functions must accept at least valid JSON input, and output *bytes*.
#
# For example, to use msgpack:
# packer = 'msgpack.packb', unpacker='msgpack.unpackb'
# pack/unpack : callables
# You can also set the pack/unpack callables for serialization directly.
# session : bytes
# the ID of this Session object. The default is to generate a new UUID.
# username : unicode
# username added to message headers. The default is to ask the OS.
# key : bytes
# The key used to initialize an HMAC signature. If unset, messages
# will not be signed or checked.
# keyfile : filepath
# The file containing a key. If this is set, `key` will be initialized
# to the contents of the file.
# Username for the Session. Default is your system username.
# c.Session.username = u'scollis'
# The name of the unpacker for unserializing messages. Only used with custom
# functions for `packer`.
# c.Session.unpacker = 'json'
# Threshold (in bytes) beyond which a buffer should be sent without copying.
# c.Session.copy_threshold = 65536
# The name of the packer for serializing messages. Should be one of 'json',
# 'pickle', or an import name for a custom callable serializer.
# c.Session.packer = 'json'
# The maximum number of digests to remember.
#
# The digest history will be culled when it exceeds this value.
# c.Session.digest_history_size = 65536
# The UUID identifying this session.
# c.Session.session = u''
# The digest scheme used to construct the message signatures. Must have the form
# 'hmac-HASH'.
# c.Session.signature_scheme = 'hmac-sha256'
# execution key, for signing messages.
# c.Session.key = ''
# Debug output in the Session
# c.Session.debug = False
# The maximum number of items for a container to be introspected for custom
# serialization. Containers larger than this are pickled outright.
# c.Session.item_threshold = 64
# path to file containing execution key.
# c.Session.keyfile = ''
# Threshold (in bytes) beyond which an object's buffer should be extracted to
# avoid pickling.
# c.Session.buffer_threshold = 1024
# Metadata dictionary, which serves as the default top-level metadata dict for
# each message.
# c.Session.metadata = {}
#------------------------------------------------------------------------------
# HubFactory configuration
#------------------------------------------------------------------------------
# The Configurable for setting up a Hub.
# HubFactory will inherit config from: RegistrationFactory
# Client/Engine Port pair for Control queue
# c.HubFactory.control = None
# 0MQ transport for monitor messages. [default : tcp]
# c.HubFactory.monitor_transport = 'tcp'
# IP on which to listen for client connections. [default: loopback]
# c.HubFactory.client_ip = u''
# Client/Engine Port pair for Task queue
# c.HubFactory.task = None
# 0MQ transport for engine connections. [default: tcp]
# c.HubFactory.engine_transport = 'tcp'
# 0MQ transport for client connections. [default : tcp]
# c.HubFactory.client_transport = 'tcp'
# Monitor (SUB) port for queue traffic
# c.HubFactory.mon_port = 0
# The IP address for registration. This is generally either '127.0.0.1' for
# loopback only or '*' for all interfaces.
c.HubFactory.ip = '*'
# Engine registration timeout in seconds [default:
# max(30,10*heartmonitor.period)]
# c.HubFactory.registration_timeout = 0
# Client/Engine Port pair for MUX queue
# c.HubFactory.mux = None
# PUB port for sending engine status notifications
# c.HubFactory.notifier_port = 0
# The port on which the Hub listens for registration.
# c.HubFactory.regport = 0
# The 0MQ url used for registration. This sets transport, ip, and port in one
# variable. For example: url='tcp://127.0.0.1:12345' or url='epgm://*:90210'
# c.HubFactory.url = ''
# IP on which to listen for engine connections. [default: loopback]
# c.HubFactory.engine_ip = u''
# Client/Engine Port pair for IOPub relay
# c.HubFactory.iopub = None
# PUB/ROUTER Port pair for Engine heartbeats
# c.HubFactory.hb = None
# The class to use for the DB backend
#
# Options include:
#
# SQLiteDB: SQLite MongoDB : use MongoDB DictDB : in-memory storage (fastest,
# but be mindful of memory growth of the Hub) NoDB : disable database
# altogether (default)
# c.HubFactory.db_class = 'NoDB'
# IP on which to listen for monitor messages. [default: loopback]
# c.HubFactory.monitor_ip = u''
# The 0MQ transport for communications. This will likely be the default of
# 'tcp', but other values include 'ipc', 'epgm', 'inproc'.
# c.HubFactory.transport = 'tcp'
#------------------------------------------------------------------------------
# TaskScheduler configuration
#------------------------------------------------------------------------------
# Python TaskScheduler object.
#
# This is the simplest object that supports msg_id based DAG dependencies.
# *Only* task msg_ids are checked, not msg_ids of jobs submitted via the MUX
# queue.
# select the task scheduler scheme [default: Python LRU] Options are: 'pure',
# 'lru', 'plainrandom', 'weighted', 'twobin','leastload'
# c.TaskScheduler.scheme_name = 'leastload'
# specify the High Water Mark (HWM) for the downstream socket in the Task
# scheduler. This is the maximum number of allowed outstanding tasks on each
# engine.
#
# The default (1) means that only one task can be outstanding on each engine.
# Setting TaskScheduler.hwm=0 means there is no limit, and the engines continue
# to be assigned tasks while they are working, effectively hiding network
# latency behind computation, but can result in an imbalance of work when
# submitting many heterogenous tasks all at once. Any positive value greater
# than one is a compromise between the two.
# c.TaskScheduler.hwm = 1
#------------------------------------------------------------------------------
# HeartMonitor configuration
#------------------------------------------------------------------------------
# A basic HeartMonitor class pingstream: a PUB stream pongstream: an ROUTER
# stream period: the period of the heartbeat in milliseconds
# Whether to include every heartbeat in debugging output.
#
# Has to be set explicitly, because there will be *a lot* of output.
# c.HeartMonitor.debug = False
# The frequency at which the Hub pings the engines for heartbeats (in ms)
# c.HeartMonitor.period = 3000
# Allowed consecutive missed pings from controller Hub to engine before
# unregistering.
# c.HeartMonitor.max_heartmonitor_misses = 10
#------------------------------------------------------------------------------
# DictDB configuration
#------------------------------------------------------------------------------
# Basic in-memory dict-based object for saving Task Records.
#
# This is the first object to present the DB interface for logging tasks out of
# memory.
#
# The interface is based on MongoDB, so adding a MongoDB backend should be
# straightforward.
# The fraction by which the db should culled when one of the limits is exceeded
#
# In general, the db size will spend most of its time with a size in the range:
#
# [limit * (1-cull_fraction), limit]
#
# for each of size_limit and record_limit.
# c.DictDB.cull_fraction = 0.1
# The maximum total size (in bytes) of the buffers stored in the db
#
# When the db exceeds this size, the oldest records will be culled until the
# total size is under size_limit * (1-cull_fraction). default: 1 GB
# c.DictDB.size_limit = 1073741824
# The maximum number of records in the db
#
# When the history exceeds this size, the first record_limit * cull_fraction
# records will be culled.
# c.DictDB.record_limit = 1024
#------------------------------------------------------------------------------
# SQLiteDB configuration
#------------------------------------------------------------------------------
# SQLite3 TaskRecord backend.
# The SQLite Table to use for storing tasks for this session. If unspecified, a
# new table will be created with the Hub's IDENT. Specifying the table will
# result in tasks from previous sessions being available via Clients' db_query
# and get_result methods.
# c.SQLiteDB.table = 'ipython-tasks'
# The directory containing the sqlite task database. The default is to use the
# cluster_dir location.
# c.SQLiteDB.location = ''
# The filename of the sqlite task database. [default: 'tasks.db']
# c.SQLiteDB.filename = 'tasks.db'
| c = get_config()
c.HubFactory.ip = '*' |
# Package Constants
# Meraki dashboard API key, set either at instantiation or as an environment variable
API_KEY_ENVIRONMENT_VARIABLE = 'MERAKI_DASHBOARD_API_KEY'
# Base URL preceding all endpoint resources
DEFAULT_BASE_URL = 'https://api.meraki.com/api/v1'
# Maximum number of seconds for each API call
SINGLE_REQUEST_TIMEOUT = 60
# Path for TLS/SSL certificate verification if behind local proxy
CERTIFICATE_PATH = ''
# Proxy server and port, if needed, for HTTPS
REQUESTS_PROXY = ''
# Retry if 429 rate limit error encountered?
WAIT_ON_RATE_LIMIT = True
# Nginx 429 retry wait time
NGINX_429_RETRY_WAIT_TIME = 60
# Action batch concurrency error retry wait time
ACTION_BATCH_RETRY_WAIT_TIME = 60
# Retry if encountering other 4XX error (besides 429)?
RETRY_4XX_ERROR = False
# Other 4XX error retry wait time
RETRY_4XX_ERROR_WAIT_TIME = 60
# Retry up to this many times when encountering 429s or other server-side errors
MAXIMUM_RETRIES = 2
# Create an output log file?
OUTPUT_LOG = True
# Path to output log; by default, working directory of script if not specified
LOG_PATH = ''
# Log file name appended with date and timestamp
LOG_FILE_PREFIX = 'meraki_api_'
# Print output logging to console?
PRINT_TO_CONSOLE = True
# Disable all logging? You're on your own then!
SUPPRESS_LOGGING = False
# Simulate POST/PUT/DELETE calls to prevent changes?
SIMULATE_API_CALLS = False
# Number of concurrent API requests for asynchronous class
AIO_MAXIMUM_CONCURRENT_REQUESTS = 8
# Optional partner identifier for API usage tracking; can also be set as an environment variable BE_GEO_ID
BE_GEO_ID = ''
# Optional identifier for API usage tracking; can also be set as an environment variable MERAKI_PYTHON_SDK_CALLER
MERAKI_PYTHON_SDK_CALLER = ''
| api_key_environment_variable = 'MERAKI_DASHBOARD_API_KEY'
default_base_url = 'https://api.meraki.com/api/v1'
single_request_timeout = 60
certificate_path = ''
requests_proxy = ''
wait_on_rate_limit = True
nginx_429_retry_wait_time = 60
action_batch_retry_wait_time = 60
retry_4_xx_error = False
retry_4_xx_error_wait_time = 60
maximum_retries = 2
output_log = True
log_path = ''
log_file_prefix = 'meraki_api_'
print_to_console = True
suppress_logging = False
simulate_api_calls = False
aio_maximum_concurrent_requests = 8
be_geo_id = ''
meraki_python_sdk_caller = '' |
class Solution:
# @param word1 & word2: Two string.
# @return: The minimum number of steps.
def minDistance(self, word1, word2):
# write your code here
dp = []
for i in range(len(word1) + 1):
dp.append([])
for j in range(len(word2) + 1):
if (i == 0):
dp[i].append(j)
elif (j == 0):
dp[i].append(i)
else:
a = dp[i - 1][j] + 1
b = dp[i][j - 1] + 1
c = dp[i - 1][j - 1] if word1[i - 1] == word2[j - 1] else dp[i - 1][j - 1] + 1
dp[i].append(min(a, b, c))
return dp[-1][-1]
| class Solution:
def min_distance(self, word1, word2):
dp = []
for i in range(len(word1) + 1):
dp.append([])
for j in range(len(word2) + 1):
if i == 0:
dp[i].append(j)
elif j == 0:
dp[i].append(i)
else:
a = dp[i - 1][j] + 1
b = dp[i][j - 1] + 1
c = dp[i - 1][j - 1] if word1[i - 1] == word2[j - 1] else dp[i - 1][j - 1] + 1
dp[i].append(min(a, b, c))
return dp[-1][-1] |
fp = open("assets/virus2.csv", "r", encoding="utf-8")
lines = fp.readlines()
fp.close()
n = len(lines)
if lines[n-1][0:10] == lines[n-2][0:10]:
lines.pop(n-2)
pass
with open("assets/virus2.csv", "w", encoding="utf-8") as fp:
start = 10
stop = 26
id = 0
for line in lines:
if id !=0:
fp.write(line[0: 10:] + line[26::])
else:
fp.write(line)
id += 1
print("finished!") | fp = open('assets/virus2.csv', 'r', encoding='utf-8')
lines = fp.readlines()
fp.close()
n = len(lines)
if lines[n - 1][0:10] == lines[n - 2][0:10]:
lines.pop(n - 2)
pass
with open('assets/virus2.csv', 'w', encoding='utf-8') as fp:
start = 10
stop = 26
id = 0
for line in lines:
if id != 0:
fp.write(line[0:10] + line[26:])
else:
fp.write(line)
id += 1
print('finished!') |
#
# PySNMP MIB module ZHONE-COM-IP-FILTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-IP-FILTER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:40:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibIdentifier, ObjectIdentity, NotificationType, Unsigned32, Counter32, Integer32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Bits, TimeTicks, Gauge32, Counter64, iso = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "ObjectIdentity", "NotificationType", "Unsigned32", "Counter32", "Integer32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Bits", "TimeTicks", "Gauge32", "Counter64", "iso")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
zhoneModules, zhoneIp = mibBuilder.importSymbols("Zhone", "zhoneModules", "zhoneIp")
ZhoneRowStatus, ZhoneAdminString = mibBuilder.importSymbols("Zhone-TC", "ZhoneRowStatus", "ZhoneAdminString")
comIpFilter = ModuleIdentity((1, 3, 6, 1, 4, 1, 5504, 6, 58))
comIpFilter.setRevisions(('2005-01-10 10:16', '2005-01-03 09:24', '2004-12-21 09:25', '2004-08-30 11:00', '2004-04-06 00:17', '2001-01-17 08:48', '2000-09-11 16:22',))
if mibBuilder.loadTexts: comIpFilter.setLastUpdated('200501100015Z')
if mibBuilder.loadTexts: comIpFilter.setOrganization('Zhone Technologies, Inc.')
filter = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8))
if mibBuilder.loadTexts: filter.setStatus('current')
filterGlobal = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1))
if mibBuilder.loadTexts: filterGlobal.setStatus('current')
fltGlobalIndexNext = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fltGlobalIndexNext.setStatus('current')
fltGlobalTimeout = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: fltGlobalTimeout.setStatus('current')
filterSpecTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2), )
if mibBuilder.loadTexts: filterSpecTable.setStatus('current')
filterSpecEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "fltSpecIndex"))
if mibBuilder.loadTexts: filterSpecEntry.setStatus('current')
fltSpecIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: fltSpecIndex.setStatus('current')
fltSpecName = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 2), ZhoneAdminString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltSpecName.setStatus('current')
fltSpecDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 3), SnmpAdminString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltSpecDesc.setStatus('current')
fltSpecVersion1 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 4), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltSpecVersion1.setStatus('current')
fltSpecVersion2 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 5), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltSpecVersion2.setStatus('current')
fltSpecLanguageVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 6), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltSpecLanguageVersion.setStatus('current')
fltSpecRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 7), ZhoneRowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltSpecRowStatus.setStatus('current')
filterStatementTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3), )
if mibBuilder.loadTexts: filterStatementTable.setStatus('current')
filterStatementEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "fltSpecIndex"), (0, "ZHONE-COM-IP-FILTER-MIB", "fltStmtIndex"))
if mibBuilder.loadTexts: filterStatementEntry.setStatus('current')
fltStmtIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: fltStmtIndex.setStatus('current')
fltStmtIpSrcAddrLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 2), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtIpSrcAddrLow.setStatus('current')
fltStmtIpSrcAddrHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 3), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtIpSrcAddrHigh.setStatus('current')
fltStmtSrcPortLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtSrcPortLow.setStatus('current')
fltStmtSrcPortHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtSrcPortHigh.setStatus('current')
fltStmtIpDstAddrLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 6), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtIpDstAddrLow.setStatus('current')
fltStmtIpDstAddrHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 7), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtIpDstAddrHigh.setStatus('current')
fltStmtDstPortLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtDstPortLow.setStatus('current')
fltStmtDstPortHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtDstPortHigh.setStatus('current')
fltStmtIpProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("any", 1), ("ip", 2), ("tcp", 3), ("udp", 4), ("icmp", 5))).clone('any')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtIpProtocol.setStatus('current')
fltStmtArbValueBase = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("none", 1), ("ip", 2), ("udp", 3), ("tcp", 4), ("icmp", 5), ("ipOptions", 6), ("tcpOptions", 7))).clone('none')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtArbValueBase.setStatus('current')
fltStmtArbOffset = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtArbOffset.setStatus('current')
fltStmtArbMask = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 13), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtArbMask.setStatus('current')
fltStmtArbValueLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 14), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtArbValueLow.setStatus('current')
fltStmtArbValueHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 15), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtArbValueHigh.setStatus('current')
fltStmtModifier = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 16), Bits().clone(namedValues=NamedValues(("notIpSrc", 0), ("notSrcPort", 1), ("notDstIp", 2), ("notPortDst", 3), ("notProtocol", 4), ("notArbitrary", 5), ("notStatement", 6)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtModifier.setStatus('current')
fltStmtAction = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 17), Bits().clone(namedValues=NamedValues(("reset", 0), ("permit", 1), ("deny", 2), ("forward", 3), ("reject", 4), ("log", 5))).clone(namedValues=NamedValues(("deny", 2)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtAction.setStatus('current')
fltStmtActionArg = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 18), Integer32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtActionArg.setStatus('current')
fltStmtRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 19), ZhoneRowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: fltStmtRowStatus.setStatus('current')
filterStmtRenumTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4), )
if mibBuilder.loadTexts: filterStmtRenumTable.setStatus('current')
filterStmtRenumEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4, 1), )
filterStatementEntry.registerAugmentions(("ZHONE-COM-IP-FILTER-MIB", "filterStmtRenumEntry"))
filterStmtRenumEntry.setIndexNames(*filterStatementEntry.getIndexNames())
if mibBuilder.loadTexts: filterStmtRenumEntry.setStatus('current')
fltStmtIndexNew = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: fltStmtIndexNew.setStatus('current')
filterStatsTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5), )
if mibBuilder.loadTexts: filterStatsTable.setStatus('current')
filterStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "ZHONE-COM-IP-FILTER-MIB", "fltStatDirection"))
if mibBuilder.loadTexts: filterStatsEntry.setStatus('current')
fltStatDirection = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ingress", 1), ("egress", 2))))
if mibBuilder.loadTexts: fltStatDirection.setStatus('current')
fltStatResetPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 2), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: fltStatResetPkts.setStatus('current')
fltStatPermitPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 3), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: fltStatPermitPkts.setStatus('current')
fltStatDenyPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 4), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: fltStatDenyPkts.setStatus('current')
fltStatForwardPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 5), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: fltStatForwardPkts.setStatus('current')
fltStatRejectPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 6), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: fltStatRejectPkts.setStatus('current')
fltStatLogPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 7), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: fltStatLogPkts.setStatus('current')
fltStatDefaultPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fltStatDefaultPkts.setStatus('current')
fltStatSpecVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 9), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: fltStatSpecVersion.setStatus('current')
fltStatSpecIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: fltStatSpecIndex.setStatus('current')
mcastControl = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6))
if mibBuilder.loadTexts: mcastControl.setStatus('current')
mcastControlListTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1), )
if mibBuilder.loadTexts: mcastControlListTable.setStatus('current')
mcastControlListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "mcastControlListControlId"), (0, "ZHONE-COM-IP-FILTER-MIB", "mcastControlListControlPrecedence"))
if mibBuilder.loadTexts: mcastControlListEntry.setStatus('current')
mcastControlListControlId = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: mcastControlListControlId.setStatus('current')
mcastControlListControlPrecedence = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: mcastControlListControlPrecedence.setStatus('current')
mcastControlListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 3), ZhoneRowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mcastControlListRowStatus.setStatus('current')
mcastControlListIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 4), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mcastControlListIpAddress.setStatus('current')
mcastControlListType = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("normal", 1), ("always-on", 2), ("periodic", 3))).clone('normal')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mcastControlListType.setStatus('current')
portAccessControl = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7))
if mibBuilder.loadTexts: portAccessControl.setStatus('current')
portAccessNextIndex = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: portAccessNextIndex.setStatus('current')
portAccessTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2), )
if mibBuilder.loadTexts: portAccessTable.setStatus('current')
portAccessEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "portAccessIndex"))
if mibBuilder.loadTexts: portAccessEntry.setStatus('current')
portAccessIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100)))
if mibBuilder.loadTexts: portAccessIndex.setStatus('current')
portAccessRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 2), ZhoneRowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: portAccessRowStatus.setStatus('current')
portAccessNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1023))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: portAccessNumber.setStatus('current')
portAccessSrcAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 4), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: portAccessSrcAddr.setStatus('current')
portAccessNetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 5), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: portAccessNetMask.setStatus('current')
mibBuilder.exportSymbols("ZHONE-COM-IP-FILTER-MIB", fltStmtSrcPortHigh=fltStmtSrcPortHigh, fltStmtArbMask=fltStmtArbMask, mcastControlListIpAddress=mcastControlListIpAddress, fltSpecDesc=fltSpecDesc, fltSpecName=fltSpecName, fltStmtIpSrcAddrLow=fltStmtIpSrcAddrLow, mcastControlListRowStatus=mcastControlListRowStatus, fltStmtArbOffset=fltStmtArbOffset, fltStatPermitPkts=fltStatPermitPkts, fltStmtRowStatus=fltStmtRowStatus, mcastControlListTable=mcastControlListTable, fltStatDenyPkts=fltStatDenyPkts, filterStatementTable=filterStatementTable, filterGlobal=filterGlobal, PYSNMP_MODULE_ID=comIpFilter, fltStmtIpDstAddrLow=fltStmtIpDstAddrLow, fltStmtDstPortHigh=fltStmtDstPortHigh, fltStmtActionArg=fltStmtActionArg, portAccessNextIndex=portAccessNextIndex, fltSpecVersion1=fltSpecVersion1, filterSpecEntry=filterSpecEntry, filterStmtRenumTable=filterStmtRenumTable, portAccessEntry=portAccessEntry, mcastControlListControlPrecedence=mcastControlListControlPrecedence, portAccessSrcAddr=portAccessSrcAddr, portAccessControl=portAccessControl, mcastControlListControlId=mcastControlListControlId, fltSpecLanguageVersion=fltSpecLanguageVersion, fltStmtIpSrcAddrHigh=fltStmtIpSrcAddrHigh, fltStatDirection=fltStatDirection, mcastControl=mcastControl, fltStatSpecIndex=fltStatSpecIndex, fltStmtArbValueBase=fltStmtArbValueBase, fltStmtArbValueHigh=fltStmtArbValueHigh, fltStmtSrcPortLow=fltStmtSrcPortLow, fltStmtIpProtocol=fltStmtIpProtocol, fltSpecIndex=fltSpecIndex, fltStmtArbValueLow=fltStmtArbValueLow, fltGlobalTimeout=fltGlobalTimeout, fltStmtModifier=fltStmtModifier, fltStatForwardPkts=fltStatForwardPkts, filterSpecTable=filterSpecTable, fltStmtDstPortLow=fltStmtDstPortLow, filterStatsEntry=filterStatsEntry, fltStatDefaultPkts=fltStatDefaultPkts, portAccessRowStatus=portAccessRowStatus, fltStmtAction=fltStmtAction, fltStmtIpDstAddrHigh=fltStmtIpDstAddrHigh, portAccessNetMask=portAccessNetMask, portAccessTable=portAccessTable, filterStatementEntry=filterStatementEntry, filter=filter, fltSpecVersion2=fltSpecVersion2, fltStmtIndexNew=fltStmtIndexNew, filterStmtRenumEntry=filterStmtRenumEntry, fltSpecRowStatus=fltSpecRowStatus, filterStatsTable=filterStatsTable, portAccessIndex=portAccessIndex, fltStatSpecVersion=fltStatSpecVersion, portAccessNumber=portAccessNumber, fltGlobalIndexNext=fltGlobalIndexNext, mcastControlListEntry=mcastControlListEntry, mcastControlListType=mcastControlListType, fltStmtIndex=fltStmtIndex, fltStatRejectPkts=fltStatRejectPkts, comIpFilter=comIpFilter, fltStatLogPkts=fltStatLogPkts, fltStatResetPkts=fltStatResetPkts)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, constraints_intersection, single_value_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueRangeConstraint')
(if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex')
(snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(mib_identifier, object_identity, notification_type, unsigned32, counter32, integer32, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, bits, time_ticks, gauge32, counter64, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'ObjectIdentity', 'NotificationType', 'Unsigned32', 'Counter32', 'Integer32', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Bits', 'TimeTicks', 'Gauge32', 'Counter64', 'iso')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
(zhone_modules, zhone_ip) = mibBuilder.importSymbols('Zhone', 'zhoneModules', 'zhoneIp')
(zhone_row_status, zhone_admin_string) = mibBuilder.importSymbols('Zhone-TC', 'ZhoneRowStatus', 'ZhoneAdminString')
com_ip_filter = module_identity((1, 3, 6, 1, 4, 1, 5504, 6, 58))
comIpFilter.setRevisions(('2005-01-10 10:16', '2005-01-03 09:24', '2004-12-21 09:25', '2004-08-30 11:00', '2004-04-06 00:17', '2001-01-17 08:48', '2000-09-11 16:22'))
if mibBuilder.loadTexts:
comIpFilter.setLastUpdated('200501100015Z')
if mibBuilder.loadTexts:
comIpFilter.setOrganization('Zhone Technologies, Inc.')
filter = object_identity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8))
if mibBuilder.loadTexts:
filter.setStatus('current')
filter_global = object_identity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1))
if mibBuilder.loadTexts:
filterGlobal.setStatus('current')
flt_global_index_next = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
fltGlobalIndexNext.setStatus('current')
flt_global_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setUnits('seconds').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
fltGlobalTimeout.setStatus('current')
filter_spec_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2))
if mibBuilder.loadTexts:
filterSpecTable.setStatus('current')
filter_spec_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1)).setIndexNames((0, 'ZHONE-COM-IP-FILTER-MIB', 'fltSpecIndex'))
if mibBuilder.loadTexts:
filterSpecEntry.setStatus('current')
flt_spec_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647)))
if mibBuilder.loadTexts:
fltSpecIndex.setStatus('current')
flt_spec_name = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 2), zhone_admin_string()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltSpecName.setStatus('current')
flt_spec_desc = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 3), snmp_admin_string()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltSpecDesc.setStatus('current')
flt_spec_version1 = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 4), unsigned32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltSpecVersion1.setStatus('current')
flt_spec_version2 = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 5), unsigned32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltSpecVersion2.setStatus('current')
flt_spec_language_version = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 6), unsigned32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltSpecLanguageVersion.setStatus('current')
flt_spec_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 7), zhone_row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltSpecRowStatus.setStatus('current')
filter_statement_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3))
if mibBuilder.loadTexts:
filterStatementTable.setStatus('current')
filter_statement_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1)).setIndexNames((0, 'ZHONE-COM-IP-FILTER-MIB', 'fltSpecIndex'), (0, 'ZHONE-COM-IP-FILTER-MIB', 'fltStmtIndex'))
if mibBuilder.loadTexts:
filterStatementEntry.setStatus('current')
flt_stmt_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647)))
if mibBuilder.loadTexts:
fltStmtIndex.setStatus('current')
flt_stmt_ip_src_addr_low = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 2), ip_address().clone(hexValue='00000000')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtIpSrcAddrLow.setStatus('current')
flt_stmt_ip_src_addr_high = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 3), ip_address().clone(hexValue='00000000')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtIpSrcAddrHigh.setStatus('current')
flt_stmt_src_port_low = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtSrcPortLow.setStatus('current')
flt_stmt_src_port_high = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtSrcPortHigh.setStatus('current')
flt_stmt_ip_dst_addr_low = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 6), ip_address().clone(hexValue='00000000')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtIpDstAddrLow.setStatus('current')
flt_stmt_ip_dst_addr_high = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 7), ip_address().clone(hexValue='00000000')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtIpDstAddrHigh.setStatus('current')
flt_stmt_dst_port_low = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtDstPortLow.setStatus('current')
flt_stmt_dst_port_high = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 9), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtDstPortHigh.setStatus('current')
flt_stmt_ip_protocol = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('any', 1), ('ip', 2), ('tcp', 3), ('udp', 4), ('icmp', 5))).clone('any')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtIpProtocol.setStatus('current')
flt_stmt_arb_value_base = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=named_values(('none', 1), ('ip', 2), ('udp', 3), ('tcp', 4), ('icmp', 5), ('ipOptions', 6), ('tcpOptions', 7))).clone('none')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtArbValueBase.setStatus('current')
flt_stmt_arb_offset = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 12), integer32().subtype(subtypeSpec=value_range_constraint(0, 64))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtArbOffset.setStatus('current')
flt_stmt_arb_mask = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 13), unsigned32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtArbMask.setStatus('current')
flt_stmt_arb_value_low = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 14), unsigned32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtArbValueLow.setStatus('current')
flt_stmt_arb_value_high = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 15), unsigned32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtArbValueHigh.setStatus('current')
flt_stmt_modifier = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 16), bits().clone(namedValues=named_values(('notIpSrc', 0), ('notSrcPort', 1), ('notDstIp', 2), ('notPortDst', 3), ('notProtocol', 4), ('notArbitrary', 5), ('notStatement', 6)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtModifier.setStatus('current')
flt_stmt_action = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 17), bits().clone(namedValues=named_values(('reset', 0), ('permit', 1), ('deny', 2), ('forward', 3), ('reject', 4), ('log', 5))).clone(namedValues=named_values(('deny', 2)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtAction.setStatus('current')
flt_stmt_action_arg = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 18), integer32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtActionArg.setStatus('current')
flt_stmt_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 19), zhone_row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
fltStmtRowStatus.setStatus('current')
filter_stmt_renum_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4))
if mibBuilder.loadTexts:
filterStmtRenumTable.setStatus('current')
filter_stmt_renum_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4, 1))
filterStatementEntry.registerAugmentions(('ZHONE-COM-IP-FILTER-MIB', 'filterStmtRenumEntry'))
filterStmtRenumEntry.setIndexNames(*filterStatementEntry.getIndexNames())
if mibBuilder.loadTexts:
filterStmtRenumEntry.setStatus('current')
flt_stmt_index_new = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
fltStmtIndexNew.setStatus('current')
filter_stats_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5))
if mibBuilder.loadTexts:
filterStatsTable.setStatus('current')
filter_stats_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'ZHONE-COM-IP-FILTER-MIB', 'fltStatDirection'))
if mibBuilder.loadTexts:
filterStatsEntry.setStatus('current')
flt_stat_direction = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('ingress', 1), ('egress', 2))))
if mibBuilder.loadTexts:
fltStatDirection.setStatus('current')
flt_stat_reset_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 2), counter32()).setUnits('packets').setMaxAccess('readonly')
if mibBuilder.loadTexts:
fltStatResetPkts.setStatus('current')
flt_stat_permit_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 3), counter32()).setUnits('packets').setMaxAccess('readonly')
if mibBuilder.loadTexts:
fltStatPermitPkts.setStatus('current')
flt_stat_deny_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 4), counter32()).setUnits('packets').setMaxAccess('readonly')
if mibBuilder.loadTexts:
fltStatDenyPkts.setStatus('current')
flt_stat_forward_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 5), counter32()).setUnits('packets').setMaxAccess('readonly')
if mibBuilder.loadTexts:
fltStatForwardPkts.setStatus('current')
flt_stat_reject_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 6), counter32()).setUnits('packets').setMaxAccess('readonly')
if mibBuilder.loadTexts:
fltStatRejectPkts.setStatus('current')
flt_stat_log_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 7), counter32()).setUnits('packets').setMaxAccess('readonly')
if mibBuilder.loadTexts:
fltStatLogPkts.setStatus('current')
flt_stat_default_pkts = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
fltStatDefaultPkts.setStatus('current')
flt_stat_spec_version = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 9), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
fltStatSpecVersion.setStatus('current')
flt_stat_spec_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
fltStatSpecIndex.setStatus('current')
mcast_control = object_identity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6))
if mibBuilder.loadTexts:
mcastControl.setStatus('current')
mcast_control_list_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1))
if mibBuilder.loadTexts:
mcastControlListTable.setStatus('current')
mcast_control_list_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1)).setIndexNames((0, 'ZHONE-COM-IP-FILTER-MIB', 'mcastControlListControlId'), (0, 'ZHONE-COM-IP-FILTER-MIB', 'mcastControlListControlPrecedence'))
if mibBuilder.loadTexts:
mcastControlListEntry.setStatus('current')
mcast_control_list_control_id = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647)))
if mibBuilder.loadTexts:
mcastControlListControlId.setStatus('current')
mcast_control_list_control_precedence = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647)))
if mibBuilder.loadTexts:
mcastControlListControlPrecedence.setStatus('current')
mcast_control_list_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 3), zhone_row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mcastControlListRowStatus.setStatus('current')
mcast_control_list_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 4), ip_address()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mcastControlListIpAddress.setStatus('current')
mcast_control_list_type = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('normal', 1), ('always-on', 2), ('periodic', 3))).clone('normal')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
mcastControlListType.setStatus('current')
port_access_control = object_identity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7))
if mibBuilder.loadTexts:
portAccessControl.setStatus('current')
port_access_next_index = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
portAccessNextIndex.setStatus('current')
port_access_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2))
if mibBuilder.loadTexts:
portAccessTable.setStatus('current')
port_access_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1)).setIndexNames((0, 'ZHONE-COM-IP-FILTER-MIB', 'portAccessIndex'))
if mibBuilder.loadTexts:
portAccessEntry.setStatus('current')
port_access_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 100)))
if mibBuilder.loadTexts:
portAccessIndex.setStatus('current')
port_access_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 2), zhone_row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
portAccessRowStatus.setStatus('current')
port_access_number = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 1023))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
portAccessNumber.setStatus('current')
port_access_src_addr = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 4), ip_address()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
portAccessSrcAddr.setStatus('current')
port_access_net_mask = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 5), ip_address()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
portAccessNetMask.setStatus('current')
mibBuilder.exportSymbols('ZHONE-COM-IP-FILTER-MIB', fltStmtSrcPortHigh=fltStmtSrcPortHigh, fltStmtArbMask=fltStmtArbMask, mcastControlListIpAddress=mcastControlListIpAddress, fltSpecDesc=fltSpecDesc, fltSpecName=fltSpecName, fltStmtIpSrcAddrLow=fltStmtIpSrcAddrLow, mcastControlListRowStatus=mcastControlListRowStatus, fltStmtArbOffset=fltStmtArbOffset, fltStatPermitPkts=fltStatPermitPkts, fltStmtRowStatus=fltStmtRowStatus, mcastControlListTable=mcastControlListTable, fltStatDenyPkts=fltStatDenyPkts, filterStatementTable=filterStatementTable, filterGlobal=filterGlobal, PYSNMP_MODULE_ID=comIpFilter, fltStmtIpDstAddrLow=fltStmtIpDstAddrLow, fltStmtDstPortHigh=fltStmtDstPortHigh, fltStmtActionArg=fltStmtActionArg, portAccessNextIndex=portAccessNextIndex, fltSpecVersion1=fltSpecVersion1, filterSpecEntry=filterSpecEntry, filterStmtRenumTable=filterStmtRenumTable, portAccessEntry=portAccessEntry, mcastControlListControlPrecedence=mcastControlListControlPrecedence, portAccessSrcAddr=portAccessSrcAddr, portAccessControl=portAccessControl, mcastControlListControlId=mcastControlListControlId, fltSpecLanguageVersion=fltSpecLanguageVersion, fltStmtIpSrcAddrHigh=fltStmtIpSrcAddrHigh, fltStatDirection=fltStatDirection, mcastControl=mcastControl, fltStatSpecIndex=fltStatSpecIndex, fltStmtArbValueBase=fltStmtArbValueBase, fltStmtArbValueHigh=fltStmtArbValueHigh, fltStmtSrcPortLow=fltStmtSrcPortLow, fltStmtIpProtocol=fltStmtIpProtocol, fltSpecIndex=fltSpecIndex, fltStmtArbValueLow=fltStmtArbValueLow, fltGlobalTimeout=fltGlobalTimeout, fltStmtModifier=fltStmtModifier, fltStatForwardPkts=fltStatForwardPkts, filterSpecTable=filterSpecTable, fltStmtDstPortLow=fltStmtDstPortLow, filterStatsEntry=filterStatsEntry, fltStatDefaultPkts=fltStatDefaultPkts, portAccessRowStatus=portAccessRowStatus, fltStmtAction=fltStmtAction, fltStmtIpDstAddrHigh=fltStmtIpDstAddrHigh, portAccessNetMask=portAccessNetMask, portAccessTable=portAccessTable, filterStatementEntry=filterStatementEntry, filter=filter, fltSpecVersion2=fltSpecVersion2, fltStmtIndexNew=fltStmtIndexNew, filterStmtRenumEntry=filterStmtRenumEntry, fltSpecRowStatus=fltSpecRowStatus, filterStatsTable=filterStatsTable, portAccessIndex=portAccessIndex, fltStatSpecVersion=fltStatSpecVersion, portAccessNumber=portAccessNumber, fltGlobalIndexNext=fltGlobalIndexNext, mcastControlListEntry=mcastControlListEntry, mcastControlListType=mcastControlListType, fltStmtIndex=fltStmtIndex, fltStatRejectPkts=fltStatRejectPkts, comIpFilter=comIpFilter, fltStatLogPkts=fltStatLogPkts, fltStatResetPkts=fltStatResetPkts) |
class Solution(object):
def findDuplicate(self, paths):
"""
:type paths: List[str]
:rtype: List[List[str]]
"""
ret = []
hm = dict()
self.buildHashMap(paths, hm)
return [v for v in hm.itervalues() if len(v)>1]
def buildHashMap(self, paths, hm):
for s in paths:
tmpList = s.split()
folder = tmpList[0]
for i in xrange(1, len(tmpList)):
fileName, fileContent = tmpList[i].split('(')
fileContent = fileContent[:len(fileContent)-1]
group = hm.setdefault(fileContent, [])
group.append(folder + '/' + fileName) | class Solution(object):
def find_duplicate(self, paths):
"""
:type paths: List[str]
:rtype: List[List[str]]
"""
ret = []
hm = dict()
self.buildHashMap(paths, hm)
return [v for v in hm.itervalues() if len(v) > 1]
def build_hash_map(self, paths, hm):
for s in paths:
tmp_list = s.split()
folder = tmpList[0]
for i in xrange(1, len(tmpList)):
(file_name, file_content) = tmpList[i].split('(')
file_content = fileContent[:len(fileContent) - 1]
group = hm.setdefault(fileContent, [])
group.append(folder + '/' + fileName) |
user = ""
password = ""
host = "127.0.0.1"
database = ""
raise_on_warnings = True
config = {
"user": user,
"password": password,
"host": host,
"database": database,
"raise_on_warnings": raise_on_warnings,
}
def set_configs(user=None, password=None, database=None):
config["user"] = user
config["password"] = password
config["database"] = database
| user = ''
password = ''
host = '127.0.0.1'
database = ''
raise_on_warnings = True
config = {'user': user, 'password': password, 'host': host, 'database': database, 'raise_on_warnings': raise_on_warnings}
def set_configs(user=None, password=None, database=None):
config['user'] = user
config['password'] = password
config['database'] = database |
dic = {
'color':'red',
'typw':'car',
'price': 1250
} | dic = {'color': 'red', 'typw': 'car', 'price': 1250} |
"""
Return text based on the tab number passed
"""
def descriptions(index):
if index == 0: # Machine Tab
return text_0
elif index == 1: # Display Tab
return text_1
elif index == 2: # Axis Tab
return text_2
elif index == 3: # Spindle Tab
return text_3
elif index == 4: # Inputs Tab
return text_4
elif index == 5: # Outputs Tab
return text_5
elif index == 6: # Tool Changer Tab
return text_6
elif index == 70: # SS Cards Tab 0 - 8
return text_70
elif index == 71: # SS Cards Tab 0 - 8
return text_71
elif index == 72: # SS Cards Tab 0 - 8
return text_72
elif index == 73: # SS Cards Tab 0 - 8
return text_73
elif index == 74: # SS Cards Tab 0 - 8
return text_74
elif index == 75: # SS Cards Tab 0 - 8
return text_75
elif index == 76: # SS Cards Tab 0 - 8
return text_76
elif index == 77: # SS Cards Tab 0 - 8
return text_77
elif index == 78: # SS Cards Tab 0 - 8
return text_78
elif index == 8: # Options Tab
return text_8
elif index == 9: # PLC Tab
return text_9
elif index == 10: # Pins Tab
return text_10
elif index == 11: # Info Tab
return text_11
elif index == 12: # PC Tab
return text_12
elif index == 20:
return text_20
elif index == 30:
return text_30
else:
return text_no
text_0 = """
Help Text for Machine Tab
IP Address 10.10.10.10 is recommended to avoid conflicts on your LAN
10.10.10.10 W1 Down W2 Up
192.168.1.121 W1 Down W2 Down
Maximum Linear Velocity is in Selected Units per second.
Firmware
To read the current firmware select the IP Address first.
After reading the current firmware the Copy button will place the text in the clipboard.
To flash a card select the firmware and IP Address first.
After flashing Reload or Power Cycle the card
Only select encoders and stepgens if you want less that default.
"""
text_1 = """
Help Text for Display Tab
Offset and Feedback display use relative (including offsets) or absolute machine.
Overrides use percent of programed value.
QtPyVCP can only be installed on Debian 9
"""
text_2 = """
Help Text for Axis Tab
Joints must be configured starting with 0 and not skipping any.
Any joint can have any axis letter.
Scale is the number of steps to move one user unit (inch or mm).
Limits are in user units.
Velocity is user units per second, Acceleration is user units per second per second
PID Settings
P = Proportional P = (Commanded - Measured) * Pgain.
I = Integral I(new) = I(old) + Igain * (Commanded - Measured).
D = Derivative D = Dgain * (New_measured - Old_Measured)
FF0 = Commanded position * FF0 + Output
FF1 = First derivative of position * FF1
FF2 = Second derivative of position * FF2
FF0 is proportional to position (assuming an axis) or otherwise whatever
parameter is the input to the PID.
FF1 is the first derivative of position, so that is proportional
to velocity.
FF2 is second derivative of position, so it is proportional to acceleration.
Axis, PID Settings and StepGen Settings are required.
Homing fields are optional.
For gantry type of machines just select the same axis for each joint.
"""
text_3 = """
Help Text for Spindle Tab
"""
text_4 = """
Help Text for Inputs Tab
Inputs are optional
If the input is a type that is associated with an axis the axis must be
specified.
"""
text_5 = """
Help Text for Outputs Tab
Outputs are optional.
"""
text_6 = """
Help Text for Tool Changer Tab
"""
text_70 = """
Help Text for SS Cards Tab
"""
text_71 = """
Help Text for 7i64 Tab
"""
text_72 = """
Help Text for 7i69 Tab
"""
text_73 = """
Help Text for 7i70 Tab
"""
text_74 = """
Help Text for 7i71 Tab
"""
text_75 = """
Help Text for 7i72 Tab
"""
text_76 = """
Help Text for 7i73 Tab
Powered up no config running CR1 is solid red and CR2 is off
Powered up and LinuxCNC running CR1 is off and CR2 is blinking green
"""
text_77 = """
Help Text for 7i84 Tab
"""
text_78 = """
Help Text for 7i87 Tab
"""
text_8 = """
Help Text for Options Tab
On Screen Prompt for Manual Tool Change
This option is if you run G code with more than one tool and the tools can be
preset like BT and Cat holders. If you have collet type like ER and R8 you
should not check this and you should only one tool per G code program and
touch it off before running the program.
Hal User Interface
This option enables halui which exports hal pins so they can be connected to
physical or VCP or used in your hal configuration. These include pins related
to abort, tool, spindle, program, mode, mdi, coolant, max velocity, machine,
lube, joint, jog, feed override, rapid override, e stop, axis and home.
PyVCP Panel
This option adds the connections and a basic PyVCP panel.
GladeVCP Panel
Not functioning at this point.
Debug Options
This sets the debug level that is used when an error happens. When an error
occours the error information is sent to dmesg. Open a terminal and clear
dmesg with sudo dmesg -c then run your configuration and to view the error
in a terminal type dmesg.
"""
text_9 = """
Help Text for PLC Tab
Classicladder PLC will add a basic PLC to the configuration. You can also set
the number of components that Classicladder starts with.
"""
text_10 = """
Help Text for Pins Tab
If you have the 7i80 connected press get pins to get the current pinout
"""
text_11 = """
Help Text for Info Tab
Get CPU information and NIC information
"""
text_12 = """
Help Text for PC Tab
To check if the network packet time is ok get the CPU speed from the Info Tab.
Then get the tmax time and put those values into the boxes then hit calculate.
Make sure you select if the CPU speed is gHz or mHz.
To get tMax you must have the 7i80 connected to the PC and be running the
configuration with LinuxCNC.
"""
text_20 = """
Help Text for Building the Configuration
Opening the sample ini file and modifying is the fastest way to get a working configuration.
Check Configuration will scan the configuration for errors
Build Configuration will build all the configuration files needed.
The ini file is always overwritten.
The configName.hal file will always be overwritten.
The tool table, variable file, postgui.hal, custom.hal, configName.clp,
configName.xml files are never overwritten if present. To get a new one delete
the file and a new one will be created when you build the configuration.
"""
text_30 = """
Help Text for PC Setup
7i80 card requires the Master Branch of LinuxCNC
Mesa Ethernet Cards require LinuxCNC Uspace and the PREEMPT kernel.
Instructions to download and install Debian 9 and LinuxCNC Uspace with the
desktop of your choice
https://cdimage.debian.org/cdimage/unofficial/non-free/cd-including-firmware/
drill down to the latest version of the nonfree amd64 iso-cd netinst.iso
Burn to a CD if you have a PCI Ethernet card remove it, setup with the on board LAN only
Boot from the CD
Graphical Install, Do Not enter a Root Password! Just hit enter
Debian desktop environment, Mate, SSH server,Print server, standard system utilities
after booting to Debian 9 open a terminal
sudo nano /etc/lightdm/lightdm.conf
to log in without your user name a password uncomment and add your user name
autologin-user=yourusername
autologin-user-timeout=0
CTRL X and yes to save and exit.
Open the Synaptic Package Manager
search for linux-image and install linux-image-latest.version-rt
reboot the pc
in a terminal
uname -a # it should report back PREEMT RT
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install dirmngr
sudo apt-get install software-properties-common
*** to get the buildbot current build
sudo apt-key adv --keyserver hkp://keys.gnupg.net --recv-key E0EE663E
sudo add-apt-repository "deb http://buildbot.linuxcnc.org/ stretch master-rtpreempt"
sudo apt-get update
sudo apt-get install linuxcnc-uspace
Configure the network adapter to work with an Ethernet card
To find the Ethernet adapter name
ip link show
sudo nano /etc/network/interfaces
auto enp0s25 << change to match your interface name
iface enp0s25 inet static
address 10.10.10.1
netmask 255.255.255.0
shutdown and install a second LAN card if you need to connect to the internet
for git and programming tools
sudo apt-get install git-core git-gui make gcc
to add open in terminal to caja
sudo apt-get install caja-open-terminal
to be able to edit the menu add mozo
sudo apt-get install mozo
You will find it in System > Control Center > Main Menu
"""
text_no = """
No Help is found for this tab
"""
| """
Return text based on the tab number passed
"""
def descriptions(index):
if index == 0:
return text_0
elif index == 1:
return text_1
elif index == 2:
return text_2
elif index == 3:
return text_3
elif index == 4:
return text_4
elif index == 5:
return text_5
elif index == 6:
return text_6
elif index == 70:
return text_70
elif index == 71:
return text_71
elif index == 72:
return text_72
elif index == 73:
return text_73
elif index == 74:
return text_74
elif index == 75:
return text_75
elif index == 76:
return text_76
elif index == 77:
return text_77
elif index == 78:
return text_78
elif index == 8:
return text_8
elif index == 9:
return text_9
elif index == 10:
return text_10
elif index == 11:
return text_11
elif index == 12:
return text_12
elif index == 20:
return text_20
elif index == 30:
return text_30
else:
return text_no
text_0 = '\nHelp Text for Machine Tab\n\nIP Address 10.10.10.10 is recommended to avoid conflicts on your LAN\n\t10.10.10.10 W1 Down W2 Up\n\t192.168.1.121 W1 Down W2 Down\n\nMaximum Linear Velocity is in Selected Units per second.\n\nFirmware\nTo read the current firmware select the IP Address first.\n\tAfter reading the current firmware the Copy button will place the text in the clipboard.\nTo flash a card select the firmware and IP Address first.\n\tAfter flashing Reload or Power Cycle the card\n\nOnly select encoders and stepgens if you want less that default.\n'
text_1 = '\nHelp Text for Display Tab\n\nOffset and Feedback display use relative (including offsets) or absolute machine.\nOverrides use percent of programed value.\nQtPyVCP can only be installed on Debian 9\n'
text_2 = '\nHelp Text for Axis Tab\n\nJoints must be configured starting with 0 and not skipping any.\n\nAny joint can have any axis letter.\n\nScale is the number of steps to move one user unit (inch or mm).\nLimits are in user units.\nVelocity is user units per second, Acceleration is user units per second per second\n\nPID Settings\nP = Proportional P = (Commanded - Measured) * Pgain. \nI = Integral I(new) = I(old) + Igain * (Commanded - Measured). \nD = Derivative D = Dgain * (New_measured - Old_Measured)\nFF0 = Commanded position * FF0 + Output\nFF1 = First derivative of position * FF1\nFF2 = Second derivative of position * FF2\n\nFF0 is proportional to position (assuming an axis) or otherwise whatever\nparameter is the input to the PID.\n\nFF1 is the first derivative of position, so that is proportional\nto velocity.\n\nFF2 is second derivative of position, so it is proportional to acceleration.\n\nAxis, PID Settings and StepGen Settings are required.\n\nHoming fields are optional.\n\nFor gantry type of machines just select the same axis for each joint.\n'
text_3 = '\nHelp Text for Spindle Tab\n'
text_4 = '\nHelp Text for Inputs Tab\n\nInputs are optional\n\nIf the input is a type that is associated with an axis the axis must be\nspecified.\n'
text_5 = '\nHelp Text for Outputs Tab\n\nOutputs are optional.\n'
text_6 = '\nHelp Text for Tool Changer Tab\n\n'
text_70 = '\nHelp Text for SS Cards Tab\n'
text_71 = '\nHelp Text for 7i64 Tab\n'
text_72 = '\nHelp Text for 7i69 Tab\n'
text_73 = '\nHelp Text for 7i70 Tab\n'
text_74 = '\nHelp Text for 7i71 Tab\n'
text_75 = '\nHelp Text for 7i72 Tab\n'
text_76 = '\nHelp Text for 7i73 Tab\n\nPowered up no config running CR1 is solid red and CR2 is off\nPowered up and LinuxCNC running CR1 is off and CR2 is blinking green\n\n'
text_77 = '\nHelp Text for 7i84 Tab\n'
text_78 = '\nHelp Text for 7i87 Tab\n'
text_8 = '\nHelp Text for Options Tab\n\nOn Screen Prompt for Manual Tool Change\n\tThis option is if you run G code with more than one tool and the tools can be\n\tpreset like BT and Cat holders. If you have collet type like ER and R8 you\n\tshould not check this and you should only one tool per G code program and\n\ttouch it off before running the program.\n\nHal User Interface\n\tThis option enables halui which exports hal pins so they can be connected to\n\tphysical or VCP or used in your hal configuration. These include pins related\n\tto abort, tool, spindle, program, mode, mdi, coolant, max velocity, machine,\n\tlube, joint, jog, feed override, rapid override, e stop, axis and home.\n\nPyVCP Panel\n\tThis option adds the connections and a basic PyVCP panel.\n\nGladeVCP Panel\n\tNot functioning at this point.\n\nDebug Options\n\tThis sets the debug level that is used when an error happens. When an error\n\toccours the error information is sent to dmesg. Open a terminal and clear\n\tdmesg with sudo dmesg -c then run your configuration and to view the error\n\tin a terminal type dmesg.\n'
text_9 = '\nHelp Text for PLC Tab\n\nClassicladder PLC will add a basic PLC to the configuration. You can also set\nthe number of components that Classicladder starts with.\n'
text_10 = '\nHelp Text for Pins Tab\n\nIf you have the 7i80 connected press get pins to get the current pinout\n'
text_11 = '\nHelp Text for Info Tab\n\nGet CPU information and NIC information\n'
text_12 = '\nHelp Text for PC Tab\n\nTo check if the network packet time is ok get the CPU speed from the Info Tab.\nThen get the tmax time and put those values into the boxes then hit calculate.\nMake sure you select if the CPU speed is gHz or mHz.\n\nTo get tMax you must have the 7i80 connected to the PC and be running the\nconfiguration with LinuxCNC.\n'
text_20 = '\nHelp Text for Building the Configuration\n\nOpening the sample ini file and modifying is the fastest way to get a working configuration.\nCheck Configuration will scan the configuration for errors\nBuild Configuration will build all the configuration files needed.\n\tThe ini file is always overwritten.\n\tThe configName.hal file will always be overwritten.\n\tThe tool table, variable file, postgui.hal, custom.hal, configName.clp,\n\tconfigName.xml files are never overwritten if present. To get a new one delete\n\tthe file and a new one will be created when you build the configuration.\n'
text_30 = '\nHelp Text for PC Setup\n\n7i80 card requires the Master Branch of LinuxCNC\n\nMesa Ethernet Cards require LinuxCNC Uspace and the PREEMPT kernel.\n\nInstructions to download and install Debian 9 and LinuxCNC Uspace with the\ndesktop of your choice\n\nhttps://cdimage.debian.org/cdimage/unofficial/non-free/cd-including-firmware/\ndrill down to the latest version of the nonfree amd64 iso-cd netinst.iso\n\nBurn to a CD if you have a PCI Ethernet card remove it, setup with the on board LAN only\nBoot from the CD\nGraphical Install, Do Not enter a Root Password! Just hit enter\nDebian desktop environment, Mate, SSH server,Print server, standard system utilities\n\nafter booting to Debian 9 open a terminal\nsudo nano /etc/lightdm/lightdm.conf\nto log in without your user name a password uncomment and add your user name\nautologin-user=yourusername\nautologin-user-timeout=0\nCTRL X and yes to save and exit.\n\nOpen the Synaptic Package Manager\nsearch for linux-image and install linux-image-latest.version-rt\n\nreboot the pc\n\nin a terminal\nuname -a # it should report back PREEMT RT\nsudo apt-get update\nsudo apt-get dist-upgrade\nsudo apt-get install dirmngr\nsudo apt-get install software-properties-common\n*** to get the buildbot current build\nsudo apt-key adv --keyserver hkp://keys.gnupg.net --recv-key E0EE663E\nsudo add-apt-repository "deb http://buildbot.linuxcnc.org/ stretch master-rtpreempt"\nsudo apt-get update\nsudo apt-get install linuxcnc-uspace\n\nConfigure the network adapter to work with an Ethernet card\nTo find the Ethernet adapter name\nip link show\n\nsudo nano /etc/network/interfaces\nauto enp0s25 << change to match your interface name\n iface enp0s25 inet static\n address 10.10.10.1\n netmask 255.255.255.0\n\nshutdown and install a second LAN card if you need to connect to the internet\n\nfor git and programming tools\nsudo apt-get install git-core git-gui make gcc\n\nto add open in terminal to caja\nsudo apt-get install caja-open-terminal\n\nto be able to edit the menu add mozo\nsudo apt-get install mozo\nYou will find it in System > Control Center > Main Menu\n'
text_no = '\nNo Help is found for this tab\n' |
# Store the RSS feed IDs for each of the topics in the CNBC client.
cnbc_rss_feeds_id = {
'top_news': 100003114,
'world_news': 100727362,
'us_news': 15837362,
'asia_news': 19832390,
'europe_news': 19794221,
'business': 10001147,
'earnings': 15839135,
'commentary': 100370673,
'economy': 20910258,
'finance': 10000664,
'technology': 19854910,
'politics': 10000113,
'health_care': 10000108,
'real_estate': 10000115,
'wealth': 10001054,
'autos': 10000101,
'energy': 19836768,
'media': 10000110,
'retail': 10000116,
'travel': 10000739,
'small_business': 44877279,
'investing': 15839069,
'financial_advisors': 100646281,
'personal_finance': 21324812,
'charting_asia': 23103686,
'funny_business': 17646093,
'market_insider': 20409666,
'netnet': 38818154,
'trader_talk': 20398120,
'buffett_watch': 19206666,
'top_video': 15839263,
'digital_workshop': 100616801,
'latest_video': 100004038,
'ceo_interviews': 100004032,
'analyst_interviews': 100004033,
'must_watch': 101014894,
'squawk_box': 15838368,
'squawk_on_the_street': 15838381,
'power_lunch': 15838342,
'street_signs': 15838408,
'options_action': 28282083,
'closing_bell': 15838421,
'fast_money': 15838499,
'mad_money': 15838459,
'kudlow_report': 15838446,
'futures_now': 48227449,
'suze_orman': 15838523,
'capital_connection': 17501773,
'squawk_box_europe': 15838652,
'worldwide_exchange': 15838355,
'squawk_box_asia': 15838831,
'the_call': 37447855,
}
| cnbc_rss_feeds_id = {'top_news': 100003114, 'world_news': 100727362, 'us_news': 15837362, 'asia_news': 19832390, 'europe_news': 19794221, 'business': 10001147, 'earnings': 15839135, 'commentary': 100370673, 'economy': 20910258, 'finance': 10000664, 'technology': 19854910, 'politics': 10000113, 'health_care': 10000108, 'real_estate': 10000115, 'wealth': 10001054, 'autos': 10000101, 'energy': 19836768, 'media': 10000110, 'retail': 10000116, 'travel': 10000739, 'small_business': 44877279, 'investing': 15839069, 'financial_advisors': 100646281, 'personal_finance': 21324812, 'charting_asia': 23103686, 'funny_business': 17646093, 'market_insider': 20409666, 'netnet': 38818154, 'trader_talk': 20398120, 'buffett_watch': 19206666, 'top_video': 15839263, 'digital_workshop': 100616801, 'latest_video': 100004038, 'ceo_interviews': 100004032, 'analyst_interviews': 100004033, 'must_watch': 101014894, 'squawk_box': 15838368, 'squawk_on_the_street': 15838381, 'power_lunch': 15838342, 'street_signs': 15838408, 'options_action': 28282083, 'closing_bell': 15838421, 'fast_money': 15838499, 'mad_money': 15838459, 'kudlow_report': 15838446, 'futures_now': 48227449, 'suze_orman': 15838523, 'capital_connection': 17501773, 'squawk_box_europe': 15838652, 'worldwide_exchange': 15838355, 'squawk_box_asia': 15838831, 'the_call': 37447855} |
# START PROBLEM SET 01
print('PROBLEM SET 01 \n')
# PROBLEM 01A (25 points)
# Uncomment the variable name and assigned value that adheres to the styling
# convention described in PEP 08 for function and variable names
# (see https://www.python.org/dev/peps/pep-0008/#function-and-variable-names)
# Choose wisely or you will trigger a syntax error.
# Hint: uncomment = remove hash symbol ('#') and any leading whitespace in front
# of the variable name.
# Guido van Rossum is the original author of Python and former
# Benevolent dictator for life (BDFL) of the project.
# BEGIN 01A SOLUTION
# 1st_bdfl = 'Guido van Rossum'
# benevolent_dictator_for_life! = 'Guido van Rossum'
# python author = 'Guido van Rossum'
# python_author = 'Guido van Rossum'
# lambda = 'Guido van Rossum'
# END 01A SOLUTION
# PROBLEM 01B (25 points)
# Use the appropriate operator to append (i.e., concatenate) Guido's current position
# at the Python Software Foundation (see https://www.python.org/psf/members/#officers)
# to the value assigned to the variable you chose you in Problem 01A. Assign
# the concatenated value to the variable python_foundation_officer.
# Adopt the following format for the new string:
# "<name>, President"
python_foundation_officer = ''
# Note use of the .join() function to join a list of items to an
# empty string in order to form a new string
print(''.join(['python_foundation_officer=', python_foundation_officer, '\n']))
# END 01B SOLUTION
# START PROBLEM 01C-E SETUP (do not modify)
# The Zen of Python, by Tim Peters (1999)
# Mail list (1999): https://mail.python.org/pipermail/python-list/1999-June/001951.html
# PEP 20 (2004): https://www.python.org/dev/peps/pep-0020/
# Note the use of triple (""") quotes to denote a multi-line string.
zen_of_python = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
print(''.join(['zen_of_python=', zen_of_python, '\n']))
# END SETUP
# PROBLEM 01C (25 points)
# Count the number of characters in the string assigned to the
# variable zen_of_python and assign the value to the variable num_chars.
# BEGIN 01C SOLUTION
num_chars = 0
print(''.join(['num_chars=', str(num_chars), '\n']))
# END 01C SOLUTION
# PROBLEM 01D (25 points)
# Count the number of "words" separated by whitespace (word is used
# figuratively since not all the character chunks you will encounter are
# actually words) in the string assigned to the variable zen_of_python
# and assign the value to the variable num_char_chunks.
# BEGIN 01D SOLUTION
num_char_chunks = 0
# Note use of the built-in str() function to format num_char_chunks as a string.
print(''.join(['num_char_chunks=', str(num_char_chunks), '\n']))
# END 01D SOLUTION
# PROBLEM 01E (25 points)
# Use floor division to divide num_char_chunks by 19 (i.e., the number of lines
# in the Zen of Python). Return an integer rather than a floating point value.
# Assign the value to the variable avg_num_chunks_per_line.
# BEGIN 01E SOLUTION
avg_num_chunks_per_line = 0
print(''.join(['avg_num_chunks_per_line=', str(avg_num_chunks_per_line), '\n']))
# END 01E SOLUTION
# PROBLEM 01F (25 points)
# Substitute your U-M email address for all occurrences of the word "Dutch" using
# the appropriate built-in function in the zen_of_python string. Assign the modified
# Zen of Python string to a new variable named "zen_of_python_uniqname".
# BEGIN 01F SOLUTION
zen_of_python_uniqname = ''
print(''.join(['zen_of_python_uniqname=', zen_of_python_uniqname, '\n']))
# END 01F SOLUTION
# END PROBLEM SET
| print('PROBLEM SET 01 \n')
python_foundation_officer = ''
print(''.join(['python_foundation_officer=', python_foundation_officer, '\n']))
zen_of_python = "Beautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!"
print(''.join(['zen_of_python=', zen_of_python, '\n']))
num_chars = 0
print(''.join(['num_chars=', str(num_chars), '\n']))
num_char_chunks = 0
print(''.join(['num_char_chunks=', str(num_char_chunks), '\n']))
avg_num_chunks_per_line = 0
print(''.join(['avg_num_chunks_per_line=', str(avg_num_chunks_per_line), '\n']))
zen_of_python_uniqname = ''
print(''.join(['zen_of_python_uniqname=', zen_of_python_uniqname, '\n'])) |
class BasicCalculator:
def __init__(self):
return
def sum(self, num1, num2): return num1 + num2
def sub(self, num1, num2): return num1 - num2
def mul(self, num1, num2): return num1 * num2
def div(self, num1, num2): return num1 / num2
class AdvancedCalculator(BasicCalculator):
def __init__(self):
return
def pow(self, num, power):
foo = num
while power > 0:
print(power)
num *= foo
power -= 1
return num
def square(self, num): return pow(self, num, 2)
def cube(self, num): return pow(self, num, 3)
class ScientificCalculator(AdvancedCalculator):
def __init__(self):
return
def average(self, *nums):
sum = 0
count = 0
for num in nums:
count += 1
sum += num
return int(sum / count)
| class Basiccalculator:
def __init__(self):
return
def sum(self, num1, num2):
return num1 + num2
def sub(self, num1, num2):
return num1 - num2
def mul(self, num1, num2):
return num1 * num2
def div(self, num1, num2):
return num1 / num2
class Advancedcalculator(BasicCalculator):
def __init__(self):
return
def pow(self, num, power):
foo = num
while power > 0:
print(power)
num *= foo
power -= 1
return num
def square(self, num):
return pow(self, num, 2)
def cube(self, num):
return pow(self, num, 3)
class Scientificcalculator(AdvancedCalculator):
def __init__(self):
return
def average(self, *nums):
sum = 0
count = 0
for num in nums:
count += 1
sum += num
return int(sum / count) |
#!/usr/bin/env python3
# Print out all the unique pairwise amino acid combinations
# AC is the same as CA
# Skip AA, CC etc.
# Also print out how many combinations there are
amino = 'ACDEFGHIKLMNPQRSTVWY'
k = 1
i = -1
for i in range(i, len(amino)):
i += 1
for i2 in range(i+1, len(amino)):
print(amino[i], amino[i2])
"""
s = 'ACCGTACTGCATCAATCGATG'
k = 3
for i in range(len(s)-k+1):
print(s[i:i + 2]) #kmers
print('- end of loop 6')
"""
"""
t = 'ACCGTACTGCATCAATCGATG'
k = 3
for i in range(len(t)-k+1):
print(t[i:i + k]) #kmers
print('- end of loop 6')
s = 'ACGT' # a string
# Square brackets let you access sub-strings as 'slices'
# Follow closely below, because the endpoints can be confusing
# The first number before : is the starting index
# The second number : is one larger than the last index
print(s, s[0], s[1])
print(s[2], s[2:3], s[2:4], s[2:5])
print(s[-1:])
"""
"""
python3 25aapairs.py
A C
A D
A E
A F
A G
A H
A I
A K
A L
A M
A N
A P
A Q
A R
A S
A T
A V
A W
A Y
C D
C E
C F
C G
C H
C I
C K
C L
C M
C N
C P
C Q
C R
C S
C T
C V
C W
C Y
D E
D F
D G
D H
D I
D K
D L
D M
D N
D P
D Q
D R
D S
D T
D V
D W
D Y
E F
E G
E H
E I
E K
E L
E M
E N
E P
E Q
E R
E S
E T
E V
E W
E Y
F G
F H
F I
F K
F L
F M
F N
F P
F Q
F R
F S
F T
F V
F W
F Y
G H
G I
G K
G L
G M
G N
G P
G Q
G R
G S
G T
G V
G W
G Y
H I
H K
H L
H M
H N
H P
H Q
H R
H S
H T
H V
H W
H Y
I K
I L
I M
I N
I P
I Q
I R
I S
I T
I V
I W
I Y
K L
K M
K N
K P
K Q
K R
K S
K T
K V
K W
K Y
L M
L N
L P
L Q
L R
L S
L T
L V
L W
L Y
M N
M P
M Q
M R
M S
M T
M V
M W
M Y
N P
N Q
N R
N S
N T
N V
N W
N Y
P Q
P R
P S
P T
P V
P W
P Y
Q R
Q S
Q T
Q V
Q W
Q Y
R S
R T
R V
R W
R Y
S T
S V
S W
S Y
T V
T W
T Y
V W
V Y
W Y
190
"""
| amino = 'ACDEFGHIKLMNPQRSTVWY'
k = 1
i = -1
for i in range(i, len(amino)):
i += 1
for i2 in range(i + 1, len(amino)):
print(amino[i], amino[i2])
"\ns = 'ACCGTACTGCATCAATCGATG'\nk = 3\nfor i in range(len(s)-k+1):\n\tprint(s[i:i + 2]) #kmers\nprint('- end of loop 6')\n\n\n"
"\nt = 'ACCGTACTGCATCAATCGATG'\nk = 3\nfor i in range(len(t)-k+1):\n\tprint(t[i:i + k]) #kmers\nprint('- end of loop 6')\n\ns = 'ACGT' # a string\n\n# Square brackets let you access sub-strings as 'slices'\n# Follow closely below, because the endpoints can be confusing\n# The first number before : is the starting index\n# The second number : is one larger than the last index\n\nprint(s, s[0], s[1])\nprint(s[2], s[2:3], s[2:4], s[2:5])\nprint(s[-1:])\n"
'\npython3 25aapairs.py\nA C\nA D\nA E\nA F\nA G\nA H\nA I\nA K\nA L\nA M\nA N\nA P\nA Q\nA R\nA S\nA T\nA V\nA W\nA Y\nC D\nC E\nC F\nC G\nC H\nC I\nC K\nC L\nC M\nC N\nC P\nC Q\nC R\nC S\nC T\nC V\nC W\nC Y\nD E\nD F\nD G\nD H\nD I\nD K\nD L\nD M\nD N\nD P\nD Q\nD R\nD S\nD T\nD V\nD W\nD Y\nE F\nE G\nE H\nE I\nE K\nE L\nE M\nE N\nE P\nE Q\nE R\nE S\nE T\nE V\nE W\nE Y\nF G\nF H\nF I\nF K\nF L\nF M\nF N\nF P\nF Q\nF R\nF S\nF T\nF V\nF W\nF Y\nG H\nG I\nG K\nG L\nG M\nG N\nG P\nG Q\nG R\nG S\nG T\nG V\nG W\nG Y\nH I\nH K\nH L\nH M\nH N\nH P\nH Q\nH R\nH S\nH T\nH V\nH W\nH Y\nI K\nI L\nI M\nI N\nI P\nI Q\nI R\nI S\nI T\nI V\nI W\nI Y\nK L\nK M\nK N\nK P\nK Q\nK R\nK S\nK T\nK V\nK W\nK Y\nL M\nL N\nL P\nL Q\nL R\nL S\nL T\nL V\nL W\nL Y\nM N\nM P\nM Q\nM R\nM S\nM T\nM V\nM W\nM Y\nN P\nN Q\nN R\nN S\nN T\nN V\nN W\nN Y\nP Q\nP R\nP S\nP T\nP V\nP W\nP Y\nQ R\nQ S\nQ T\nQ V\nQ W\nQ Y\nR S\nR T\nR V\nR W\nR Y\nS T\nS V\nS W\nS Y\nT V\nT W\nT Y\nV W\nV Y\nW Y\n190\n' |
#!/usr/bin/env python3
def harmasosztas(szam):
if szam in range(0, 10):
return "00" + str(szam)
elif szam in range(10, 100):
return "0" + str(szam)
elif szam in range(100, 1000):
return szam
else:
return str(harmasosztas(szam // 1000)) + " " + str(harmasosztas(szam % 1000))
def main():
print(harmasosztas(1000222))
main()
| def harmasosztas(szam):
if szam in range(0, 10):
return '00' + str(szam)
elif szam in range(10, 100):
return '0' + str(szam)
elif szam in range(100, 1000):
return szam
else:
return str(harmasosztas(szam // 1000)) + ' ' + str(harmasosztas(szam % 1000))
def main():
print(harmasosztas(1000222))
main() |
keywords = ["asm","else","new","this","auto","enum","operator","throw","bool","explicit","private","true","break","export","protected","try","case","extern","public","typedef","catch","false","register","typeid","char","float","reinterpret_cast","typename","class","for","return","union","const","friend","short","unsigned","const_cast","goto","signed", "using","continue","if","sizeof","virtual","default","inline","static","void","delete", "int","static_cast","volatile","do","long","struct","wchar_t","double","mutable","switch","while",'dynamic_cast',"namespace","template"]
operator = ["+", "-", "*", "/", "%", "="]
punc_marks = ["<", ">", "#", "}", "{", "(", ")", ":", ";", ","]
key_count = [0]*len(keywords)
op_count = [0]*len(operator)
pun_count = [0]*len(punc_marks)
with open('1.cpp', 'r') as f:
sample = f.read()
words = []
lines = sample.split("\n")
for i in lines:
for j in range(0, len(i)):
if i[j] == "/" and i[j+1] == "/":
lines.remove(i)
for word in lines:
words.append(word.split(" "))
if word.split("(") not in words:
words.append(word.split("("))
else:
if word.split(")") not in words:
words.append(word.split(")"))
else:
if word.split(")") not in words:
words.append(word.split(")"))
else:
if word.split("#") not in words:
words.append(word.split(";"))
else:
if word.split("#") not in words:
words.append(word.split("#"))
else:
if word.split("<") not in words:
words.append(word.split("<"))
else:
if word.split(">") not in words:
words.append(word.split(">"))
else:
if word.split(":") not in words:
words.append(word.split(":"))
for line in sample:
for ch in line:
for i in range(0, len(operator)):
if ch == operator[i]:
op_count[i] += 1
for i in range(0, len(punc_marks)):
if ch == punc_marks[i]:
pun_count[i] += 1
q = []
for i in words:
for j in i:
q.append(j)
for i in range(0, len(q)):
if q[i] in keywords:
ind = keywords.index(q[i])
key_count[ind] += 1
if q[i] in operator:
ind = operator.index(q[i])
op_count[ind] += 1
if q[i] in punc_marks:
ind = punc_marks.index(q[i])
pun_count[ind] += 1
print("Keywords :")
for i in range(0, len(keywords)):
if key_count[i] > 0:
print(keywords[i], ": ", key_count[i])
print("\nOperators :")
for i in range(0, len(operator)):
if op_count[i] > 0:
print(operator[i], ": ", op_count[i])
print("\nPunctuation Marks :")
for i in range(0, len(punc_marks)):
if pun_count[i] > 0:
print(punc_marks[i], ": ", pun_count[i]) | keywords = ['asm', 'else', 'new', 'this', 'auto', 'enum', 'operator', 'throw', 'bool', 'explicit', 'private', 'true', 'break', 'export', 'protected', 'try', 'case', 'extern', 'public', 'typedef', 'catch', 'false', 'register', 'typeid', 'char', 'float', 'reinterpret_cast', 'typename', 'class', 'for', 'return', 'union', 'const', 'friend', 'short', 'unsigned', 'const_cast', 'goto', 'signed', 'using', 'continue', 'if', 'sizeof', 'virtual', 'default', 'inline', 'static', 'void', 'delete', 'int', 'static_cast', 'volatile', 'do', 'long', 'struct', 'wchar_t', 'double', 'mutable', 'switch', 'while', 'dynamic_cast', 'namespace', 'template']
operator = ['+', '-', '*', '/', '%', '=']
punc_marks = ['<', '>', '#', '}', '{', '(', ')', ':', ';', ',']
key_count = [0] * len(keywords)
op_count = [0] * len(operator)
pun_count = [0] * len(punc_marks)
with open('1.cpp', 'r') as f:
sample = f.read()
words = []
lines = sample.split('\n')
for i in lines:
for j in range(0, len(i)):
if i[j] == '/' and i[j + 1] == '/':
lines.remove(i)
for word in lines:
words.append(word.split(' '))
if word.split('(') not in words:
words.append(word.split('('))
elif word.split(')') not in words:
words.append(word.split(')'))
elif word.split(')') not in words:
words.append(word.split(')'))
elif word.split('#') not in words:
words.append(word.split(';'))
elif word.split('#') not in words:
words.append(word.split('#'))
elif word.split('<') not in words:
words.append(word.split('<'))
elif word.split('>') not in words:
words.append(word.split('>'))
elif word.split(':') not in words:
words.append(word.split(':'))
for line in sample:
for ch in line:
for i in range(0, len(operator)):
if ch == operator[i]:
op_count[i] += 1
for i in range(0, len(punc_marks)):
if ch == punc_marks[i]:
pun_count[i] += 1
q = []
for i in words:
for j in i:
q.append(j)
for i in range(0, len(q)):
if q[i] in keywords:
ind = keywords.index(q[i])
key_count[ind] += 1
if q[i] in operator:
ind = operator.index(q[i])
op_count[ind] += 1
if q[i] in punc_marks:
ind = punc_marks.index(q[i])
pun_count[ind] += 1
print('Keywords :')
for i in range(0, len(keywords)):
if key_count[i] > 0:
print(keywords[i], ': ', key_count[i])
print('\nOperators :')
for i in range(0, len(operator)):
if op_count[i] > 0:
print(operator[i], ': ', op_count[i])
print('\nPunctuation Marks :')
for i in range(0, len(punc_marks)):
if pun_count[i] > 0:
print(punc_marks[i], ': ', pun_count[i]) |
EventRandomDialogue = 1
EventRandomEffects = 2
EventEstateGravity = 3
EventGlobalGravity = 4
EventSirMaxBirthday = 5
RandomCheesyList = [
1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 11, 11]
RandomCheesyMinTime = 3
RandomCheesyMaxTime = 60 | event_random_dialogue = 1
event_random_effects = 2
event_estate_gravity = 3
event_global_gravity = 4
event_sir_max_birthday = 5
random_cheesy_list = [1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 11, 11]
random_cheesy_min_time = 3
random_cheesy_max_time = 60 |
mylist = [[1,2,3],[4,5,6],[4,3,8]]
print("Multi-Dimensional List",mylist)
mylist[1].reverse()
mylist[0].reverse()
print("Multi-Dimensional After Sublist-List",mylist)
| mylist = [[1, 2, 3], [4, 5, 6], [4, 3, 8]]
print('Multi-Dimensional List', mylist)
mylist[1].reverse()
mylist[0].reverse()
print('Multi-Dimensional After Sublist-List', mylist) |
def print_metrics(counter,
metrics,
summary_writer=None,
prefix=None,
model_name=""):
if 'cls_report' in metrics.keys():
metrics = metrics.copy()
del metrics['cls_report']
# print(prefix + "\t" + "\t".join([f"{key}:{value:.5f}" for key, value in metrics.items()]))
if summary_writer is not None:
assert prefix is not None
for key, value in metrics.items():
summary_writer.add_scalar(f'{model_name}_{prefix}_{key}', value, counter)
| def print_metrics(counter, metrics, summary_writer=None, prefix=None, model_name=''):
if 'cls_report' in metrics.keys():
metrics = metrics.copy()
del metrics['cls_report']
if summary_writer is not None:
assert prefix is not None
for (key, value) in metrics.items():
summary_writer.add_scalar(f'{model_name}_{prefix}_{key}', value, counter) |
# Argument that are used to create simulation objects.
#
# They are resolved as follows:
#
# 1. Numeric values are inlined.
# 2. List and Tuples are iterated over, creating a
# separate simulation object for each value.
# 3. Strings are evaluated as previous keys of ARGS.
# If it fails to find a key, the value is inlined.
#
# Example
# ARGS = {
# 'x': 10, # Evaluates to "x 10"
# 'y': [10, 20, 30], # Create one simulation for
# # each value of y
# 'logfile': '~/mylog.txt' # As there is no previous entry with
# # the key `logfile`, the string
# # '~/mylog.txt' is inlined.
# # It evaluates to "logfile ~/mylog.txt"
# 'other_x': 'x', # Because `x` is a previous key,
# # 'other_x' will have the same value
# # of x.
# # It evaluates to "other_x 10"
# }
ARGS = dict()
# Sequencial arguments to be passed to the executable.
# To set keyword arguments, use `ARGS`
# Example:
# SEQ_ARGS = [ '-one', '-two' ]
SEQ_ARGS = list()
# Executable
EXECUTABLE = None
# Redirect standard input
STDIN = None
# Redirect standard output
STDOUT = None
# Redirect standard error
STDERR = None
# Number of parallel instaces used on the simulation.
# Internally, the implementation uses subprocesses to
# spawn instances. Avoid using more than the number of
# cpus available
PARALLEL_INSTANCES = 1
# If True, pysim will capture all SIGINT interruptions and
# send them to pysim.core.signals.keyboard_interrupt.
CAPTURE_SIGINT = False
| args = dict()
seq_args = list()
executable = None
stdin = None
stdout = None
stderr = None
parallel_instances = 1
capture_sigint = False |
def entrada():
p,n = map(int,input().split())
x = input().split()
for i in range(len(x)):
x[i] = int(x[i])
return p,n,x
def verifica(a,b,p):
if abs(a-b) > p:
return True
else:
return False
def main():
p,n,x = entrada()
a = False
for i in range(n-1):
a = verifica(x[i],x[i+1],p)
if a == True:
print('GAME OVER')
break
if a == False:
print('YOU WIN')
main()
| def entrada():
(p, n) = map(int, input().split())
x = input().split()
for i in range(len(x)):
x[i] = int(x[i])
return (p, n, x)
def verifica(a, b, p):
if abs(a - b) > p:
return True
else:
return False
def main():
(p, n, x) = entrada()
a = False
for i in range(n - 1):
a = verifica(x[i], x[i + 1], p)
if a == True:
print('GAME OVER')
break
if a == False:
print('YOU WIN')
main() |
'''
*** A program for the cryptanalysis of Caesar cipher and identify the plaintext ***
'''
#All albhabet Frequencies in Known and meaningful English words
al_freq = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966,
0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,
0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074]
chi_square = [0] * 25
#Decryption of ciphertext with relative decryption key
def decrypt(ciphertext, s):
pltext = ""
for i in range(len(ciphertext)):
char = ciphertext[i]
if (char.isupper()):
pltext += chr((ord(char) - s - 65) % 26 + 65)
else:
pltext += chr((ord(char) - s - 97) % 26 + 97)
return pltext
#Finding the key by applying Chi - Square method
def find_key(ciphertext, k):
l = len(ciphertext)
cipher_freq = [0] * 26
ci = [0] * 26
ei = [0] * 26
#ci and ei are Current value of letter and Expected value of letter.
for i in range(65, 91):
j = i-65
cipher_freq[j] = ciphertext.count(chr(i))
ci[j] = cipher_freq[j]
ei[j] = al_freq[j] * l
#Calculating Chi - Square value for every plain text with relative decryption key
div = 0
for m in range(0, l):
num = (ci[int(ord(ciphertext[m]) - 65) % 26] - ei[int(ord(ciphertext[m]) - 65) % 26]) ** 2
den = ei[int(ord(ciphertext[m]) - 65) % 26]
div = num / den
chi_square[k-1] += div
for n in range(0, 26):
if ci[n] == 0:
chi_square[k-1] += ei[n]
#cipher = "aoljhlzhyjpwolypzvulvmaollhysplzaruvduhukzptwslzajpwolyzpapzhafwlvmzbizapabapvujpwolypudopjolhjoslaalypuaolwshpualeapzzopmalkhjlyahpuubtilyvmwshjlzkvduaolhswohila"
#cipher = "YMJHFJXFWHNUMJWNXTSJTKYMJJFWQNJXYPSTBSFSIXNRUQJXYHNUMJWX"
print("\nEnter the cipher text : ", end="")
cipher = str(input())
#Calculating 25 Decrypted(Plain) text with key value 1 to 25
for k in range(1, 26):
ciphertext = decrypt(cipher, k)
#print(ciphertext + str(k))
ciphertext = ciphertext.upper()
find_key(ciphertext, k)
#Getting the index of minimum chi - square value which is our Decryption key.
index = min(range(25), key = chi_square.__getitem__)
index += 1
index = int(index)
print("\nFound Decryption Key : " + str(index))
print("\nThe Decrypted Text (Plain Text) : ", end="")
print(decrypt(cipher, index))
print("\n")
| """
*** A program for the cryptanalysis of Caesar cipher and identify the plaintext ***
"""
al_freq = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.0236, 0.0015, 0.01974, 0.00074]
chi_square = [0] * 25
def decrypt(ciphertext, s):
pltext = ''
for i in range(len(ciphertext)):
char = ciphertext[i]
if char.isupper():
pltext += chr((ord(char) - s - 65) % 26 + 65)
else:
pltext += chr((ord(char) - s - 97) % 26 + 97)
return pltext
def find_key(ciphertext, k):
l = len(ciphertext)
cipher_freq = [0] * 26
ci = [0] * 26
ei = [0] * 26
for i in range(65, 91):
j = i - 65
cipher_freq[j] = ciphertext.count(chr(i))
ci[j] = cipher_freq[j]
ei[j] = al_freq[j] * l
div = 0
for m in range(0, l):
num = (ci[int(ord(ciphertext[m]) - 65) % 26] - ei[int(ord(ciphertext[m]) - 65) % 26]) ** 2
den = ei[int(ord(ciphertext[m]) - 65) % 26]
div = num / den
chi_square[k - 1] += div
for n in range(0, 26):
if ci[n] == 0:
chi_square[k - 1] += ei[n]
print('\nEnter the cipher text : ', end='')
cipher = str(input())
for k in range(1, 26):
ciphertext = decrypt(cipher, k)
ciphertext = ciphertext.upper()
find_key(ciphertext, k)
index = min(range(25), key=chi_square.__getitem__)
index += 1
index = int(index)
print('\nFound Decryption Key : ' + str(index))
print('\nThe Decrypted Text (Plain Text) : ', end='')
print(decrypt(cipher, index))
print('\n') |
def main():
usernameStr = input("Enter username:")
passwordStr = input("Enter password:")
browser = webdriver.Chrome()
browser.get(('http://192.168.100.100:8090/'))
# fill in username and hit the next button
username = browser.find_element_by_id('username')
username.send_keys(usernameStr)
nextButton = browser.find_element_by_id('password')
nextButton.click()
# wait for transition then continue to fill items
password = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.NAME, "password")))
password.send_keys(passwordStr)
signInButton = browser.find_element_by_id('loginbutton')
signInButton.click()
| def main():
username_str = input('Enter username:')
password_str = input('Enter password:')
browser = webdriver.Chrome()
browser.get('http://192.168.100.100:8090/')
username = browser.find_element_by_id('username')
username.send_keys(usernameStr)
next_button = browser.find_element_by_id('password')
nextButton.click()
password = web_driver_wait(browser, 10).until(EC.presence_of_element_located((By.NAME, 'password')))
password.send_keys(passwordStr)
sign_in_button = browser.find_element_by_id('loginbutton')
signInButton.click() |
class LinearSchedule(object):
r"""A linear scheduling from an initial to a final value over a certain timesteps, then the final
value is fixed constantly afterwards.
.. note::
This could be useful for following use cases:
* Decay of epsilon-greedy: initialized with :math:`1.0` and keep with :attr:`start` time steps, then linearly
decay to :attr:`final` over :attr:`N` time steps, and then fixed constantly as :attr:`final` afterwards.
* Beta parameter in prioritized experience replay.
Note that for learning rate decay, one should use PyTorch ``optim.lr_scheduler`` instead.
Example:
>>> scheduler = LinearSchedule(initial=1.0, final=0.1, N=3, start=0)
>>> [scheduler(i) for i in range(6)]
[1.0, 0.7, 0.4, 0.1, 0.1, 0.1]
Args:
initial (float): initial value
final (float): final value
N (int): number of scheduling timesteps
start (int, optional): the timestep to start the scheduling. Default: 0
"""
def __init__(self, initial, final, N, start=0):
assert N > 0, f'expected N as positive integer, got {N}'
assert start >= 0, f'expected start as non-negative integer, got {start}'
self.initial = initial
self.final = final
self.N = N
self.start = start
self.x = None
def __call__(self, x):
r"""Returns the current value of the scheduling.
Args:
x (int): the current timestep.
Returns:
float: current value of the scheduling.
"""
assert isinstance(x, int) and x >= 0, f'expected as a non-negative integer, got {x}'
if x == 0 or x < self.start:
self.x = self.initial
elif x >= self.start + self.N:
self.x = self.final
else: # scheduling over N steps
delta = self.final - self.initial
ratio = (x - self.start)/self.N
self.x = self.initial + ratio*delta
return self.x
def get_current(self):
return self.x
| class Linearschedule(object):
"""A linear scheduling from an initial to a final value over a certain timesteps, then the final
value is fixed constantly afterwards.
.. note::
This could be useful for following use cases:
* Decay of epsilon-greedy: initialized with :math:`1.0` and keep with :attr:`start` time steps, then linearly
decay to :attr:`final` over :attr:`N` time steps, and then fixed constantly as :attr:`final` afterwards.
* Beta parameter in prioritized experience replay.
Note that for learning rate decay, one should use PyTorch ``optim.lr_scheduler`` instead.
Example:
>>> scheduler = LinearSchedule(initial=1.0, final=0.1, N=3, start=0)
>>> [scheduler(i) for i in range(6)]
[1.0, 0.7, 0.4, 0.1, 0.1, 0.1]
Args:
initial (float): initial value
final (float): final value
N (int): number of scheduling timesteps
start (int, optional): the timestep to start the scheduling. Default: 0
"""
def __init__(self, initial, final, N, start=0):
assert N > 0, f'expected N as positive integer, got {N}'
assert start >= 0, f'expected start as non-negative integer, got {start}'
self.initial = initial
self.final = final
self.N = N
self.start = start
self.x = None
def __call__(self, x):
"""Returns the current value of the scheduling.
Args:
x (int): the current timestep.
Returns:
float: current value of the scheduling.
"""
assert isinstance(x, int) and x >= 0, f'expected as a non-negative integer, got {x}'
if x == 0 or x < self.start:
self.x = self.initial
elif x >= self.start + self.N:
self.x = self.final
else:
delta = self.final - self.initial
ratio = (x - self.start) / self.N
self.x = self.initial + ratio * delta
return self.x
def get_current(self):
return self.x |
"""
There are several cards arranged in a row, and each card has an associated
number of points The points are given in the integer array cardPoints.
In one step, you can take one card from the beginning or from the end of
the row. You have to take exactly k cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array cardPoints and the integer k, return the maximum
score you can obtain.
Example:
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
Explanation: After the first step, your score will always be 1. However,
choosing the rightmost card first will maximize your total
score. The optimal strategy is to take the three cards on the
right, giving a final score of 1 + 6 + 5 = 12.
Constraints:
- 1 <= cardPoints.length <= 10^5
- 1 <= cardPoints[i] <= 10^4
- 1 <= k <= cardPoints.length
"""
#Difficulty: Medium
#40 / 40 test cases passed.
#Runtime: 464 ms
#Memory Usage: 26.8 MB
#Runtime: 464 ms, faster than 76.94% of Python3 online submissions for Maximum Points You Can Obtain from Cards.
#Memory Usage: 26.8 MB, less than 89.35% of Python3 online submissions for Maximum Points You Can Obtain from Cards.
class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
i = 0
l = len(cardPoints)
total = sum(cardPoints)
points = sum(cardPoints[:k])
window = sum(cardPoints[i:l-k+i])
while l - k + i < l:
points = max(points, total - window)
window = window - cardPoints[i] + cardPoints[l-k+i]
i += 1
return points
| """
There are several cards arranged in a row, and each card has an associated
number of points The points are given in the integer array cardPoints.
In one step, you can take one card from the beginning or from the end of
the row. You have to take exactly k cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array cardPoints and the integer k, return the maximum
score you can obtain.
Example:
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
Explanation: After the first step, your score will always be 1. However,
choosing the rightmost card first will maximize your total
score. The optimal strategy is to take the three cards on the
right, giving a final score of 1 + 6 + 5 = 12.
Constraints:
- 1 <= cardPoints.length <= 10^5
- 1 <= cardPoints[i] <= 10^4
- 1 <= k <= cardPoints.length
"""
class Solution:
def max_score(self, cardPoints: List[int], k: int) -> int:
i = 0
l = len(cardPoints)
total = sum(cardPoints)
points = sum(cardPoints[:k])
window = sum(cardPoints[i:l - k + i])
while l - k + i < l:
points = max(points, total - window)
window = window - cardPoints[i] + cardPoints[l - k + i]
i += 1
return points |
class DkuApplication(object):
def __init__(self, name, label, source, model_func, preprocessing, weights, input_shape=None):
self.name = name
self.label = label
self.source = source
self.model_func = model_func
self.preprocessing = preprocessing
self.input_shape = input_shape
self.weights = weights
self.model = None
def is_keras_application(self):
return self.source == "keras"
def get_weights_url(self, trained_on):
assert trained_on in self.weights, "You provided a wrong field 'trained_on'. Avilable are {}.".format(
str(self.weights.keys())
)
return self.weights.get(trained_on)
def jsonify(self):
return self.name.value
| class Dkuapplication(object):
def __init__(self, name, label, source, model_func, preprocessing, weights, input_shape=None):
self.name = name
self.label = label
self.source = source
self.model_func = model_func
self.preprocessing = preprocessing
self.input_shape = input_shape
self.weights = weights
self.model = None
def is_keras_application(self):
return self.source == 'keras'
def get_weights_url(self, trained_on):
assert trained_on in self.weights, "You provided a wrong field 'trained_on'. Avilable are {}.".format(str(self.weights.keys()))
return self.weights.get(trained_on)
def jsonify(self):
return self.name.value |
# Use for, .split(), and if to create a Statement that will print out words that start with 's':
print("Challenge 1 : ")
st = 'Print only the words that start with s in this sentence'
for word in st.split():
if word[0]=='s' or word[0]=='S':
print(word)
# Use range() to print all the even numbers from 0 to 10.
l1= list(range(0,11,2))
print(l1)
for num in range(0,11,2):
print(num)
# Use a List Comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.
print("Challenge 3 : ")
list1 =[i for i in range(1,51) if i%3==0]
print(list1)
# Go through the string below and if the length of a word is even print "even!"
st1 = 'Print every word in this sentence that has an even number of letters'
print("Challenge 4 : ")
for i in st1.split():
if len(i) %2==0:
print(f"{i}: even")
# Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
for n in range(1,101):
if n % 3==0 and n % 5== 0:
print("FizzBuzz")
elif n % 3 ==0:
print("Fizz")
elif n % 5 ==0:
print("Buzz")
else:
print(n)
# Use List Comprehension to create a list of the first letters of every word in the string below:
st2 = 'Create a list of the first letters of every word in this string'
list1 =[ i[0] for i in st2.split()]
print(list1) | print('Challenge 1 : ')
st = 'Print only the words that start with s in this sentence'
for word in st.split():
if word[0] == 's' or word[0] == 'S':
print(word)
l1 = list(range(0, 11, 2))
print(l1)
for num in range(0, 11, 2):
print(num)
print('Challenge 3 : ')
list1 = [i for i in range(1, 51) if i % 3 == 0]
print(list1)
st1 = 'Print every word in this sentence that has an even number of letters'
print('Challenge 4 : ')
for i in st1.split():
if len(i) % 2 == 0:
print(f'{i}: even')
for n in range(1, 101):
if n % 3 == 0 and n % 5 == 0:
print('FizzBuzz')
elif n % 3 == 0:
print('Fizz')
elif n % 5 == 0:
print('Buzz')
else:
print(n)
st2 = 'Create a list of the first letters of every word in this string'
list1 = [i[0] for i in st2.split()]
print(list1) |
eUnit = {
0: "Academy, Disabled",
1: "Gator, disabled",
3: "Archer, D",
4: "Archer",
5: "Hand Cannoneer",
6: "Elite Skirmisher",
7: "Skirmisher",
8: "Longbowman",
9: "Arrow",
10: "Archery Range 3",
11: "Mangudai",
12: "Barracks",
13: "Fishing Ship",
14: "Archery Range 4",
15: "Junk",
16: "Bombard Cannon, D",
17: "Trade Cog",
18: "Blacksmith 3",
19: "Blacksmith 4",
20: "Barracks 4",
21: "War Galley",
22: "Berserk, D",
23: "Battering Ram, D",
24: "Crossbowman",
25: "Teutonic Knight",
26: "Crossbowman, D",
27: "Cataphract, D",
28: "Cho-Ko-Nu, D",
29: "Trading Cog, D",
30: "Monastery 2",
31: "Monastery 3",
32: "Monastery 4",
33: "Castle 4",
34: "Cavalry Archer, D",
35: "Battering Ram",
36: "Bombard Cannon",
37: "LANCE",
38: "Knight",
39: "Cavalry Archer",
40: "Cataphract",
41: "Huskarl",
42: "Trebuchet (Unpacked)",
43: "Deer, D",
44: "Mameluke, D",
45: "Dock",
46: "Janissary",
47: "Dock 3",
48: "Boar",
49: "Siege Workshop",
50: "Farm",
51: "Dock 4",
52: "Fish 1, Disabled",
53: "Fish (Perch)",
54: "Proj, VOL",
55: "Fishing Ship, D",
56: "Fisher, M",
57: "Fisher, F",
58: "Fisher, M D",
59: "Forage Bush",
60: "Fisher, F D",
61: "Galley, D (Canoe?)",
62: "Huskarl (E?), D",
63: "Gate, AA3",
64: "Gate, AA2",
65: "Deer",
66: "Gold Mine",
67: "Gate, AB3",
68: "Mill",
69: "Fish, Shore",
70: "House",
71: "Town Center 2",
72: "Wall, Palisade",
73: "Chu Ko Nu",
74: "Militia",
75: "Man At Arms",
76: "Heavy Swordsman",
77: "Long Swordsman",
78: "Gate, AB2",
79: "Watch Tower",
80: "Gate, AC3",
81: "Gate, AC2",
82: "Castle",
83: "Villager, M",
84: "Market",
85: "Gate, BA3",
86: "Stable 3",
87: "Archery Range",
88: "Gate, BA2",
89: "Dire Wolf",
90: "Gate, BB3",
91: "Gate, BB2",
92: "Gate, BC3",
93: "Spearman",
94: "Berserk 2",
95: "Gate, BC2",
96: "Hawk",
97: "Arrow 1",
98: "Hand Cannoneer, D",
99: "Heavy Swordsman, D",
100: "Elite Skirmisher, D",
101: "Stable",
102: "Stone Mine",
103: "Blacksmith",
104: "Monastery",
105: "Blacksmith 2",
106: "Infiltrator, D",
107: "Janissary, D",
108: "Junk, D",
109: "Town Center",
110: "Trade Workshop",
111: "Knight, D",
112: "Flare",
113: "Lance, D",
114: "Longboat, D",
115: "Longbowman, D",
116: "Market 3",
117: "Wall, Stone",
118: "Builder, M",
119: "Fisherman, disabled",
120: "Forager, M",
121: "Mangonel, D",
122: "Hunter, M",
123: "Lumberjack, M",
124: "Stone Miner, M",
125: "Monk",
126: "Wolf",
127: "Explorer, Old",
128: "Trade Cart, Empty",
129: "Mill 2",
130: "Mill 3",
131: "Mill 4",
132: "Barracks 3",
133: "Dock 2",
134: "Monk, D",
135: "Mangudai, D",
136: "War Elephant, D",
137: "Market 4",
138: "OUTLW, D",
139: "Paladin, D",
140: "Spearman, D",
141: "Town Center 3",
142: "Town Center 4",
143: "Rubble 1 X 1",
144: "Rubble 2 X 2",
145: "Rubble 3 X 3",
146: "Rubble 4 X 4",
147: "Rubble 6",
148: "Rubble 5 X 5",
149: "Scorpion, D",
150: "Siege Workshop 4",
151: "Samurai, D",
152: "Militia, D",
153: "Stable 4",
154: "Man-At-Arms, D",
155: "Wall, Fortified",
156: "Repairer, M",
157: "Throwing Axeman, D",
158: "OUTLW",
159: "Relic Cart",
160: "Richard The Lionharted",
161: "The Black Prince",
162: "FLAGX",
163: "Friar Tuck",
164: "Sherrif Of Notingham",
165: "Charlemagne",
166: "Roland",
167: "Belisarius",
168: "Theodoric The Goth",
169: "Aethelfirth",
170: "Siegfried",
171: "Erik The Red",
172: "Tamerlane",
173: "King Arthur",
174: "Lancelot",
175: "Gawain",
176: "Mordred",
177: "Archbishop",
178: "Trade Cart, D",
179: "Trade Workshop 4",
180: "Long Swordsman, D",
181: "Teutonic Knight, D",
182: "TMISA",
183: "TMISB",
184: "TMISC",
185: "TMISD",
186: "TMISE",
187: "TMISF",
188: "TMISG",
189: "TMISH",
190: "TMISI",
191: "TMISJ",
192: "TMISK",
193: "TMISL",
194: "Trebuchet, D",
195: "Kitabatake",
196: "Minamoto",
197: "Alexander Nevski",
198: "El Cid",
199: "Fish Trap",
200: "Robin Hood",
201: "FLR_R",
202: "Rabid Wolf",
203: "Rabid Wolf, D",
204: "Trade Cart, Full",
205: "Trade Cart, Full D",
206: "VMDL",
207: "VMDL, D",
208: "TWAL",
209: "University",
210: "University 4",
211: "Villager, F D",
212: "Builder, F",
213: "Builder, F D",
214: "Farmer, F",
215: "Farmer, F D",
216: "Hunter, F",
217: "Hunter, F D",
218: "Lumberjack, F",
219: "Lumberjack, F D",
220: "Stone Miner, F",
221: "Stone Miner, F D",
222: "Repairer, F",
223: "Repairer, F D",
224: "Villager, M D",
225: "Builder, M D",
226: "Farmer, M D",
227: "Hunter, M D",
228: "Lumberjack, M D",
229: "Stone Miner, M D",
230: "Repairer, M D",
232: "Woad Raider",
233: "Woad Raider, D",
234: "Guard Tower",
235: "Keep",
236: "Bombard Tower",
237: "Wolf, D",
238: "Skirmisher, D",
239: "War Elephant",
240: "TERRC",
241: "Cracks",
242: "Stone, Catapult",
243: "DOPL",
244: "Stone, Catapult F",
245: "Bolt (Scorpion Proj.)",
246: "Bolt, F",
247: "Smoke",
248: "Pile Of Stone",
249: "POREX",
250: "Longboat",
251: "Goldminer, Disabled",
252: "Pile Of Gold",
253: "Pile Of Wood",
254: "PILE1",
255: "PILE2",
256: "PILE3",
257: "PILE4",
258: "PILE6",
259: "Farmer, M",
260: "Fish3, Disabled",
261: "PILE8",
262: "Pile Of Food",
263: "Fish4, Disabled",
264: "Cliff 1",
265: "Cliff 2",
266: "Cliff 3",
267: "Cliff 4",
268: "Cliff 5",
269: "Cliff 6",
270: "Cliff 7",
271: "Cliff 8",
272: "Cliff 9",
273: "Cliff 10",
274: "Flare 2",
276: "Wonder",
278: "Fishtrap, D",
279: "Scorpion",
280: "Mangonel",
281: "Throwing Axeman",
282: "Mameluke",
283: "Cavalier",
284: "Tree TD",
285: "Relic",
286: "Monk With Relic",
287: "British Relic",
288: "Byzantine Relic",
289: "Chinese Relic",
290: "Frankish Relic",
291: "Samurai",
292: "Gothic Relic",
293: "Villager, F",
294: "Japanese Relic",
295: "Persian Relic",
296: "Saracen Relic",
297: "Teutonic Relic",
298: "Turkish Relic",
299: "Infiltrator",
300: "Monk With British Relic",
301: "Monk With Byzantine Relic",
302: "Monk With Chinese Relic",
303: "Monk With Frankish Relic",
304: "Monk With Gothic Relic",
305: "Monk With Japanese Relic",
306: "Monk With Persian Relic",
307: "Monk With Saracen Relic",
308: "Monk With Teutonic Relic",
309: "Monk With Turkish Relic",
310: "Mountain 1",
311: "Mountain 2",
312: "Arrow 2",
313: "Stone, Treb",
314: "Stone, Mangonel",
315: "Arrow 3",
316: "Arrow 4",
317: "Arrow 5",
318: "Arrow 6",
319: "Arrow 7",
320: "Arrow 8",
321: "Arrow 9",
322: "Arrow 10",
323: "Stone, Catapult 1",
324: "Stone, Catapult 2",
325: "Stone, Catapult 3",
326: "Stone, Catapult 4",
327: "Stone, Catapult 5",
328: "Arrow, F",
329: "Camel",
330: "Heavy Camel",
331: "Trebuchet, P",
332: "Flare 3",
333: "Deer, Nomeat",
334: "Flowers 1",
335: "Flowers 2",
336: "Flowers 3",
337: "Flowers 4",
338: "Path 4",
339: "Path 1",
340: "Path 2",
341: "Path 3",
342: "TERRU",
343: "TERRV",
344: "TERRW",
345: "Ruins",
346: "TERRY",
347: "TERRZ",
348: "Forest, Bamboo",
349: "Forest, Oak",
350: "Forest, Pine",
351: "Forest, Palm",
352: "OREMN",
353: "Forager, M D",
354: "Forager, F",
355: "Forager, F D",
356: "Board, D",
357: "Farm, D Crash",
358: "Pikeman",
359: "Halberdier",
360: "Arrow 2, F",
363: "Proj, Archer",
364: "Proj, Crossbowman",
365: "Proj, Skirmisher",
366: "Proj, Elite Skirmisher",
367: "Proj, Scorpion",
368: "Proj, Bombard Cannon",
369: "Proj, Mangonel",
370: "Fish 2, Disabled",
371: "Proj, Trebuchet",
372: "Proj, Galleon",
373: "Proj, War Galley",
374: "Proj, Cannon Galleon",
375: "Proj, Crossbowman F",
376: "Proj, Skirmisher F",
377: "Proj, Elite Skirmisher F",
378: "Proj, Scorpion F",
380: "Proj, H Cannoneer",
381: "Bolt, F",
385: "Bolt 1, F",
389: "Sea Rocks 1",
390: "TERRB",
391: "TERRD",
392: "TERRE",
393: "TERRF",
394: "TERRH",
395: "TERRI",
396: "Sea Rocks 2",
397: "TERRK",
398: "TERRL",
399: "Tree A",
400: "Tree B",
401: "Tree C",
402: "Tree D",
403: "Tree E",
404: "Tree F",
405: "Tree G",
406: "Tree H",
407: "Tree I",
408: "Tree J",
409: "Tree K",
410: "Tree L",
411: "Forest Tree",
413: "Snow Pine Tree",
414: "Jungle Tree",
415: "Stump",
416: "Debris",
417: "Dust C",
418: "TROCK",
419: "Debris B",
420: "Cannon Galleon",
421: "Cannon Galleon, D",
422: "Capped Ram",
423: "Capped Ram, D",
424: "Charles Martel",
425: "Charles Martel, D",
426: "Harald Hardraade",
427: "Harald Hardraade, D",
428: "Hrolf The Ganger",
429: "Hrolf The Ganger, D",
430: "Joan The Maid",
431: "Joan The Maid, D",
432: "William Wallace",
433: "William Wallace, D",
434: "King",
435: "King, D",
436: "OMTBO",
437: "OMTBO, D",
438: "STRBO",
439: "STRRBO, D",
440: "Petard",
441: "Hussar",
442: "Galleon",
443: "Galleon, Dead",
444: "PTWC",
445: "Church 4",
446: "Port",
447: "Purple Spots",
448: "Scout Cavalry",
449: "Scout Cavalry, D",
450: "Marlin 1",
451: "Marlin 2",
452: "DOLP3",
453: "DOLP4",
454: "DOLP5",
455: "Fish, Dorado",
456: "Fish, Salmon",
457: "Fish, Tuna",
458: "Fish, Snapper",
459: "FISH5",
460: "WHAL1",
461: "WHAL2",
462: "Proj, Mangonel F2",
463: "House 2",
464: "House 3",
465: "House 4",
466: "Proj, Archer F",
468: "Projectile, Mangonel F",
469: "Projectile, Treb F",
470: "Proj, Galleon F",
471: "Proj, War Galley F",
473: "Two Handed Swordsman",
474: "Heavy Cavalry Archer",
475: "Proj, HAR F",
476: "Proj, Harold Haraade F",
477: "Proj, HAR",
478: "Proj, Harold Haraade",
479: "PMANG",
480: "Hussar, D",
481: "Town Center 3A",
482: "Town Center 3B",
483: "Town Center 3C",
484: "Town Center 3X",
485: "Arrow, Town Center",
487: "Gate, AX2",
488: "Gate, AX3",
490: "Gate, BX2",
491: "Gate, BX3",
492: "Arbalest",
493: "Adv Heavy Crossbowman",
494: "Camel, D",
495: "Heavy Camel, D",
496: "Arbalest, D",
497: "AH Crossbowman, D",
498: "Barracks 2",
499: "Torch",
500: "Two-Handed Swordsman, D",
501: "Pikeman, D",
502: "Halberdier, D",
503: "Proj, Watch Tower",
504: "Proj, Guard Tower",
505: "Proj, Keep",
506: "Proj, Bombard Tower",
507: "Proj, Arbalest",
508: "Proj, AH Crossbowman",
509: "Proj, Villager",
510: "Proj, Cho Ko Nu",
511: "Proj, Longbowman",
512: "Proj, Longboat",
513: "Proj, MSU",
514: "Proj, MPC",
515: "Proj, Axeman",
516: "Proj, Watch Tower F",
517: "Proj, Guard Tower F",
518: "Proj, Keep F",
519: "Proj, Arbalest F",
520: "Proj, AH Crossbowman F",
521: "Proj, Villager F",
522: "Proj, Cho Ko Nu F",
523: "Proj, Longbowman F",
524: "Proj, Longboat F",
525: "Proj, MPC F",
526: "Proj, MSU F",
527: "Demolition Ship",
528: "Heavy Demolition Ship",
529: "Fire Ship",
530: "Elite Longbowman",
531: "Elite Throwing Axeman",
532: "Fast Fire Ship",
533: "Elite Longboat",
534: "Elite Woad Raider",
535: "BDGAL",
536: "ABGAL",
537: "Proj, FRG",
538: "Proj, HFG",
539: "Galley",
540: "Proj, Galley",
541: "Proj, Galley F",
542: "Heavy Scorpion",
543: "Heavy Scorpion, D",
544: "FLDOG",
545: "Transport Ship",
546: "Light Cavalry",
547: "Light Cavalry, D",
548: "Siege Ram",
549: "Siege Ram, D",
550: "Onager",
551: "Proj, Onager",
552: "Proj, Onager F",
553: "Elite Cataphract",
554: "Elite Teutonic Knight",
555: "Elite Huskarl",
556: "Elite Mameluke",
557: "Elite Janissary",
558: "Elite War Elephant",
559: "Elite Chu Ko Nu",
560: "Elite Samurai",
561: "Elite Mangudai",
562: "Lumber Camp",
563: "Lumber Camp 2",
564: "Lumber Camp 3",
565: "Lumber Camp 4",
566: "WCTWR",
567: "Champion",
568: "Champion, Dead",
569: "Paladin",
570: "Paladin, D",
571: "RFARC",
572: "RFARC, D",
573: "RFSWD",
574: "RFSWD, D",
575: "RCSWD",
576: "RCSWD, D",
577: "RCARC",
578: "RCARC, D",
579: "Gold Miner, M",
580: "Gold Miner, M D",
581: "Gold Miner, F",
582: "Gold Miner, F D",
583: "Genitour",
584: "Mining Camp",
585: "Mining Camp 2",
586: "Mining Camp 3",
587: "Mining Camp 4",
588: "Siege Onager",
589: "Siege Onager, D",
590: "Shepherd, F",
591: "Shepherd, F D",
592: "Shepherd, M",
593: "Shepherd, M D",
594: "Sheep",
595: "Sheep, D",
596: "Elite Genitour",
597: "Town Center 4X",
598: "Outpost",
599: "Cathedral",
600: "Flag A",
601: "Flag B",
602: "Flag C",
603: "Flag D",
604: "Flag E",
605: "Bridge A Top",
606: "Bridge A Middle",
607: "Bridge A Bottom",
608: "Bridge B Top",
609: "Bridge B Middle",
610: "Bridge B Bottom",
611: "Town Center 4A",
612: "Town Center 4B",
613: "Town Center 4C",
614: "Town Center 2A",
615: "Town Center 2B",
616: "Town Center 2C",
617: "Town Center 2X",
618: "Town Center 1A",
619: "Town Center 1B",
620: "Town Center 1C",
621: "Town Center 1X",
622: "D Iron Boar",
623: "Rock",
624: "Pavilion 1",
625: "Pavilion 3",
626: "Pavilion 2",
627: "Proj, Heavy Scorpion",
628: "Proj, Heavy Scorpion F",
629: "Joan Of Arc",
630: "Joan Of Arc, D",
631: "Subotai, D",
632: "Frankish Paladin",
633: "Frankish Paladin, D",
634: "Sieur De Metz",
635: "Sieur De Metz, D",
636: "Sieur Bertrand",
637: "Sieur Bertrand, D",
638: "Duke D'Alencon",
639: "Duke D'Alencon, D",
640: "La Hire",
641: "La Hire, D",
642: "Lord De Graville",
643: "Lord De Graville, D",
644: "Jean De Lorrain",
645: "Jean De Lorrain, D",
646: "Constable Richemont",
647: "Constable Richemont, D",
648: "Guy Josselyne",
649: "Guy Josselyne, D",
650: "Jean Bureau",
651: "Jean Bureau, D",
652: "Sir John Fastolf",
653: "Sir John Fastolf, D",
654: "S_SMOKE",
655: "Mosque",
656: "Proj, MNB",
657: "Proj, GP1",
658: "Proj, MNB F",
659: "Gate, CA2",
660: "Gate, CA3",
661: "Gate, CB2",
662: "Gate, CB3",
663: "Gate, CC2",
664: "Gate, CC3",
665: "Gate, CX2",
666: "Gate, CX3",
667: "Gate, DA2",
668: "Gate, DA3",
669: "Gate, DB2",
670: "Gate, DB3",
671: "Gate, DC2",
672: "Gate, DC3",
673: "Gate, DX2",
674: "Gate, DX3",
675: "Onager, D",
676: "Proj, FFG F",
677: "S_Fire",
678: "Reynald De Chatillon",
679: "Reynald De Chatillon, D",
680: "Master Of The Templar",
681: "Master Of The Templar, D",
682: "Bad Neighbor",
683: "Gods Own Sling",
684: "The Accursed Tower",
685: "The Tower Of Flies",
686: "Archer Of The Eyes",
687: "Archer Of The Eyes, D",
688: "Piece Of The True Cross",
689: "Pyramid",
690: "Dome Of The Rock",
691: "Elite Cannon Galleon",
692: "Berserk",
693: "Berserk, D",
694: "Elite Berserk",
695: "Elite Berserk, D",
696: "Great Pyramid",
697: "Flare 4",
698: "Subotai",
699: "Subotai, D",
700: "Hunting Wolf",
701: "Hunting Wolf, D",
702: "Kushluk",
703: "Kushluk, D",
704: "Shah",
705: "Shah, D",
706: "Saboteur",
707: "Ornlu The Wolf",
708: "Ornlu The Wolf, D",
709: "Cactus",
710: "Skeleton",
711: "Rugs",
712: "Yurt",
713: "Yurt 2",
714: "Yurt 3",
715: "Yurt 4",
716: "Yurt 5",
717: "Yurt 6",
718: "Yurt 7",
719: "Yurt 8",
720: "Nine Bands",
721: "Shipwreck",
722: "Shipwreck 2",
723: "Crater",
724: "Genitour, Dead",
725: "Jaguar Warrior",
726: "Elite Jaguar Warrior",
728: "Ice Spots",
729: "Gods Own Sling, Packed",
730: "Bad Neighbor, Packed",
731: "Genghis Khan",
732: "Genghis Khan, D",
733: "Emperor In A Barrel",
734: "Emperor In A Barrel, D",
735: "Trebuchet, Packed D",
736: "Proj, Mameluke",
737: "Stump B",
738: "Bridge A Middle Broken",
739: "Bridge A Middle Broken 2",
740: "Bridge A Middle Broken 3",
741: "Bridge B Middle Broken",
742: "Bridge B Middle Broken 2",
743: "Bridge B Middle Broken 3",
744: "Mountain 3",
745: "Mountain 4",
746: "Proj, Castle",
747: "Proj, Castle Flaming",
748: "Cobra Car",
749: "Cobra, D",
750: "Jaguar Warrior, D",
751: "Eagle Warrior",
752: "Elite Eagle Warrior",
754: "Eagle Warrior, D",
755: "Tarkan",
756: "Tarkan, D",
757: "Elite Tarkan",
759: "Huskarl",
760: "Huskarl, Dead",
761: "Elite Huskarl",
762: "Elite Huskarl, Dead",
763: "Plumed Archer",
764: "Plumed Archer, D",
765: "Elite Plumed Archer",
766: "Elite Plumed Archer, D",
767: "Proj, Elite Cannon Galleon",
771: "Conquistador",
772: "Conquistador, D",
773: "Elite Conquistador",
774: "Elite Conquistador, D",
775: "Missionary",
776: "Missionary, D",
777: "Attila The Hun",
778: "Atilla The Hun, D",
779: "Bleda The Hun",
780: "Bleda The Hun, D",
781: "Pope Leo I",
782: "Pope Leo I, D",
783: "Scythian Wild Woman",
784: "Scythian Wild Woman, D",
785: "Sea Tower",
786: "Proj, Sea Tower",
787: "Proj, Sea Tower Flaming",
788: "Sea Wall",
789: "Sea Gate, AA",
790: "Sea Gate, AB",
791: "Sea Gate, AC",
792: "Sea Gate, AX",
793: "Sea Gate, BA",
794: "Sea Gate, BB",
795: "Sea Gate, BC",
796: "Sea Gate, BX",
797: "Sea Gate, CA",
798: "Sea Gate, CB",
799: "Sea Gate, CC",
800: "Sea Gate, CX",
801: "Sea Gate, DA",
802: "Sea Gate, DB",
803: "Sea Gate, DC",
804: "Sea Gate, DX",
805: "S Dock",
806: "S Dock 2",
807: "S Dock 3",
808: "S Dock 4",
809: "Stump 2",
810: "Iron Boar",
811: "Iron Boar, D",
812: "Jaguar",
813: "Jaguar, D",
814: "Horse",
815: "Horse, D",
816: "Macaw",
817: "Statue",
818: "Plants",
819: "Sign",
820: "Grave",
821: "Head",
822: "Javelina",
823: "Javelina, D",
824: "El Cid Campeador",
825: "El Cid Campeador, D",
826: "Monument (KotH)",
827: "War Wagon",
828: "War Wagon, D",
829: "Elite War Wagon",
830: "Elite War Wagon, D",
831: "Turtle Ship",
832: "Elite Turtle Ship",
833: "Turkey",
834: "Turkey, Dead",
835: "Wild Horse",
836: "Wild Horse, D",
837: "Map Revealer",
838: "King Sancho",
839: "King Sancho, D",
840: "King Alfonso",
841: "King Alfonso, D",
842: "Imam",
843: "Imam, D",
844: "Admiral Yi Sun Shin",
845: "Nobunaga",
846: "Nobunaga, D",
847: "Henry V",
848: "Henry V, D",
849: "William The Conqueror",
850: "William The Conqueror, D",
851: "Flag, ES",
852: "Scythian Scout",
853: "Scythian Scout, D",
854: "Torch 2",
855: "Old Stone Head",
856: "Roman Ruins",
857: "Hay Stack",
858: "Broken Cart",
859: "Flower Bed",
860: "Furious The Monkey Boy",
861: "Furious The Monkey Boy, D",
862: "Stormy Dog",
863: "Rubble 1 X 1",
864: "Rubble 2 X 2",
865: "Rubble 3 X 3"
} | e_unit = {0: 'Academy, Disabled', 1: 'Gator, disabled', 3: 'Archer, D', 4: 'Archer', 5: 'Hand Cannoneer', 6: 'Elite Skirmisher', 7: 'Skirmisher', 8: 'Longbowman', 9: 'Arrow', 10: 'Archery Range 3', 11: 'Mangudai', 12: 'Barracks', 13: 'Fishing Ship', 14: 'Archery Range 4', 15: 'Junk', 16: 'Bombard Cannon, D', 17: 'Trade Cog', 18: 'Blacksmith 3', 19: 'Blacksmith 4', 20: 'Barracks 4', 21: 'War Galley', 22: 'Berserk, D', 23: 'Battering Ram, D', 24: 'Crossbowman', 25: 'Teutonic Knight', 26: 'Crossbowman, D', 27: 'Cataphract, D', 28: 'Cho-Ko-Nu, D', 29: 'Trading Cog, D', 30: 'Monastery 2', 31: 'Monastery 3', 32: 'Monastery 4', 33: 'Castle 4', 34: 'Cavalry Archer, D', 35: 'Battering Ram', 36: 'Bombard Cannon', 37: 'LANCE', 38: 'Knight', 39: 'Cavalry Archer', 40: 'Cataphract', 41: 'Huskarl', 42: 'Trebuchet (Unpacked)', 43: 'Deer, D', 44: 'Mameluke, D', 45: 'Dock', 46: 'Janissary', 47: 'Dock 3', 48: 'Boar', 49: 'Siege Workshop', 50: 'Farm', 51: 'Dock 4', 52: 'Fish 1, Disabled', 53: 'Fish (Perch)', 54: 'Proj, VOL', 55: 'Fishing Ship, D', 56: 'Fisher, M', 57: 'Fisher, F', 58: 'Fisher, M D', 59: 'Forage Bush', 60: 'Fisher, F D', 61: 'Galley, D (Canoe?)', 62: 'Huskarl (E?), D', 63: 'Gate, AA3', 64: 'Gate, AA2', 65: 'Deer', 66: 'Gold Mine', 67: 'Gate, AB3', 68: 'Mill', 69: 'Fish, Shore', 70: 'House', 71: 'Town Center 2', 72: 'Wall, Palisade', 73: 'Chu Ko Nu', 74: 'Militia', 75: 'Man At Arms', 76: 'Heavy Swordsman', 77: 'Long Swordsman', 78: 'Gate, AB2', 79: 'Watch Tower', 80: 'Gate, AC3', 81: 'Gate, AC2', 82: 'Castle', 83: 'Villager, M', 84: 'Market', 85: 'Gate, BA3', 86: 'Stable 3', 87: 'Archery Range', 88: 'Gate, BA2', 89: 'Dire Wolf', 90: 'Gate, BB3', 91: 'Gate, BB2', 92: 'Gate, BC3', 93: 'Spearman', 94: 'Berserk 2', 95: 'Gate, BC2', 96: 'Hawk', 97: 'Arrow 1', 98: 'Hand Cannoneer, D', 99: 'Heavy Swordsman, D', 100: 'Elite Skirmisher, D', 101: 'Stable', 102: 'Stone Mine', 103: 'Blacksmith', 104: 'Monastery', 105: 'Blacksmith 2', 106: 'Infiltrator, D', 107: 'Janissary, D', 108: 'Junk, D', 109: 'Town Center', 110: 'Trade Workshop', 111: 'Knight, D', 112: 'Flare', 113: 'Lance, D', 114: 'Longboat, D', 115: 'Longbowman, D', 116: 'Market 3', 117: 'Wall, Stone', 118: 'Builder, M', 119: 'Fisherman, disabled', 120: 'Forager, M', 121: 'Mangonel, D', 122: 'Hunter, M', 123: 'Lumberjack, M', 124: 'Stone Miner, M', 125: 'Monk', 126: 'Wolf', 127: 'Explorer, Old', 128: 'Trade Cart, Empty', 129: 'Mill 2', 130: 'Mill 3', 131: 'Mill 4', 132: 'Barracks 3', 133: 'Dock 2', 134: 'Monk, D', 135: 'Mangudai, D', 136: 'War Elephant, D', 137: 'Market 4', 138: 'OUTLW, D', 139: 'Paladin, D', 140: 'Spearman, D', 141: 'Town Center 3', 142: 'Town Center 4', 143: 'Rubble 1 X 1', 144: 'Rubble 2 X 2', 145: 'Rubble 3 X 3', 146: 'Rubble 4 X 4', 147: 'Rubble 6', 148: 'Rubble 5 X 5', 149: 'Scorpion, D', 150: 'Siege Workshop 4', 151: 'Samurai, D', 152: 'Militia, D', 153: 'Stable 4', 154: 'Man-At-Arms, D', 155: 'Wall, Fortified', 156: 'Repairer, M', 157: 'Throwing Axeman, D', 158: 'OUTLW', 159: 'Relic Cart', 160: 'Richard The Lionharted', 161: 'The Black Prince', 162: 'FLAGX', 163: 'Friar Tuck', 164: 'Sherrif Of Notingham', 165: 'Charlemagne', 166: 'Roland', 167: 'Belisarius', 168: 'Theodoric The Goth', 169: 'Aethelfirth', 170: 'Siegfried', 171: 'Erik The Red', 172: 'Tamerlane', 173: 'King Arthur', 174: 'Lancelot', 175: 'Gawain', 176: 'Mordred', 177: 'Archbishop', 178: 'Trade Cart, D', 179: 'Trade Workshop 4', 180: 'Long Swordsman, D', 181: 'Teutonic Knight, D', 182: 'TMISA', 183: 'TMISB', 184: 'TMISC', 185: 'TMISD', 186: 'TMISE', 187: 'TMISF', 188: 'TMISG', 189: 'TMISH', 190: 'TMISI', 191: 'TMISJ', 192: 'TMISK', 193: 'TMISL', 194: 'Trebuchet, D', 195: 'Kitabatake', 196: 'Minamoto', 197: 'Alexander Nevski', 198: 'El Cid', 199: 'Fish Trap', 200: 'Robin Hood', 201: 'FLR_R', 202: 'Rabid Wolf', 203: 'Rabid Wolf, D', 204: 'Trade Cart, Full', 205: 'Trade Cart, Full D', 206: 'VMDL', 207: 'VMDL, D', 208: 'TWAL', 209: 'University', 210: 'University 4', 211: 'Villager, F D', 212: 'Builder, F', 213: 'Builder, F D', 214: 'Farmer, F', 215: 'Farmer, F D', 216: 'Hunter, F', 217: 'Hunter, F D', 218: 'Lumberjack, F', 219: 'Lumberjack, F D', 220: 'Stone Miner, F', 221: 'Stone Miner, F D', 222: 'Repairer, F', 223: 'Repairer, F D', 224: 'Villager, M D', 225: 'Builder, M D', 226: 'Farmer, M D', 227: 'Hunter, M D', 228: 'Lumberjack, M D', 229: 'Stone Miner, M D', 230: 'Repairer, M D', 232: 'Woad Raider', 233: 'Woad Raider, D', 234: 'Guard Tower', 235: 'Keep', 236: 'Bombard Tower', 237: 'Wolf, D', 238: 'Skirmisher, D', 239: 'War Elephant', 240: 'TERRC', 241: 'Cracks', 242: 'Stone, Catapult', 243: 'DOPL', 244: 'Stone, Catapult F', 245: 'Bolt (Scorpion Proj.)', 246: 'Bolt, F', 247: 'Smoke', 248: 'Pile Of Stone', 249: 'POREX', 250: 'Longboat', 251: 'Goldminer, Disabled', 252: 'Pile Of Gold', 253: 'Pile Of Wood', 254: 'PILE1', 255: 'PILE2', 256: 'PILE3', 257: 'PILE4', 258: 'PILE6', 259: 'Farmer, M', 260: 'Fish3, Disabled', 261: 'PILE8', 262: 'Pile Of Food', 263: 'Fish4, Disabled', 264: 'Cliff 1', 265: 'Cliff 2', 266: 'Cliff 3', 267: 'Cliff 4', 268: 'Cliff 5', 269: 'Cliff 6', 270: 'Cliff 7', 271: 'Cliff 8', 272: 'Cliff 9', 273: 'Cliff 10', 274: 'Flare 2', 276: 'Wonder', 278: 'Fishtrap, D', 279: 'Scorpion', 280: 'Mangonel', 281: 'Throwing Axeman', 282: 'Mameluke', 283: 'Cavalier', 284: 'Tree TD', 285: 'Relic', 286: 'Monk With Relic', 287: 'British Relic', 288: 'Byzantine Relic', 289: 'Chinese Relic', 290: 'Frankish Relic', 291: 'Samurai', 292: 'Gothic Relic', 293: 'Villager, F', 294: 'Japanese Relic', 295: 'Persian Relic', 296: 'Saracen Relic', 297: 'Teutonic Relic', 298: 'Turkish Relic', 299: 'Infiltrator', 300: 'Monk With British Relic', 301: 'Monk With Byzantine Relic', 302: 'Monk With Chinese Relic', 303: 'Monk With Frankish Relic', 304: 'Monk With Gothic Relic', 305: 'Monk With Japanese Relic', 306: 'Monk With Persian Relic', 307: 'Monk With Saracen Relic', 308: 'Monk With Teutonic Relic', 309: 'Monk With Turkish Relic', 310: 'Mountain 1', 311: 'Mountain 2', 312: 'Arrow 2', 313: 'Stone, Treb', 314: 'Stone, Mangonel', 315: 'Arrow 3', 316: 'Arrow 4', 317: 'Arrow 5', 318: 'Arrow 6', 319: 'Arrow 7', 320: 'Arrow 8', 321: 'Arrow 9', 322: 'Arrow 10', 323: 'Stone, Catapult 1', 324: 'Stone, Catapult 2', 325: 'Stone, Catapult 3', 326: 'Stone, Catapult 4', 327: 'Stone, Catapult 5', 328: 'Arrow, F', 329: 'Camel', 330: 'Heavy Camel', 331: 'Trebuchet, P', 332: 'Flare 3', 333: 'Deer, Nomeat', 334: 'Flowers 1', 335: 'Flowers 2', 336: 'Flowers 3', 337: 'Flowers 4', 338: 'Path 4', 339: 'Path 1', 340: 'Path 2', 341: 'Path 3', 342: 'TERRU', 343: 'TERRV', 344: 'TERRW', 345: 'Ruins', 346: 'TERRY', 347: 'TERRZ', 348: 'Forest, Bamboo', 349: 'Forest, Oak', 350: 'Forest, Pine', 351: 'Forest, Palm', 352: 'OREMN', 353: 'Forager, M D', 354: 'Forager, F', 355: 'Forager, F D', 356: 'Board, D', 357: 'Farm, D Crash', 358: 'Pikeman', 359: 'Halberdier', 360: 'Arrow 2, F', 363: 'Proj, Archer', 364: 'Proj, Crossbowman', 365: 'Proj, Skirmisher', 366: 'Proj, Elite Skirmisher', 367: 'Proj, Scorpion', 368: 'Proj, Bombard Cannon', 369: 'Proj, Mangonel', 370: 'Fish 2, Disabled', 371: 'Proj, Trebuchet', 372: 'Proj, Galleon', 373: 'Proj, War Galley', 374: 'Proj, Cannon Galleon', 375: 'Proj, Crossbowman F', 376: 'Proj, Skirmisher F', 377: 'Proj, Elite Skirmisher F', 378: 'Proj, Scorpion F', 380: 'Proj, H Cannoneer', 381: 'Bolt, F', 385: 'Bolt 1, F', 389: 'Sea Rocks 1', 390: 'TERRB', 391: 'TERRD', 392: 'TERRE', 393: 'TERRF', 394: 'TERRH', 395: 'TERRI', 396: 'Sea Rocks 2', 397: 'TERRK', 398: 'TERRL', 399: 'Tree A', 400: 'Tree B', 401: 'Tree C', 402: 'Tree D', 403: 'Tree E', 404: 'Tree F', 405: 'Tree G', 406: 'Tree H', 407: 'Tree I', 408: 'Tree J', 409: 'Tree K', 410: 'Tree L', 411: 'Forest Tree', 413: 'Snow Pine Tree', 414: 'Jungle Tree', 415: 'Stump', 416: 'Debris', 417: 'Dust C', 418: 'TROCK', 419: 'Debris B', 420: 'Cannon Galleon', 421: 'Cannon Galleon, D', 422: 'Capped Ram', 423: 'Capped Ram, D', 424: 'Charles Martel', 425: 'Charles Martel, D', 426: 'Harald Hardraade', 427: 'Harald Hardraade, D', 428: 'Hrolf The Ganger', 429: 'Hrolf The Ganger, D', 430: 'Joan The Maid', 431: 'Joan The Maid, D', 432: 'William Wallace', 433: 'William Wallace, D', 434: 'King', 435: 'King, D', 436: 'OMTBO', 437: 'OMTBO, D', 438: 'STRBO', 439: 'STRRBO, D', 440: 'Petard', 441: 'Hussar', 442: 'Galleon', 443: 'Galleon, Dead', 444: 'PTWC', 445: 'Church 4', 446: 'Port', 447: 'Purple Spots', 448: 'Scout Cavalry', 449: 'Scout Cavalry, D', 450: 'Marlin 1', 451: 'Marlin 2', 452: 'DOLP3', 453: 'DOLP4', 454: 'DOLP5', 455: 'Fish, Dorado', 456: 'Fish, Salmon', 457: 'Fish, Tuna', 458: 'Fish, Snapper', 459: 'FISH5', 460: 'WHAL1', 461: 'WHAL2', 462: 'Proj, Mangonel F2', 463: 'House 2', 464: 'House 3', 465: 'House 4', 466: 'Proj, Archer F', 468: 'Projectile, Mangonel F', 469: 'Projectile, Treb F', 470: 'Proj, Galleon F', 471: 'Proj, War Galley F', 473: 'Two Handed Swordsman', 474: 'Heavy Cavalry Archer', 475: 'Proj, HAR F', 476: 'Proj, Harold Haraade F', 477: 'Proj, HAR', 478: 'Proj, Harold Haraade', 479: 'PMANG', 480: 'Hussar, D', 481: 'Town Center 3A', 482: 'Town Center 3B', 483: 'Town Center 3C', 484: 'Town Center 3X', 485: 'Arrow, Town Center', 487: 'Gate, AX2', 488: 'Gate, AX3', 490: 'Gate, BX2', 491: 'Gate, BX3', 492: 'Arbalest', 493: 'Adv Heavy Crossbowman', 494: 'Camel, D', 495: 'Heavy Camel, D', 496: 'Arbalest, D', 497: 'AH Crossbowman, D', 498: 'Barracks 2', 499: 'Torch', 500: 'Two-Handed Swordsman, D', 501: 'Pikeman, D', 502: 'Halberdier, D', 503: 'Proj, Watch Tower', 504: 'Proj, Guard Tower', 505: 'Proj, Keep', 506: 'Proj, Bombard Tower', 507: 'Proj, Arbalest', 508: 'Proj, AH Crossbowman', 509: 'Proj, Villager', 510: 'Proj, Cho Ko Nu', 511: 'Proj, Longbowman', 512: 'Proj, Longboat', 513: 'Proj, MSU', 514: 'Proj, MPC', 515: 'Proj, Axeman', 516: 'Proj, Watch Tower F', 517: 'Proj, Guard Tower F', 518: 'Proj, Keep F', 519: 'Proj, Arbalest F', 520: 'Proj, AH Crossbowman F', 521: 'Proj, Villager F', 522: 'Proj, Cho Ko Nu F', 523: 'Proj, Longbowman F', 524: 'Proj, Longboat F', 525: 'Proj, MPC F', 526: 'Proj, MSU F', 527: 'Demolition Ship', 528: 'Heavy Demolition Ship', 529: 'Fire Ship', 530: 'Elite Longbowman', 531: 'Elite Throwing Axeman', 532: 'Fast Fire Ship', 533: 'Elite Longboat', 534: 'Elite Woad Raider', 535: 'BDGAL', 536: 'ABGAL', 537: 'Proj, FRG', 538: 'Proj, HFG', 539: 'Galley', 540: 'Proj, Galley', 541: 'Proj, Galley F', 542: 'Heavy Scorpion', 543: 'Heavy Scorpion, D', 544: 'FLDOG', 545: 'Transport Ship', 546: 'Light Cavalry', 547: 'Light Cavalry, D', 548: 'Siege Ram', 549: 'Siege Ram, D', 550: 'Onager', 551: 'Proj, Onager', 552: 'Proj, Onager F', 553: 'Elite Cataphract', 554: 'Elite Teutonic Knight', 555: 'Elite Huskarl', 556: 'Elite Mameluke', 557: 'Elite Janissary', 558: 'Elite War Elephant', 559: 'Elite Chu Ko Nu', 560: 'Elite Samurai', 561: 'Elite Mangudai', 562: 'Lumber Camp', 563: 'Lumber Camp 2', 564: 'Lumber Camp 3', 565: 'Lumber Camp 4', 566: 'WCTWR', 567: 'Champion', 568: 'Champion, Dead', 569: 'Paladin', 570: 'Paladin, D', 571: 'RFARC', 572: 'RFARC, D', 573: 'RFSWD', 574: 'RFSWD, D', 575: 'RCSWD', 576: 'RCSWD, D', 577: 'RCARC', 578: 'RCARC, D', 579: 'Gold Miner, M', 580: 'Gold Miner, M D', 581: 'Gold Miner, F', 582: 'Gold Miner, F D', 583: 'Genitour', 584: 'Mining Camp', 585: 'Mining Camp 2', 586: 'Mining Camp 3', 587: 'Mining Camp 4', 588: 'Siege Onager', 589: 'Siege Onager, D', 590: 'Shepherd, F', 591: 'Shepherd, F D', 592: 'Shepherd, M', 593: 'Shepherd, M D', 594: 'Sheep', 595: 'Sheep, D', 596: 'Elite Genitour', 597: 'Town Center 4X', 598: 'Outpost', 599: 'Cathedral', 600: 'Flag A', 601: 'Flag B', 602: 'Flag C', 603: 'Flag D', 604: 'Flag E', 605: 'Bridge A Top', 606: 'Bridge A Middle', 607: 'Bridge A Bottom', 608: 'Bridge B Top', 609: 'Bridge B Middle', 610: 'Bridge B Bottom', 611: 'Town Center 4A', 612: 'Town Center 4B', 613: 'Town Center 4C', 614: 'Town Center 2A', 615: 'Town Center 2B', 616: 'Town Center 2C', 617: 'Town Center 2X', 618: 'Town Center 1A', 619: 'Town Center 1B', 620: 'Town Center 1C', 621: 'Town Center 1X', 622: 'D Iron Boar', 623: 'Rock', 624: 'Pavilion 1', 625: 'Pavilion 3', 626: 'Pavilion 2', 627: 'Proj, Heavy Scorpion', 628: 'Proj, Heavy Scorpion F', 629: 'Joan Of Arc', 630: 'Joan Of Arc, D', 631: 'Subotai, D', 632: 'Frankish Paladin', 633: 'Frankish Paladin, D', 634: 'Sieur De Metz', 635: 'Sieur De Metz, D', 636: 'Sieur Bertrand', 637: 'Sieur Bertrand, D', 638: "Duke D'Alencon", 639: "Duke D'Alencon, D", 640: 'La Hire', 641: 'La Hire, D', 642: 'Lord De Graville', 643: 'Lord De Graville, D', 644: 'Jean De Lorrain', 645: 'Jean De Lorrain, D', 646: 'Constable Richemont', 647: 'Constable Richemont, D', 648: 'Guy Josselyne', 649: 'Guy Josselyne, D', 650: 'Jean Bureau', 651: 'Jean Bureau, D', 652: 'Sir John Fastolf', 653: 'Sir John Fastolf, D', 654: 'S_SMOKE', 655: 'Mosque', 656: 'Proj, MNB', 657: 'Proj, GP1', 658: 'Proj, MNB F', 659: 'Gate, CA2', 660: 'Gate, CA3', 661: 'Gate, CB2', 662: 'Gate, CB3', 663: 'Gate, CC2', 664: 'Gate, CC3', 665: 'Gate, CX2', 666: 'Gate, CX3', 667: 'Gate, DA2', 668: 'Gate, DA3', 669: 'Gate, DB2', 670: 'Gate, DB3', 671: 'Gate, DC2', 672: 'Gate, DC3', 673: 'Gate, DX2', 674: 'Gate, DX3', 675: 'Onager, D', 676: 'Proj, FFG F', 677: 'S_Fire', 678: 'Reynald De Chatillon', 679: 'Reynald De Chatillon, D', 680: 'Master Of The Templar', 681: 'Master Of The Templar, D', 682: 'Bad Neighbor', 683: 'Gods Own Sling', 684: 'The Accursed Tower', 685: 'The Tower Of Flies', 686: 'Archer Of The Eyes', 687: 'Archer Of The Eyes, D', 688: 'Piece Of The True Cross', 689: 'Pyramid', 690: 'Dome Of The Rock', 691: 'Elite Cannon Galleon', 692: 'Berserk', 693: 'Berserk, D', 694: 'Elite Berserk', 695: 'Elite Berserk, D', 696: 'Great Pyramid', 697: 'Flare 4', 698: 'Subotai', 699: 'Subotai, D', 700: 'Hunting Wolf', 701: 'Hunting Wolf, D', 702: 'Kushluk', 703: 'Kushluk, D', 704: 'Shah', 705: 'Shah, D', 706: 'Saboteur', 707: 'Ornlu The Wolf', 708: 'Ornlu The Wolf, D', 709: 'Cactus', 710: 'Skeleton', 711: 'Rugs', 712: 'Yurt', 713: 'Yurt 2', 714: 'Yurt 3', 715: 'Yurt 4', 716: 'Yurt 5', 717: 'Yurt 6', 718: 'Yurt 7', 719: 'Yurt 8', 720: 'Nine Bands', 721: 'Shipwreck', 722: 'Shipwreck 2', 723: 'Crater', 724: 'Genitour, Dead', 725: 'Jaguar Warrior', 726: 'Elite Jaguar Warrior', 728: 'Ice Spots', 729: 'Gods Own Sling, Packed', 730: 'Bad Neighbor, Packed', 731: 'Genghis Khan', 732: 'Genghis Khan, D', 733: 'Emperor In A Barrel', 734: 'Emperor In A Barrel, D', 735: 'Trebuchet, Packed D', 736: 'Proj, Mameluke', 737: 'Stump B', 738: 'Bridge A Middle Broken', 739: 'Bridge A Middle Broken 2', 740: 'Bridge A Middle Broken 3', 741: 'Bridge B Middle Broken', 742: 'Bridge B Middle Broken 2', 743: 'Bridge B Middle Broken 3', 744: 'Mountain 3', 745: 'Mountain 4', 746: 'Proj, Castle', 747: 'Proj, Castle Flaming', 748: 'Cobra Car', 749: 'Cobra, D', 750: 'Jaguar Warrior, D', 751: 'Eagle Warrior', 752: 'Elite Eagle Warrior', 754: 'Eagle Warrior, D', 755: 'Tarkan', 756: 'Tarkan, D', 757: 'Elite Tarkan', 759: 'Huskarl', 760: 'Huskarl, Dead', 761: 'Elite Huskarl', 762: 'Elite Huskarl, Dead', 763: 'Plumed Archer', 764: 'Plumed Archer, D', 765: 'Elite Plumed Archer', 766: 'Elite Plumed Archer, D', 767: 'Proj, Elite Cannon Galleon', 771: 'Conquistador', 772: 'Conquistador, D', 773: 'Elite Conquistador', 774: 'Elite Conquistador, D', 775: 'Missionary', 776: 'Missionary, D', 777: 'Attila The Hun', 778: 'Atilla The Hun, D', 779: 'Bleda The Hun', 780: 'Bleda The Hun, D', 781: 'Pope Leo I', 782: 'Pope Leo I, D', 783: 'Scythian Wild Woman', 784: 'Scythian Wild Woman, D', 785: 'Sea Tower', 786: 'Proj, Sea Tower', 787: 'Proj, Sea Tower Flaming', 788: 'Sea Wall', 789: 'Sea Gate, AA', 790: 'Sea Gate, AB', 791: 'Sea Gate, AC', 792: 'Sea Gate, AX', 793: 'Sea Gate, BA', 794: 'Sea Gate, BB', 795: 'Sea Gate, BC', 796: 'Sea Gate, BX', 797: 'Sea Gate, CA', 798: 'Sea Gate, CB', 799: 'Sea Gate, CC', 800: 'Sea Gate, CX', 801: 'Sea Gate, DA', 802: 'Sea Gate, DB', 803: 'Sea Gate, DC', 804: 'Sea Gate, DX', 805: 'S Dock', 806: 'S Dock 2', 807: 'S Dock 3', 808: 'S Dock 4', 809: 'Stump 2', 810: 'Iron Boar', 811: 'Iron Boar, D', 812: 'Jaguar', 813: 'Jaguar, D', 814: 'Horse', 815: 'Horse, D', 816: 'Macaw', 817: 'Statue', 818: 'Plants', 819: 'Sign', 820: 'Grave', 821: 'Head', 822: 'Javelina', 823: 'Javelina, D', 824: 'El Cid Campeador', 825: 'El Cid Campeador, D', 826: 'Monument (KotH)', 827: 'War Wagon', 828: 'War Wagon, D', 829: 'Elite War Wagon', 830: 'Elite War Wagon, D', 831: 'Turtle Ship', 832: 'Elite Turtle Ship', 833: 'Turkey', 834: 'Turkey, Dead', 835: 'Wild Horse', 836: 'Wild Horse, D', 837: 'Map Revealer', 838: 'King Sancho', 839: 'King Sancho, D', 840: 'King Alfonso', 841: 'King Alfonso, D', 842: 'Imam', 843: 'Imam, D', 844: 'Admiral Yi Sun Shin', 845: 'Nobunaga', 846: 'Nobunaga, D', 847: 'Henry V', 848: 'Henry V, D', 849: 'William The Conqueror', 850: 'William The Conqueror, D', 851: 'Flag, ES', 852: 'Scythian Scout', 853: 'Scythian Scout, D', 854: 'Torch 2', 855: 'Old Stone Head', 856: 'Roman Ruins', 857: 'Hay Stack', 858: 'Broken Cart', 859: 'Flower Bed', 860: 'Furious The Monkey Boy', 861: 'Furious The Monkey Boy, D', 862: 'Stormy Dog', 863: 'Rubble 1 X 1', 864: 'Rubble 2 X 2', 865: 'Rubble 3 X 3'} |
#Return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
def get_middle(s):
if len(s) % 2 == 0:
return s[int(len(s) / 2) - 1] + s[int((len(s) / 2))]
else:
return s[int(len(s) / 2)]
#Alternate Solution
def get_middle(s):
index, odd = divmod(len(s), 2)
return s[index] if odd else s[index - 1:index + 1] | def get_middle(s):
if len(s) % 2 == 0:
return s[int(len(s) / 2) - 1] + s[int(len(s) / 2)]
else:
return s[int(len(s) / 2)]
def get_middle(s):
(index, odd) = divmod(len(s), 2)
return s[index] if odd else s[index - 1:index + 1] |
# codeforces round 600 div 2 - A
# solved in time
# https://codeforces.com/contest/1253/problem/A?locale=en
t = int(input())
for i in range(t):
n = int(input())
a_list = input().split(' ')
b_list = input().split(' ')
prev_diff = 0
current_diff = 0
diff_found = 0
result = ''
if n == 1:
if b_list[0] >= a_list[0]:
result = 'YES'
else:
result = 'NO'
else:
for j in range(n):
current_diff = int(b_list[j]) - int(a_list[j])
if current_diff < 0:
result = 'NO'
else:
if diff_found == 0:
if current_diff != 0:
prev_diff = current_diff
diff_found = 1
else:
if current_diff == 0:
prev_diff = current_diff
else:
if prev_diff == 0:
result = 'NO'
if prev_diff != 0 and prev_diff != current_diff:
result = 'NO'
if result == '':
result = 'YES'
print(result)
#1
#3
#1 2 3
#2 2 4
| t = int(input())
for i in range(t):
n = int(input())
a_list = input().split(' ')
b_list = input().split(' ')
prev_diff = 0
current_diff = 0
diff_found = 0
result = ''
if n == 1:
if b_list[0] >= a_list[0]:
result = 'YES'
else:
result = 'NO'
else:
for j in range(n):
current_diff = int(b_list[j]) - int(a_list[j])
if current_diff < 0:
result = 'NO'
elif diff_found == 0:
if current_diff != 0:
prev_diff = current_diff
diff_found = 1
elif current_diff == 0:
prev_diff = current_diff
else:
if prev_diff == 0:
result = 'NO'
if prev_diff != 0 and prev_diff != current_diff:
result = 'NO'
if result == '':
result = 'YES'
print(result) |
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'HOST': '',
'NAME': '',
'USER': '',
'PASSWORD': '',
}
}
| secret_key = ''
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'HOST': '', 'NAME': '', 'USER': '', 'PASSWORD': ''}} |
def add_native_methods(clazz):
def __java_init______(a0):
raise NotImplementedError()
def selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__(a0, a1):
raise NotImplementedError()
clazz.__java_init______ = __java_init______
clazz.selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__ = staticmethod(selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__)
| def add_native_methods(clazz):
def __java_init______(a0):
raise not_implemented_error()
def select_alternatives__com_sun_xml_internal_ws_policy__effective_policy_modifier__com_sun_xml_internal_ws_policy__assertion_validation_processor__(a0, a1):
raise not_implemented_error()
clazz.__java_init______ = __java_init______
clazz.selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__ = staticmethod(selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__) |
############### Configuration file for Bayesian ###############
n_epochs = 10000
lr_start = 0.0001
num_workers = 16
valid_size = 0.1
batch_size = 1024
train_ens = 1
valid_ens = 1
record_mean_var = True
recording_freq_per_epoch = 8
record_layers = ['fc5']
# Cross-module global variables
mean_var_dir = None
record_now = False
curr_epoch_no = None
curr_batch_no = None
| n_epochs = 10000
lr_start = 0.0001
num_workers = 16
valid_size = 0.1
batch_size = 1024
train_ens = 1
valid_ens = 1
record_mean_var = True
recording_freq_per_epoch = 8
record_layers = ['fc5']
mean_var_dir = None
record_now = False
curr_epoch_no = None
curr_batch_no = None |
'''
Solve the problem of skyscrapers game
github: https://github.com/VictoriyaRoy/skyscrapers
'''
def read_input(path: str) -> list:
"""
Read game board file from path.
Return list of str.
"""
with open(path, mode = 'r', encoding = 'utf-8') as file:
board = file.read().split('\n')
return board
def is_visible(input_line: str, index: int) -> bool:
'''
Check if skyscraper on index position is visible
>>> is_visible('*13245*', 2)
True
>>> is_visible('*13245*', 3)
False
>>> is_visible('132345*', 3)
False
'''
check_number = input_line[index]
for element in input_line[1:index]:
if element >= check_number:
return False
return True
def left_to_right_check(input_line: str, pivot: int) -> bool:
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the input_line.
>>> left_to_right_check("412453*", 4)
True
>>> left_to_right_check("452453*", 5)
False
>>> left_to_right_check("132345*", 3)
True
"""
count = 0
for index, _ in enumerate(input_line[1:-1]):
if is_visible(input_line, index+1):
count += 1
return count == pivot
def check_not_finished_board(board: list) -> bool:
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', \
'*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215', \
'*35214*', '*41532*', '*2*1***'])
False
"""
for line in board:
if '?' in line:
return False
return True
def check_uniqueness_in_rows(board: list) -> bool:
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
True
>>> check_uniqueness_in_rows(['***21**', '452453*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
False
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*553215', \
'*35214*', '*41532*', '*2*1***'])
False
"""
for line in board[1:-1]:
if len(set(line[1:-1])) != len(line[1:-1]):
return False
return True
def check_horizontal_visibility(board: list) -> bool:
"""
Check row-wise visibility (left-right and vice versa)
Return True if all horizontal hints are satisfiable,
i.e., for line 412453* , hint is 4, and 1245 are the four buildings
that could be observed from the hint looking to the right.
>>> check_horizontal_visibility(['***21**', '412453*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
True
>>> check_horizontal_visibility(['***21**', '452453*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
False
>>> check_horizontal_visibility(['***21**', '452413*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
False
"""
for line in board[1:-1]:
check = line[0]
if check != '*':
if not left_to_right_check(line, int(check)):
return False
check = line[-1]
if check != '*':
line = line[::-1]
if not left_to_right_check(line, int(check)):
return False
return True
def check_columns(board: list) -> bool:
"""
Check column-wise compliance of the board for uniqueness (buildings of unique height)
and visibility (top-bottom and vice versa).
Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns.
>>> check_columns(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_columns(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41232*', '*2*1***'])
False
>>> check_columns(['***21**', '412553*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
False
"""
length = len(board)
new_board = ['' for i in range(length)]
for line in board:
for index, element in enumerate(line):
new_board[index] += element
return check_horizontal_visibility(new_board) and check_uniqueness_in_rows(new_board)
def check_skyscrapers(input_path: str) -> bool:
"""
Main function to check the status of skyscraper game board.
Return True if the board status is compliant with the rules,
False otherwise.
"""
board = read_input(input_path)
if check_not_finished_board(board) and check_uniqueness_in_rows(board):
if check_horizontal_visibility(board) and check_columns(board):
return True
return False
if __name__ == "__main__":
print(check_skyscrapers('check.txt'))
| """
Solve the problem of skyscrapers game
github: https://github.com/VictoriyaRoy/skyscrapers
"""
def read_input(path: str) -> list:
"""
Read game board file from path.
Return list of str.
"""
with open(path, mode='r', encoding='utf-8') as file:
board = file.read().split('\n')
return board
def is_visible(input_line: str, index: int) -> bool:
"""
Check if skyscraper on index position is visible
>>> is_visible('*13245*', 2)
True
>>> is_visible('*13245*', 3)
False
>>> is_visible('132345*', 3)
False
"""
check_number = input_line[index]
for element in input_line[1:index]:
if element >= check_number:
return False
return True
def left_to_right_check(input_line: str, pivot: int) -> bool:
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the input_line.
>>> left_to_right_check("412453*", 4)
True
>>> left_to_right_check("452453*", 5)
False
>>> left_to_right_check("132345*", 3)
True
"""
count = 0
for (index, _) in enumerate(input_line[1:-1]):
if is_visible(input_line, index + 1):
count += 1
return count == pivot
def check_not_finished_board(board: list) -> bool:
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215', '*35214*', '*41532*', '*2*1***'])
False
"""
for line in board:
if '?' in line:
return False
return True
def check_uniqueness_in_rows(board: list) -> bool:
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_uniqueness_in_rows(['***21**', '452453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
False
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*553215', '*35214*', '*41532*', '*2*1***'])
False
"""
for line in board[1:-1]:
if len(set(line[1:-1])) != len(line[1:-1]):
return False
return True
def check_horizontal_visibility(board: list) -> bool:
"""
Check row-wise visibility (left-right and vice versa)
Return True if all horizontal hints are satisfiable,
i.e., for line 412453* , hint is 4, and 1245 are the four buildings
that could be observed from the hint looking to the right.
>>> check_horizontal_visibility(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_horizontal_visibility(['***21**', '452453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
False
>>> check_horizontal_visibility(['***21**', '452413*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
False
"""
for line in board[1:-1]:
check = line[0]
if check != '*':
if not left_to_right_check(line, int(check)):
return False
check = line[-1]
if check != '*':
line = line[::-1]
if not left_to_right_check(line, int(check)):
return False
return True
def check_columns(board: list) -> bool:
"""
Check column-wise compliance of the board for uniqueness (buildings of unique height)
and visibility (top-bottom and vice versa).
Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns.
>>> check_columns(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_columns(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41232*', '*2*1***'])
False
>>> check_columns(['***21**', '412553*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
False
"""
length = len(board)
new_board = ['' for i in range(length)]
for line in board:
for (index, element) in enumerate(line):
new_board[index] += element
return check_horizontal_visibility(new_board) and check_uniqueness_in_rows(new_board)
def check_skyscrapers(input_path: str) -> bool:
"""
Main function to check the status of skyscraper game board.
Return True if the board status is compliant with the rules,
False otherwise.
"""
board = read_input(input_path)
if check_not_finished_board(board) and check_uniqueness_in_rows(board):
if check_horizontal_visibility(board) and check_columns(board):
return True
return False
if __name__ == '__main__':
print(check_skyscrapers('check.txt')) |
# Copyright (c) 2012-2021 Esri R&D Center Zurich
# 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
# https://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.
# A copy of the license is available in the repository's LICENSE file.
def visualize_prt_results(models):
"""visualize_prt_results(models)
This helper function is used to output the geometry and report information of a
list of GeneratedModel instances.
Parameters:
models: List[GeneratedModel]
"""
print('\nNumber of generated geometries (= nber of initial shapes):')
print(len(models))
for m in models:
if m:
geometry_vertices = m.get_vertices()
rep = m.get_report()
print()
print('Initial Shape Index: ' + str(m.get_initial_shape_index()))
if len(geometry_vertices) > 0:
print()
print('Size of the model vertices vector: ' +
str(len(geometry_vertices)))
print('Number of model vertices: ' +
str(int(len(geometry_vertices)/3)))
print('Size of the model faces vector: ' +
str(len(m.get_faces())))
if len(rep) > 0:
print()
print('Report of the generated model:')
print(rep)
else:
print('\nError while instanciating the model generator.')
def vertices_vector_to_matrix(vertices):
"""vertices_vector_to_matrix(vertices) -> List[List[float]]
PyPRT outputs the GeneratedModel vertex coordinates as a list. The list
contains the x, y, z coordinates of all the vertices. This function converts the
vertex list into a list of N vertex coordinates lists (with N, the number
of geometry vertices).
Parameters:
vertices: List[float]
Returns:
List[List[float]]
Example:
``[[-10.0, 0.0, 10.0], [-10.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 0.0, 10.0]]
= vertices_vector_to_matrix([-10.0, 0.0, 10.0, -10.0, 0.0, 0.0, 10.0, 0.0, 0.0,
10.0, 0.0, 10.0])``
"""
vertices_as_matrix = []
for count in range(0, int(len(vertices)/3)):
vector_per_pt = [vertices[count*3],
vertices[count*3+1], vertices[count*3+2]]
vertices_as_matrix.append(vector_per_pt)
return vertices_as_matrix
def faces_indices_vectors_to_matrix(indices, faces):
"""faces_indices_vectors_to_matrix(indices, faces) -> List[List[int]]
PyPRT outputs the GeneratedModel face information as a list of vertex indices
and a list of face indices count. This function converts these two lists into
one list of lists containing the vertex indices per face.
Parameters:
indices: List[int]
faces: List[int]
Returns:
List[List[int]]
Example:
``[[1, 0, 3, 2], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
= faces_indices_vectors_to_matrix(([1, 0, 3, 2, 4, 5, 6, 7, 0, 1, 5, 4, 1, 2, 6, 5,
2, 3, 7, 6, 3, 0, 4, 7],[4, 4, 4, 4, 4, 4]))``
"""
faces_as_matrix = []
offset = 0
for f in faces:
ind_per_face = indices[offset:offset+f]
offset += f
faces_as_matrix.append(ind_per_face)
return faces_as_matrix
| def visualize_prt_results(models):
"""visualize_prt_results(models)
This helper function is used to output the geometry and report information of a
list of GeneratedModel instances.
Parameters:
models: List[GeneratedModel]
"""
print('\nNumber of generated geometries (= nber of initial shapes):')
print(len(models))
for m in models:
if m:
geometry_vertices = m.get_vertices()
rep = m.get_report()
print()
print('Initial Shape Index: ' + str(m.get_initial_shape_index()))
if len(geometry_vertices) > 0:
print()
print('Size of the model vertices vector: ' + str(len(geometry_vertices)))
print('Number of model vertices: ' + str(int(len(geometry_vertices) / 3)))
print('Size of the model faces vector: ' + str(len(m.get_faces())))
if len(rep) > 0:
print()
print('Report of the generated model:')
print(rep)
else:
print('\nError while instanciating the model generator.')
def vertices_vector_to_matrix(vertices):
"""vertices_vector_to_matrix(vertices) -> List[List[float]]
PyPRT outputs the GeneratedModel vertex coordinates as a list. The list
contains the x, y, z coordinates of all the vertices. This function converts the
vertex list into a list of N vertex coordinates lists (with N, the number
of geometry vertices).
Parameters:
vertices: List[float]
Returns:
List[List[float]]
Example:
``[[-10.0, 0.0, 10.0], [-10.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 0.0, 10.0]]
= vertices_vector_to_matrix([-10.0, 0.0, 10.0, -10.0, 0.0, 0.0, 10.0, 0.0, 0.0,
10.0, 0.0, 10.0])``
"""
vertices_as_matrix = []
for count in range(0, int(len(vertices) / 3)):
vector_per_pt = [vertices[count * 3], vertices[count * 3 + 1], vertices[count * 3 + 2]]
vertices_as_matrix.append(vector_per_pt)
return vertices_as_matrix
def faces_indices_vectors_to_matrix(indices, faces):
"""faces_indices_vectors_to_matrix(indices, faces) -> List[List[int]]
PyPRT outputs the GeneratedModel face information as a list of vertex indices
and a list of face indices count. This function converts these two lists into
one list of lists containing the vertex indices per face.
Parameters:
indices: List[int]
faces: List[int]
Returns:
List[List[int]]
Example:
``[[1, 0, 3, 2], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
= faces_indices_vectors_to_matrix(([1, 0, 3, 2, 4, 5, 6, 7, 0, 1, 5, 4, 1, 2, 6, 5,
2, 3, 7, 6, 3, 0, 4, 7],[4, 4, 4, 4, 4, 4]))``
"""
faces_as_matrix = []
offset = 0
for f in faces:
ind_per_face = indices[offset:offset + f]
offset += f
faces_as_matrix.append(ind_per_face)
return faces_as_matrix |
class ClassPropertyDescriptor(object):
"""Based on https://stackoverflow.com/questions/5189699/how-to-make-a-class-property"""
def __init__(self, fget):
self.fget = fget
def __get__(self, obj, klass):
if klass is None:
klass = type(obj)
return self.fget.__get__(obj, klass)()
def classproperty(func):
return ClassPropertyDescriptor(classmethod(func))
| class Classpropertydescriptor(object):
"""Based on https://stackoverflow.com/questions/5189699/how-to-make-a-class-property"""
def __init__(self, fget):
self.fget = fget
def __get__(self, obj, klass):
if klass is None:
klass = type(obj)
return self.fget.__get__(obj, klass)()
def classproperty(func):
return class_property_descriptor(classmethod(func)) |
# Exceptions indicating the reaction completer has an error
#
__author__ = 'Haoyan Huo'
__maintainer__ = 'Haoyan Huo'
__email__ = 'haoyan.huo@lbl.gov'
class FormulaException(Exception):
"""
A chemical formula cannot be parsed.
"""
pass
class CannotBalance(Exception):
"""
A general exception suggesting that reaction completer
is unable to create a valid reaction
"""
pass
class TooFewPrecursors(CannotBalance):
"""
Too few precursors cannot be balanced.
"""
pass
class TooManyPrecursors(CannotBalance):
"""
Too many precursors cannot be balanced. For example:
Ba + O + BaO + TiO2 == ? == BaTiO3
"""
pass
class StupidRecipe(CannotBalance):
"""
Exception shows that the recipe is not meaningful for parsing.
List of possible reasons:
1. Target equals precursors: BaTiO3 == BaTiO3
2. Target only has less than three elements: 2H + O == H2O
"""
pass
class ExpressionPrintException(CannotBalance):
"""
A math formula cannot be printed.
"""
pass
| __author__ = 'Haoyan Huo'
__maintainer__ = 'Haoyan Huo'
__email__ = 'haoyan.huo@lbl.gov'
class Formulaexception(Exception):
"""
A chemical formula cannot be parsed.
"""
pass
class Cannotbalance(Exception):
"""
A general exception suggesting that reaction completer
is unable to create a valid reaction
"""
pass
class Toofewprecursors(CannotBalance):
"""
Too few precursors cannot be balanced.
"""
pass
class Toomanyprecursors(CannotBalance):
"""
Too many precursors cannot be balanced. For example:
Ba + O + BaO + TiO2 == ? == BaTiO3
"""
pass
class Stupidrecipe(CannotBalance):
"""
Exception shows that the recipe is not meaningful for parsing.
List of possible reasons:
1. Target equals precursors: BaTiO3 == BaTiO3
2. Target only has less than three elements: 2H + O == H2O
"""
pass
class Expressionprintexception(CannotBalance):
"""
A math formula cannot be printed.
"""
pass |
'''
Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
More formally check if there exists two indices i and j such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
Example 1:
Input: arr = [10,2,5,3]
Output: true
Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.
Example 2:
Input: arr = [7,1,14,11]
Output: true
Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.
Example 3:
Input: arr = [3,1,7,11]
Output: false
Explanation: In this case does not exist N and M, such that N = 2 * M.
'''
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
# step 1: deal with exceptions
if arr==None:
return False
if len(arr)<=1:
return False
# step 2: traverse the list
tb = set()
for num in arr:
if (2*num in tb)|(num/2 in tb):
return True
if num not in tb:
tb.add(num)
return False
| """
Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
More formally check if there exists two indices i and j such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
Example 1:
Input: arr = [10,2,5,3]
Output: true
Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.
Example 2:
Input: arr = [7,1,14,11]
Output: true
Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.
Example 3:
Input: arr = [3,1,7,11]
Output: false
Explanation: In this case does not exist N and M, such that N = 2 * M.
"""
class Solution:
def check_if_exist(self, arr: List[int]) -> bool:
if arr == None:
return False
if len(arr) <= 1:
return False
tb = set()
for num in arr:
if (2 * num in tb) | (num / 2 in tb):
return True
if num not in tb:
tb.add(num)
return False |
# Author: btjanaka (Bryon Tjanaka)
# Problem: (HackerRank) summing-the-n-series
# Title: Summing the N series
# Link: https://www.hackerrank.com/challenges/summing-the-n-series/problem
# Idea: The terms cancel out such that the sum is just n^2.
# Difficulty: easy
# Tags: math
t = int(input())
MOD = 10**9 + 7
for i in range(t):
n = int(input()) % MOD
print((n * n) % MOD)
| t = int(input())
mod = 10 ** 9 + 7
for i in range(t):
n = int(input()) % MOD
print(n * n % MOD) |
def classify(entries):
for entry in entries:
entry['category_id'] = 1
entry['event_id'] = 1
return entries
| def classify(entries):
for entry in entries:
entry['category_id'] = 1
entry['event_id'] = 1
return entries |
# __***__ are especial functions and attributes
def dynamic_function():
print('dynamic_function')
class MyClass:
"""A simple example class""" # default: __doc__=...
i: int # it is a instance attribute
att = 'static' # it is a static attribute
def __init__(self, name): # constructor: __init__
print('Init MyClass:', name)
self.i = len(name)
self.name = name # 'other' is a instance attribute
self.dynamic = dynamic_function
def public(self): # public
return 'hello world (' + str(self.i) + ')'
def __private(self): # private
pass
print('0- type of class: ', type(MyClass))
print('1 ---------------- ')
my_class = MyClass('me')
my_class.dynamic()
my_class.new_attribute = "New!!!"
my_class.new_function = dynamic_function
print(my_class.new_attribute)
# Inheritance
class ChildClass(MyClass):
def __init__(self):
super().__init__('child')
print('2 ---------------- ')
ChildClass()
class Two:
two: str
def __init__(self):
print('Init Two')
# Multiple inheritance
class Multiple(MyClass, Two):
value: str
print('3 ---------------- ')
multiple = Multiple('multiple')
multiple.i = 3
multiple.name = "name"
multiple.two = "2"
multiple.value = "value"
class WithDecorator:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@classmethod
def from_string(cls, name_str):
first_name, last_name = map(str, name_str.split(' '))
return cls(first_name, last_name)
@staticmethod
def is_full_name(name_str):
names = name_str.split(' ')
return len(names) > 1
# __doc__ __init__ __name__ __module__ __call__ ...
print('4 ---------------- ')
print('__doc__ ', MyClass.__doc__)
print('__name__ ', MyClass.__name__)
print('__module__ ', MyClass.__module__)
class Callable:
def __call__(self, value): # class default function
print('__call__ >> value: ', value)
my_callable = Callable()
my_callable("!!!") # class is callable my_callable.__call__(23)
# my_class() ERROR!!!
| def dynamic_function():
print('dynamic_function')
class Myclass:
"""A simple example class"""
i: int
att = 'static'
def __init__(self, name):
print('Init MyClass:', name)
self.i = len(name)
self.name = name
self.dynamic = dynamic_function
def public(self):
return 'hello world (' + str(self.i) + ')'
def __private(self):
pass
print('0- type of class: ', type(MyClass))
print('1 ---------------- ')
my_class = my_class('me')
my_class.dynamic()
my_class.new_attribute = 'New!!!'
my_class.new_function = dynamic_function
print(my_class.new_attribute)
class Childclass(MyClass):
def __init__(self):
super().__init__('child')
print('2 ---------------- ')
child_class()
class Two:
two: str
def __init__(self):
print('Init Two')
class Multiple(MyClass, Two):
value: str
print('3 ---------------- ')
multiple = multiple('multiple')
multiple.i = 3
multiple.name = 'name'
multiple.two = '2'
multiple.value = 'value'
class Withdecorator:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@classmethod
def from_string(cls, name_str):
(first_name, last_name) = map(str, name_str.split(' '))
return cls(first_name, last_name)
@staticmethod
def is_full_name(name_str):
names = name_str.split(' ')
return len(names) > 1
print('4 ---------------- ')
print('__doc__ ', MyClass.__doc__)
print('__name__ ', MyClass.__name__)
print('__module__ ', MyClass.__module__)
class Callable:
def __call__(self, value):
print('__call__ >> value: ', value)
my_callable = callable()
my_callable('!!!') |
# Given list of values. We play a game against the opponent and we always grab
# one value from either left or right side of our list of values. Our opponent
# does the same move. What is the maximum value we can grab if our opponent
# plays optimally, just like us.
def optimal_values(V):
T = [[0]*(len(V)+1) for _ in range(len(V)+1)]
for i in range(1, len(V)+1):
T[0][i] = i
for i in range(1, len(V)+1):
T[i][0] = i
for i in range(1, len(T)):
T[i][i] = (V[i-1], 0)
for value in range(2, len(V)+1):
for i in range(1, len(T)-value+1):
j = i+value-1
for k in range(i, j):
first = max(T[i][j-1][1] + V[j-1], T[i+1][j][1]+V[i-1])
second = min(T[i][j-1][0], T[i+1][j][0])
T[i][j] = (first, second)
return T[1][-1][0]
V = [3, 8, 4, 5, 1, 7, 6]
print(optimal_values(V))
| def optimal_values(V):
t = [[0] * (len(V) + 1) for _ in range(len(V) + 1)]
for i in range(1, len(V) + 1):
T[0][i] = i
for i in range(1, len(V) + 1):
T[i][0] = i
for i in range(1, len(T)):
T[i][i] = (V[i - 1], 0)
for value in range(2, len(V) + 1):
for i in range(1, len(T) - value + 1):
j = i + value - 1
for k in range(i, j):
first = max(T[i][j - 1][1] + V[j - 1], T[i + 1][j][1] + V[i - 1])
second = min(T[i][j - 1][0], T[i + 1][j][0])
T[i][j] = (first, second)
return T[1][-1][0]
v = [3, 8, 4, 5, 1, 7, 6]
print(optimal_values(V)) |
"""
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y
x // y floored quotient of x and y
x % y remainder of x / y
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x
int(x) x converted to integer
float(x) x converted to floating point
complex(re, im) a complex number with real part re, imaginary part im. im defaults to zero.
c.conjugate() conjugate of the complex number c
divmod(x, y) the pair (x // y, x % y)
pow(x, y) x to the power y
x ** y x to the power y
math.trunc(x) x truncated to Integral
round(x[, n]) x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
math.floor(x) the greatest Integral <= x
math.ceil(x) the least Integral >= x
~x the bits of x inverted
float.is_integer()
Return True if the float instance is finite with integral value, and False otherwise
"""
"""
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n or n * s equivalent to adding s to itself n times
s[i] ith item of s, origin 0
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
s.index(x[, i[, j]]) index of the first occurrence of x in s (at or after index i and before index j)
s.count(x) total number of occurrences of x in s
"""
"""
Python String Methods
capitalize() - Returns the string with first letter capitalized and the rest lowercased.
casefold() - Returns a lowercase string, generally used for caseless matching. This is more aggressive than the lower() method.
center() - Center the string within the specified width with optional fill character.
count() - Count the non-overlapping occurrence of supplied substring in the string.
encode() - Return the encoded version of the string as a bytes object.
endswith() - Returns ture if the string ends with the supplied substring.
expandtabs() - Return a string where all the tab characters are replaced by the supplied number of spaces.
find() - Return the index of the first occurrence of supplied substring in the string. Return -1 if not found.
format() - Format the given string.
format_map() - Format the given string.
index() - Return the index of the first occurrence of supplied substring in the string. Raise ValueError if not found.
isalnum() - Return true if the string is non-empty and all characters are alphanumeric.
isalpha() - Return true if the string is non-empty and all characters are alphabetic.
isdecimal() - Return true if the string is non-empty and all characters are decimal characters.
isdigit() - Return true if the string is non-empty and all characters are digits.
isidentifier() - Return true if the string is a valid identifier.
islower() - Return true if the string has all lowercased characters and at least one is cased character.
isnumeric() - Return true if the string is non-empty and all characters are numeric.
isprintable() - Return true if the string is empty or all characters are printable.
isspace() - Return true if the string is non-empty and all characters are whitespaces.
istitle() - Return true if the string is non-empty and titlecased.
isupper() - Return true if the string has all uppercased characters and at least one is cased character.
join() - Concatenate strings in the provided iterable with separator between them being the string providing this method.
ljust() - Left justify the string in the provided width with optional fill characters.
lower() - Return a copy of all lowercased string.
lstrip() - Return a string with provided leading characters removed.
maketrans() - Return a translation table.
partition() - Partition the string at first occurrence of substring (separator) and return a 3-tuple with part before separator, the separator and part after separator.
replace() - Replace all old substrings with new substrings.
rfind() - Return the index of the last occurrence of supplied substring in the string. Return -1 if not found.
rindex() - Return the index of the last occurrence of supplied substring in the string. Raise ValueError if not found.
rjust() - Right justify the string in the provided width with optional fill characters.
rpartition() - Partition the string at last occurrence of substring (separator) and return a 3-tuple with part before separator, the separator and part after separator.
rsplit() - Return a list of words delimited by the provided subtring. If maximum number of split is specified, it is done from the right.
rstrip() - Return a string with provided trailing characters removed.
split() - Return a list of words delimited by the provided subtring. If maximum number of split is specified, it is done from the left.
splitlines() - Return a list of lines in the string.
startswith() - Return true if the string starts with the provided substring.
strip() - Return a string with provided leading and trailing characters removed.
swapcase() - Return a string with lowercase characters converted to uppercase and vice versa.
title() - Return a title (first character of each word capitalized, others lowercased) cased string.
translate() - Return a copy of string that has been mapped according to the provided map.
upper() - Return a copy of all uppercased string.
zfill() - Return a numeric string left filled with zeros in the provided width.
sort alphabetically the words form a string provided by the user
breakdown the string into a list of words
words = my_str.split()
sort the list
words.sort()
"""
"""
enumerate() -> tuplas
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
"""
| """
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y
x // y floored quotient of x and y
x % y remainder of x / y
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x
int(x) x converted to integer
float(x) x converted to floating point
complex(re, im) a complex number with real part re, imaginary part im. im defaults to zero.
c.conjugate() conjugate of the complex number c
divmod(x, y) the pair (x // y, x % y)
pow(x, y) x to the power y
x ** y x to the power y
math.trunc(x) x truncated to Integral
round(x[, n]) x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
math.floor(x) the greatest Integral <= x
math.ceil(x) the least Integral >= x
~x the bits of x inverted
float.is_integer()
Return True if the float instance is finite with integral value, and False otherwise
"""
'\n\nx in s\tTrue if an item of s is equal to x, else False\nx not in s\tFalse if an item of s is equal to x, else True\ns + t\tthe concatenation of s and t\ns * n or n * s\tequivalent to adding s to itself n times\ns[i]\tith item of s, origin 0\ns[i:j]\tslice of s from i to j\ns[i:j:k]\tslice of s from i to j with step k\nlen(s)\tlength of s\t \nmin(s)\tsmallest item of s\t \nmax(s)\tlargest item of s\t \ns.index(x[, i[, j]])\tindex of the first occurrence of x in s (at or after index i and before index j)\ns.count(x)\ttotal number of occurrences of x in s\n\n'
'\n\nPython String Methods\ncapitalize() - Returns the string with first letter capitalized and the rest lowercased.\ncasefold() - Returns a lowercase string, generally used for caseless matching. This is more aggressive than the lower() method.\ncenter() - Center the string within the specified width with optional fill character.\ncount() - Count the non-overlapping occurrence of supplied substring in the string.\nencode() - Return the encoded version of the string as a bytes object.\nendswith() - Returns ture if the string ends with the supplied substring.\nexpandtabs() - Return a string where all the tab characters are replaced by the supplied number of spaces.\nfind() - Return the index of the first occurrence of supplied substring in the string. Return -1 if not found.\nformat() - Format the given string.\nformat_map() - Format the given string.\nindex() - Return the index of the first occurrence of supplied substring in the string. Raise ValueError if not found.\nisalnum() - Return true if the string is non-empty and all characters are alphanumeric.\nisalpha() - Return true if the string is non-empty and all characters are alphabetic.\nisdecimal() - Return true if the string is non-empty and all characters are decimal characters.\nisdigit() - Return true if the string is non-empty and all characters are digits.\nisidentifier() - Return true if the string is a valid identifier.\nislower() - Return true if the string has all lowercased characters and at least one is cased character.\nisnumeric() - Return true if the string is non-empty and all characters are numeric.\nisprintable() - Return true if the string is empty or all characters are printable.\nisspace() - Return true if the string is non-empty and all characters are whitespaces.\nistitle() - Return true if the string is non-empty and titlecased.\nisupper() - Return true if the string has all uppercased characters and at least one is cased character.\njoin() - Concatenate strings in the provided iterable with separator between them being the string providing this method.\nljust() - Left justify the string in the provided width with optional fill characters.\nlower() - Return a copy of all lowercased string.\nlstrip() - Return a string with provided leading characters removed.\nmaketrans() - Return a translation table.\npartition() - Partition the string at first occurrence of substring (separator) and return a 3-tuple with part before separator, the separator and part after separator.\nreplace() - Replace all old substrings with new substrings.\nrfind() - Return the index of the last occurrence of supplied substring in the string. Return -1 if not found.\nrindex() - Return the index of the last occurrence of supplied substring in the string. Raise ValueError if not found.\nrjust() - Right justify the string in the provided width with optional fill characters.\nrpartition() - Partition the string at last occurrence of substring (separator) and return a 3-tuple with part before separator, the separator and part after separator.\nrsplit() - Return a list of words delimited by the provided subtring. If maximum number of split is specified, it is done from the right.\nrstrip() - Return a string with provided trailing characters removed.\nsplit() - Return a list of words delimited by the provided subtring. If maximum number of split is specified, it is done from the left.\nsplitlines() - Return a list of lines in the string.\nstartswith() - Return true if the string starts with the provided substring.\nstrip() - Return a string with provided leading and trailing characters removed.\nswapcase() - Return a string with lowercase characters converted to uppercase and vice versa.\ntitle() - Return a title (first character of each word capitalized, others lowercased) cased string.\ntranslate() - Return a copy of string that has been mapped according to the provided map.\nupper() - Return a copy of all uppercased string.\nzfill() - Return a numeric string left filled with zeros in the provided width.\n\nsort alphabetically the words form a string provided by the user\nbreakdown the string into a list of words\nwords = my_str.split()\n\nsort the list\nwords.sort()\n\n'
"\n\nenumerate() -> tuplas\n\n>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']\n>>> list(enumerate(seasons))\n[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]\n>>> list(enumerate(seasons, start=1))\n[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]\n\n" |
stars = ""
for i in range(0, 5, 1):
for j in range(0, i, 1):
stars += "*"
print(stars) | stars = ''
for i in range(0, 5, 1):
for j in range(0, i, 1):
stars += '*'
print(stars) |
# -*- coding: utf-8 -*-
class TestClient(object):
"""
fake_client will call the wrapped api function,
going through all middlewares
"""
def __init__(self, app):
self.app = app
def __getattr__(self, item):
api = self.app.api_map.get(item)
if api is None:
raise ValueError(
'app didn\'t registered this api: {}'.format(item))
return self.app.api_map.get(item)
class FakeClient(TestClient):
"""
fake_client will call the original api function directly,
bypass all middlewares
"""
def __init__(self, app):
self.app = app
def __getattr__(self, item):
api = self.app.api_map.get(item)
if api is None:
raise ValueError(
'app didn\'t registered this api: {}'.format(item))
return self.app.api_map.get(item).__wrapped__ | class Testclient(object):
"""
fake_client will call the wrapped api function,
going through all middlewares
"""
def __init__(self, app):
self.app = app
def __getattr__(self, item):
api = self.app.api_map.get(item)
if api is None:
raise value_error("app didn't registered this api: {}".format(item))
return self.app.api_map.get(item)
class Fakeclient(TestClient):
"""
fake_client will call the original api function directly,
bypass all middlewares
"""
def __init__(self, app):
self.app = app
def __getattr__(self, item):
api = self.app.api_map.get(item)
if api is None:
raise value_error("app didn't registered this api: {}".format(item))
return self.app.api_map.get(item).__wrapped__ |
'''
Configuration for the style, size, and elements of the GUI
will be configured here
'''
class window:
scale_height = 0.5
scale_width = 0.5
| """
Configuration for the style, size, and elements of the GUI
will be configured here
"""
class Window:
scale_height = 0.5
scale_width = 0.5 |
linestyles = {'wind_speed': '-', 'wind_gust': '--', 'pressure': '-'}
fig, axes = plt.subplots(1, len(plot_variables), sharex=True, figsize=(18, 6))
for ax, var_names in zip(axes, plot_variables):
for var_name in var_names:
# Grab the color from our dictionary and pass it to plot()
color = colors[var_name]
linestyle = linestyles[var_name]
ax.plot(df.time, df[var_name], color, linestyle=linestyle)
ax.set_ylabel(var_name)
ax.set_title('Buoy {}'.format(var_name))
ax.grid(True)
ax.set_xlabel('Time')
ax.xaxis.set_major_formatter(DateFormatter('%m/%d'))
ax.xaxis.set_major_locator(DayLocator()) | linestyles = {'wind_speed': '-', 'wind_gust': '--', 'pressure': '-'}
(fig, axes) = plt.subplots(1, len(plot_variables), sharex=True, figsize=(18, 6))
for (ax, var_names) in zip(axes, plot_variables):
for var_name in var_names:
color = colors[var_name]
linestyle = linestyles[var_name]
ax.plot(df.time, df[var_name], color, linestyle=linestyle)
ax.set_ylabel(var_name)
ax.set_title('Buoy {}'.format(var_name))
ax.grid(True)
ax.set_xlabel('Time')
ax.xaxis.set_major_formatter(date_formatter('%m/%d'))
ax.xaxis.set_major_locator(day_locator()) |
#! /usr/bin/env python3
REQUEST = 'Request'
PRE_PREPARE = 'PrePrepare'
PREPARE = 'Prepare'
COMMIT = 'Commit'
RESULT = 'Result'
VIEW_CHANGE = 'ViewChange'
NEW_VIEW = 'NewView'
# Decouple actual message from preprepare message is highly recommended for optimization (etc. choice of protocol for small and big sized messages)
# Message is only in Preprepare for educational reasons!
class PBFTPreprepareMessage:
'''
Pre-prepare message
'''
def __init__(self, phase, viewNum, seqNum, digest, signature, message):
self.phase = phase
self.viewNum = viewNum
self.seqNum = seqNum
self.digest = digest
self.signature = signature
# Better use a separate message for the actual request
self.message = message
def __str__(self):
return f'''
(
"self.phase" = {self.phase}
"self.viewNum" = {self.viewNum}
"self.seqNum" = {self.seqNum}
"self.digest" = {self.digest}
"self.signature" = {self.signature}
"self.message" = {self.message}
)
'''
class PBFTMessage:
'''
Message object for Prepare and Commit
'''
def __init__(self, phase, viewNum, seqNum, digest, signature, fromNode):
self.phase = phase
self.viewNum = viewNum
self.seqNum = seqNum
self.digest = digest
self.signature = signature
self.fromNode = fromNode
def __str__(self):
return f'''
(
"self.phase" = {self.phase}
"self.viewNum" = {self.viewNum}
"self.seqNum" = {self.seqNum}
"self.digest" = {self.digest}
"self.signature" = {self.signature}
"self.fromNode" = {self.fromNode}
)
'''
class PBFTResultMessage:
'''
Message object for result
'''
def __init__(self, viewNum, timestamp, toClientHost, toClientPort, fromNode, result, signature):
self.phase = RESULT
self.viewNum = viewNum
self.timestamp = timestamp
self.toClientHost = toClientHost
self.toClientPort = toClientPort
self.fromNode = fromNode
self.result = result
self.signature = signature
def __str__(self):
return f'''
(
"self.phase" = {self.phase}
"self.viewNum" = {self.viewNum}
"self.timestamp" = {self.timestamp}
"self.fromNode" = {self.fromNode}
"self.result" = {self.result}
"self.signature" = {self.signature}
)
''' | request = 'Request'
pre_prepare = 'PrePrepare'
prepare = 'Prepare'
commit = 'Commit'
result = 'Result'
view_change = 'ViewChange'
new_view = 'NewView'
class Pbftprepreparemessage:
"""
Pre-prepare message
"""
def __init__(self, phase, viewNum, seqNum, digest, signature, message):
self.phase = phase
self.viewNum = viewNum
self.seqNum = seqNum
self.digest = digest
self.signature = signature
self.message = message
def __str__(self):
return f'\n (\n "self.phase" = {self.phase}\n "self.viewNum" = {self.viewNum}\n "self.seqNum" = {self.seqNum}\n "self.digest" = {self.digest}\n "self.signature" = {self.signature}\n "self.message" = {self.message}\n )\n '
class Pbftmessage:
"""
Message object for Prepare and Commit
"""
def __init__(self, phase, viewNum, seqNum, digest, signature, fromNode):
self.phase = phase
self.viewNum = viewNum
self.seqNum = seqNum
self.digest = digest
self.signature = signature
self.fromNode = fromNode
def __str__(self):
return f'\n (\n "self.phase" = {self.phase}\n "self.viewNum" = {self.viewNum}\n "self.seqNum" = {self.seqNum}\n "self.digest" = {self.digest}\n "self.signature" = {self.signature}\n "self.fromNode" = {self.fromNode}\n )\n '
class Pbftresultmessage:
"""
Message object for result
"""
def __init__(self, viewNum, timestamp, toClientHost, toClientPort, fromNode, result, signature):
self.phase = RESULT
self.viewNum = viewNum
self.timestamp = timestamp
self.toClientHost = toClientHost
self.toClientPort = toClientPort
self.fromNode = fromNode
self.result = result
self.signature = signature
def __str__(self):
return f'\n (\n "self.phase" = {self.phase}\n "self.viewNum" = {self.viewNum}\n "self.timestamp" = {self.timestamp}\n "self.fromNode" = {self.fromNode}\n "self.result" = {self.result}\n "self.signature" = {self.signature}\n )\n ' |
{
"targets": [{
"target_name": "picosat",
"include_dirs": [
"<!(node -e \"require('napi-macros')\")"
],
"sources": [ "index.c", "lib/picosat.c" ]
}]
}
| {'targets': [{'target_name': 'picosat', 'include_dirs': ['<!(node -e "require(\'napi-macros\')")'], 'sources': ['index.c', 'lib/picosat.c']}]} |
################################# FINAL SETTING!
# model settings
voxel_size = [0.05, 0.05, 0.1]
point_cloud_range = [0, -40, -3, 70.4, 40, 1]
# MOCO Model
model = dict(
# type='Inter_Intro_moco',
type='Inter_Intro_moco_better',
img_backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=-1,
# norm_cfg=dict(type='BN'), # for debug
norm_cfg=dict(type='SyncBN', eps=1e-3, momentum=0.01),
norm_eval=False,
style='pytorch'),
# With MOCO
pts_backbone=dict(
type='PointNet2SAMSG',
in_channels=4,
num_points=(4096, 1024, (512, 512)),
radii=((0.2, 0.4, 0.8), (0.4, 0.8, 1.6), (1.6, 3.2, 4.8)),
num_samples=((32, 32, 64), (32, 32, 64), (16, 16, 16)),
sa_channels=(((32, 32, 64), (32, 32, 64), (64, 64, 128)),
((64, 64, 128), (64, 64, 128), (128, 128, 256)),
((128, 128, 256), (128, 128, 256), (256, 256, 512))),
aggregation_channels=(128, 256, 1024),
fps_mods=(('D-FPS'), ('FS'), ('F-FPS', 'D-FPS')),
fps_sample_range_lists=((-1), (-1), (512, -1)),
norm_cfg=dict(type='BN2d', eps=1e-3, momentum=0.1),
sa_cfg=dict(
type='PointSAModuleMSG',
pool_mod='max',
# use_xyz=True,
use_xyz=False,
normalize_xyz=False)),
# model training and testing settings
train_cfg=dict(
cl_strategy = dict(
pts_intro_hidden_dim=1024,
pts_intro_out_dim=128,
img_inter_hidden_dim=2048,
img_inter_out_dim=128,
pts_inter_hidden_dim=1024,
pts_inter_out_dim=128,
pts_feat_dim=1024,
img_feat_dim=2048,
K=8192*4,
m=0.999,
T=0.07,
points_center=[35.2, 0, -1],
cross_factor=1,
moco=False,
simsiam=False,
############################################
img_moco=False,
point_intro=True, # intro-loss
point_branch=True # if pts backbone
)))
# dataset settings
dataset_type = 'KittiDataset'
data_root = 'data/kitti/'
class_names = ['Pedestrian', 'Cyclist', 'Car']
img_norm_cfg = dict(
mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)
input_modality = dict(use_lidar=True, use_camera=True)
# db_sampler = dict(
# data_root=data_root,
# info_path=data_root + 'kitti_dbinfos_train.pkl',
# rate=1.0,
# prepare=dict(filter_by_difficulty=[-1], filter_by_min_points=dict(Car=5)),
# classes=class_names,
# sample_groups=dict(Car=15))
file_client_args = dict(backend='disk')
# Uncomment the following if use ceph or other file clients.
# See https://mmcv.readthedocs.io/en/latest/api.html#mmcv.fileio.FileClient
# for more details.
# file_client_args = dict(
# backend='petrel', path_mapping=dict(data='s3://kitti_data/'))
train_pipeline = [
dict(type='LoadPointsFromFile', coord_type='LIDAR', load_dim=4, use_dim=4),
dict(type='LoadImageFromFile'),
dict(type='PointsRangeFilter', point_cloud_range=point_cloud_range), # filter range
dict(type='IndoorPointSample', num_points=16384), # sample here only for pretrain!
dict(type='LoadAnnotations3D', with_bbox_3d=True, with_label_3d=True),
##############################
dict(
type='Resize',
# img_scale=[(640, 192), (2560, 768)],
img_scale=[(640, 192), (2400, 720)],
multiscale_mode='range',
keep_ratio=True),
##############################
dict(
type='GlobalRotScaleTrans',
# rot_range=[-0.78539816, 0.78539816],
# scale_ratio_range=[0.95, 1.05],
rot_range=[-1.5707963, 1.5707963],
scale_ratio_range=[0.75, 1.25],
translation_std=[0, 0, 0],
points_center=[35.2, 0, -1]),
dict(type='RandomFlip3D', flip_ratio_bev_horizontal=0.5),
# dict(type='ObjectRangeFilter', point_cloud_range=point_cloud_range),
dict(type='PointShuffle'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle3D', class_names=class_names),
dict(
type='Collect3D',
keys=['points', 'img', 'gt_bboxes_3d', 'gt_labels_3d', 'points_ori']),
]
test_pipeline = [] # No need to test
# for dataset
pretraining=True
cross=True # for cross pretrain
data = dict(
samples_per_gpu=4,
workers_per_gpu=4,
# samples_per_gpu=3,
# workers_per_gpu=3,
train=dict(
type='RepeatDataset',
times=1,
dataset=dict(
type=dataset_type,
data_root=data_root,
ann_file=data_root + 'kitti_infos_train.pkl',
split='training',
pts_prefix='velodyne_reduced',
pipeline=train_pipeline,
modality=input_modality,
classes=class_names,
test_mode=False,
pretraining=True,
cross=True,
# we use box_type_3d='LiDAR' in kitti and nuscenes dataset
# and box_type_3d='Depth' in sunrgbd and scannet dataset.
box_type_3d='LiDAR')),
# actually there is no val
val=dict(
type=dataset_type,
data_root=data_root,
ann_file=data_root + 'kitti_infos_val.pkl',
split='training',
pts_prefix='velodyne_reduced',
pipeline=test_pipeline,
modality=input_modality,
classes=class_names,
test_mode=True,
pretraining=True,
box_type_3d='LiDAR'))
# Not be used in pretrain
evaluation = dict(start=9999, interval=1) # No use
# optimizer
optimizer = dict(
constructor='HybridOptimizerConstructor',
pts=dict(
type='AdamW',
# lr=0.002,
lr=0.001,
betas=(0.95, 0.99),
weight_decay=0.01,
step_interval=1),
img=dict(
type='SGD',
# lr=0.03,
lr=0.03,
momentum=0.9,
weight_decay=0.0001,
step_interval=1),
mlp=dict(
type='SGD',
# lr=0.03,
lr=0.03,
momentum=0.9,
weight_decay=0.0001,
step_interval=1))
# optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
optimizer_config = dict(grad_clip=None)
# lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_iters=10, warmup_ratio=0.001, warmup_by_epoch=True)
lr_config = dict(policy='Exp', gamma=0.99)
# runtime settings
checkpoint_config = dict(interval=5)
# yapf:disable
log_config = dict(
interval=30,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = None
load_from = None
resume_from = None
workflow = [('train', 1)]
total_epochs = 100
runner = dict(type='EpochBasedRunner', max_epochs=total_epochs)
find_unused_parameters=True # I cannot find it | voxel_size = [0.05, 0.05, 0.1]
point_cloud_range = [0, -40, -3, 70.4, 40, 1]
model = dict(type='Inter_Intro_moco_better', img_backbone=dict(type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='SyncBN', eps=0.001, momentum=0.01), norm_eval=False, style='pytorch'), pts_backbone=dict(type='PointNet2SAMSG', in_channels=4, num_points=(4096, 1024, (512, 512)), radii=((0.2, 0.4, 0.8), (0.4, 0.8, 1.6), (1.6, 3.2, 4.8)), num_samples=((32, 32, 64), (32, 32, 64), (16, 16, 16)), sa_channels=(((32, 32, 64), (32, 32, 64), (64, 64, 128)), ((64, 64, 128), (64, 64, 128), (128, 128, 256)), ((128, 128, 256), (128, 128, 256), (256, 256, 512))), aggregation_channels=(128, 256, 1024), fps_mods=('D-FPS', 'FS', ('F-FPS', 'D-FPS')), fps_sample_range_lists=(-1, -1, (512, -1)), norm_cfg=dict(type='BN2d', eps=0.001, momentum=0.1), sa_cfg=dict(type='PointSAModuleMSG', pool_mod='max', use_xyz=False, normalize_xyz=False)), train_cfg=dict(cl_strategy=dict(pts_intro_hidden_dim=1024, pts_intro_out_dim=128, img_inter_hidden_dim=2048, img_inter_out_dim=128, pts_inter_hidden_dim=1024, pts_inter_out_dim=128, pts_feat_dim=1024, img_feat_dim=2048, K=8192 * 4, m=0.999, T=0.07, points_center=[35.2, 0, -1], cross_factor=1, moco=False, simsiam=False, img_moco=False, point_intro=True, point_branch=True)))
dataset_type = 'KittiDataset'
data_root = 'data/kitti/'
class_names = ['Pedestrian', 'Cyclist', 'Car']
img_norm_cfg = dict(mean=[103.53, 116.28, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)
input_modality = dict(use_lidar=True, use_camera=True)
file_client_args = dict(backend='disk')
train_pipeline = [dict(type='LoadPointsFromFile', coord_type='LIDAR', load_dim=4, use_dim=4), dict(type='LoadImageFromFile'), dict(type='PointsRangeFilter', point_cloud_range=point_cloud_range), dict(type='IndoorPointSample', num_points=16384), dict(type='LoadAnnotations3D', with_bbox_3d=True, with_label_3d=True), dict(type='Resize', img_scale=[(640, 192), (2400, 720)], multiscale_mode='range', keep_ratio=True), dict(type='GlobalRotScaleTrans', rot_range=[-1.5707963, 1.5707963], scale_ratio_range=[0.75, 1.25], translation_std=[0, 0, 0], points_center=[35.2, 0, -1]), dict(type='RandomFlip3D', flip_ratio_bev_horizontal=0.5), dict(type='PointShuffle'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle3D', class_names=class_names), dict(type='Collect3D', keys=['points', 'img', 'gt_bboxes_3d', 'gt_labels_3d', 'points_ori'])]
test_pipeline = []
pretraining = True
cross = True
data = dict(samples_per_gpu=4, workers_per_gpu=4, train=dict(type='RepeatDataset', times=1, dataset=dict(type=dataset_type, data_root=data_root, ann_file=data_root + 'kitti_infos_train.pkl', split='training', pts_prefix='velodyne_reduced', pipeline=train_pipeline, modality=input_modality, classes=class_names, test_mode=False, pretraining=True, cross=True, box_type_3d='LiDAR')), val=dict(type=dataset_type, data_root=data_root, ann_file=data_root + 'kitti_infos_val.pkl', split='training', pts_prefix='velodyne_reduced', pipeline=test_pipeline, modality=input_modality, classes=class_names, test_mode=True, pretraining=True, box_type_3d='LiDAR'))
evaluation = dict(start=9999, interval=1)
optimizer = dict(constructor='HybridOptimizerConstructor', pts=dict(type='AdamW', lr=0.001, betas=(0.95, 0.99), weight_decay=0.01, step_interval=1), img=dict(type='SGD', lr=0.03, momentum=0.9, weight_decay=0.0001, step_interval=1), mlp=dict(type='SGD', lr=0.03, momentum=0.9, weight_decay=0.0001, step_interval=1))
optimizer_config = dict(grad_clip=None)
lr_config = dict(policy='Exp', gamma=0.99)
checkpoint_config = dict(interval=5)
log_config = dict(interval=30, hooks=[dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook')])
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = None
load_from = None
resume_from = None
workflow = [('train', 1)]
total_epochs = 100
runner = dict(type='EpochBasedRunner', max_epochs=total_epochs)
find_unused_parameters = True |
class ScoreCard:
def __init__(self, score_text: str):
score_texts = score_text.split('|')
self.normal_turns = [score_texts[i] for i in range(10)]
if len(score_texts) == 12:
self.additional_turns = [score_texts[11]]
self.all_turns = self.normal_turns + self.additional_turns
def to_score(self):
sum = 0
for i in range(len(self.normal_turns)):
sum = sum + self.get_score_by_turn(i)
return sum
def get_score_by_turn(self, turn: int)->int:
score = self.text_to_score(self.normal_turns[turn])
if self.__is_strike(self.normal_turns[turn]) or self.__is_spare(self.normal_turns[turn]):
return score + self.__get_bonus_score(turn)
else:
return score
def __get_bonus_score(self, turn:int)->int:
if turn + 1 == len(self.normal_turns):
return self.text_to_score(self.additional_turns[0])
next_2_balls = str(self.all_turns[turn + 1] + self.all_turns[turn + 2])[0:2]
return self.text_to_score(next_2_balls)
def text_to_score(self, score_text:str)->int:
if score_text.find('/') == 1:
return 10
score = 0
for i in range(len(score_text)):
score = score + self.__char_to_score(score_text[i])
return score
def __char_to_score(self, score_text:str)->int:
if self.__is_strike(score_text):
return 10
elif score_text == '-':
return 0
else:
return int(score_text)
def __is_strike(self, score_text: str)->bool:
return True if score_text.upper() == 'X' else False
def __is_spare(self, score_text: str)->bool:
return True if score_text.find('/') == 1 else False
| class Scorecard:
def __init__(self, score_text: str):
score_texts = score_text.split('|')
self.normal_turns = [score_texts[i] for i in range(10)]
if len(score_texts) == 12:
self.additional_turns = [score_texts[11]]
self.all_turns = self.normal_turns + self.additional_turns
def to_score(self):
sum = 0
for i in range(len(self.normal_turns)):
sum = sum + self.get_score_by_turn(i)
return sum
def get_score_by_turn(self, turn: int) -> int:
score = self.text_to_score(self.normal_turns[turn])
if self.__is_strike(self.normal_turns[turn]) or self.__is_spare(self.normal_turns[turn]):
return score + self.__get_bonus_score(turn)
else:
return score
def __get_bonus_score(self, turn: int) -> int:
if turn + 1 == len(self.normal_turns):
return self.text_to_score(self.additional_turns[0])
next_2_balls = str(self.all_turns[turn + 1] + self.all_turns[turn + 2])[0:2]
return self.text_to_score(next_2_balls)
def text_to_score(self, score_text: str) -> int:
if score_text.find('/') == 1:
return 10
score = 0
for i in range(len(score_text)):
score = score + self.__char_to_score(score_text[i])
return score
def __char_to_score(self, score_text: str) -> int:
if self.__is_strike(score_text):
return 10
elif score_text == '-':
return 0
else:
return int(score_text)
def __is_strike(self, score_text: str) -> bool:
return True if score_text.upper() == 'X' else False
def __is_spare(self, score_text: str) -> bool:
return True if score_text.find('/') == 1 else False |
class RefreshIPOperation(object):
def __init__(self, vm_service, resource_id_parser):
"""
:param vm_service: cloudshell.cp.azure.domain.services.virtual_machine_service.VirtualMachineService
:param resource_id_parser: cloudshell.cp.azure.common.parsers.azure_model_parser.AzureModelsParser
:return:
"""
self.vm_service = vm_service
self.resource_id_parser = resource_id_parser
def refresh_ip(self, cloudshell_session, compute_client, network_client, resource_group_name, vm_name,
private_ip_on_resource, public_ip_on_resource_attr_tuple, resource_fullname, logger):
"""Refresh Public and Private IP on CloudShell resource from corresponding deployed Azure instance
:param cloudshell_session: cloudshell.api.cloudshell_api.CloudShellAPISession instance
:param compute_client: azure.mgmt.compute.ComputeManagementClient instance
:param network_client: azure.mgmt.network.NetworkManagementClient instance
:param resource_group_name: The name of the resource group
:param vm_name: The name of the virtual machine
:param private_ip_on_resource: private IP on the CloudShell resource
:param public_ip_on_resource_attr_tuple: (key,val) public IP on the CloudShell resource (we preserve public ip namespace key)
:param resource_fullname: full resource name on the CloudShell
:param logger: logging.Logger instance
:return
"""
# check if VM exists and in the correct state
logger.info("Check that VM {} exists under resource group {} and is active".format(
vm_name, resource_group_name))
public_ip_key = public_ip_on_resource_attr_tuple[0]
public_ip_on_resource = public_ip_on_resource_attr_tuple[1]
vm = self.vm_service.get_active_vm(
compute_management_client=compute_client,
group_name=resource_group_name,
vm_name=vm_name)
# find the primary nic
primary_nic_ref = next(iter(filter(lambda x: x.primary, vm.network_profile.network_interfaces)), None)
nic_reference = primary_nic_ref if primary_nic_ref else vm.network_profile.network_interfaces[0]
nic_name = self.resource_id_parser.get_name_from_resource_id(nic_reference.id)
logger.info("Retrieving NIC {} for VM {}".format(nic_name, vm_name))
nic = network_client.network_interfaces.get(resource_group_name, nic_name)
vm_ip_configuration = nic.ip_configurations[0]
private_ip_on_azure = vm_ip_configuration.private_ip_address
public_ip_reference = vm_ip_configuration.public_ip_address
if public_ip_reference is None:
logger.info("There is no Public IP attached to VM {}".format(vm_name))
public_ip_on_azure = ""
else:
public_ip_name = self.resource_id_parser.get_name_from_resource_id(public_ip_reference.id)
logger.info("Retrieving Public IP {} for VM {}".format(public_ip_name, vm_name))
pub_ip_addr = network_client.public_ip_addresses.get(resource_group_name, public_ip_name)
public_ip_on_azure = pub_ip_addr.ip_address
logger.info("Public IP on Azure: '{}'".format(public_ip_on_azure))
logger.info("Public IP on CloudShell: '{}'".format(public_ip_on_resource))
if public_ip_on_azure != public_ip_on_resource:
logger.info("Updating Public IP on the resource to '{}' ...".format(public_ip_on_azure))
cloudshell_session.SetAttributeValue(resource_fullname, public_ip_key, public_ip_on_azure)
logger.info("Private IP on Azure: '{}'".format(private_ip_on_azure))
logger.info("Private IP on CloudShell: '{}'".format(private_ip_on_resource))
if private_ip_on_azure != private_ip_on_resource:
logger.info("Updating Private IP on the resource to '{}' ...".format(private_ip_on_azure))
cloudshell_session.UpdateResourceAddress(resource_fullname, private_ip_on_azure)
| class Refreshipoperation(object):
def __init__(self, vm_service, resource_id_parser):
"""
:param vm_service: cloudshell.cp.azure.domain.services.virtual_machine_service.VirtualMachineService
:param resource_id_parser: cloudshell.cp.azure.common.parsers.azure_model_parser.AzureModelsParser
:return:
"""
self.vm_service = vm_service
self.resource_id_parser = resource_id_parser
def refresh_ip(self, cloudshell_session, compute_client, network_client, resource_group_name, vm_name, private_ip_on_resource, public_ip_on_resource_attr_tuple, resource_fullname, logger):
"""Refresh Public and Private IP on CloudShell resource from corresponding deployed Azure instance
:param cloudshell_session: cloudshell.api.cloudshell_api.CloudShellAPISession instance
:param compute_client: azure.mgmt.compute.ComputeManagementClient instance
:param network_client: azure.mgmt.network.NetworkManagementClient instance
:param resource_group_name: The name of the resource group
:param vm_name: The name of the virtual machine
:param private_ip_on_resource: private IP on the CloudShell resource
:param public_ip_on_resource_attr_tuple: (key,val) public IP on the CloudShell resource (we preserve public ip namespace key)
:param resource_fullname: full resource name on the CloudShell
:param logger: logging.Logger instance
:return
"""
logger.info('Check that VM {} exists under resource group {} and is active'.format(vm_name, resource_group_name))
public_ip_key = public_ip_on_resource_attr_tuple[0]
public_ip_on_resource = public_ip_on_resource_attr_tuple[1]
vm = self.vm_service.get_active_vm(compute_management_client=compute_client, group_name=resource_group_name, vm_name=vm_name)
primary_nic_ref = next(iter(filter(lambda x: x.primary, vm.network_profile.network_interfaces)), None)
nic_reference = primary_nic_ref if primary_nic_ref else vm.network_profile.network_interfaces[0]
nic_name = self.resource_id_parser.get_name_from_resource_id(nic_reference.id)
logger.info('Retrieving NIC {} for VM {}'.format(nic_name, vm_name))
nic = network_client.network_interfaces.get(resource_group_name, nic_name)
vm_ip_configuration = nic.ip_configurations[0]
private_ip_on_azure = vm_ip_configuration.private_ip_address
public_ip_reference = vm_ip_configuration.public_ip_address
if public_ip_reference is None:
logger.info('There is no Public IP attached to VM {}'.format(vm_name))
public_ip_on_azure = ''
else:
public_ip_name = self.resource_id_parser.get_name_from_resource_id(public_ip_reference.id)
logger.info('Retrieving Public IP {} for VM {}'.format(public_ip_name, vm_name))
pub_ip_addr = network_client.public_ip_addresses.get(resource_group_name, public_ip_name)
public_ip_on_azure = pub_ip_addr.ip_address
logger.info("Public IP on Azure: '{}'".format(public_ip_on_azure))
logger.info("Public IP on CloudShell: '{}'".format(public_ip_on_resource))
if public_ip_on_azure != public_ip_on_resource:
logger.info("Updating Public IP on the resource to '{}' ...".format(public_ip_on_azure))
cloudshell_session.SetAttributeValue(resource_fullname, public_ip_key, public_ip_on_azure)
logger.info("Private IP on Azure: '{}'".format(private_ip_on_azure))
logger.info("Private IP on CloudShell: '{}'".format(private_ip_on_resource))
if private_ip_on_azure != private_ip_on_resource:
logger.info("Updating Private IP on the resource to '{}' ...".format(private_ip_on_azure))
cloudshell_session.UpdateResourceAddress(resource_fullname, private_ip_on_azure) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.