content stringlengths 7 1.05M |
|---|
# taxes.tests
# Tax tests
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Sat Apr 14 16:36:54 2018 -0400
#
# ID: tests.py [20315d2] benjamin@bengfort.com $
"""
Tax tests
"""
##########################################################################
## Imports
##########################################################################
|
#!/usr/bin/python
# 1. Retourner VRAI si N est parfait, faux sinon
# 2. Afficher la liste des nombres parfait compris entre 1 et 10 000
def est_parfait(n):
somme = 0
for i in range(1, n):
if n % i == 0:
somme += i
if somme == n:
return True
else:
return False
for i in range(10000):
if est_parfait(i):
print(i)
|
class Credentials(object):
@staticmethod
def refresh(request, **kwargs):
pass
@property
def token(self):
return "PASSWORD"
def default(scopes: list, **kwargs):
return Credentials(), "myproject"
class Request(object):
pass
|
distancia = int(input('Digite a distancia da sua viagem: '))
valor1 = distancia*0.5
valor2 = distancia*0.45
if distancia <= 200:
print('O preço dessa viagem vai custar R${:.2f}'.format(valor1))
else:
print('O preço dessa viagem vai custar R${:.2f}'.format(valor2))
print('--fim--')
|
xCoordinate = [1,2,3,4,5,6,7,8,9,10]
xCdt = [1,2,3,4,5,6,7,8,9,10]
def setup():
size(500,500)
smooth()
noStroke()
for i in range(len(xCoordinate)):
xCoordinate[i] = 35*i + 90
for j in range(len(xCdt)):
xCdt[j] = 35*j + 90
def draw():
background(50)
for j in range(len(xCdt)):
fill(200,40)
ellipse( xCdt[j], 340, 150-j*15, 150-j*15)
fill(0)
ellipse(xCdt[j], 340, 3, 3)
for i in range(len(xCoordinate)):
fill(200,40)
ellipse(xCoordinate[i], 250, 15*i, 15*i)
fill(0)
ellipse(xCoordinate[i], 250, 3, 3)
|
class LostFocusEventManager(WeakEventManager):
""" Provides a System.Windows.WeakEventManager implementation so that you can use the "weak event listener" pattern to attach listeners for the System.Windows.UIElement.LostFocus or System.Windows.ContentElement.LostFocus events. """
@staticmethod
def AddHandler(source,handler):
""" AddHandler(source: DependencyObject,handler: EventHandler[RoutedEventArgs]) """
pass
@staticmethod
def AddListener(source,listener):
"""
AddListener(source: DependencyObject,listener: IWeakEventListener)
Adds the provided listener to the list of listeners on the provided source.
source: The object with the event.
listener: The object to add as a listener.
"""
pass
@staticmethod
def RemoveHandler(source,handler):
""" RemoveHandler(source: DependencyObject,handler: EventHandler[RoutedEventArgs]) """
pass
@staticmethod
def RemoveListener(source,listener):
"""
RemoveListener(source: DependencyObject,listener: IWeakEventListener)
Removes the specified listener from the list of listeners on the provided
source.
source: The object to remove the listener from.
listener: The listener to remove.
"""
pass
ReadLock=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Establishes a read-lock on the underlying data table,and returns an System.IDisposable.
"""
WriteLock=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Establishes a write-lock on the underlying data table,and returns an System.IDisposable.
"""
|
#TeamLeague
class Team:
def __init__(self, owner, value, id1, name):
self.owner = owner
self.value = value
self.id1 = id1
self.name = name
class League:
def __init__(self, team_list, league):
self.league = league
self.team_list = team_list
def find_minimum_team_by_Id(self):
minim = 999999
obj = None
for each in self.team_list:
if each.id1 < minim:
minim = each.id1
obj = each
return obj
def sort_by_team_Id(self):
l = []
for each in self.team_list:
l.append(each.id1)
return sorted(l) if len(l)!=0 else None
n = int(input())
l = []
for i in range(n):
own = input()
value = float(input())
id = int(input())
name = input()
l.append(Team(own,value,id,name))
obj = League(l,"league")
x = obj.find_minimum_team_by_Id()
y = obj.sort_by_team_Id()
if x == None:
print("No Data Found")
else:
print(x.owner)
print(x.value)
print(x.id1)
print(x.name)
if y == None:
print("No Data Found")
else:
for i in y:
print(i)
|
## Solution Challenge 10
def data_url(country):
'''
Function to build url for data retrieval
'''
BASE_URL = "http://berkeleyearth.lbl.gov/auto/Regional/TAVG/Text/"
SUFFIX_URL = "-TAVG-Trend.txt"
return(BASE_URL + country + SUFFIX_URL) |
"""
The hyperexponentiation of a number
"""
def pow_mod_recursive(a, x, mod):
if x == 0 or x == 1:
return a ** x % mod
elif x % 2 == 0:
return pow_mod_recursive(a, x//2, mod) ** 2 % mod
else:
return a* pow_mod_recursive(a, x//2, mod)** 2 % mod
def pow_mod(a, x, mod):
pow_value = 1
while x > 0:
if x & 1 == 1:
pow_value = pow_value *a % mod
a = a ** 2 % mod
x >>= 1
return pow_value
if __name__ == '__main__':
result = 1
for i in range(1855):
result = pow_mod(1777, result, 100**8)
print(result) |
"""
ensemble module
"""
class BaseEnsembler:
def __init__(self, *args, **kwargs):
super().__init__()
def fit(self, predictions, label, identifiers, feval, *args, **kwargs):
pass
def ensemble(self, predictions, identifiers, *args, **kwargs):
pass
@classmethod
def build_ensembler_from_args(cls, args):
"""Build a new ensembler instance."""
raise NotImplementedError(
"Ensembler must implement the build_ensembler_from_args method"
)
|
class Solution(object):
def hammingDistance(self, x, y):
cnt = 0
n=x^y
while n>0:
cnt += 1
n = n&(n-1)
return cnt
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count('1')
|
# Faça um algoritmo que leia o salário de um funcionário e mostre seu
# novo salário com 15% de aumento.
print('-'*50)
salario = float(input('Digite o salário do funcionário: R$'))
novoSalario = salario + (salario*15/100)
print('O salário de R${:.2f}, com o aumento de 15%,\npassa a ser R${:.2f}.'.format(salario, novoSalario))
print('-'*50) |
#
# PySNMP MIB module RFC1382-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/RFC1382-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:26:33 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( OctetString, ObjectIdentifier, Integer, ) = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
( ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection")
( PositiveInteger, ) = mibBuilder.importSymbols("RFC1253-MIB", "PositiveInteger")
( EntryStatus, ) = mibBuilder.importSymbols("RFC1271-MIB", "EntryStatus")
( IfIndexType, ) = mibBuilder.importSymbols("RFC1381-MIB", "IfIndexType")
( ModuleCompliance, NotificationGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
( IpAddress, iso, ObjectIdentity, MibIdentifier, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Counter32, NotificationType, transmission, Bits, TimeTicks, Integer32, Gauge32, Counter64, Unsigned32, ) = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "iso", "ObjectIdentity", "MibIdentifier", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Counter32", "NotificationType", "transmission", "Bits", "TimeTicks", "Integer32", "Gauge32", "Counter64", "Unsigned32")
( TextualConvention, DisplayString, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
x25 = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 5))
class X121Address(OctetString):
subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,17)
x25AdmnTable = MibTable((1, 3, 6, 1, 2, 1, 10, 5, 1), )
if mibBuilder.loadTexts: x25AdmnTable.setDescription('This table contains the administratively\n set configuration parameters for an X.25\n Packet Level Entity (PLE).\n\n Most of the objects in this table have\n corresponding objects in the x25OperTable.\n This table contains the values as last set\n by the administrator. The x25OperTable\n contains the values actually in use by an\n X.25 PLE.\n\n Changing an administrative value may or may\n not change a current operating value. The\n operating value may not change until the\n interface is restarted. Some\n implementations may change the values\n immediately upon changing the administrative\n table. All implementations are required to\n load the values from the administrative\n table when initializing a PLE.')
x25AdmnEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 5, 1, 1), ).setIndexNames((0, "RFC1382-MIB", "x25AdmnIndex"))
if mibBuilder.loadTexts: x25AdmnEntry.setDescription('Entries of x25AdmnTable.')
x25AdmnIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 1), IfIndexType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25AdmnIndex.setDescription('The ifIndex value for the X.25 Interface.')
x25AdmnInterfaceMode = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("dte", 1), ("dce", 2), ("dxe", 3),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnInterfaceMode.setDescription('Identifies DCE/DTE mode in which the\n interface operates. A value of dxe\n indicates the mode will be determined by XID\n negotiation.')
x25AdmnMaxActiveCircuits = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4096))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnMaxActiveCircuits.setDescription('The maximum number of circuits this PLE can\n support; including PVCs.')
x25AdmnPacketSequencing = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("modulo8", 1), ("modulo128", 2),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnPacketSequencing.setDescription('The modulus of the packet sequence number\n space.')
x25AdmnRestartTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 5), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnRestartTimer.setDescription('The T20 restart timer in milliseconds.')
x25AdmnCallTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 6), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnCallTimer.setDescription('The T21 Call timer in milliseconds.')
x25AdmnResetTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 7), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnResetTimer.setDescription('The T22 Reset timer in milliseconds.')
x25AdmnClearTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 8), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnClearTimer.setDescription('The T23 Clear timer in milliseconds.')
x25AdmnWindowTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 9), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnWindowTimer.setDescription('The T24 window status transmission timer in\n milliseconds. A value of 2147483647\n indicates no window timer in use.')
x25AdmnDataRxmtTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 10), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnDataRxmtTimer.setDescription('The T25 data retransmission timer in\n\n\n milliseconds. A value of 2147483647\n indicates no data retransmission timer in\n use.')
x25AdmnInterruptTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 11), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnInterruptTimer.setDescription('The T26 interrupt timer in milliseconds. A\n value of 2147483647 indicates no interrupt\n timer in use.')
x25AdmnRejectTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 12), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnRejectTimer.setDescription('The T27 Reject retransmission timer in\n milliseconds. A value of 2147483647\n indicates no reject timer in use.')
x25AdmnRegistrationRequestTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 13), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnRegistrationRequestTimer.setDescription('The T28 registration timer in milliseconds.\n A value of 2147483647 indicates no\n registration timer in use.')
x25AdmnMinimumRecallTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 14), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnMinimumRecallTimer.setDescription('Minimum time interval between unsuccessful\n call attempts in milliseconds.')
x25AdmnRestartCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 15), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnRestartCount.setDescription('The R20 restart retransmission count.')
x25AdmnResetCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 16), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnResetCount.setDescription('The r22 Reset retransmission count.')
x25AdmnClearCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnClearCount.setDescription('The r23 Clear retransmission count.')
x25AdmnDataRxmtCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnDataRxmtCount.setDescription('The R25 Data retransmission count. This\n value is irrelevant if the\n x25AdmnDataRxmtTimer indicates no timer in\n use.')
x25AdmnRejectCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnRejectCount.setDescription('The R27 reject retransmission count. This\n value is irrelevant if the\n x25AdmnRejectTimer indicates no timer in\n use.')
x25AdmnRegistrationRequestCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 20), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnRegistrationRequestCount.setDescription('The R28 Registration retransmission Count.\n This value is irrelevant if the\n x25AdmnRegistrationRequestTimer indicates no\n timer in use.')
x25AdmnNumberPVCs = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4096))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnNumberPVCs.setDescription('The number of PVC configured for this PLE.\n The PVCs use channel numbers from 1 to this\n number.')
x25AdmnDefCallParamId = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 22), ObjectIdentifier()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnDefCallParamId.setDescription('This identifies the instance of the\n x25CallParmIndex for the entry in the\n x25CallParmTable which contains the default\n call parameters for this PLE.')
x25AdmnLocalAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 23), X121Address()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnLocalAddress.setDescription('The local address for this PLE subnetwork.\n A zero length address maybe returned by PLEs\n that only support PVCs.')
x25AdmnProtocolVersionSupported = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 1, 1, 24), ObjectIdentifier()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25AdmnProtocolVersionSupported.setDescription('Identifies the version of the X.25 protocol\n this interface should support. Object\n identifiers for common versions are defined\n below in the x25ProtocolVersion subtree.')
x25OperTable = MibTable((1, 3, 6, 1, 2, 1, 10, 5, 2), )
if mibBuilder.loadTexts: x25OperTable.setDescription('The operation parameters in use by the X.25\n PLE.')
x25OperEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 5, 2, 1), ).setIndexNames((0, "RFC1382-MIB", "x25OperIndex"))
if mibBuilder.loadTexts: x25OperEntry.setDescription('Entries of x25OperTable.')
x25OperIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 1), IfIndexType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperIndex.setDescription('The ifIndex value for the X.25 interface.')
x25OperInterfaceMode = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("dte", 1), ("dce", 2), ("dxe", 3),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperInterfaceMode.setDescription('Identifies DCE/DTE mode in which the\n interface operates. A value of dxe\n indicates the role will be determined by XID\n negotiation at the Link Layer and that\n negotiation has not yet taken place.')
x25OperMaxActiveCircuits = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4096))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperMaxActiveCircuits.setDescription('Maximum number of circuits this PLE can\n support.')
x25OperPacketSequencing = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("modulo8", 1), ("modulo128", 2),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperPacketSequencing.setDescription('The modulus of the packet sequence number\n space.')
x25OperRestartTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 5), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperRestartTimer.setDescription('The T20 restart timer in milliseconds.')
x25OperCallTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 6), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperCallTimer.setDescription('The T21 Call timer in milliseconds.')
x25OperResetTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 7), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperResetTimer.setDescription('The T22 Reset timer in milliseconds.')
x25OperClearTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 8), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperClearTimer.setDescription('The T23 Clear timer in milliseconds.')
x25OperWindowTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 9), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperWindowTimer.setDescription('The T24 window status transmission timer\n\n\n milliseconds. A value of 2147483647\n indicates no window timer in use.')
x25OperDataRxmtTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 10), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperDataRxmtTimer.setDescription('The T25 Data Retransmission timer in\n milliseconds. A value of 2147483647\n indicates no data retransmission timer in\n use.')
x25OperInterruptTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 11), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperInterruptTimer.setDescription('The T26 Interrupt timer in milliseconds. A\n value of 2147483647 indicates interrupts are\n not being used.')
x25OperRejectTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 12), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperRejectTimer.setDescription('The T27 Reject retransmission timer in\n milliseconds. A value of 2147483647\n indicates no reject timer in use.')
x25OperRegistrationRequestTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 13), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperRegistrationRequestTimer.setDescription('The T28 registration timer in milliseconds.\n A value of 2147483647 indicates no\n registration timer in use.')
x25OperMinimumRecallTimer = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 14), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperMinimumRecallTimer.setDescription('Minimum time interval between unsuccessful\n call attempts in milliseconds.')
x25OperRestartCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 15), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperRestartCount.setDescription('The R20 restart retransmission count.')
x25OperResetCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 16), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperResetCount.setDescription('The r22 Reset retransmission count.')
x25OperClearCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperClearCount.setDescription('The r23 Clear retransmission count.')
x25OperDataRxmtCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperDataRxmtCount.setDescription('The R25 Data retransmission count. This\n value is undefined if the\n x25OperDataRxmtTimer indicates no timer in\n use.')
x25OperRejectCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperRejectCount.setDescription('The R27 reject retransmission count. This\n value is undefined if the x25OperRejectTimer\n indicates no timer in use.')
x25OperRegistrationRequestCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 20), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperRegistrationRequestCount.setDescription('The R28 Registration retransmission Count.\n This value is undefined if the\n x25OperREgistrationRequestTimer indicates no\n timer in use.')
x25OperNumberPVCs = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4096))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperNumberPVCs.setDescription('The number of PVC configured for this PLE.\n The PVCs use channel numbers from 1 to this\n number.')
x25OperDefCallParamId = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 22), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperDefCallParamId.setDescription('This identifies the instance of the\n x25CallParmIndex for the entry in the\n x25CallParmTable that contains the default\n call parameters for this PLE.')
x25OperLocalAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 23), X121Address()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperLocalAddress.setDescription('The local address for this PLE subnetwork.\n A zero length address maybe returned by PLEs\n that only support PVCs.')
x25OperDataLinkId = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 24), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperDataLinkId.setDescription('This identifies the instance of the index\n object in the first table of the most device\n specific MIB for the interface used by this\n PLE.')
x25OperProtocolVersionSupported = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 2, 1, 25), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25OperProtocolVersionSupported.setDescription('Identifies the version of the X.25 protocol\n this interface supports. Object identifiers\n for common versions are defined below in the\n x25ProtocolVersion subtree.')
x25StatTable = MibTable((1, 3, 6, 1, 2, 1, 10, 5, 3), )
if mibBuilder.loadTexts: x25StatTable.setDescription('Statistics information about this X.25\n PLE.')
x25StatEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 5, 3, 1), ).setIndexNames((0, "RFC1382-MIB", "x25StatIndex"))
if mibBuilder.loadTexts: x25StatEntry.setDescription('Entries of the x25StatTable.')
x25StatIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 1), IfIndexType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatIndex.setDescription('The ifIndex value for the X.25 interface.')
x25StatInCalls = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatInCalls.setDescription('The number of incoming calls received.')
x25StatInCallRefusals = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatInCallRefusals.setDescription('The number of incoming calls refused. This\n includes calls refused by the PLE and by\n higher layers. This also includes calls\n cleared because of restricted fast select.')
x25StatInProviderInitiatedClears = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatInProviderInitiatedClears.setDescription('The number of clear requests with a cause\n code other than DTE initiated.')
x25StatInRemotelyInitiatedResets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatInRemotelyInitiatedResets.setDescription('The number of reset requests received with\n\n\n cause code DTE initiated.')
x25StatInProviderInitiatedResets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatInProviderInitiatedResets.setDescription('The number of reset requests received with\n cause code other than DTE initiated.')
x25StatInRestarts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatInRestarts.setDescription('The number of remotely initiated (including\n provider initiated) restarts experienced by\n the PLE excluding the restart associated\n with bringing up the PLE interface. This\n only counts restarts received when the PLE\n already has an established connection with\n the remove PLE.')
x25StatInDataPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatInDataPackets.setDescription('The number of data packets received.')
x25StatInAccusedOfProtocolErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatInAccusedOfProtocolErrors.setDescription('The number of packets received containing a\n procedure error cause code. These include\n clear, reset, restart, or diagnostic\n packets.')
x25StatInInterrupts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatInInterrupts.setDescription('The number of interrupt packets received by\n the PLE or over the PVC/VC.')
x25StatOutCallAttempts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatOutCallAttempts.setDescription('The number of calls attempted.')
x25StatOutCallFailures = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatOutCallFailures.setDescription('The number of call attempts which failed.\n This includes calls that were cleared\n because of restrictive fast select.')
x25StatOutInterrupts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatOutInterrupts.setDescription('The number of interrupt packets send by the\n PLE or over the PVC/VC.')
x25StatOutDataPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatOutDataPackets.setDescription('The number of data packets sent by this\n PLE.')
x25StatOutgoingCircuits = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 15), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatOutgoingCircuits.setDescription('The number of active outgoing circuits.\n This includes call requests sent but not yet\n confirmed. This does not count PVCs.')
x25StatIncomingCircuits = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 16), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatIncomingCircuits.setDescription('The number of active Incoming Circuits.\n This includes call indications received but\n not yet acknowledged. This does not count\n PVCs.')
x25StatTwowayCircuits = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 17), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatTwowayCircuits.setDescription('The number of active two-way Circuits.\n This includes call requests sent but not yet\n confirmed. This does not count PVCs.')
x25StatRestartTimeouts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatRestartTimeouts.setDescription('The number of times the T20 restart timer\n expired.')
x25StatCallTimeouts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 19), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatCallTimeouts.setDescription('The number of times the T21 call timer\n expired.')
x25StatResetTimeouts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 20), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatResetTimeouts.setDescription('The number of times the T22 reset timer\n expired.')
x25StatClearTimeouts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 21), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatClearTimeouts.setDescription('The number of times the T23 clear timer\n expired.')
x25StatDataRxmtTimeouts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 22), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatDataRxmtTimeouts.setDescription('The number of times the T25 data timer\n expired.')
x25StatInterruptTimeouts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 23), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatInterruptTimeouts.setDescription('The number of times the T26 interrupt timer\n expired.')
x25StatRetryCountExceededs = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 24), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatRetryCountExceededs.setDescription('The number of times a retry counter was\n exhausted.')
x25StatClearCountExceededs = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 3, 1, 25), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25StatClearCountExceededs.setDescription('The number of times the R23 clear count was\n exceeded.')
x25ChannelTable = MibTable((1, 3, 6, 1, 2, 1, 10, 5, 4), )
if mibBuilder.loadTexts: x25ChannelTable.setDescription('These objects contain information about the\n channel number configuration in an X.25 PLE.\n These values are the configured values.\n changes in these values after the interfaces\n has started may not be reflected in the\n operating PLE.')
x25ChannelEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 5, 4, 1), ).setIndexNames((0, "RFC1382-MIB", "x25ChannelIndex"))
if mibBuilder.loadTexts: x25ChannelEntry.setDescription('Entries of x25ChannelTable.')
x25ChannelIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 4, 1, 1), IfIndexType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ChannelIndex.setDescription('The ifIndex value for the X.25 Interface.')
x25ChannelLIC = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4095))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25ChannelLIC.setDescription('Lowest Incoming channel.')
x25ChannelHIC = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4095))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25ChannelHIC.setDescription('Highest Incoming channel. A value of zero\n indicates no channels in this range.')
x25ChannelLTC = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 4, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4095))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25ChannelLTC.setDescription('Lowest Two-way channel.')
x25ChannelHTC = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4095))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25ChannelHTC.setDescription('Highest Two-way channel. A value of zero\n indicates no channels in this range.')
x25ChannelLOC = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 4, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4095))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25ChannelLOC.setDescription('Lowest outgoing channel.')
x25ChannelHOC = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 4, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4095))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25ChannelHOC.setDescription('Highest outgoing channel. A value of zero\n\n\n indicates no channels in this range.')
x25CircuitTable = MibTable((1, 3, 6, 1, 2, 1, 10, 5, 5), )
if mibBuilder.loadTexts: x25CircuitTable.setDescription('These objects contain general information\n about a specific circuit of an X.25 PLE.')
x25CircuitEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 5, 5, 1), ).setIndexNames((0, "RFC1382-MIB", "x25CircuitIndex"), (0, "RFC1382-MIB", "x25CircuitChannel"))
if mibBuilder.loadTexts: x25CircuitEntry.setDescription('Entries of x25CircuitTable.')
x25CircuitIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 1), IfIndexType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitIndex.setDescription('The ifIndex value for the X.25 Interface.')
x25CircuitChannel = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4095))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitChannel.setDescription('The channel number for this circuit.')
x25CircuitStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,))).clone(namedValues=NamedValues(("invalid", 1), ("closed", 2), ("calling", 3), ("open", 4), ("clearing", 5), ("pvc", 6), ("pvcResetting", 7), ("startClear", 8), ("startPvcResetting", 9), ("other", 10),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CircuitStatus.setDescription("This object reports the current status of\n the circuit.\n\n An existing instance of this object can only\n be set to startClear, startPvcResetting, or\n invalid. An instance with the value calling\n or open can only be set to startClear and\n that action will start clearing the circuit.\n An instance with the value PVC can only be\n set to startPvcResetting or invalid and that\n action resets the PVC or deletes the circuit\n respectively. The values startClear or\n startPvcResetting will never be returned by\n an agent. An attempt to set the status of\n an existing instance to a value other than\n one of these values will result in an error.\n\n A non-existing instance can be set to PVC to\n create a PVC if the implementation supports\n dynamic creation of PVCs. Some\n implementations may only allow creation and\n deletion of PVCs if the interface is down.\n Since the instance identifier will supply\n the PLE index and the channel number,\n setting this object alone supplies\n sufficient information to create the\n instance. All the DEFVAL clauses for the\n other objects of this table are appropriate\n for creating a PVC; PLEs creating entries\n for placed or accepted calls will use values\n appropriate for the call rather than the\n value of the DEFVAL clause. Two managers\n trying to create the same PVC can determine\n from the return code which manager succeeded\n and which failed (the failing manager fails\n because it can not set a value of PVC for an\n existing object).\n\n\n An entry in the closed or invalid state may\n be deleted or reused at the agent's\n convence. If the entry is kept in the\n closed state, the values of the parameters\n associated with the entry must be correct.\n Closed implies the values in the circuit\n table are correct.\n\n The value of invalid indicates the other\n values in the table are invalid. Many\n agents may never return a value of invalid\n because they dynamically allocate and free\n unused table entries. An agent for a\n statically configured systems can return\n invalid to indicate the entry has not yet\n been used so the counters contain no\n information.")
x25CircuitEstablishTime = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitEstablishTime.setDescription('The value of sysUpTime when the channel was\n associated with this circuit. For outgoing\n SVCs, this is the time the first call packet\n was sent. For incoming SVCs, this is the\n time the call indication was received. For\n PVCs this is the time the PVC was able to\n pass data to a higher layer entity without\n loss of data.')
x25CircuitDirection = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("incoming", 1), ("outgoing", 2), ("pvc", 3),)).clone('pvc')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CircuitDirection.setDescription('The direction of the call that established\n this circuit.')
x25CircuitInOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitInOctets.setDescription('The number of octets of user data delivered\n to upper layer.')
x25CircuitInPdus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitInPdus.setDescription('The number of PDUs received for this\n circuit.')
x25CircuitInRemotelyInitiatedResets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitInRemotelyInitiatedResets.setDescription('The number of Resets received for this\n circuit with cause code of DTE initiated.')
x25CircuitInProviderInitiatedResets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitInProviderInitiatedResets.setDescription('The number of Resets received for this\n circuit with cause code other than DTE\n initiated.')
x25CircuitInInterrupts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitInInterrupts.setDescription('The number of interrupt packets received\n for this circuit.')
x25CircuitOutOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitOutOctets.setDescription('The number of octets of user data sent for\n this circuit.')
x25CircuitOutPdus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitOutPdus.setDescription('The number of PDUs sent for this circuit.')
x25CircuitOutInterrupts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitOutInterrupts.setDescription('The number of interrupt packets sent on\n this circuit.')
x25CircuitDataRetransmissionTimeouts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitDataRetransmissionTimeouts.setDescription('The number of times the T25 data\n retransmission timer expired for this\n circuit.')
x25CircuitResetTimeouts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitResetTimeouts.setDescription('The number of times the T22 reset timer\n expired for this circuit.')
x25CircuitInterruptTimeouts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CircuitInterruptTimeouts.setDescription('The number of times the T26 Interrupt timer\n expired for this circuit.')
x25CircuitCallParamId = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 17), ObjectIdentifier()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CircuitCallParamId.setDescription('This identifies the instance of the\n x25CallParmIndex for the entry in the\n x25CallParmTable which contains the call\n parameters in use with this circuit. The\n entry referenced must contain the values\n that are currently in use by the circuit\n rather than proposed values. A value of\n NULL indicates the circuit is a PVC or is\n using all the default parameters.')
x25CircuitCalledDteAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 18), X121Address().clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CircuitCalledDteAddress.setDescription('For incoming calls, this is the called\n address from the call indication packet.\n For outgoing calls, this is the called\n\n\n address from the call confirmation packet.\n This will be zero length for PVCs.')
x25CircuitCallingDteAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 19), X121Address().clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CircuitCallingDteAddress.setDescription('For incoming calls, this is the calling\n address from the call indication packet.\n For outgoing calls, this is the calling\n address from the call confirmation packet.\n This will be zero length for PVCs.')
x25CircuitOriginallyCalledAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 20), X121Address().clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CircuitOriginallyCalledAddress.setDescription('For incoming calls, this is the address in\n the call Redirection or Call Deflection\n Notification facility if the call was\n deflected or redirected, otherwise it will\n be called address from the call indication\n packet. For outgoing calls, this is the\n address from the call request packet. This\n will be zero length for PVCs.')
x25CircuitDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 5, 1, 21), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0,255)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CircuitDescr.setDescription("A descriptive string associated with this\n circuit. This provides a place for the\n agent to supply any descriptive information\n it knows about the use or owner of the\n circuit. The agent may return the process\n identifier and user name for the process\n\n\n using the circuit. Alternative the agent\n may return the name of the configuration\n entry that caused a bridge to establish the\n circuit. A zero length value indicates the\n agent doesn't have any additional\n information.")
x25ClearedCircuitEntriesRequested = MibScalar((1, 3, 6, 1, 2, 1, 10, 5, 6), PositiveInteger()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25ClearedCircuitEntriesRequested.setDescription('The requested number of entries for the\n agent to keep in the x25ClearedCircuit\n table.')
x25ClearedCircuitEntriesGranted = MibScalar((1, 3, 6, 1, 2, 1, 10, 5, 7), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitEntriesGranted.setDescription('The actual number of entries the agent will\n keep in the x25ClearedCircuit Table.')
x25ClearedCircuitTable = MibTable((1, 3, 6, 1, 2, 1, 10, 5, 8), )
if mibBuilder.loadTexts: x25ClearedCircuitTable.setDescription('A table of entries about closed circuits.\n Entries must be made in this table whenever\n circuits are closed and the close request or\n close indication packet contains a clearing\n cause other than DTE Originated or a\n Diagnostic code field other than Higher\n Layer Initiated disconnection-normal. An\n agent may optionally make entries for normal\n closes (to record closing facilities or\n\n\n other information).\n\n Agents will delete the oldest entry in the\n table when adding a new entry would exceed\n agent resources. Agents are required to\n keep the last entry put in the table and may\n keep more entries. The object\n x25OperClearEntriesGranted returns the\n maximum number of entries kept in the\n table.')
x25ClearedCircuitEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 5, 8, 1), ).setIndexNames((0, "RFC1382-MIB", "x25ClearedCircuitIndex"))
if mibBuilder.loadTexts: x25ClearedCircuitEntry.setDescription('Information about a cleared circuit.')
x25ClearedCircuitIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 1), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitIndex.setDescription('An index that uniquely distinguishes one\n entry in the clearedCircuitTable from\n another. This index will start at\n 2147483647 and will decrease by one for each\n new entry added to the table. Upon reaching\n one, the index will reset to 2147483647.\n Because the index starts at 2147483647 and\n decreases, a manager may do a getnext on\n entry zero and obtain the most recent entry.\n When the index has the value of 1, the next\n entry will delete all entries in the table\n and that entry will be numbered 2147483647.')
x25ClearedCircuitPleIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 2), IfIndexType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitPleIndex.setDescription('The value of ifIndex for the PLE which\n cleared the circuit that created the entry.')
x25ClearedCircuitTimeEstablished = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitTimeEstablished.setDescription('The value of sysUpTime when the circuit was\n established. This will be the same value\n that was in the x25CircuitEstablishTime for\n the circuit.')
x25ClearedCircuitTimeCleared = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitTimeCleared.setDescription('The value of sysUpTime when the circuit was\n cleared. For locally initiated clears, this\n\n\n will be the time when the clear confirmation\n was received. For remotely initiated\n clears, this will be the time when the clear\n indication was received.')
x25ClearedCircuitChannel = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4095))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitChannel.setDescription('The channel number for the circuit that was\n cleared.')
x25ClearedCircuitClearingCause = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitClearingCause.setDescription('The Clearing Cause from the clear request\n or clear indication packet that cleared the\n circuit.')
x25ClearedCircuitDiagnosticCode = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitDiagnosticCode.setDescription('The Diagnostic Code from the clear request\n or clear indication packet that cleared the\n circuit.')
x25ClearedCircuitInPdus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitInPdus.setDescription('The number of PDUs received on the\n circuit.')
x25ClearedCircuitOutPdus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitOutPdus.setDescription('The number of PDUs transmitted on the\n circuit.')
x25ClearedCircuitCalledAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 10), X121Address()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitCalledAddress.setDescription('The called address from the cleared\n circuit.')
x25ClearedCircuitCallingAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 11), X121Address()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitCallingAddress.setDescription('The calling address from the cleared\n circuit.')
x25ClearedCircuitClearFacilities = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 8, 1, 12), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0,109))).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25ClearedCircuitClearFacilities.setDescription('The facilities field from the clear request\n or clear indication packet that cleared the\n circuit. A size of zero indicates no\n facilities were present.')
x25CallParmTable = MibTable((1, 3, 6, 1, 2, 1, 10, 5, 9), )
if mibBuilder.loadTexts: x25CallParmTable.setDescription('These objects contain the parameters that\n can be varied between X.25 calls. The\n entries in this table are independent of the\n PLE. There exists only one of these tables\n for the entire system. The indexes for the\n entries are independent of any PLE or any\n circuit. Other tables reference entries in\n this table. Entries in this table can be\n used for default PLE parameters, for\n parameters to use to place/answer a call,\n for the parameters currently in use for a\n circuit, or parameters that were used by a\n circuit.\n\n The number of references to a given set of\n parameters can be found in the\n x25CallParmRefCount object sharing the same\n instance identifier with the parameters.\n The value of this reference count also\n affects the access of the objects in this\n table. An object in this table with the\n same instance identifier as the instance\n identifier of an x25CallParmRefCount must be\n consider associated with that reference\n count. An object with an associated\n reference count of zero can be written (if\n its ACCESS clause allows it). An object\n with an associated reference count greater\n than zero can not be written (regardless of\n the ACCESS clause). This ensures that a set\n of call parameters being referenced from\n another table can not be modified or changed\n in a ways inappropriate for continued use by\n that table.')
x25CallParmEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 5, 9, 1), ).setIndexNames((0, "RFC1382-MIB", "x25CallParmIndex"))
if mibBuilder.loadTexts: x25CallParmEntry.setDescription('Entries of x25CallParmTable.')
x25CallParmIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 1), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CallParmIndex.setDescription('A value that distinguishes this entry from\n another entry. Entries in this table are\n referenced from other objects which identify\n call parameters.\n\n It is impossible to know which other objects\n in the MIB reference entries in the table by\n looking at this table. Because of this,\n changes to parameters must be accomplished\n by creating a new entry in this table and\n then changing the referencing table to\n identify the new entry.\n\n Note that an agent will only use the values\n in this table when another table is changed\n to reference those values. The number of\n other tables that reference an index object\n in this table can be found in\n x25CallParmRefCount. The value of the\n reference count will affect the writability\n of the objects as explained above.\n\n Entries in this table which have a reference\n count of zero maybe deleted at the convence\n of the agent. Care should be taken by the\n agent to give the NMS sufficient time to\n create a reference to newly created entries.\n\n Should a Management Station not find a free\n index with which to create a new entry, it\n may feel free to delete entries with a\n\n\n reference count of zero. However in doing\n so the Management Station much realize it\n may impact other Management Stations.')
x25CallParmStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 2), EntryStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmStatus.setDescription('The status of this call parameter entry.\n See RFC 1271 for details of usage.')
x25CallParmRefCount = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 3), PositiveInteger()).setMaxAccess("readonly")
if mibBuilder.loadTexts: x25CallParmRefCount.setDescription('The number of references know by a\n management station to exist to this set of\n call parameters. This is the number of\n other objects that have returned a value of,\n and will return a value of, the index for\n this set of call parameters. Examples of\n such objects are the x25AdmnDefCallParamId,\n x25OperDataLinkId, or x25AdmnDefCallParamId\n objects defined above.')
x25CallParmInPacketSize = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4096)).clone(128)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmInPacketSize.setDescription('The maximum receive packet size in octets\n for a circuit. A size of zero for a circuit\n means use the PLE default size. A size of\n zero for the PLE means use a default size of\n 128.')
x25CallParmOutPacketSize = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,4096)).clone(128)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmOutPacketSize.setDescription('The maximum transmit packet size in octets\n for a circuit. A size of zero for a circuit\n means use the PLE default size. A size of\n zero for the PLE default means use a default\n size of 128.')
x25CallParmInWindowSize = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,127)).clone(2)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmInWindowSize.setDescription('The receive window size for a circuit. A\n size of zero for a circuit means use the PLE\n default size. A size of zero for the PLE\n default means use 2.')
x25CallParmOutWindowSize = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,127)).clone(2)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmOutWindowSize.setDescription('The transmit window size for a circuit. A\n size of zero for a circuit means use the PLE\n default size. A size of zero for the PLE\n default means use 2.')
x25CallParmAcceptReverseCharging = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("default", 1), ("accept", 2), ("refuse", 3), ("neverAccept", 4),)).clone('refuse')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmAcceptReverseCharging.setDescription('An enumeration defining if the PLE will\n accept or refuse charges. A value of\n default for a circuit means use the PLE\n default value. A value of neverAccept is\n only used for the PLE default and indicates\n the PLE will never accept reverse charging.\n A value of default for a PLE default means\n refuse.')
x25CallParmProposeReverseCharging = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("default", 1), ("reverse", 2), ("local", 3),)).clone('local')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmProposeReverseCharging.setDescription('An enumeration defining if the PLE should\n propose reverse or local charging. The\n value of default for a circuit means use the\n PLE default. The value of default for the\n PLE default means use local.')
x25CallParmFastSelect = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6,))).clone(namedValues=NamedValues(("default", 1), ("notSpecified", 2), ("fastSelect", 3), ("restrictedFastResponse", 4), ("noFastSelect", 5), ("noRestrictedFastResponse", 6),)).clone('noFastSelect')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmFastSelect.setDescription('Expresses preference for use of fast select\n facility. The value of default for a\n circuit is the PLE default. A value of\n\n\n default for the PLE means noFastSelect. A\n value of noFastSelect or\n noRestrictedFastResponse indicates a circuit\n may not use fast select or restricted fast\n response.')
x25CallParmInThruPutClasSize = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,))).clone(namedValues=NamedValues(("tcReserved1", 1), ("tcReserved2", 2), ("tc75", 3), ("tc150", 4), ("tc300", 5), ("tc600", 6), ("tc1200", 7), ("tc2400", 8), ("tc4800", 9), ("tc9600", 10), ("tc19200", 11), ("tc48000", 12), ("tc64000", 13), ("tcReserved14", 14), ("tcReserved15", 15), ("tcReserved0", 16), ("tcNone", 17), ("tcDefault", 18),)).clone('tcNone')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmInThruPutClasSize.setDescription('The incoming throughput class to negotiate.\n A value of tcDefault for a circuit means use\n the PLE default. A value of tcDefault for\n the PLE default means tcNone. A value of\n tcNone means do not negotiate throughtput\n class.')
x25CallParmOutThruPutClasSize = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,))).clone(namedValues=NamedValues(("tcReserved1", 1), ("tcReserved2", 2), ("tc75", 3), ("tc150", 4), ("tc300", 5), ("tc600", 6), ("tc1200", 7), ("tc2400", 8), ("tc4800", 9), ("tc9600", 10), ("tc19200", 11), ("tc48000", 12), ("tc64000", 13), ("tcReserved14", 14), ("tcReserved15", 15), ("tcReserved0", 16), ("tcNone", 17), ("tcDefault", 18),)).clone('tcNone')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmOutThruPutClasSize.setDescription('The outgoing throughput class to negotiate.\n A value of tcDefault for a circuit means use\n the PLE default. A value of tcDefault for\n the PLE default means use tcNone. A value\n of tcNone means do not negotiate throughtput\n class.')
x25CallParmCug = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 13), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0,4)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmCug.setDescription('The Closed User Group to specify. This\n consists of two or four octets containing\n the characters 0 through 9. A zero length\n string indicates no facility requested. A\n string length of three containing the\n characters DEF for a circuit means use the\n PLE default, (the PLE default parameter may\n not reference an entry of DEF.)')
x25CallParmCugoa = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 14), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0,4)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmCugoa.setDescription('The Closed User Group with Outgoing Access\n to specify. This consists of two or four\n octets containing the characters 0 through\n 9. A string length of three containing the\n characters DEF for a circuit means use the\n PLE default (the PLE default parameters may\n not reference an entry of DEF). A zero\n length string indicates no facility\n requested.')
x25CallParmBcug = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 15), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0,3)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmBcug.setDescription('The Bilateral Closed User Group to specify.\n This consists of two octets containing the\n characters 0 through 9. A string length of\n three containing the characters DEF for a\n circuit means use the PLE default (the PLE\n default parameter may not reference an entry\n of DEF). A zero length string indicates no\n facility requested.')
x25CallParmNui = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 16), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0,108)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmNui.setDescription('The Network User Identifier facility. This\n is binary value to be included immediately\n after the length field. The PLE will supply\n the length octet. A zero length string\n indicates no facility requested. This value\n is ignored for the PLE default parameters\n entry.')
x25CallParmChargingInfo = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("default", 1), ("noFacility", 2), ("noChargingInfo", 3), ("chargingInfo", 4),)).clone('noFacility')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmChargingInfo.setDescription('The charging Information facility. A value\n of default for a circuit means use the PLE\n default. The value of default for the\n default PLE parameters means use noFacility.\n The value of noFacility means do not include\n a facility.')
x25CallParmRpoa = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 18), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0,108)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmRpoa.setDescription('The RPOA facility. The octet string\n contains n * 4 sequences of the characters\n 0-9 to specify a facility with n entries.\n The octet string containing the 3 characters\n DEF for a circuit specifies use of the PLE\n default (the entry for the PLE default may\n not contain DEF). A zero length string\n indicates no facility requested.')
x25CallParmTrnstDly = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,65537)).clone(65536)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmTrnstDly.setDescription('The Transit Delay Selection and Indication\n value. A value of 65536 indicates no\n facility requested. A value of 65537 for a\n circuit means use the PLE default (the PLE\n\n\n default parameters entry may not use the\n value 65537). The value 65535 may only be\n used to indicate the value in use by a\n circuit.')
x25CallParmCallingExt = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 20), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0,40)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmCallingExt.setDescription('The Calling Extension facility. This\n contains one of the following:\n\n A sequence of hex digits with the value to\n be put in the facility. These digits will be\n converted to binary by the agent and put in\n the facility. These octets do not include\n the length octet.\n\n A value containing the three character DEF\n for a circuit means use the PLE default,\n (the entry for the PLE default parameters\n may not use the value DEF).\n\n A zero length string indicates no facility\n requested.')
x25CallParmCalledExt = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 21), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0,40)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmCalledExt.setDescription('The Called Extension facility. This\n contains one of the following:\n\n A sequence of hex digits with the value to\n be put in the facility. These digits will be\n converted to binary by the agent and put in\n the facility. These octets do not include\n\n\n the length octet.\n\n A value containing the three character DEF\n for a circuit means use the PLE default,\n (the entry for the PLE default parameters\n may not use the value DEF).\n\n A zero length string indicates no facility\n requested.')
x25CallParmInMinThuPutCls = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 22), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,17)).clone(17)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmInMinThuPutCls.setDescription('The minimum input throughput Class. A\n value of 16 for a circuit means use the PLE\n default (the PLE parameters entry may not\n use this value). A value of 17 indicates no\n facility requested.')
x25CallParmOutMinThuPutCls = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 23), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,17)).clone(17)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmOutMinThuPutCls.setDescription('The minimum output throughput Class. A\n value of 16 for a circuit means use the PLE\n default (the PLE parameters entry may not\n use this value). A value of 17 indicates no\n facility requested.')
x25CallParmEndTrnsDly = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 24), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0,6)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmEndTrnsDly.setDescription('The End-to-End Transit Delay to negotiate.\n An octet string of length 2, 4, or 6\n\n\n contains the facility encoded as specified\n in ISO/IEC 8208 section 15.3.2.4. An octet\n string of length 3 containing the three\n character DEF for a circuit means use the\n PLE default (the entry for the PLE default\n can not contain the characters DEF). A zero\n length string indicates no facility\n requested.')
x25CallParmPriority = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 25), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0,6)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmPriority.setDescription('The priority facility to negotiate. The\n octet string encoded as specified in ISO/IEC\n 8208 section 15.3.2.5. A zero length string\n indicates no facility requested. The entry\n for the PLE default parameters must be zero\n length.')
x25CallParmProtection = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 26), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0,108)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmProtection.setDescription('A string contains the following:\n A hex string containing the value for the\n protection facility. This will be converted\n from hex to the octets actually in the\n packet by the agent. The agent will supply\n the length field and the length octet is not\n contained in this string.\n\n An string containing the 3 characters DEF\n for a circuit means use the PLE default (the\n entry for the PLE default parameters may not\n use the value DEF).\n\n A zero length string mean no facility\n requested.')
x25CallParmExptData = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("default", 1), ("noExpeditedData", 2), ("expeditedData", 3),)).clone('noExpeditedData')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmExptData.setDescription('The Expedited Data facility to negotiate.\n A value of default for a circuit means use\n the PLE default value. The entry for the\n PLE default parameters may not have the\n value default.')
x25CallParmUserData = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 28), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0,128)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmUserData.setDescription('The call user data as placed in the packet.\n A zero length string indicates no call user\n data. If both the circuit call parameters\n and the PLE default have call user data\n defined, the data from the circuit call\n parameters will be used. If only the PLE\n has data defined, the PLE entry will be\n used. If neither the circuit call\n parameters or the PLE default entry has a\n value, no call user data will be sent.')
x25CallParmCallingNetworkFacilities = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 29), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0,108)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmCallingNetworkFacilities.setDescription('The calling network facilities. The\n facilities are encoded here exactly as\n encoded in the call packet. These\n\n\n facilities do not include the marker\n facility code.\n\n A zero length string in the entry for the\n parameter to use when establishing a circuit\n means use the PLE default. A zero length\n string in the entry for PLE default\n parameters indicates no default facilities.')
x25CallParmCalledNetworkFacilities = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 5, 9, 1, 30), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0,108)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: x25CallParmCalledNetworkFacilities.setDescription('The called network facilities. The\n facilities are encoded here exactly as\n encoded in the call packet. These\n facilities do not include the marker\n facility code.\n\n A zero length string in the entry for the\n parameter to use when establishing a circuit\n means use the PLE default. A zero length\n string in the entry for PLE default\n parameters indicates no default facilities.')
x25Restart = NotificationType((1, 3, 6, 1, 2, 1, 10, 5) + (0,1)).setObjects(*(("RFC1382-MIB", "x25OperIndex"),))
if mibBuilder.loadTexts: x25Restart.setDescription('This trap means the X.25 PLE sent or\n received a restart packet. The restart that\n brings up the link should not send a\n x25Restart trap so the interface should send\n a linkUp trap. Sending this trap means the\n agent does not send a linkDown and linkUp\n trap.')
x25Reset = NotificationType((1, 3, 6, 1, 2, 1, 10, 5) + (0,2)).setObjects(*(("RFC1382-MIB", "x25CircuitIndex"), ("RFC1382-MIB", "x25CircuitChannel"),))
if mibBuilder.loadTexts: x25Reset.setDescription('If the PLE sends or receives a reset, the\n agent should send an x25Reset trap.')
x25ProtocolVersion = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 5, 10))
x25protocolCcittV1976 = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 5, 10, 1))
x25protocolCcittV1980 = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 5, 10, 2))
x25protocolCcittV1984 = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 5, 10, 3))
x25protocolCcittV1988 = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 5, 10, 4))
x25protocolIso8208V1987 = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 5, 10, 5))
x25protocolIso8208V1989 = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 5, 10, 6))
mibBuilder.exportSymbols("RFC1382-MIB", x25CallParmAcceptReverseCharging=x25CallParmAcceptReverseCharging, x25StatRetryCountExceededs=x25StatRetryCountExceededs, x25StatEntry=x25StatEntry, x25StatOutInterrupts=x25StatOutInterrupts, x25StatInCalls=x25StatInCalls, x25StatInRestarts=x25StatInRestarts, x25ClearedCircuitIndex=x25ClearedCircuitIndex, x25CallParmFastSelect=x25CallParmFastSelect, x25CircuitOutOctets=x25CircuitOutOctets, x25AdmnRestartCount=x25AdmnRestartCount, x25OperRejectTimer=x25OperRejectTimer, x25ChannelLIC=x25ChannelLIC, x25ChannelTable=x25ChannelTable, x25AdmnPacketSequencing=x25AdmnPacketSequencing, x25StatIndex=x25StatIndex, x25OperLocalAddress=x25OperLocalAddress, x25AdmnMinimumRecallTimer=x25AdmnMinimumRecallTimer, x25ChannelHTC=x25ChannelHTC, x25StatOutCallFailures=x25StatOutCallFailures, x25Reset=x25Reset, x25StatResetTimeouts=x25StatResetTimeouts, x25CircuitEstablishTime=x25CircuitEstablishTime, x25CallParmInPacketSize=x25CallParmInPacketSize, x25protocolCcittV1976=x25protocolCcittV1976, x25=x25, x25OperDataLinkId=x25OperDataLinkId, x25StatCallTimeouts=x25StatCallTimeouts, x25OperClearCount=x25OperClearCount, x25ClearedCircuitInPdus=x25ClearedCircuitInPdus, x25OperDataRxmtTimer=x25OperDataRxmtTimer, X121Address=X121Address, x25OperResetTimer=x25OperResetTimer, x25StatDataRxmtTimeouts=x25StatDataRxmtTimeouts, x25CallParmCallingExt=x25CallParmCallingExt, x25CallParmCalledNetworkFacilities=x25CallParmCalledNetworkFacilities, x25ClearedCircuitCallingAddress=x25ClearedCircuitCallingAddress, x25AdmnLocalAddress=x25AdmnLocalAddress, x25AdmnMaxActiveCircuits=x25AdmnMaxActiveCircuits, x25CallParmOutMinThuPutCls=x25CallParmOutMinThuPutCls, x25CircuitOutPdus=x25CircuitOutPdus, x25ProtocolVersion=x25ProtocolVersion, x25CircuitOutInterrupts=x25CircuitOutInterrupts, x25CircuitCallParamId=x25CircuitCallParamId, x25OperPacketSequencing=x25OperPacketSequencing, x25AdmnDefCallParamId=x25AdmnDefCallParamId, x25CallParmRefCount=x25CallParmRefCount, x25AdmnResetTimer=x25AdmnResetTimer, x25AdmnRegistrationRequestCount=x25AdmnRegistrationRequestCount, x25CircuitInOctets=x25CircuitInOctets, x25CallParmOutPacketSize=x25CallParmOutPacketSize, x25ClearedCircuitClearingCause=x25ClearedCircuitClearingCause, x25AdmnInterfaceMode=x25AdmnInterfaceMode, x25CircuitInPdus=x25CircuitInPdus, x25CallParmOutThruPutClasSize=x25CallParmOutThruPutClasSize, x25CallParmProtection=x25CallParmProtection, x25OperCallTimer=x25OperCallTimer, x25AdmnRejectCount=x25AdmnRejectCount, x25OperNumberPVCs=x25OperNumberPVCs, x25CircuitOriginallyCalledAddress=x25CircuitOriginallyCalledAddress, x25ClearedCircuitTimeEstablished=x25ClearedCircuitTimeEstablished, x25AdmnIndex=x25AdmnIndex, x25OperTable=x25OperTable, x25CallParmStatus=x25CallParmStatus, x25AdmnClearTimer=x25AdmnClearTimer, x25CallParmCalledExt=x25CallParmCalledExt, x25CallParmEntry=x25CallParmEntry, x25CircuitChannel=x25CircuitChannel, x25StatOutDataPackets=x25StatOutDataPackets, x25OperInterfaceMode=x25OperInterfaceMode, x25AdmnResetCount=x25AdmnResetCount, x25StatOutgoingCircuits=x25StatOutgoingCircuits, x25CircuitCalledDteAddress=x25CircuitCalledDteAddress, x25AdmnCallTimer=x25AdmnCallTimer, x25ChannelHOC=x25ChannelHOC, x25CallParmExptData=x25CallParmExptData, x25CallParmProposeReverseCharging=x25CallParmProposeReverseCharging, x25CircuitDescr=x25CircuitDescr, x25CallParmInMinThuPutCls=x25CallParmInMinThuPutCls, x25ClearedCircuitClearFacilities=x25ClearedCircuitClearFacilities, x25CallParmTrnstDly=x25CallParmTrnstDly, x25CallParmNui=x25CallParmNui, x25StatInProviderInitiatedResets=x25StatInProviderInitiatedResets, x25CallParmChargingInfo=x25CallParmChargingInfo, x25StatRestartTimeouts=x25StatRestartTimeouts, x25protocolCcittV1984=x25protocolCcittV1984, x25protocolIso8208V1987=x25protocolIso8208V1987, x25CircuitIndex=x25CircuitIndex, x25OperRestartTimer=x25OperRestartTimer, x25ClearedCircuitPleIndex=x25ClearedCircuitPleIndex, x25OperInterruptTimer=x25OperInterruptTimer, x25CallParmCug=x25CallParmCug, x25StatTwowayCircuits=x25StatTwowayCircuits, x25AdmnWindowTimer=x25AdmnWindowTimer, x25ClearedCircuitCalledAddress=x25ClearedCircuitCalledAddress, x25ClearedCircuitTimeCleared=x25ClearedCircuitTimeCleared, x25CallParmPriority=x25CallParmPriority, x25OperRegistrationRequestTimer=x25OperRegistrationRequestTimer, x25AdmnClearCount=x25AdmnClearCount, x25protocolCcittV1980=x25protocolCcittV1980, x25protocolCcittV1988=x25protocolCcittV1988, x25ClearedCircuitEntriesGranted=x25ClearedCircuitEntriesGranted, x25CallParmInWindowSize=x25CallParmInWindowSize, x25ChannelLOC=x25ChannelLOC, x25CircuitDataRetransmissionTimeouts=x25CircuitDataRetransmissionTimeouts, x25OperClearTimer=x25OperClearTimer, x25StatOutCallAttempts=x25StatOutCallAttempts, x25CallParmRpoa=x25CallParmRpoa, x25CallParmInThruPutClasSize=x25CallParmInThruPutClasSize, x25ClearedCircuitEntriesRequested=x25ClearedCircuitEntriesRequested, x25StatInterruptTimeouts=x25StatInterruptTimeouts, x25OperIndex=x25OperIndex, x25CallParmUserData=x25CallParmUserData, x25AdmnRejectTimer=x25AdmnRejectTimer, x25ClearedCircuitEntry=x25ClearedCircuitEntry, x25ClearedCircuitTable=x25ClearedCircuitTable, x25protocolIso8208V1989=x25protocolIso8208V1989, x25StatClearCountExceededs=x25StatClearCountExceededs, x25OperMaxActiveCircuits=x25OperMaxActiveCircuits, x25StatInCallRefusals=x25StatInCallRefusals, x25CircuitInRemotelyInitiatedResets=x25CircuitInRemotelyInitiatedResets, x25OperRestartCount=x25OperRestartCount, x25OperProtocolVersionSupported=x25OperProtocolVersionSupported, x25CallParmOutWindowSize=x25CallParmOutWindowSize, x25OperRejectCount=x25OperRejectCount, x25StatIncomingCircuits=x25StatIncomingCircuits, x25ClearedCircuitChannel=x25ClearedCircuitChannel, x25StatInAccusedOfProtocolErrors=x25StatInAccusedOfProtocolErrors, x25CircuitInterruptTimeouts=x25CircuitInterruptTimeouts, x25AdmnNumberPVCs=x25AdmnNumberPVCs, x25OperDefCallParamId=x25OperDefCallParamId, x25AdmnInterruptTimer=x25AdmnInterruptTimer, x25CircuitInProviderInitiatedResets=x25CircuitInProviderInitiatedResets, x25StatInRemotelyInitiatedResets=x25StatInRemotelyInitiatedResets, x25OperResetCount=x25OperResetCount, x25ChannelIndex=x25ChannelIndex, x25ChannelLTC=x25ChannelLTC, x25CallParmTable=x25CallParmTable, x25CallParmCugoa=x25CallParmCugoa, x25AdmnDataRxmtTimer=x25AdmnDataRxmtTimer, x25ChannelEntry=x25ChannelEntry, x25ChannelHIC=x25ChannelHIC, x25CircuitInInterrupts=x25CircuitInInterrupts, x25StatInProviderInitiatedClears=x25StatInProviderInitiatedClears, x25AdmnTable=x25AdmnTable, x25AdmnDataRxmtCount=x25AdmnDataRxmtCount, x25AdmnEntry=x25AdmnEntry, x25ClearedCircuitDiagnosticCode=x25ClearedCircuitDiagnosticCode, x25CircuitResetTimeouts=x25CircuitResetTimeouts, x25Restart=x25Restart, x25CallParmEndTrnsDly=x25CallParmEndTrnsDly, x25CallParmIndex=x25CallParmIndex, x25OperMinimumRecallTimer=x25OperMinimumRecallTimer, x25OperWindowTimer=x25OperWindowTimer, x25AdmnRestartTimer=x25AdmnRestartTimer, x25OperEntry=x25OperEntry, x25CircuitCallingDteAddress=x25CircuitCallingDteAddress, x25CircuitDirection=x25CircuitDirection, x25ClearedCircuitOutPdus=x25ClearedCircuitOutPdus, x25CallParmBcug=x25CallParmBcug, x25StatInInterrupts=x25StatInInterrupts, x25AdmnRegistrationRequestTimer=x25AdmnRegistrationRequestTimer, x25StatTable=x25StatTable, x25AdmnProtocolVersionSupported=x25AdmnProtocolVersionSupported, x25OperRegistrationRequestCount=x25OperRegistrationRequestCount, x25CallParmCallingNetworkFacilities=x25CallParmCallingNetworkFacilities, x25OperDataRxmtCount=x25OperDataRxmtCount, x25CircuitStatus=x25CircuitStatus, x25CircuitTable=x25CircuitTable, x25CircuitEntry=x25CircuitEntry, x25StatInDataPackets=x25StatInDataPackets, x25StatClearTimeouts=x25StatClearTimeouts)
|
def main(filepath):
with open(filepath) as file:
rows = [int(x.strip()) for x in file.readlines()]
rows.append(0)
rows.sort()
rows.append(rows[-1]+3)
current_volts = 0
one_volts = 0
three_volts = 0
for i in range(len(rows)):
if rows[i] - current_volts == 0:
continue
if rows[i] - current_volts == 1:
current_volts = rows[i]
one_volts += 1
continue
if rows[i] - current_volts == 2:
current_volts = rows[i]
continue
if rows[i] - current_volts == 3:
current_volts = rows[i]
three_volts += 1
continue
print("Part a solution: "+ str(three_volts*one_volts))
rows.reverse()
memo = {}
memo[rows[0]] = 1
for i in range(1,len(rows)):
memo[rows[i]] = memo.get(rows[i] + 1, 0) + memo.get(rows[i] + 2, 0) + memo.get(rows[i] + 3, 0)
print("Part b solution: "+ str(memo[0]))
|
# -*- coding:utf-8 -*-
def decorator_singleton(cls):
"""
装饰器实现方式
:param cls:
:return:
"""
instances = {}
def _singleton(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return _singleton
class NewSingleton(object):
"""
需要单例实现的类继承该类
注意:该方法不适用于多线程下的单例模式
"""
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(NewSingleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class DstClass(object):
"""
模块实例引用法, 直接实例化目标类,其他地方引用该类时,就是永远都是单例模式
"""
def __init__(self, *args, **kwargs):
pass
DstClass = DstClass()
|
def find_min_max(nums):
if nums[0]<nums[1]:
min = nums[0]
max = nums[1]
else:
min = nums[1]
max = nums[0]
for i in range(len(nums)-2):
if nums[i+2] < min:
min = nums[i+2]
elif nums[i+2] > max:
max = nums[i+2]
return (min, max)
def main():
print(find_min_max([3, 5, 1, 2, 4, 8]))
if __name__== "__main__":
main() |
def daily_sleeping_hours(hours=7):
return hours
print(daily_sleeping_hours(10))
print(daily_sleeping_hours()) |
x=1
grenais = 0
inter = 0
gremio = 0
empate = 0
while x == 1:
y = input().split()
a,b=y
a=int(a)
b=int(b)
grenais = grenais + 1
if a > b:
inter = inter + 1
if a < b:
gremio = gremio + 1
if a == b:
empate = empate + 1
while True:
x = int(input('Novo grenal (1-sim 2-nao)'))
if x == 2 or x == 1:
break
print('{} grenais'.format(grenais))
print('Inter:{}'.format(inter))
print('Gremio:{}'.format(gremio))
print('Empates:{}'.format(empate))
if inter > gremio:
print('Inter venceu mais')
if gremio > inter:
print('Gremio venceu mais')
if gremio == inter:
print('Nao houve vencedor')
|
#
# PySNMP MIB module SNR-ERD-PRO-Mini (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNR-ERD-PRO-Mini
# Produced by pysmi-0.3.4 at Mon Apr 29 21:00:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
ModuleIdentity, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, Bits, Unsigned32, MibIdentifier, ObjectIdentity, Counter32, iso, TimeTicks, Counter64, enterprises, IpAddress, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "Bits", "Unsigned32", "MibIdentifier", "ObjectIdentity", "Counter32", "iso", "TimeTicks", "Counter64", "enterprises", "IpAddress", "Gauge32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
snr = ModuleIdentity((1, 3, 6, 1, 4, 1, 40418))
snr.setRevisions(('2015-04-29 12:00',))
if mibBuilder.loadTexts: snr.setLastUpdated('201504291200Z')
if mibBuilder.loadTexts: snr.setOrganization('NAG ')
snr_erd = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2)).setLabel("snr-erd")
snr_erd_pro_mini = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5)).setLabel("snr-erd-pro-mini")
measurements = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1))
sensesstate = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5, 2))
management = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5, 3))
counters = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5, 8))
options = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5, 10))
snrSensors = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1))
temperatureSensors = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1))
powerSensors = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2))
alarmSensCnts = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5, 8, 2))
erdproMiniTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0))
voltageSensor = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageSensor.setStatus('current')
serialS1 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 10), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serialS1.setStatus('current')
serialS2 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 11), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serialS2.setStatus('current')
serialS3 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 12), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serialS3.setStatus('current')
serialS4 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 13), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serialS4.setStatus('current')
serialS5 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 14), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serialS5.setStatus('current')
serialS6 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 15), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serialS6.setStatus('current')
serialS7 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 16), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serialS7.setStatus('current')
serialS8 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 17), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serialS8.setStatus('current')
serialS9 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 18), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serialS9.setStatus('current')
serialS10 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 19), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: serialS10.setStatus('current')
temperatureS1 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: temperatureS1.setStatus('current')
temperatureS2 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: temperatureS2.setStatus('current')
temperatureS3 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: temperatureS3.setStatus('current')
temperatureS4 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: temperatureS4.setStatus('current')
temperatureS5 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: temperatureS5.setStatus('current')
temperatureS6 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: temperatureS6.setStatus('current')
temperatureS7 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: temperatureS7.setStatus('current')
temperatureS8 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: temperatureS8.setStatus('current')
temperatureS9 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: temperatureS9.setStatus('current')
temperatureS10 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: temperatureS10.setStatus('current')
voltageS1 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageS1.setStatus('current')
currentS1 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: currentS1.setStatus('current')
voltageS2 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageS2.setStatus('current')
currentS2 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: currentS2.setStatus('current')
voltageS3 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageS3.setStatus('current')
currentS3 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: currentS3.setStatus('current')
voltageS4 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageS4.setStatus('current')
currentS4 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 11), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: currentS4.setStatus('current')
voltageS5 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 13), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageS5.setStatus('current')
currentS5 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 14), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: currentS5.setStatus('current')
voltageS6 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 16), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageS6.setStatus('current')
currentS6 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 17), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: currentS6.setStatus('current')
voltageS7 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 19), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageS7.setStatus('current')
currentS7 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 20), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: currentS7.setStatus('current')
voltageS8 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 22), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageS8.setStatus('current')
currentS8 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 23), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: currentS8.setStatus('current')
voltageS9 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 25), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageS9.setStatus('current')
currentS9 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 26), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: currentS9.setStatus('current')
voltageS10 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 28), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: voltageS10.setStatus('current')
currentS10 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 1, 1, 2, 29), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: currentS10.setStatus('current')
alarmSensor1 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0))).clone(namedValues=NamedValues(("high", 1), ("low", 0)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: alarmSensor1.setStatus('current')
alarmSensor2 = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0))).clone(namedValues=NamedValues(("high", 1), ("low", 0)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: alarmSensor2.setStatus('current')
uSensor = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0))).clone(namedValues=NamedValues(("no", 1), ("yes", 0)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: uSensor.setStatus('current')
smart1State = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0, 2))).clone(namedValues=NamedValues(("on", 1), ("off", 0), ("reset", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: smart1State.setStatus('current')
smart2State = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 3, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0, 2))).clone(namedValues=NamedValues(("on", 1), ("off", 0), ("reset", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: smart2State.setStatus('current')
smart1ResetTime = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 3, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: smart1ResetTime.setStatus('current')
smart2ResetTime = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 3, 6), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: smart2ResetTime.setStatus('current')
alarmSensor1cnt = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 8, 2, 1), Counter32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: alarmSensor1cnt.setStatus('current')
alarmSensor2cnt = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 8, 2, 2), Counter32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: alarmSensor2cnt.setStatus('current')
dataType = MibScalar((1, 3, 6, 1, 4, 1, 40418, 2, 5, 10, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("integer", 0), ("float", 1), ("ufloat", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: dataType.setStatus('current')
aSense1Alarm = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 1))
if mibBuilder.loadTexts: aSense1Alarm.setStatus('current')
aSense1Release = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 2))
if mibBuilder.loadTexts: aSense1Release.setStatus('current')
aSense2Alarm = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 3))
if mibBuilder.loadTexts: aSense2Alarm.setStatus('current')
aSense2Release = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 4))
if mibBuilder.loadTexts: aSense2Release.setStatus('current')
uSenseAlarm = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 9))
if mibBuilder.loadTexts: uSenseAlarm.setStatus('current')
uSenseRelease = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 10))
if mibBuilder.loadTexts: uSenseRelease.setStatus('current')
smart1ThermoOn = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 13))
if mibBuilder.loadTexts: smart1ThermoOn.setStatus('current')
smart1ThermoOff = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 14))
if mibBuilder.loadTexts: smart1ThermoOff.setStatus('current')
smart2ThermoOn = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 15))
if mibBuilder.loadTexts: smart2ThermoOn.setStatus('current')
smart2ThermoOff = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 16))
if mibBuilder.loadTexts: smart2ThermoOff.setStatus('current')
tempSensorAlarm = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 29))
if mibBuilder.loadTexts: tempSensorAlarm.setStatus('current')
tempSensorRelease = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 30))
if mibBuilder.loadTexts: tempSensorRelease.setStatus('current')
voltSensorAlarm = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 31))
if mibBuilder.loadTexts: voltSensorAlarm.setStatus('current')
voltSensorRelease = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 32))
if mibBuilder.loadTexts: voltSensorRelease.setStatus('current')
task1Done = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 36))
if mibBuilder.loadTexts: task1Done.setStatus('current')
task2Done = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 37))
if mibBuilder.loadTexts: task2Done.setStatus('current')
task3Done = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 38))
if mibBuilder.loadTexts: task3Done.setStatus('current')
task4Done = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 39))
if mibBuilder.loadTexts: task4Done.setStatus('current')
pingLost = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 45))
if mibBuilder.loadTexts: pingLost.setStatus('current')
batteryChargeLow = NotificationType((1, 3, 6, 1, 4, 1, 40418, 2, 5, 0, 47))
if mibBuilder.loadTexts: batteryChargeLow.setStatus('current')
erdProMiniTrapGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 40418, 2, 5, 99)).setObjects(("SNR-ERD-PRO-Mini", "aSense1Alarm"), ("SNR-ERD-PRO-Mini", "aSense1Release"), ("SNR-ERD-PRO-Mini", "aSense2Alarm"), ("SNR-ERD-PRO-Mini", "aSense2Release"), ("SNR-ERD-PRO-Mini", "uSenseAlarm"), ("SNR-ERD-PRO-Mini", "uSenseRelease"), ("SNR-ERD-PRO-Mini", "smart1ThermoOn"), ("SNR-ERD-PRO-Mini", "smart1ThermoOff"), ("SNR-ERD-PRO-Mini", "smart2ThermoOn"), ("SNR-ERD-PRO-Mini", "smart2ThermoOff"), ("SNR-ERD-PRO-Mini", "tempSensorAlarm"), ("SNR-ERD-PRO-Mini", "tempSensorRelease"), ("SNR-ERD-PRO-Mini", "voltSensorAlarm"), ("SNR-ERD-PRO-Mini", "voltSensorRelease"), ("SNR-ERD-PRO-Mini", "task1Done"), ("SNR-ERD-PRO-Mini", "task2Done"), ("SNR-ERD-PRO-Mini", "task3Done"), ("SNR-ERD-PRO-Mini", "task4Done"), ("SNR-ERD-PRO-Mini", "pingLost"), ("SNR-ERD-PRO-Mini", "batteryChargeLow"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
erdProMiniTrapGroup = erdProMiniTrapGroup.setStatus('current')
mibBuilder.exportSymbols("SNR-ERD-PRO-Mini", temperatureS2=temperatureS2, voltageS10=voltageS10, snr=snr, temperatureS8=temperatureS8, smart2ThermoOff=smart2ThermoOff, options=options, temperatureS6=temperatureS6, serialS5=serialS5, pingLost=pingLost, smart1ThermoOff=smart1ThermoOff, alarmSensor1=alarmSensor1, temperatureS9=temperatureS9, currentS2=currentS2, currentS6=currentS6, currentS9=currentS9, serialS6=serialS6, temperatureS4=temperatureS4, currentS10=currentS10, sensesstate=sensesstate, task2Done=task2Done, aSense1Alarm=aSense1Alarm, smart1ThermoOn=smart1ThermoOn, voltageS6=voltageS6, serialS1=serialS1, smart1ResetTime=smart1ResetTime, voltageS9=voltageS9, aSense2Release=aSense2Release, alarmSensor2cnt=alarmSensor2cnt, temperatureS1=temperatureS1, uSensor=uSensor, alarmSensor2=alarmSensor2, currentS3=currentS3, voltSensorRelease=voltSensorRelease, batteryChargeLow=batteryChargeLow, voltageS1=voltageS1, smart2State=smart2State, voltageSensor=voltageSensor, serialS2=serialS2, powerSensors=powerSensors, task1Done=task1Done, tempSensorRelease=tempSensorRelease, erdProMiniTrapGroup=erdProMiniTrapGroup, measurements=measurements, smart2ResetTime=smart2ResetTime, tempSensorAlarm=tempSensorAlarm, voltageS2=voltageS2, serialS8=serialS8, currentS1=currentS1, task4Done=task4Done, snrSensors=snrSensors, voltageS5=voltageS5, temperatureS3=temperatureS3, currentS8=currentS8, counters=counters, voltageS8=voltageS8, serialS10=serialS10, temperatureSensors=temperatureSensors, management=management, snr_erd_pro_mini=snr_erd_pro_mini, alarmSensor1cnt=alarmSensor1cnt, PYSNMP_MODULE_ID=snr, snr_erd=snr_erd, aSense2Alarm=aSense2Alarm, serialS4=serialS4, smart2ThermoOn=smart2ThermoOn, alarmSensCnts=alarmSensCnts, voltSensorAlarm=voltSensorAlarm, currentS7=currentS7, voltageS4=voltageS4, serialS3=serialS3, temperatureS7=temperatureS7, temperatureS10=temperatureS10, serialS7=serialS7, currentS5=currentS5, smart1State=smart1State, currentS4=currentS4, aSense1Release=aSense1Release, uSenseRelease=uSenseRelease, voltageS7=voltageS7, temperatureS5=temperatureS5, voltageS3=voltageS3, task3Done=task3Done, uSenseAlarm=uSenseAlarm, erdproMiniTraps=erdproMiniTraps, dataType=dataType, serialS9=serialS9)
|
class ComputeRank(object):
def __init__(self, var_name):
self.var_name = var_name
def __call__(self, documents):
for i, document in enumerate(documents, 1):
document[self.var_name] = i
return documents
def test_rank():
plugin = ComputeRank("rank")
docs = [{}, {}]
result = plugin(docs)
doc1, doc2 = result
assert doc1["rank"] == 1
assert doc2["rank"] == 2 |
'''
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers
in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order.
However, you are not allowed to reorder the integers in each array pieces[i].
Return true if it is possible to form the array arr from pieces. Otherwise, return false.
Ex. Input - arr : [91,4,64,78], pieces : [[78],[4,64],[91]]
Output - true
Explanation - Concatenate [91] then [4,64] then [78]
Input - arr : [49,18,16], pieces : [[16,18,49]]
Output - false
Explanation - Even though the numbers match, we cannot reorder pieces[0].
Constraints -
1 <= pieces.length <= arr.length <= 100
sum(pieces[i].length) == arr.length
1 <= pieces[i].length <= arr.length
1 <= arr[i], pieces[i][j] <= 100
Solution Complexity -
Time : O(m + n); m = pieces.length, n = arr.length
Space : O(m)
'''
def canFormArray(arr, pieces):
indexing = {}
for i in pieces:
indexing[i[0]] = i
i = 0
while i < len(arr):
try:
tmp = indexing[arr[i]]
for ele in tmp:
if ele == arr[i]:
i += 1
else:
return False
except KeyError:
return False
return True
if __name__ == '__main__':
size = input().split()
arr = input().split()
pieces = []
for _ in range(int(size[1])):
pieces.append(input().split())
print(canFormArray(arr, pieces))
|
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
count = dict()
for words in cpdomains:
times, cpdomain = words.split(' ')
times = int(times)
keys = cpdomain.split('.')
keys = ['.'.join(keys[i:]) for i in range(len(keys))]
for key in keys:
count[key] = times if count.get(key) is None else count[key] + times
ans = ['{} {}'.format(count[key], key) for key in count.keys()]
return ans |
ENTITY = "<<Entity>>"
REL = 'Rel/'
ATTR = 'Attr/'
SOME = 'SOME'
ALL = 'ALL'
GRAPH = 'GRAPH'
LIST = 'LIST'
TEXT = 'TEXT'
SHAPE = 'SHAPE'
SOME_LIMIT = 15
EXACT_MATCH = 'EXACT_MATCH'
REGEX_MATCH = 'REGEX_MATCH'
SYNONYM_MATCH = 'SYNONYM_MATCH' |
def calculate(arr, index=0):
back = - 1 - index
if arr[index] != arr[back]:
return False
elif abs(back) == (index+1):
return True
return calculate(arr, index+1)
arr = [int(i) for i in input().split()]
print(calculate(arr))
|
"""
Find the parant and the node to be deleted. [0]
Deleting the node means replacing its reference by something else. [1]
For the node to be deleted, if it only has no child, just remove it from the parent. Return None. [2]
If it has one child, return the child. So its parent will directly connect to its child. [3]
If it has both child. Update the node's val to the minimum value in the right subtree. Remove the minimum value node in the right subtree. [4]
This is equivalent to replacing the node by the minimum value node in the right subtree.
Another option is to replace the node by the maximum value node in the left subtree.
Find the minimum value in the left subtree is easy. The leftest node value in the tree is the smallest. [5]
Time Complexity: O(LogN). O(LogN) for finding the node to be deleted.
The recursive call in `remove()` will be apply to a much smaller subtree. And much smaller subtree...
So can be ignored.
Space complexity is O(LogN). Because the recursive call will at most be called LogN times.
N is the number of nodes. And LogN can be consider the height of the tree.
"""
class Solution(object):
def deleteNode(self, root, key):
def find_min(root):
curr = root
while curr.left: curr = curr.left
return curr.val#[5]
def remove(node):
if node.left and node.right:
node.val = find_min(node.right)
node.right = self.deleteNode(node.right, node.val)
return node #[4]
elif node.left and not node.right:
return node.left #[3]
elif node.right and not node.left:
return node.right #[3]
else:
return None #[2]
if not root: return root
node = root
while node: #[0]
if node.val==key:
return remove(node) #[1]
elif node.left and node.left.val==key:
node.left = remove(node.left) #[1]
return root
elif node.right and node.right.val==key:
node.right = remove(node.right) #[1]
return root
if key>node.val and node.right:
node = node.right
elif key<node.val and node.left:
node = node.left
else:
break
return root
class Solution(object):
def deleteNode(self, node, key):
if not node:
return node
elif key<node.val:
node.left = self.deleteNode(node.left, key)
return node
elif key>node.val:
node.right = self.deleteNode(node.right, key)
return node
elif key==node.val:
if not node.left and not node.right:
return None
elif not node.left:
return node.right
elif not node.right:
return node.left
else:
node.val = self.findMin(node.right) #min value in the right subtree
node.right = self.deleteNode(node.right, node.val)
return node
def findMin(self, root):
ans = float('inf')
stack = [root]
while stack:
node = stack.pop()
ans = min(ans, node.val)
if node.left: stack.append(node.left)
if node.right: stack.append(node.right)
return ans
|
class IberException(Exception):
pass
class ResponseException(IberException):
def __init__(self, status_code):
super().__init__("Response error, code: {}".format(status_code))
class LoginException(IberException):
def __init__(self, username):
super().__init__(f'Unable to log in with user {username}')
class SessionException(IberException):
def __init__(self):
super().__init__('Session required, use login() method to obtain a session')
class NoResponseException(IberException):
pass
class SelectContractException(IberException):
pass
|
v = 6.0 # velocity of seismic waves [km/s]
def earthquake_epicenter(x1, y1, t1, x2, y2, t2, x3, y3, t3):
x = 0
y = 0
# Your code goes here!
return x, y
|
class Logi:
def __init__(self, email, password):
self.email = email
self.password = password
|
class StringFormatFlags(Enum, IComparable, IFormattable, IConvertible):
"""
Specifies the display and layout information for text strings.
enum (flags) StringFormatFlags,values: DirectionRightToLeft (1),DirectionVertical (2),DisplayFormatControl (32),FitBlackBox (4),LineLimit (8192),MeasureTrailingSpaces (2048),NoClip (16384),NoFontFallback (1024),NoWrap (4096)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self, *args):
pass
def __gt__(self, *args):
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args):
pass
def __lt__(self, *args):
pass
def __ne__(self, *args):
pass
def __reduce_ex__(self, *args):
pass
def __str__(self, *args):
pass
DirectionRightToLeft = None
DirectionVertical = None
DisplayFormatControl = None
FitBlackBox = None
LineLimit = None
MeasureTrailingSpaces = None
NoClip = None
NoFontFallback = None
NoWrap = None
value__ = None
|
requestDict = {
'instances':
[
{
"Lat": 37.4434774, "Long": -122.1652269,
"Altitude": 21.0, "Date_": "7/4/17",
"Time_": "23:37:25", "dt_": "7/4/17 23:37"
#driving meet conjestion
},
{
"Lat": 37.429302, "Long": -122.16145,
"Altitude": 20.0, "Date_": "7/4/17",
"Time_": "09:37:25", "dt_": "7/4/17 09:37"
#driving meet conjestion
}
]
} |
#!/usr/local/bin/python3
class Object(object):
def __init__(self, id):
self.id = id
self.children = []
self.parent = None
root = Object("COM")
objects = {"COM": root}
def get_object(id):
if id not in objects:
objects[id] = Object(id)
return objects[id]
with open("input.txt") as f:
for line in f.readlines():
parent, child = map(get_object, line.strip().split(")"))
parent.children.append(child)
child.parent = parent
def get_path(node):
path = []
while node:
path.insert(0, node)
node = node.parent
return path
you_path = get_path(objects["YOU"])
santa_path = get_path(objects["SAN"])
for common_ancestor_index in range(min(len(you_path), len(santa_path))):
you_node = you_path[common_ancestor_index]
santa_node = santa_path[common_ancestor_index]
if you_node != santa_node:
break
print("transfers: %d" % (len(you_path) + len(santa_path) - 2 * (common_ancestor_index + 1)))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
将每日的数据进行处理,并导出到MYSQL中,并对未生成的数据进行记录,可选择进行重跑或者手动重跑
""" |
def fizzbuzz(num):
if (num >= 0 and num % 3 == 0 and num % 5 == 0):
return "Fizz Buzz"
if (num >= 0 and num % 3 == 0):
return "Fizz"
if (num >= 0 and num % 5 == 0):
return "Buzz"
if (num >= 0):
return ""
|
dataset_paths = {
'ffhq': '',
'celeba_test': '',
'cars_train': '',
'cars_test': '',
'church_train': '',
'church_test': '',
'horse_train': '',
'horse_test': '',
'afhq_wild_train': '',
'afhq_wild_test': '',
'font_train': '/mnt/data01/AWS_S3_CONTAINER/personnel-records/1956/seg/firm/stylegan2_crops/pr',
'font_test': '/mnt/data01/AWS_S3_CONTAINER/personnel-records/1956/seg/firm/stylegan2_crops_sample/pr',
'font_gs_train': '/mnt/data01/AWS_S3_CONTAINER/personnel-records/1956/seg/firm/stylegan2_crops_grayscale/pr',
'font_gs_test': '/mnt/data01/AWS_S3_CONTAINER/personnel-records/1956/seg/firm/stylegan2_crops_grayscale_sample/pr',
'font_train_modern': '/mnt/data02/Japan/font_gen/paired_training_data/pr/labeled_validated_rendered_chars',
'font_test_modern': '/mnt/data02/Japan/font_gen/paired_training_data/pr/rendered_chars_for_overfitting',
'font_train_historical': '/mnt/data02/Japan/font_gen/paired_training_data/pr/labeled_validated_char_crops',
'font_test_historical': '/mnt/data02/Japan/font_gen/paired_training_data/pr/char_crops_for_overfitting',
}
model_paths = {
'ir_se50': 'pretrained_models/model_ir_se50.pth',
'resnet34': '/mnt/workspace/pretrained_models/resnet34-333f7ec4.pth',
'stylegan_ffhq': 'pretrained_models/stylegan2-ffhq-config-f.pt',
'stylegan_cars': 'pretrained_models/stylegan2-car-config-f.pt',
'stylegan_church': 'pretrained_models/stylegan2-church-config-f.pt',
'stylegan_horse': 'pretrained_models/stylegan2-horse-config-f.pt',
'stylegan_ada_wild': 'pretrained_models/afhqwild.pt',
'stylegan_toonify': 'pretrained_models/ffhq_cartoon_blended.pt',
'shape_predictor': 'pretrained_models/shape_predictor_68_face_landmarks.dat',
'circular_face': 'pretrained_models/CurricularFace_Backbone.pth',
'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy',
'mtcnn_rnet': 'pretrained_models/mtcnn/rnet.npy',
'mtcnn_onet': 'pretrained_models/mtcnn/onet.npy',
'moco': '/mnt/workspace/pretrained_models/moco_v2_800ep_pretrain.pt'
}
|
def v(kod):
if (k == len(kod)):
print(' '.join(kod))
return
if (len(kod) != 0):
for i in range(int(kod[-1]) + 1, n + 1):
if (str(i) not in kod):
gg = kod.copy()
gg.append(str(i))
v(gg)
else:
for i in range(1, n + 1):
gg = kod.copy()
gg.append(str(i))
v(gg)
n, k = map(int, input().split())
v([])
|
#! /usr/bin/env python3
""" Carian converter
The transliteration scheme is as follows
-------------------------------------------------------------------
| a 𐊠 | b 𐊡 | d 𐊢 | l 𐊣 | y 𐊤 | y2 𐋐 |
| r 𐊥 | L 𐊦 | L2 𐋎 | A2 𐊧 | q 𐊨 | b 𐊩 |
| m 𐊪 | o 𐊫 | D2 𐊬 | t 𐊭 | sh 𐊮 | sh2 𐊯 |
| s 𐊰 | 18 𐊱 | u 𐊲 | N 𐊳 | c 𐊴 | n 𐊵 |
| T2 𐊶 | p 𐊷 | 's,ś 𐊸 | i 𐊹 | e 𐊺 | ý,'y 𐊻 |
| k 𐊼 | k2 𐊽 | dh 𐊾 | w 𐊿 | G 𐋀 | G2 𐋁 |
| z2 𐋂 | z 𐋃 | ng 𐋄 | j 𐋅 | 39 𐋆 | T 𐋇 |
| y3 𐋈 | r2 𐋉 | mb 𐋊 | mb2 𐋋 | mb3 𐋌 | mb4 𐋍 |
| e2 𐋏 | |
-------------------------------------------------------------------
"""
def alpha_to_carian(input):
"""
Parameters
----------
input : str
Text input with syllables separated by dashes and words by spaces.
Returns
-------
output : str
Transliterated text in Carian Script
"""
# print(input.translate(script))
output = input
output = output.replace("a", "𐊠")
output = output.replace("e2", "𐋏")
output = output.replace("r2", "𐋉")
output = output.replace("z2", "𐋂")
output = output.replace("b", "𐊡")
output = output.replace("d", "𐊢")
output = output.replace("l", "𐊣")
output = output.replace("y3", "𐋈")
output = output.replace("y2", "𐋐")
output = output.replace("ý", "𐊻")
output = output.replace("'y", "𐊻")
output = output.replace("y", "𐊤")
output = output.replace("r", "𐊥")
output = output.replace("L2", "𐋎")
output = output.replace("L", "𐊦")
output = output.replace("A2", "𐊧")
output = output.replace("q", "𐊨")
output = output.replace("b", "𐊩")
output = output.replace("m", "𐊪")
output = output.replace("o", "𐊫")
output = output.replace("D2", "𐊬")
output = output.replace("t", "𐊭")
output = output.replace("sh2", "𐊯")
output = output.replace("sh", "𐊮")
output = output.replace("'s", "𐊸")
output = output.replace("ś", "𐊸")
output = output.replace("s", "𐊰")
output = output.replace("18", "𐊱")
output = output.replace("u", "𐊲")
output = output.replace("N", "𐊳")
output = output.replace("c", "𐊴")
output = output.replace("n", "𐊵")
output = output.replace("T2", "𐊶")
output = output.replace("p", "𐊷")
output = output.replace("i", "𐊹")
output = output.replace("e", "𐊺")
output = output.replace("k2", "𐊽")
output = output.replace("k", "𐊼")
output = output.replace("dh", "𐊾")
output = output.replace("w", "𐊿")
output = output.replace("G2", "𐋁")
output = output.replace("G", "𐋀")
output = output.replace("z", "𐋃")
output = output.replace("ng", "𐋄")
output = output.replace("j", "𐋅")
output = output.replace("39", "𐋆")
output = output.replace("T", "𐋇")
output = output.replace("mb2", "𐋋")
output = output.replace("mb3", "𐋌")
output = output.replace("mb4", "𐋍")
output = output.replace("mb", "𐋊")
return output
if __name__ == "__main__":
a = """
esbe
"""
b = alpha_to_carian(a)
print(b)
|
'''
(0-1 Knapsack) example
The example solves the 0/1 Knapsack Problem:
how we get the maximum value, given our knapsack just can hold a maximum weight of w,
while the value of the i-th item is a1[i], and the weight of the i-th item is a2[i]?
i = total item
w = total weigh of knapsack can carry
'''
# a1: item value
a1 = [100, 70, 50, 10]
# a2: item weight
a2 = [10, 4, 6, 12]
def knapsack01(items, weight):
if (w == 0) or (i < 0):
return 0
elif (a2[i] > w):
return knapsack01(i-1, w)
else:
return max(a1[i] + knapsack01(i-1, w-a2[i], knapsack01(i-1, w)))
if __name__ == "__main__":
i = 3
w = 12
print (knapsack01(items=i, weight=w)) |
list_fruits = ['🍎', '🥭', '🍊', '🍌']
# for fruit in list_fruits:
# print(fruit)
def find_average_height(list_heights):
temp = 0
for height in list_heights:
temp += height
average_height = temp / len(list_heights)
print(f'Average height is {round(average_height)}')
print(sum(list_heights) // len(list_heights))
# find_average_height([180, 124, 165, 173, 189, 169, 146])
def find_max(list_numbers):
maximum = list_numbers[0]
for number in list_numbers:
if number > maximum:
maximum = number
print(f'The maximum number in the list is {maximum}')
print(max(list_numbers))
# find_max([78, 65, 89, 55, 91, 64, 89])
def calculate_all_evens(type_of):
total_evens = 0
if type_of == 1:
for number in range(0, 101):
if number % 2 == 0:
total_evens += number
else:
for number in range(2, 101, 2):
total_evens += number
print(total_evens)
# calculate_all_evens(1)
def fizzbuzz():
for item in range(1, 101):
if item % 3 == 0 and item % 5 == 0:
print('fizzBuzz')
elif item % 3 == 0:
print('fizz')
elif item % 5 == 0:
print('buzz')
# fizzbuzz()
'''
- Make a password generator
'''
'''
- While loop
'''
# value = 10
# while value > 1:
# value -= 1
# print(f'This is amazing loop {value}')
#
|
administrator_user_id = 403569083402158090
reaction_message_ids = [832010993542365184, 573059396259807232]
current_year = 2021
|
class NoneTypeFont(Exception):
pass
class PortraitBoolError(Exception):
pass
class NoneStringObject(Exception):
pass
class BMPvalidationError(Exception):
pass
|
""""
题目描述
密码要求:
1.长度超过8位
2.包括大小写字母.数字.其它符号,以上四种至少三种
3.不能有相同长度超2的子串重复
说明:长度超过2的子串
输入描述:
一组或多组长度超过2的子符串。每组占一行
输出描述:
如果符合要求输出:OK,否则输出NG
示例1
输入
021Abc9000
021Abc9Abc1
021ABC9000
021$bc9000
输出
OK
NG
NG
OK
"""
def isLong(s):
if len(s) > 8:
return True
else:
return False
def isMoreClass(s):
isNum = 0
isBig = 0
isSmall = 0
isNor = 0
for n in s:
if (ord(n) - ord('0')) >= 0 and (ord(n) - ord('9')) <= 0:
isNum = 1
elif (ord(n) - ord('a')) >= 0 and (ord(n) - ord('z')) <= 0:
isSmall = 1
elif (ord(n) - ord('A')) >= 0 and (ord(n) - ord('Z')) <= 0:
isBig = 1
else:
isNor = 1
if isNum + isBig + isSmall + isNor >= 3:
return True
else:
return False
def isSubSentence(s):
for i in range(len(s) - 2):
if s[i:i + 3] in s[i + 1:]:
return False
break
return True
while True:
try:
s = input()
if isMoreClass(s) and isSubSentence(s) and isLong(s):
print('OK')
else:
print('NG')
except:
break
# if isLong(s):
# print("isLong OK")
# else:
# print("isLong NG")
# if isSubSentence(s):
# print("isSubSentence OK")
# else:
# print("isSubSentence NG")
# if isMoreClass(s):
# print("isMoreClass OK")
# else:
# print("isMoreClass NG")
|
n = str(input('Nome: '))
if n == 'Nicolas':
print('TOP')
elif n == 'Claudia':
print('Eca...')
else:
print('Olá!')
|
default_values = {
'mode': 'train',
'net': 'resnet32_cifar',
'device': 'cuda:0',
'num_epochs': 300,
'activation_type': 'deepBspline_explicit_linear',
'spline_init': 'leaky_relu',
'spline_size': 51,
'spline_range': 4,
'save_memory': False,
'knot_threshold': 0.,
'num_hidden_layers': 2,
'num_hidden_neurons': 4,
'lipschitz': False,
'lmbda': 1e-4,
'optimizer': ['SGD', 'Adam'],
'lr': 1e-1,
'aux_lr': 1e-3,
'weight_decay': 5e-4,
'gamma': 0.1,
'milestones': [150, 225, 262],
'log_dir': './ckpt',
'model_name': 'deepspline',
'resume': False,
'resume_from_best': False,
'ckpt_filename': None,
'ckpt_nmax_files': 3, # max number of saved *_net_*.ckpt
# checkpoint files at a time. Set to -1 if not restricted. '
'log_step': None,
'valid_log_step': None,
'seed': (-1),
'test_as_valid': False,
'dataset_name': 'cifar10',
'data_dir': './data',
'batch_size': 128,
# Number of subprocesses to use for data loading.
'num_workers': 4,
'plot_imgs': False,
'save_imgs': False,
'verbose': False,
'additional_info': [],
'num_classes': None
}
# This tree defines the strcuture of self.params in the Project() class.
# if it is desired to keep an entry in the first level that is also a
# leaf of deeper levels of the structure, this entry should be added to
# the first level too (e.g. as done for 'log_dir')
structure = {
'log_dir': None,
'model_name': None,
'verbose': None,
'net': None,
'knot_threshold': None,
'dataset': {
'dataset_name': None,
'log_dir': None,
'model_name': None,
'plot_imgs': None,
'save_imgs': None,
},
'dataloader': {
'data_dir': None,
'batch_size': None,
'num_workers': None,
'test_as_valid': None,
'seed': None
},
'model': {
'activation_type': None,
'spline_init': None,
'spline_size': None,
'spline_range': None,
'save_memory': None,
'knot_threshold': None,
'num_hidden_layers': None,
'num_hidden_neurons': None,
'net': None,
'verbose': None
}
}
|
class Solution:
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
k=1
m=0
for i in range(1,len(nums)):
if nums[i]>nums[i-1]:
k+=1
else:
m=max(m,k)
k=1
m=max(m,k)
return m
|
# [Newman-Conway sequence] is the one which generates the following integer sequence. 1 1 2 2 3 4 4 4 5 6 7 7….. and follows below recursive formula.
# P(1) = 1
# P(2) = 1
# for all n > 2
# P(n) = P(P(n - 1)) + P(n - P(n - 1))
def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n)
Space Complexity: O(n)
"""
# Base cases: num is 0 or 1
if num == 0:
raise ValueError
if num == 1:
return '1'
# P(1) = 1; P(2) = 1, P(3) = 2
nc_seq_nums = [0, 1, 1]
# The returned list has to be a string:
nc_seq_str = "1 1 "
for i in range(3, num + 1):
# calculating next Newman-Conway sequence value and appending
nc_seq_nums.append(nc_seq_nums[nc_seq_nums[i - 1]] + nc_seq_nums[i - nc_seq_nums[i - 1]])
# must convert to string
nc_seq_str += f"{nc_seq_nums[i]} "
return nc_seq_str[:-1] |
class Solution:
'''
如果input長度為n,那麼暴力解就是將數字兩兩相加看是不是解,
這樣的解法要算n(n-1)/2次,也就是O(n²)的時間複雜度。
'''
# def twoSum(self, nums, target):
# for i in range(len(nums)-1):
# for j in range(i+1, len(nums)):
# if nums[i] + nums[j] == target:
# return [i, j]
# def twoSum(self, nums, target):
# for i in nums:
# j = target - i
# start_index = nums.index(i)
# next_index = start_index + 1
# temp_nums = nums[next_index:]
# if j in temp_nums:
# return [nums.index(i), next_index + temp_nums.index(j)]
def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':
numMap = {}
for i in range(len(nums)):
if target - nums[i] not in numMap:
numMap[nums[i]] = i
else:
return [numMap.get(target-nums[i]), i]
# return [target-nums[i], nums[i]]
if __name__ == '__main__':
nums = [11, 2, 15, 7]
target = 9
print(Solution().twoSum(nums, target)) |
NONE = u'none'
OTHER = u'other'
PRIMARY = u'primary'
JUNIOR_SECONDARY = u'junior_secondary'
SECONDARY = u'secondary'
ASSOCIATES = u'associates'
BACHELORS = u'bachelors'
MASTERS = u'masters'
DOCTORATE = u'doctorate'
|
RESTAURANT_LIST_GET = {
'tags': ['음식점 정보'],
'description': '음식점 목록 조회',
'parameters': [
{
'name': 'sector',
'description': '음식점 종류(선호메뉴)\n'
'음식 종류가 "아무거나"일 경우 "all"',
'in': 'path',
'type': 'str',
'required': True
},
{
'name': 'reservationCount',
'description': '예약 인원 수\n'
'기본값: 1',
'in': 'query',
'type': 'int',
'required': False
},
{
'name': 'reservationTime',
'description': '예약 시간(hh:mm)\n'
'기본값: 12:00',
'in': 'query',
'type': 'str',
'required': False
},
# {
# 'name': 'priceLevel',
# 'description': '가격대\n'
# '1: 저렴\n'
# '2: 보통\n'
# '3: 기분',
# 'in': 'query',
# 'type': 'int',
# 'required': True
# },
{
'name': 'latitude',
'description': '위도',
'in': 'query',
'type': 'float',
'required': True
},
{
'name': 'longitude',
'description': '경도',
'in': 'query',
'type': 'float',
'required': True
},
{
'name': 'sortType',
'description': '정렬 기준\n'
'1: 예약 인기 높은순(기본값)\n'
'2: 거리순(가까운 거리부터)\n'
'3: 가격순(저 -> 고)\n'
'4: 가격순(고 -> 저)\n'
'5 이상: 평점순(고 -> 저)',
'in': 'query',
'type': 'int',
'required': False
},
{
'name': 'page',
'description': '음식점을 5개 단위로 pagination하기 위함\n'
'기본값: 1',
'in': 'query',
'type': 'int',
'required': False
}
],
'responses': {
'200': {
'description': '목록 조회 성공',
'examples': {
'': [
{
'name': '맛있고 비싼 식땅',
'rating': 4.0,
'distance': 1.0766231543,
'thumbnail': None
},
{
'name': '맛있고 싼 식땅',
'rating': 3.8,
'distance': 1.0767234142,
'thumbnail': None
},
{
'name': '맛있는 식땅',
'rating': 4.2,
'distance': 1.0768236836,
'thumbnail': '1e3b75c9eea13.png'
}
]
}
},
'204': {
'description': '목록 조회 실패(예약 시간이 현재보다 과거)'
}
}
}
RESTAURANT_LIST_POST = {
'tags': ['음식점 정보'],
'description': '새로운 음식점 추가',
'parameters': [
{
'name': 'sector',
'description': '음식점 종류',
'in': 'path',
'type': 'str',
'required': True
},
{
'name': 'name',
'description': '음식점 이름',
'in': 'json',
'type': 'str',
'required': True
},
{
'name': 'priceAvg',
'description': '1인당 평균 가격',
'in': 'json',
'type': 'int',
'required': True
},
{
'name': 'latitude',
'description': '음식점 위도',
'in': 'json',
'type': 'float',
'required': True
},
{
'name': 'longitude',
'description': '음식점 경도',
'in': 'json',
'type': 'str',
'required': True
},
{
'name': 'address',
'description': '음식점 주소',
'in': 'json',
'type': 'str',
'required': True
},
{
'name': 'openTime',
'description': '음식점 여는 시간(HH:MM)',
'in': 'json',
'type': 'str',
'required': True
},
{
'name': 'closeTime',
'description': '음식점 닫는 시간(HH:MM)',
'in': 'json',
'type': 'str',
'required': True
},
{
'name': 'closeDays',
'description': '음식점 휴무일(0: 일요일, 1: 월요일, ..., 6: 토요일)\n'
'ex) [0, 5, 6]',
'in': 'json',
'type': 'list',
'required': True
},
{
'name': 'minReservationCount',
'description': '최소 예약 인원',
'in': 'json',
'type': 'int',
'required': True
},
{
'name': 'maxReservationCount',
'description': '최대 예약 인원',
'in': 'json',
'type': 'int',
'required': True
},
{
'name': 'reservationGapMinutes',
'description': '예약을 위한 최소 텀(분)',
'in': 'json',
'type': 'int',
'required': True
}
],
'responses': {
'201': {
'description': '음식점 추가 성공'
}
}
}
|
class SteepshotBotError(Exception):
msg = {}
def get_msg(self, locale: str = 'en') -> str:
return self.msg.get(locale, self.msg.get('en', 'Some error occurred: ')) + str(self)
class SteepshotServerError(SteepshotBotError):
msg = {
'en': 'Some Steepshot error occurred: '
}
class SteemError(SteepshotBotError):
msg = {
'en': 'Some Steem error occurred: '
}
class PostNotFound(SteepshotBotError):
msg = {
'en': 'This post was not found: '
}
class VotedSimilarily(SteepshotBotError):
msg = {
'en': 'You have already voted in a similar way: '
}
|
class Instrument:
insId: int
name: str
urlName: str
instrument: int
isin: str
ticker: str
yahoo: str
sectorId: int
marketId: int
branchId: int
countryId: int
listingDate: str
def __init__(self, insId, name, urlName, instrument, isin, ticker, yahoo, sectorId, marketId, branchId, countryId,
listingDate):
self.insId = insId
self.name = name
self.urlName = urlName
self.instrument = instrument
self.isin = isin
self.ticker = ticker
self.yahoo = yahoo
self.sectorId = sectorId
self.marketId = marketId
self.branchId = branchId
self.countryId = countryId
self.listingDate = listingDate
def __str__(self):
return '{}: {}'.format(self.insId, self.name)
def __repr__(self):
return '{}: {}'.format(self.insId, self.name)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 20:34:09 2019
@author: Enrique Lopez Ortiz
"""
# ===========================
# PARÁMETROS DE CONFIGURACIÓN
# ===========================
# ¿Quieres preprocesar un fichero de nodos o de aristas?
el_input_es_un_fichero_de_nodos = True
# Nombre de los ficheros que se crearán
input = "nodes2-copia.csv"
output = "nodes2.csv"
# ===========================
# FUNCIONES AUXILIARES
# ===========================
def crea_fichero_aristas(file):
with open(file, 'r', encoding='utf-8') as infile:
for line in infile:
l = [x.strip() for x in line.split(",")]
if len(l) == 8:
escribe_arista(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7])
def crea_fichero_nodos(file):
with open(file, 'r', encoding='utf-8') as infile:
for line in infile:
l = [x.strip() for x in line.split(",")]
if len(l) >= 8:
escribe_nodo(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7])
def escribe_arista(n1,n2,dist,visib,sonido,transit,lock,flow):
arista = str(n1)+","+str(n2)+","+str(dist)+","+str(visib)+","+str(sonido)+","+str(transit)+","+str(lock)+","+str(flow)
with open(output, "a") as fp:
print(arista, file = fp)
def escribe_nodo(id,x,y,size,cap,hide,info,lock):
arista = str(id)+","+str(x)+","+str(y)+","+str(size)+","+str(cap)+","+str(hide)+","+str(info)+","+str(lock)
with open(output, "a") as fp:
print(arista, file = fp)
# ===========================
# CREACIÓN DEL FICHERO
# ===========================
if el_input_es_un_fichero_de_nodos:
crea_fichero_nodos(input)
else:
crea_fichero_aristas(input)
|
class WeightedUnionFind(object):
def __init__(self, n):
self.n = n
self.parents = range(n)
self.sizes = [1] * n
def find(self, p):
while p != self.parents[p]:
p = self.parents[p]
return p
def is_connected(self, p, q):
return self.find(p) == self.find(q)
def __len__(self):
return self.n
def union(self, p, q):
"""
>>> uf = WeightedUnionFind(5)
>>> uf.parents = [0, 0, 0, 3, 3]
>>> uf.sizes = [3, 1, 1, 2, 1]
>>> uf.union(2, 3)
>>> uf.parents
[0, 0, 0, 0, 3]
>>> uf.sizes
[5, 1, 1, 2, 1]
"""
p_parent = self.parents[p]
q_parent = self.parents[q]
if p_parent == q_parent:
return
if self.sizes[p_parent] < self.sizes[q_parent]:
self.sizes[q_parent] += self.sizes[p_parent]
self.parents[p_parent] = q_parent
else:
self.sizes[p_parent] += self.sizes[q_parent]
self.parents[q_parent] = p_parent
self.n -= 1
|
num = int(input("Enter a number: "))
iter_num = 0
pwr = 0
if num == 0:
root = 0
else:
root = 1
while root**pwr != num and root < num:
while pwr < 6:
iter_num += 1
if root**pwr == num:
print(root, "^", pwr, sep="")
break
pwr += 1
if root**pwr == num:
break
else:
pwr = 0
root += 1
if root**pwr != num:
print("Not found")
print("Iterations:", iter_num) |
def dict_recursive_bypass(dictionary: dict, on_node: callable) -> dict:
"""
Recursive bypass dictionary
:param dictionary:
:param on_node: callable for every node, that get value of dict end node as parameters
"""
res = {}
for k, v in dictionary.items():
if isinstance(v, dict):
res[k] = dict_recursive_bypass(v, on_node)
else:
res[k] = on_node(v)
return res
def dict_pair_recursive_bypass(dictionary1: dict, dictionary2: dict, on_node: callable) -> dict:
"""
Recursive bypass dictionary
:param dictionary1:
:param dictionary2:
:param on_node: callable for every node, that get value of dict end node as parameters
"""
res = {}
for k, v in dictionary1.items():
if isinstance(v, dict):
res[k] = dict_pair_recursive_bypass(v, dictionary2[k], on_node)
else:
res[k] = on_node(v, dictionary2[k])
return res
|
expected_output = {
"route-information": {
"route-table": {
"active-route-count": "1250009",
"destination-count": "1250009",
"hidden-route-count": "0",
"holddown-route-count": "0",
"rt": {
"rt-announced-count": "1",
"rt-destination": "10.55.0.0",
"rt-entry": {
"active-tag": "*",
"age": {"#text": "4:32"},
"announce-bits": "2",
"announce-tasks": "0-KRT 1-BGP_RT_Background",
"as-path": "AS path:2 I",
"bgp-path-attributes": {
"attr-as-path-effective": {
"aspath-effective-string": "AS path:",
"attr-value": "2 I",
}
},
"bgp-rt-flag": "Accepted",
"gateway": "10.30.0.2",
"local-as": "1",
"local-preference": "100",
"nh": {
"nh-string": "Next hop",
"session": "0xf44",
"to": "10.30.0.2",
"via": "ge-0/0/2.0",
},
"nh-address": "0x17b226b4",
"nh-index": "605",
"nh-reference-count": "800002",
"nh-type": "Router",
"peer-as": "2",
"peer-id": "192.168.19.1",
"preference": "170",
"preference2": "101",
"protocol-name": "BGP",
"rt-entry-state": "Active Ext",
"task-name": "BGP_10.144.30.0.2",
"validation-state": "unverified",
},
"rt-entry-count": {"#text": "1"},
"rt-prefix-length": "32",
"tsi": {"#text": "KRT in-kernel 10.55.0.0/32 -> {10.30.0.2}"},
},
"table-name": "inet.0",
"total-route-count": "1250009",
}
}
}
|
#!/usr/bin/python3
# python 基础语法笔记
def choose_method(a, b):
"""
python中的if语句
python中没有switch语句
只有 if: elif: else:
判断语句
:param a:
:param b:
:return:
"""
if a > b:
print("%d>%d" % (a, b))
else:
print("%d<=%d" % (a, b))
if a > 0:
print("%d>%d" % (a, 0))
elif a < 0:
print("%d<%d" % (a, 0))
else:
print("%d=%d" % (a, 0))
def boolTest():
a = True
b = False
if a:
print("a is true")
else:
print("a is true")
# bool(1-var) python 取反
print("b取反=%s" % (bool(1-b)))
def loop_method():
"""
循环写法
for var in list :
pass
其中 var 表示list中的变量 list为数组或者集合
:return:
"""
for i in range(10):
print(i)
def str_method():
"""
python 中的字符串处理方式
+ 加号 和 java中的一致
""%(a,b) %s %d 等表示变量的占位符
:return:
"""
a = "aa"
b = "bb"
c = a + b
print(c)
print("a=%s,b=%s" % (a, b))
"""
主函数 脚本启动入口
"""
if __name__ == '__main__':
# print属于基本打印函数
print("基础语法")
choose_method(-12, 14)
str_method()
boolTest()
|
""" Summation puzzle
Example:
pot + pan = bib
dog + cat = pig
boy+ girl = baby
"""
def puzzle_solve(k, S, U, solutionSeq): # we have also passed puzzles solution samples to verify the configuarion
""" Input: an integer k : length of the subset made by combination of letters,
S: Sequence of unique letters , U: Universal Set of unique letters Example: {a, b, c} """
for element in U:
# add element to the end of S
# S.append(element) # S is list
S += element # S is string
# remove element from U
U.remove(element)
if k == 1:
# test whether string S is a configuartion that solves the puzzle
# sequnce_string = "".join(S) # list
sequnce_string = S
if sequnce_string in solutionSeq: # S solves the puzzle
print("Solution Found: ", S)
return "Solution Found: ", S
else: # No solution found
print("No solution found. Configuration = {}".format(sequnce_string))
else:
puzzle_solve(k-1, S, U, solutionSeq) # recursive call to obtain configuration of desired length
#the puzzle was not solved with element 'element ' which was added to S
# so we remove it from S and add it back to U
# S.remove(element) # S is list
S = S[:-1]
U.append(element)
if __name__ == "__main__":
solutionSeq = ['bca']
k = 3
# S = [] # list
S = ""
U = ['a', 'b', 'c']
puzzle_solve(3, S, U, solutionSeq)
solutionSeq = ['pot']
k = 3
# S = [] # list
S = ""
U = ['p', 'r', 'o', 't' ]
print(U)
puzzle_solve(3, S, U, solutionSeq)
|
# class MyHashSet:
# def __init__(self):
# """
# Initialize your data structure here.
# """
# self._range = 10000
# self.list = [[]]*self._range
# def _hash(self, key: int) -> int:
# return key%self._range
# def _search(self, key: int) -> int:
# pool = self.list[self._hash(key)]
# if len(pool)==0:
# return -1
# else:
# for idx in range(len(pool)):
# if pool[idx]==key:
# return idx
# return -1
# def add(self, key: int) -> None:
# if self.contains(key)==False:
# self.list[self._hash(key)].append(key)
# def remove(self, key: int) -> None:
# if self.contains(key)==True:
# idx = self._search(key)
# self.list[self._hash(key)].pop(idx)
# def contains(self, key: int) -> bool:
# """
# Returns true if this set contains the specified element
# """
# if self._search(key)==-1:
# return False
# else:
# return True
class MyHashSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.keyRange = 769
self.bucketArray = [Bucket() for i in range(self.keyRange)]
def _hash(self, key):
return key % self.keyRange
def add(self, key):
if not self.contains(key):
self.bucketArray[self._hash(key)].insert(key)
def remove(self, key):
if self.contains(key):
self.bucketArray[self._hash(key)].delete(key)
def contains(self, key):
bucketIndex = self._hash(key)
return self.bucketArray[bucketIndex].exists(key)
class Node:
def __init__(self, value, nextNode=None):
self.value = value
self.next = nextNode
class Bucket:
def __init__(self):
self.head = Node(0) # pseudo head
def insert(self, newValue):
if not self.exists(newValue): # if not existed, add the new element to the head
newNode = Node(newValue, self.head.next)
self.head.next = newNode
def delete(self, value):
prev = self.head
curr = self.head.next
while curr is not None:
if curr.value == value:
prev.next = curr.next
return
prev = curr
curr = curr.next
def exists(self, value):
curr = self.head.next
while curr is not None:
if curr.value==value:
return True
curr = curr.next
return False
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key) |
SERVER_EMAIL = 'SERVER_EMAIL'
SERVER_PASSWORD = 'SERVER_PASSWORD'
WATCHED = {
'service': ['service'],
'process': ['process'],
}
NOTIFICATION_DETAILS = {
'service': [
{
'identifiers': ['identifiers'],
'to_emails': ['nimesh.aug11@gmail.com'],
'subject': 'subject',
'body': 'body'
},
],
'process': [
{
'identifiers': ['identifiers'],
'to_emails': ['nimesh.aug11@gmail.com'],
'subject': 'subject',
'body': 'body'
},
]
}
|
x = int(input('1º numero: '))
y = int(input('2º numero: '))
z = int(input('3º numero: '))
m = x
if z < x and z < y:
m = z
if y < x and y < z :
m = y
ma = x
if z > x and z > y:
ma = z
if y > x and y > z :
ma = y
print("O maior numero foi {} e o menor foi {}".format(ma, m))
|
# -*- coding: utf-8 -*-
"""Zeigen -- find protonated waters in structures.
\b
For complete help visit https://github.com/hydrationdynamics/zeigen
\b
License: BSD-3-Clause
Copyright © 2021, GenerisBio LLC.
All rights reserved.
""" # noqa: D301
|
print("HelloWorld")
print(len("HelloWorld"))
a_string = "Hello"
b_string = "World"
print("a_string + b_string: ", a_string+b_string)
c_string = "abcdefghijklmnopqrstuvwxyz"
print("num of letters from a to z", len(c_string))
print(c_string[:3]) #abc
print(c_string[23:]) #xyz
#step count reverse
print(c_string[::-1])
#step count forward
print(c_string[::2])
print(c_string.upper())
print(c_string.split('l'))
#string formatting
userName = "San"
color = "blue"
print(f"{userName}'s fav color is {color}")
print("{}'s fav color is {}".format(userName, color)) |
def substituter(seq, substitutions):
for item in seq:
if item in substitutions:
yield substitutions[item]
else:
yield item
|
a = input()
b = input()
ans = 0
while True:
s = a.find(b)
if s < 0:
break
ans += 1
a = a[s+len(b):]
print(ans)
|
"""Externalized strings for better structure and easier localization"""
setup_greeting = """
Dwarf - First run configuration
Insert your bot's token, or enter 'cancel' to cancel the setup:"""
not_a_token = "Invalid input. Restart Dwarf and repeat the configuration process."
choose_prefix = """Choose a prefix. A prefix is what you type before a command.
A typical prefix would be the exclamation mark.
Can be multiple characters. You will be able to change it later and add more of them.
Choose your prefix:"""
confirm_prefix = """Are you sure you want {0} as your prefix?
You will be able to issue commands like this: {0}help
Type yes to confirm or no to change it"""
setup_finished = """
The configuration is done. Leave this window always open to keep your bot online.
All commands will have to be issued through Discord's chat,
*this window will now be read only*.
Press enter to continue"""
prefix_singular = "Prefix"
prefix_plural = "Prefixes"
use_this_url = "Use this url to bring your bot to a server:"
bot_is_online = "{} is now online."
connected_to = "Connected to:"
connected_to_servers = "{} servers"
connected_to_channels = "{} channels"
connected_to_users = "{} users"
no_prefix_set = "No prefix set. Defaulting to !"
logging_into_discord = "Logging into Discord..."
invalid_credentials = """Invalid login credentials.
If they worked before Discord might be having temporary technical issues.
In this case, press enter and try again later.
Otherwise you can type 'reset' to delete the current configuration and
redo the setup process again the next start.
> """
keep_updated_win = """Make sure to keep your bot updated by running the file
update.bat"""
keep_updated = """Make sure to keep Dwarf updated by using:\n
git pull\npip3 install --upgrade
git+https://github.com/Rapptz/discord.py@async"""
official_server = "Official server: {}"
invite_link = "https://discord.me/AileenLumina"
update_the_api = """\nYou are using an outdated discord.py.\n
Update your discord.py with by running this in your cmd
prompt/terminal:\npip3 install --upgrade git+https://
github.com/Rapptz/discord.py@async"""
command_disabled = "That command is disabled."
exception_in_command = "Exception in command '{}'"
error_in_command = "Error in command '{}' - {}: {}"
not_available_in_dm = "That command is not available in DMs."
owner_recognized = "{} has been recognized and set as owner."
|
# Lecture 5, Problem 9
def semordnilapWrapper(str1, str2):
# A single-length string cannot be semordnilap.
if len(str1) == 1 or len(str2) == 1:
return False
# Equal strings cannot be semordnilap.
if str1 == str2:
return False
return semordnilap(str1, str2)
def semordnilap(str1, str2):
'''
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap;
False otherwise.
'''
if len(str1) != len(str2):
return False
elif len(str1) == 0 or len(str2) == 0:
return True
elif len(str1) == 0 and len(str2) == 0:
return False
elif str1[0] != str2[-1]:
return False
return semordnilap(str1[1:], str2[:-1]) |
#!/usr/bin/env python
# Monitoring the Mem usage of a Sonicwall
# Herward Cooper <coops@fawk.eu> - 2012
# Uses OID 1.3.6.1.4.1.8741.1.3.1.4.0
sonicwall_mem_default_values = (35, 40)
def inventory_sonicwall_mem(checkname, info):
inventory=[]
inventory.append( (None, None, "sonicwall_mem_default_values") )
return inventory
def check_sonicwall_mem(item, params, info):
warn, crit = params
state = int(info[0][0])
perfdata = [ ( "cpu", state, warn, crit ) ]
if state > crit:
return (2, "CRITICAL - Mem is %s percent" % state, perfdata)
elif state > warn:
return (1, "WARNING - Mem is %s percent" % state, perfdata)
else:
return (0, "OK - Mem is %s percent" % state, perfdata)
check_info["sonicwall_mem"] = (check_sonicwall_mem, "Sonicwall Mem", 1, inventory_sonicwall_mem)
snmp_info["sonicwall_mem"] = ( ".1.3.6.1.4.1.8741.1.3.1.4", [ "0" ] )
|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 5 2017
@author: maque
Note that the demo code is from the below link:
http://interactivepython.org/courselib/static/pythonds/SortSearch/Hashing.html
and add some other operations in the exercises.
"""
class Hash_table:
'''
put(key,val) Add a new key-value pair to the map. If the key is already in
the map then replace the old value with the new value.
get(key) Given a key, return the value stored in the map or None otherwise.
del Delete the key-value pair from the map using a statement of the form del map[key].
len() Return the number of key-value pairs stored in the map.
in Return True for a statement of the form key in map, if the given key
is in the map, False otherwise.
Note that the hash_function implements the simple remainder method. The
collision resolution technique is linear probing with a “plus 1” rehash function.
'''
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hash_value = self.hash_function(key, len(self.slots))
if self.slots[hash_value] == None:
self.slots[hash_value] = key
self.data[hash_value] = data
elif self.slots[hash_value] == key:
self.data[hash_value] = data
else:
next_slot = self.rehash(hash_value, len(self.slots))
while self.slots[next_slot] != None and self.slots[next_slot] != key:
next_slot = self.rehash(next_slot, len(self.slots))
if self.slots[next_slot] == None:
self.slots[next_slot] = key
self.data[next_slot] = data
else:
self.data[next_slot] = data
def hash_function(self, key, size):
return key % size
def rehash(self, old_hash, size):
return (old_hash + 1) % size
def get(self, key):
start_slot = self.hash_function(key, len(self.slots))
data = None
stop = False
found = False
position = start_slot
while self.slots[position] != None and not found and not stop:
if self.slots[position] == key:
found = True
data = self.data[position]
else:
position = self.rehash(position, len(self.slots))
if position == start_slot:
stop = True
return data
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, data):
self.put(key, data)
def __delitem__(self, key):
if key in self.slots:
position = self.slots.index(key)
self.slots[position] = None
self.data[position] = None
#def len(self):
def __len__(self):
length = 0
for key in self.slots:
if key != None:
length = length + 1
return length
def __contains__(self, key):
return key in self.slots
test_hash = Hash_table()
test_hash[54] = 'cat'
test_hash[26] = 'dog'
test_hash[93] = 'lion'
test_hash[17] = 'tiger'
test_hash[77] = 'bird'
test_hash[31] = 'cow'
test_hash[44] = 'goat'
test_hash[55] = 'pig'
test_hash[20] = 'chicken'
print(test_hash.slots)
print(test_hash.data)
print(test_hash[20])
print(test_hash[17])
test_hash[20] = 'duck'
print(test_hash[20])
print(test_hash[99])
del test_hash[54]
print(test_hash.slots)
print(test_hash.data)
77 in test_hash
100 in test_hash
print(len(test_hash))
|
title = 'Projects'
class Card:
def __init__(self, section, url, name, description, image):
self.section = section; self.url = url;
self.image = image; self.name = name; self.description = description
cards = [
Card('2018', 'resources/projects/awg_highres.jpg', 'Automatic Nanomanipulation Platform', 'electric tweezers research system for nanowire control', 'resources/projects/awg.png'),
Card('2018', 'resources/projects/alluvial_highres.jpg', 'Alluvial', 'three-day hexapod robot', 'resources/projects/alluvial.png'),
Card('2018', 'https://ras.ece.utexas.edu', 'UT IEEE RAS Website', 'rewritten in Bootstrap', 'resources/projects/ras.png'),
Card('2017', 'resources/projects/curmudgeon_highres.png', 'Curmudgeon', 'three-day jumping robot', 'resources/projects/curmudgeon.png'),
Card('2016', 'resources/projects/liberty_highres.jpg', 'Freedom to Make', 'maker spirit statue', 'resources/projects/liberty.jpg'),
Card('2016', 'resources/projects/chess_highres.jpg', 'Lasered Chess', 'an exercise in rapid prototyping', 'resources/projects/chess.jpg'),
Card('2016', 'resources/projects/mesa_highres.jpg', 'Battletank Mesa', 'dual-monitor workstation', 'resources/projects/mesa.jpg'),
Card('2016', 'resources/projects/piano_highres.png', 'PIano', 'Raspberry Pi keyboard system', 'resources/projects/piano.png'),
Card('2016', 'resources/projects/markovi_highres.jpg', 'MARKOVI', 'balancing robot chassis', 'resources/projects/markovi.jpg'),
Card('2016', 'resources/projects/dckx_highres.png', 'DCKX', 'xkcd headline illustrator', 'resources/projects/dckx.png'),
Card('2016', 'resources/research/hitr/hitr.jpg', 'Head Impact Test Rig', 'ballistic baseball research system', 'resources/projects/hitr.png'),
Card('2016', 'resources/research/fire/poster.pdf', 'Energy Storage Demo Rig', 'pumped-storage hydroelectricity demonstration model', 'resources/projects/fire.jpg'),
Card('2015', 'resources/projects/ultron_highres.jpg', 'Ultron', 'wooden competition roomba', 'resources/projects/ultron.jpg'),
Card('2015', 'resources/projects/sgi_highres.jpg', 'Sensel Gesture Interface', 'Swype-style keyboard with relative positioning', 'resources/projects/sgi.png'),
Card('2015', 'resources/projects/giraphphe_highres.jpg', 'GiraPHPHe', 'FTC Team 4290 2014-2015 pneumatic powerhouse', 'resources/projects/giraphphe.png'),
Card('2014', 'resources/projects/fermi_highres.jpg', 'FERmi 14', 'symmetrical teleoperated sumobot', 'resources/projects/fermi.jpg'),
Card('2014', 'resources/projects/pov.gif', 'POV Globe', 'persistence-of-vision LEDs', 'resources/projects/pov.png'),
Card('2014', 'resources/projects/4290_2014_highres.png', 'FTC 4290 2013-2014', 'experiments in gearing', 'resources/projects/4290_2014.png'),
Card('2014', 'resources/projects/sinusoidesque_highres.png', 'Sinusoidesque', 'simple arbitrary "sinusoid" visualizer', 'resources/projects/sinusoidesque.png'),
Card('2013', 'resources/projects/4290_2013_highres.png', 'FTC 4290 2012-2013', 'holonomic drives are hard', 'resources/projects/4290_2013.png'),
Card('2012', 'resources/projects/creator_3d_highres.png', 'Creator 3D', '"stochastic" "constraint solving" CAD sketcher', 'resources/projects/creator_3d.png'),
Card('2012', 'resources/projects/phobia_highres.jpg', 'PHobia', 'FTC Team 4290 2011-2012 gateway competition robot', 'resources/projects/phobia.png'),
Card('2012', 'resources/projects/tetris_highres.png', 'Tetris', 'blocks in TI-89 TI-BASIC', 'resources/projects/tetris.png'),
Card('2012', 'resources/projects/mendelssohn_highres.png', 'Mendelssohn', '3D printing from scratch', 'resources/projects/mendelssohn.png'),
]
content="""<header>
<h1>Projects / Daniel Teal</h1>
<p>I build things. Hardware, software, electronics. Here are some of them in chronological order.</p>
<p>Some favorites are the Automatic Electric Nanomanipulation platform, the Head Impact Test Rig, Ultron, and GiraPHPHe.</p>
<p>You may also be interested in my <a href="research.html">research</a>.</p>
</header>"""
sections = []
for card in cards:
if not card.section in sections:
sections.append(card.section)
content += '<div class="section">' + card.section + '</div>\n'
content += '<a class="card"' + (' href="' + card.url + '"' if card.url else '') + '>\n'
content += '<div class="left"><img src="' + card.image + '" alt="' + card.name + '"></div>\n'
content += '<div class="right"><h2>' + card.name + '</h2><p>' + card.description + '</p></div></a>\n'
|
class LastPassError(Exception):
def __init__(self, output):
self.output = output
class CliNotInstalledException(Exception):
pass
|
def grad_tmp(temp, lat: np.ndarray, lon: np.ndarray) -> np.ndarray:
"""grad_eqv_ptntl_tmp.
calcureta gradient of temperature [K/100km]
Args:
eqv_ptntl_t:
lat (np.ndarray): lat
lon (np.ndarray): lon
Returns:
np.ndarray:
"""
# horizontal equivalent_potential_temperature gradient.
de_dx = [
np.array((temp[i][j] - temp[i][j-1]) / 2 + (temp[i][j+1] - temp[i][j]) / 2) / ((lon[j+1] - lon[j-1]) * 1.11 * math.cos(math.radians(lat[i])))
if j not in (0, len(temp[0]) - 1)
else
np.nan
for i in range(len(temp))
for j in range(len(temp[0]))
]
de_dx = np.array(de_dx).reshape(len(temp), len(temp[0]))
de_dy = [
np.array((temp[i][j] - temp[i-1][j]) / 2 + (temp[i+1][j] - temp[i][j]) / 2) / ((lat[1] - lat[0]) * 1.11)
if i not in (0, len(temp) - 1)
else
np.nan
for i in range(len(temp))
for j in range(len(temp[0]))
]
de_dy = np.array(de_dy).reshape(len(temp), len(temp[0]))
return (de_dx ** 2 + de_dy ** 2) ** 0.5
|
n=int(input())
arr=[int(x) for x in input().split()]
brr=[int(x) for x in input().split()]
my_list=[]
for i in arr[1:]:
my_list.append(i)
for i in brr[1:]:
my_list.append(i)
for i in range(1,n+1):
if i in my_list:
if i == n:
print("I become the guy.")
break
else:
continue
else:
print("Oh, my keyboard!")
break
|
'''
Need 3 temporary variables to find the longest substring: start, maxLength,
and usedChars.
Start by walking through string of characters, one at a time.
Check if the current character is in the usedChars map, this would mean we
have already seen it and have stored it's corresponding index.
If it's in there and the start index is <= that index, update start
to the last seen duplicate's index+1. **This will put the start index at just
past the current value's last seen duplicate.** This allows us to have the
longest possible substring that does not contain duplicates.
If it's not in the usedChars map, we can calculate the longest substring
seen so far. Just take the current index minus the start index. If that
value is longer than maxLength, set maxLength to it.
Finally, update the usedChars map to contain the current value that we just
finished processing.
'''
class Solution:
# def lengthOfLongestSubstring(self, s):
# start = maxLength = 0
# usedChar = {}
# for i in range(len(s)):
# print("Iteration number = {}".format(i))
# if s[i] in usedChar and start <= usedChar[s[i]]:
# start = usedChar[s[i]] + 1
# print("start = {}".format(start))
# else:
# maxLength = max(maxLength, i - start + 1)
# usedChar[s[i]] = i
# print("usedChar = {}".format(usedChar))
# print("===")
# return maxLength
# def lengthOfLongestSubstring(self, s: str) -> int:
# seen = {}
# l = 0
# output = 0
# for r in range(len(s)):
# """
# There are two cases if s[r] in seen:
# case1: s[r] is inside the current window, we need to change the window by moving left pointer to seen[s[r]] + 1.
# case2: s[r] is not inside the current window, we can keep increase the window
# """
# if s[r] not in seen:
# # + 1 is to compensate the 0-indexed
# output = max(output, r-l+1)
# else:
# if seen[s[r]] < l:
# output = max(output, r-l+1)
# else:
# l = seen[s[r]] + 1
# seen[s[r]] = r
# return output
# def lengthOfLongestSubstring(self, s: str) -> int:
# """
# :type s: str
# :rtype: int abcabcbb
# """
# if len(s) == 0:
# return 0
# seen = {}
# left, right = 0, 0
# longest = 1
# while right < len(s):
# if s[right] in seen:
# left = max(left, right)
# longest = max(longest, right - left + 1)
# seen[s[right]] = right
# right += 1
# print(left, right, longest)
# print(seen)
# return longest
def lengthOfLongestSubstring(self, s: str) -> int:
seen = {}
mx = left = 0
for right, c in enumerate(s):
if c in seen:
left = max(left, seen[c] + 1)
seen[c] = right
mx = max(mx, right-left+1)
return mx
s = Solution()
print(s.lengthOfLongestSubstring("abcabcbb"))
|
class APICONTROLLERNAMEController(apicontrollersbase.APIOperationBase):
def __init__(self, apirequest):
super(APICONTROLLERNAMEController, self).__init__(apirequest)
return
def validaterequest(self):
logging.debug('performing custom validation..')
#validate required fields
#if (self._request.xyz == "null"):
# raise ValueError('xyz is required')
return
def getrequesttype(self):
'''Returns request type'''
return 'APICONTROLLERNAMERequest'
def getresponseclass(self):
''' Returns the response class '''
return apicontractsv1.APICONTROLLERNAMEResponse() |
pesos = []
q = int(input('Analisar quantas pessoas? '))
for i in range(1, q + 1):
pesos.append(float(input(f'Peso da {i}ª pessoa: ')))
print(f'\nO maior peso lido foi de {max(pesos)}Kg')
print(f'O menor peso lido foi de {min(pesos)}Kg')
|
class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def sortColors(self, nums):
# write your code here
if nums == None or len(nums) <= 1:
return
pl = 0
pr = len(nums) - 1
i = 0
while i <= pr:
if nums[i] == 0:
nums = self.swap(nums, pl, i)
pl += 1
i += 1
elif nums[i] == 1:
i += 1
else:
nums = self.swap(nums, pr, i)
pr -= 1
return nums
def swap(self, a, i, j):
tmp = a[i]
a[i] = a[j]
a[j] = tmp
return a
|
# Leo colorizer control file for c mode.
# This file is in the public domain.
# Properties for c mode.
properties = {
"commentEnd": "*/",
"commentStart": "/*",
"doubleBracketIndent": "false",
"indentCloseBrackets": "}",
"indentNextLine": "\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|for\\s*\\(.*\\))[^{;]*)",
"indentOpenBrackets": "{",
"lineComment": "//",
"lineUpClosingBracket": "true",
"wordBreakChars": ",+-=<>/?^&*",
}
# Attributes dict for c_main ruleset.
c_main_attributes_dict = {
"default": "null",
"digit_re": "(0x[[:xdigit:]]+[lL]?|[[:digit:]]+(e[[:digit:]]*)?[lLdDfF]?)",
"escape": "\\",
"highlight_digits": "true",
"ignore_case": "false",
"no_word_sep": "",
}
# Attributes dict for c_cpp ruleset.
c_cpp_attributes_dict = {
"default": "KEYWORD2",
"digit_re": "(0x[[:xdigit:]]+[lL]?|[[:digit:]]+(e[[:digit:]]*)?[lLdDfF]?)",
"escape": "\\",
"highlight_digits": "true",
"ignore_case": "false",
"no_word_sep": "",
}
# Attributes dict for c_include ruleset.
c_include_attributes_dict = {
"default": "KEYWORD2",
"digit_re": "(0x[[:xdigit:]]+[lL]?|[[:digit:]]+(e[[:digit:]]*)?[lLdDfF]?)",
"escape": "\\",
"highlight_digits": "true",
"ignore_case": "false",
"no_word_sep": "",
}
# Dictionary of attributes dictionaries for c mode.
attributesDictDict = {
"c_cpp": c_cpp_attributes_dict,
"c_include": c_include_attributes_dict,
"c_main": c_main_attributes_dict,
}
# Keywords dict for c_main ruleset.
c_main_keywords_dict = {
"NULL": "literal2",
"asm": "keyword2",
"asmlinkage": "keyword2",
"auto": "keyword1",
"break": "keyword1",
"case": "keyword1",
"char": "keyword3",
"const": "keyword1",
"continue": "keyword1",
"default": "keyword1",
"do": "keyword1",
"double": "keyword3",
"else": "keyword1",
"enum": "keyword3",
"extern": "keyword1",
"false": "literal2",
"far": "keyword2",
"float": "keyword3",
"for": "keyword1",
"goto": "keyword1",
"huge": "keyword2",
"if": "keyword1",
"inline": "keyword2",
"int": "keyword3",
"long": "keyword3",
"near": "keyword2",
"pascal": "keyword2",
"register": "keyword1",
"return": "keyword1",
"short": "keyword3",
"signed": "keyword3",
"sizeof": "keyword1",
"static": "keyword1",
"struct": "keyword3",
"switch": "keyword1",
"true": "literal2",
"typedef": "keyword3",
"union": "keyword3",
"unsigned": "keyword3",
"void": "keyword3",
"volatile": "keyword1",
"while": "keyword1",
}
# Keywords dict for c_cpp ruleset.
c_cpp_keywords_dict = {
"assert": "markup",
"define": "markup",
"elif": "markup",
"else": "markup",
"endif": "markup",
"error": "markup",
"ident": "markup",
"if": "markup",
"ifdef": "markup",
"ifndef": "markup",
"import": "markup",
"include": "markup",
"include_next": "markup",
"line": "markup",
"pragma": "markup",
"sccs": "markup",
"unassert": "markup",
"undef": "markup",
"warning": "markup",
}
# Keywords dict for c_include ruleset.
c_include_keywords_dict = {}
# Dictionary of keywords dictionaries for c mode.
keywordsDictDict = {
"c_cpp": c_cpp_keywords_dict,
"c_include": c_include_keywords_dict,
"c_main": c_main_keywords_dict,
}
# Rules for c_main ruleset.
def c_rule0(colorer, s, i):
return colorer.match_span(s, i, kind="comment3", begin="/**", end="*/",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="doxygen::doxygen",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def c_rule1(colorer, s, i):
return colorer.match_span(s, i, kind="comment3", begin="/*!", end="*/",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="doxygen::doxygen",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def c_rule2(colorer, s, i):
return colorer.match_span(s, i, kind="comment1", begin="/*", end="*/",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def c_rule3(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="\"", end="\"",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def c_rule4(colorer, s, i):
return colorer.match_span(s, i, kind="literal1", begin="'", end="'",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=True, no_word_break=False)
def c_rule5(colorer, s, i):
return colorer.match_seq(s, i, kind="keyword2", seq="##",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule6(colorer, s, i):
return colorer.match_eol_span(s, i, kind="keyword2", seq="#",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="c::cpp", exclude_match=False)
def c_rule7(colorer, s, i):
return colorer.match_eol_span(s, i, kind="comment2", seq="//",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="", exclude_match=False)
def c_rule8(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule9(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="!",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule10(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule11(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<=",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule12(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="+",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule13(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="-",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule14(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="/",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule15(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="*",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule16(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq=">",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule17(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="<",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule18(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="%",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule19(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="&",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule20(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="|",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule21(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="^",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule22(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="~",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule23(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="}",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule24(colorer, s, i):
return colorer.match_seq(s, i, kind="operator", seq="{",
at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="")
def c_rule25(colorer, s, i):
return colorer.match_mark_previous(s, i, kind="label", pattern=":",
at_line_start=False, at_whitespace_end=True, at_word_start=False, exclude_match=True)
def c_rule26(colorer, s, i):
return colorer.match_mark_previous(s, i, kind="function", pattern="(",
at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=True)
def c_rule27(colorer, s, i):
return colorer.match_keywords(s, i)
# Rules dict for c_main ruleset.
rulesDict1 = {
"!": [c_rule9,],
"\"": [c_rule3,],
"#": [c_rule5,c_rule6,],
"%": [c_rule18,],
"&": [c_rule19,],
"'": [c_rule4,],
"(": [c_rule26,],
"*": [c_rule15,],
"+": [c_rule12,],
"-": [c_rule13,],
"/": [c_rule0,c_rule1,c_rule2,c_rule7,c_rule14,],
"0": [c_rule27,],
"1": [c_rule27,],
"2": [c_rule27,],
"3": [c_rule27,],
"4": [c_rule27,],
"5": [c_rule27,],
"6": [c_rule27,],
"7": [c_rule27,],
"8": [c_rule27,],
"9": [c_rule27,],
":": [c_rule25,],
"<": [c_rule11,c_rule17,],
"=": [c_rule8,],
">": [c_rule10,c_rule16,],
"@": [c_rule27,],
"A": [c_rule27,],
"B": [c_rule27,],
"C": [c_rule27,],
"D": [c_rule27,],
"E": [c_rule27,],
"F": [c_rule27,],
"G": [c_rule27,],
"H": [c_rule27,],
"I": [c_rule27,],
"J": [c_rule27,],
"K": [c_rule27,],
"L": [c_rule27,],
"M": [c_rule27,],
"N": [c_rule27,],
"O": [c_rule27,],
"P": [c_rule27,],
"Q": [c_rule27,],
"R": [c_rule27,],
"S": [c_rule27,],
"T": [c_rule27,],
"U": [c_rule27,],
"V": [c_rule27,],
"W": [c_rule27,],
"X": [c_rule27,],
"Y": [c_rule27,],
"Z": [c_rule27,],
"^": [c_rule21,],
"_": [c_rule27,],
"a": [c_rule27,],
"b": [c_rule27,],
"c": [c_rule27,],
"d": [c_rule27,],
"e": [c_rule27,],
"f": [c_rule27,],
"g": [c_rule27,],
"h": [c_rule27,],
"i": [c_rule27,],
"j": [c_rule27,],
"k": [c_rule27,],
"l": [c_rule27,],
"m": [c_rule27,],
"n": [c_rule27,],
"o": [c_rule27,],
"p": [c_rule27,],
"q": [c_rule27,],
"r": [c_rule27,],
"s": [c_rule27,],
"t": [c_rule27,],
"u": [c_rule27,],
"v": [c_rule27,],
"w": [c_rule27,],
"x": [c_rule27,],
"y": [c_rule27,],
"z": [c_rule27,],
"{": [c_rule24,],
"|": [c_rule20,],
"}": [c_rule23,],
"~": [c_rule22,],
}
# Rules for c_cpp ruleset.
def c_rule28(colorer, s, i):
return colorer.match_span(s, i, kind="comment1", begin="/*", end="*/",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="",exclude_match=False,
no_escape=False, no_line_break=False, no_word_break=False)
def c_rule29(colorer, s, i):
return colorer.match_eol_span(s, i, kind="markup", seq="include",
at_line_start=False, at_whitespace_end=False, at_word_start=False,
delegate="c::include", exclude_match=False)
def c_rule30(colorer, s, i):
return colorer.match_keywords(s, i)
# Rules dict for c_cpp ruleset.
rulesDict2 = {
"/": [c_rule28,],
"0": [c_rule30,],
"1": [c_rule30,],
"2": [c_rule30,],
"3": [c_rule30,],
"4": [c_rule30,],
"5": [c_rule30,],
"6": [c_rule30,],
"7": [c_rule30,],
"8": [c_rule30,],
"9": [c_rule30,],
"@": [c_rule30,],
"A": [c_rule30,],
"B": [c_rule30,],
"C": [c_rule30,],
"D": [c_rule30,],
"E": [c_rule30,],
"F": [c_rule30,],
"G": [c_rule30,],
"H": [c_rule30,],
"I": [c_rule30,],
"J": [c_rule30,],
"K": [c_rule30,],
"L": [c_rule30,],
"M": [c_rule30,],
"N": [c_rule30,],
"O": [c_rule30,],
"P": [c_rule30,],
"Q": [c_rule30,],
"R": [c_rule30,],
"S": [c_rule30,],
"T": [c_rule30,],
"U": [c_rule30,],
"V": [c_rule30,],
"W": [c_rule30,],
"X": [c_rule30,],
"Y": [c_rule30,],
"Z": [c_rule30,],
"_": [c_rule30,],
"a": [c_rule30,],
"b": [c_rule30,],
"c": [c_rule30,],
"d": [c_rule30,],
"e": [c_rule30,],
"f": [c_rule30,],
"g": [c_rule30,],
"h": [c_rule30,],
"i": [c_rule29,c_rule30,],
"j": [c_rule30,],
"k": [c_rule30,],
"l": [c_rule30,],
"m": [c_rule30,],
"n": [c_rule30,],
"o": [c_rule30,],
"p": [c_rule30,],
"q": [c_rule30,],
"r": [c_rule30,],
"s": [c_rule30,],
"t": [c_rule30,],
"u": [c_rule30,],
"v": [c_rule30,],
"w": [c_rule30,],
"x": [c_rule30,],
"y": [c_rule30,],
"z": [c_rule30,],
}
# Rules for c_include ruleset.
# Rules dict for c_include ruleset.
rulesDict3 = {}
# x.rulesDictDict for c mode.
rulesDictDict = {
"c_cpp": rulesDict2,
"c_include": rulesDict3,
"c_main": rulesDict1,
}
# Import dict for c mode.
importDict = {}
|
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
intervals.sort(key = lambda interval : interval[1])
res = 0
prev = intervals[0][1]
for i in range(1, len(intervals)):
if intervals[i][0] < prev:
res +=1
else:
prev = intervals[i][1]
return res
|
#https://www.interviewbit.com/problems/max-distance/
def maximumGap(A):
left = [A[0]]
right = [A[-1]]
n = len(A)
for i in range(1,n):
left.append(min(left[-1], A[i]))
for i in range(n-2, -1, -1):
right.insert(0, max(right[0], A[i]))
i,j,gap = 0, 0, -1
while (i < n and j < n):
if left[i] < right[j]:
gap = max(gap, j-i)
j += 1 # look for a larger gap
else:
i += 1
return gap
# test cases
assert(maximumGap([3,5,4,2])==2)
assert(maximumGap([3,2,1,0])==-1) |
'''
Created on May 24, 2012
@author: newatv2user
'''
PIANO_RPC_HOST = "tuner.pandora.com"
PIANO_ONE_HOST = "internal-tuner.pandora.com"
PIANO_RPC_PATH = "/services/json/?"
class PianoUserInfo:
def __init__(self):
self.listenerId = ''
self.authToken = ''
class PianoStation:
def __init__(self):
self.isCreator = ''
self.isQuickMix = ''
self.useQuickMix = ''
self.name = ''
self.id = ''
self.seedId = ''
# Piano Song Rating Enum
PIANO_RATE_NONE = 0
PIANO_RATE_LOVE = 1
PIANO_RATE_BAN = 2
class PianoSongRating:
def __init__(self):
self.Rating = PIANO_RATE_NONE
# Piano Audio Format Enum
PIANO_AF_UNKNOWN = 0
PIANO_AF_AACPLUS = 1
PIANO_AF_MP3 = 2
PIANO_AF_MP3_HI = 3
PIANO_AF_AACPLUS_LO = 4
class PianoAudioFormat:
def __init__(self):
self.Format = PIANO_AF_UNKNOWN
class PianoSong:
def __init__(self):
self.artist = ''
self.stationId = ''
self.album = ''
self.audioUrl = ''
self.coverArt = ''
self.musicId = ''
self.title = ''
self.seedId = ''
self.feedbackId = ''
self.detailUrl = ''
self.trackToken = ''
self.fileGain = 0
self.rating = PianoSongRating()
self.audioFormat = PianoAudioFormat()
class PianoArtist:
def __init__(self):
self.name = ''
self.musicId = ''
self.seedId = ''
self.score = 0
self.next = PianoArtist()
class PianoGenre:
def __init__(self):
self.name = ''
self.musicId = ''
class PianoGenreCategory:
def __init__(self):
self.name = ''
self.genres = PianoGenre()
class PianoPartner:
def __init__(self):
self.In = ''
self.out = ''
self.authToken = ''
self.device = ''
self.user = ''
self.password = ''
self.id = 0
class PianoSearchResult:
def __init__(self):
self.songs = PianoSong()
self.artists = PianoArtist()
class PianoStationInfo:
def __init__(self):
self.songSeeds = PianoSong()
self.artistSeeds = PianoArtist()
self.stationSeeds = PianoStation()
self.feedback = PianoSong()
# Piano Request Type Enum
#/* 0 is reserved: memset (x, 0, sizeof (x)) */
PIANO_REQUEST_LOGIN = 1
PIANO_REQUEST_GET_STATIONS = 2
PIANO_REQUEST_GET_PLAYLIST = 3
PIANO_REQUEST_RATE_SONG = 4
PIANO_REQUEST_ADD_FEEDBACK = 5
PIANO_REQUEST_MOVE_SONG = 6
PIANO_REQUEST_RENAME_STATION = 7
PIANO_REQUEST_DELETE_STATION = 8
PIANO_REQUEST_SEARCH = 9
PIANO_REQUEST_CREATE_STATION = 10
PIANO_REQUEST_ADD_SEED = 11
PIANO_REQUEST_ADD_TIRED_SONG = 12
PIANO_REQUEST_SET_QUICKMIX = 13
PIANO_REQUEST_GET_GENRE_STATIONS = 14
PIANO_REQUEST_TRANSFORM_STATION = 15
PIANO_REQUEST_EXPLAIN = 16
PIANO_REQUEST_BOOKMARK_SONG = 18
PIANO_REQUEST_BOOKMARK_ARTIST = 19
PIANO_REQUEST_GET_STATION_INFO = 20
PIANO_REQUEST_DELETE_FEEDBACK = 21
PIANO_REQUEST_DELETE_SEED = 22
class PianoRequestType:
def __init__(self):
self.RequestType = PIANO_REQUEST_LOGIN
class PianoRequest:
def __init__(self):
self.type = PianoRequestType()
self.secure = False
self.data = ''
self.urlPath = [1024]
self.postData = ''
self.responseData = ''
#/* request data structures */
class PianoRequestDataLogin:
def __init__(self):
self.user = ''
self.password = ''
self.step = ''
class PianoRequestDataGetPlaylist:
def __init__(self):
self.station = PianoStation()
self.format = PianoAudioFormat()
self.retPlaylist = PianoSong()
class PianoRequestDataRateSong:
def __init__(self):
self.song = PianoSong()
self.rating = PianoSongRating()
class PianoRequestDataAddFeedback:
def __init__(self):
self.stationId = ''
self.trackToken = ''
self.rating = PianoSongRating()
class PianoRequestDataMoveSong:
def __init__(self):
self.song = PianoSong()
self.From = PianoStation()
self.to = PianoStation()
self.step = 0
class PianoRequestDataRenameStation:
def __init__(self):
self.station = PianoStation()
self.newName = ''
class PianoRequestDataSearch:
def __init__(self):
self.searchStr = ''
self.searchResult = PianoSearchResult()
class PianoRequestDataCreateStation:
def __init__(self):
self.type = ''
self.id = ''
class PianoRequestDataAddSeed:
def __init__(self):
self.station = PianoStation()
self.musicId = ''
class PianoRequestDataExplain:
def __init__(self):
self.song = PianoSong()
self.retExplain = ''
class PianoRequestDataGetStationInfo:
def __init__(self):
self.station = PianoStation()
self.info = PianoStationInfo()
class PianoRequestDataDeleteSeed:
def __init__(self):
self.song = PianoSong()
self.artist = PianoArtist()
self.station = PianoStation()
#/* pandora error code offset */
PIANO_RET_OFFSET = 1024
# Piano Return Enum
PIANO_RET_ERR = 0
PIANO_RET_OK = 1
PIANO_RET_INVALID_RESPONSE = 2
PIANO_RET_CONTINUE_REQUEST = 3
PIANO_RET_OUT_OF_MEMORY = 4
PIANO_RET_INVALID_LOGIN = 5
PIANO_RET_QUALITY_UNAVAILABLE = 6
PIANO_RET_P_INTERNAL = PIANO_RET_OFFSET + 0
PIANO_RET_P_API_VERSION_NOT_SUPPORTED = PIANO_RET_OFFSET + 11
PIANO_RET_P_BIRTH_YEAR_INVALID = PIANO_RET_OFFSET + 1025
PIANO_RET_P_BIRTH_YEAR_TOO_YOUNG = PIANO_RET_OFFSET + 1026
PIANO_RET_P_CALL_NOT_ALLOWED = PIANO_RET_OFFSET + 1008
PIANO_RET_P_CERTIFICATE_REQUIRED = PIANO_RET_OFFSET + 7
PIANO_RET_P_COMPLIMENTARY_PERIOD_ALREADY_IN_USE = PIANO_RET_OFFSET + 1007
PIANO_RET_P_DAILY_TRIAL_LIMIT_REACHED = PIANO_RET_OFFSET + 1035
PIANO_RET_P_DEVICE_ALREADY_ASSOCIATED_TO_ACCOUNT = PIANO_RET_OFFSET + 1014
PIANO_RET_P_DEVICE_DISABLED = PIANO_RET_OFFSET + 1034
PIANO_RET_P_DEVICE_MODEL_INVALID = PIANO_RET_OFFSET + 1023
PIANO_RET_P_DEVICE_NOT_FOUND = PIANO_RET_OFFSET + 1009
PIANO_RET_P_EXPLICIT_PIN_INCORRECT = PIANO_RET_OFFSET + 1018
PIANO_RET_P_EXPLICIT_PIN_MALFORMED = PIANO_RET_OFFSET + 1020
PIANO_RET_P_INSUFFICIENT_CONNECTIVITY = PIANO_RET_OFFSET + 13
PIANO_RET_P_INVALID_AUTH_TOKEN = PIANO_RET_OFFSET + 1001
PIANO_RET_P_INVALID_COUNTRY_CODE = PIANO_RET_OFFSET + 1027
PIANO_RET_P_INVALID_GENDER = PIANO_RET_OFFSET + 1027
PIANO_RET_P_INVALID_PARTNER_LOGIN = PIANO_RET_OFFSET + 1002
PIANO_RET_P_INVALID_PASSWORD = PIANO_RET_OFFSET + 1012
PIANO_RET_P_INVALID_SPONSOR = PIANO_RET_OFFSET + 1036
PIANO_RET_P_INVALID_USERNAME = PIANO_RET_OFFSET + 1011
PIANO_RET_P_LICENSING_RESTRICTIONS = PIANO_RET_OFFSET + 12
PIANO_RET_P_MAINTENANCE_MODE = PIANO_RET_OFFSET + 1
PIANO_RET_P_MAX_STATIONS_REACHED = PIANO_RET_OFFSET + 1005
PIANO_RET_P_PARAMETER_MISSING = PIANO_RET_OFFSET + 9
PIANO_RET_P_PARAMETER_TYPE_MISMATCH = PIANO_RET_OFFSET + 8
PIANO_RET_P_PARAMETER_VALUE_INVALID = PIANO_RET_OFFSET + 10
PIANO_RET_P_PARTNER_NOT_AUTHORIZED = PIANO_RET_OFFSET + 1010
PIANO_RET_P_READ_ONLY_MODE = PIANO_RET_OFFSET + 1000
PIANO_RET_P_SECURE_PROTOCOL_REQUIRED = PIANO_RET_OFFSET + 6
PIANO_RET_P_STATION_DOES_NOT_EXIST = PIANO_RET_OFFSET + 1006
PIANO_RET_P_UPGRADE_DEVICE_MODEL_INVALID = PIANO_RET_OFFSET + 1015
PIANO_RET_P_URL_PARAM_MISSING_AUTH_TOKEN = PIANO_RET_OFFSET + 3
PIANO_RET_P_URL_PARAM_MISSING_METHOD = PIANO_RET_OFFSET + 2
PIANO_RET_P_URL_PARAM_MISSING_PARTNER_ID = PIANO_RET_OFFSET + 4
PIANO_RET_P_URL_PARAM_MISSING_USER_ID = PIANO_RET_OFFSET + 5
PIANO_RET_P_USERNAME_ALREADY_EXISTS = PIANO_RET_OFFSET + 1013
PIANO_RET_P_USER_ALREADY_USED_TRIAL = PIANO_RET_OFFSET + 1037
PIANO_RET_P_LISTENER_NOT_AUTHORIZED = PIANO_RET_OFFSET + 1003
PIANO_RET_P_USER_NOT_AUTHORIZED = PIANO_RET_OFFSET + 1004
PIANO_RET_P_ZIP_CODE_INVALID = PIANO_RET_OFFSET + 1024
class PianoReturn:
def __init__(self):
self.Return = PIANO_RET_ERR
def PianoFindStationById (stations, searchStation):
#/* get station from list by id
#* @param search here
#* @param search for this
#* @return the first station structure matching the given id
#*/
for station in stations:
if station.id == searchStation:
return station
return None
def PianoErrorToStr (ret):
#/* convert return value to human-readable string
#* @param enum
#* @return error string
#*/
return {
PIANO_RET_OK: "Everything is fine :)",
PIANO_RET_ERR: "Unknown.",
PIANO_RET_INVALID_RESPONSE: "Invalid response.",
PIANO_RET_CONTINUE_REQUEST: "Fix your program.",
PIANO_RET_OUT_OF_MEMORY: "Out of memory.",
PIANO_RET_INVALID_LOGIN: "Wrong email address or password.",
PIANO_RET_QUALITY_UNAVAILABLE: "Selected audio quality is not available.",
PIANO_RET_P_INTERNAL: "Internal error.",
PIANO_RET_P_CALL_NOT_ALLOWED: "Call not allowed.",
PIANO_RET_P_INVALID_AUTH_TOKEN: "Invalid auth token.",
PIANO_RET_P_MAINTENANCE_MODE: "Maintenance mode.",
PIANO_RET_P_MAX_STATIONS_REACHED: "Max number of stations reached.",
PIANO_RET_P_READ_ONLY_MODE: "Read only mode. Try again later.",
PIANO_RET_P_STATION_DOES_NOT_EXIST: "Station does not exist.",
PIANO_RET_P_INVALID_PARTNER_LOGIN: "Invalid partner login.",
PIANO_RET_P_LICENSING_RESTRICTIONS: "Pandora is not available in your country. "\
"Set up a control proxy (see manpage).",
PIANO_RET_P_PARTNER_NOT_AUTHORIZED: "Invalid partner credentials.",
PIANO_RET_P_LISTENER_NOT_AUTHORIZED: "Listener not authorized."
}.get(ret, "No error message available.")
|
class Emplacement:
"""
documentation
"""
def __init__(self, id, line, n):
self.id = id
line = line.split(' ')
distances = {}
i = 0
for elt in line:
if elt != '':
i+=1
if i != id:
distances[i] = int(elt.replace('\n', ''))
if len(distances) != n-1:
print("ERROR: len(distances) != n-1")
self.distances = distances
self.equipment = None |
"""
Streamlined python project setup and build system.
"""
__version__ = "0.2"
DESCRIPTION = __doc__
__all__ = ['__init__', '__main__', 'parsers']
|
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
class Error(object):
@staticmethod
def exceeded_maximum_metric_capacity():
return "ErrorExceededMaximumMetricCapacity"
@staticmethod
def missing_attribute():
return "ErrorMissingAttributes"
@staticmethod
def is_not_lower():
return "ErrorNotLowerCase"
@staticmethod
def out_of_order():
return "ErrorOutOfOrder"
@staticmethod
def unable_to_sort():
return "ErrorNotSorted"
@staticmethod
def is_null():
return "ErrorNullValue"
@staticmethod
def empty_dataframe():
return "ErrorEmptyDataFrame"
|
class Singleton(type):
def __new__(meta, name, bases, attrs):
attrs["_instance"] = None
return super().__new__(meta, name, bases, attrs)
def __call__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: template_deploy
short_description: Manage TemplateDeploy objects of ConfigurationTemplates
description:
- Deploys a template.
- Returns the status of a deployed template.
version_added: '1.0.0'
author: Rafael Campos (@racampos)
options:
forcePushTemplate:
description:
- TemplateDeploymentInfo's forcePushTemplate.
type: bool
isComposite:
description:
- TemplateDeploymentInfo's isComposite.
type: bool
mainTemplateId:
description:
- TemplateDeploymentInfo's mainTemplateId.
type: str
memberTemplateDeploymentInfo:
description:
- TemplateDeploymentInfo's memberTemplateDeploymentInfo (list of any objects).
type: list
targetInfo:
description:
- TemplateDeploymentInfo's targetInfo (list of objects).
type: list
elements: dict
suboptions:
hostName:
description:
- It is the template deploy's hostName.
type: str
id:
description:
- It is the template deploy's id.
type: str
params:
description:
- It is the template deploy's params.
type: dict
type:
description:
- It is the template deploy's type.
type: str
templateId:
description:
- TemplateDeploymentInfo's templateId.
type: str
deployment_id:
description:
- DeploymentId path parameter.
- Required for state query.
type: str
requirements:
- dnacentersdk
seealso:
# Reference by module name
- module: cisco.dnac.plugins.module_utils.definitions.template_deploy
# Reference by Internet resource
- name: TemplateDeploy reference
description: Complete reference of the TemplateDeploy object model.
link: https://developer.cisco.com/docs/dna-center/api/1-3-3-x
# Reference by Internet resource
- name: TemplateDeploy reference
description: SDK reference.
link: https://dnacentersdk.readthedocs.io/en/latest/api/api.html#v2-1-1-summary
"""
EXAMPLES = r"""
- name: deploy_template
cisco.dnac.template_deploy:
state: create # required
forcePushTemplate: True # boolean
isComposite: True # boolean
mainTemplateId: SomeValue # string
memberTemplateDeploymentInfo: None
targetInfo:
- hostName: SomeValue # string
id: SomeValue # string
params:
type: SomeValue # string
templateId: SomeValue # string
- name: get_template_deployment_status
cisco.dnac.template_deploy:
state: query # required
deployment_id: SomeValue # string, required
register: nm_get_template_deployment_status
"""
RETURN = r"""
dnac_response:
description: A dictionary with the response returned by the DNA Center Python SDK
returned: always
type: dict
sample: {"response": 29, "version": "1.0"}
sdk_function:
description: The DNA Center SDK function used to execute the task
returned: always
type: str
sample: configuration_templates.deploy_template
missing_params:
description: Provided arguments do not comply with the schema of the DNA Center Python SDK function
returned: when the function request schema is not satisfied
type: list
sample:
"""
|
# -*- coding: utf-8 -*-
'''
File name: code\eight_divisors\sol_501.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #501 :: Eight Divisors
#
# For more information see:
# https://projecteuler.net/problem=501
# Problem Statement
'''
The eight divisors of 24 are 1, 2, 3, 4, 6, 8, 12 and 24.
The ten numbers not exceeding 100 having exactly eight divisors are 24, 30, 40, 42, 54, 56, 66, 70, 78 and 88.
Let f(n) be the count of numbers not exceeding n with exactly eight divisors.
You are given f(100) = 10, f(1000) = 180 and f(106) = 224427.
Find f(1012).
'''
# Solution
# Solution Approach
'''
'''
|
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/gaogaotiantian/pygictower/blob/master/NOTICE
__version__ = "0.0.1"
|
def countBits(n: int) -> list[int]:
result = [0]
for i in range(1,n+1):
count = 0
test = ~(i - 1)
while test & 1 == 0:
test >>= 1
count += 1
result.append(result[i-1] - count + 1)
return result |
class Predicate(object):
def test(self, obj):
raise NotImplementedError()
def __call__(self, obj):
return self.test(obj)
def __eq__(self, obj):
return self.test(obj)
def __ne__(self, obj):
return not self == obj
def __and__(self, other):
return And(self, other)
def __or__(self, other):
return Or(self, other)
def __str__(self):
return self.describe()
def __repr__(self):
return "<%s>" % self
def describe(self, variable="X"):
return self._describe(variable) + "?"
def _describe(self, variable):
raise NotImplementedError()
class FunctionPredicate(Predicate):
def __init__(self, func, description=None):
super(FunctionPredicate, self).__init__()
self.func = func
if description is None:
description = func.__doc__
self.description = description
def test(self, obj):
if isinstance(obj, FunctionPredicate):
return obj.func is self.func
else:
return self.func(obj)
def _describe(self, variable):
if self.description:
return self.description % dict(var=variable)
else:
return "%s(%s)" % (self.func,variable)
class Equality(Predicate):
def __init__(self, value):
super(Equality, self).__init__()
self.value = value
def test(self, obj):
if isinstance(obj, Equality):
return obj.value == self.value
else:
return obj == self.value
def _describe(self, variable):
return "%s==%s" % (variable, str(self.value))
Inequality = lambda value: Not(Equality(value))
class Or(Predicate):
def __init__(self, *preds):
super(Or, self).__init__()
self.preds = map(make_predicate, preds)
def test(self, obj):
return any(p == obj for p in self.preds)
def _describe(self, variable):
return " OR ".join("(%s)" % pred._describe(variable) for pred in self.preds)
class And(Predicate):
def __init__(self, *preds):
super(And, self).__init__()
self.preds = map(make_predicate, preds)
def test(self, obj):
return all(p == obj for p in self.preds)
def _describe(self, variable):
return " AND ".join("(%s)" % pred._describe(variable) for pred in self.preds)
class Not(Predicate):
def __init__(self, pred):
super(Not, self).__init__()
self.pred = make_predicate(pred)
def test(self, obj):
return not self.pred == obj
def _describe(self, variable):
return "NOT(%s)" % (self.pred._describe(variable),)
class _Dummy(Predicate):
def __init__(self, retval, description=""):
self.retval = retval
self.description = description
def test(self, other):
return self.retval
def _describe(self, variable):
return self.description
IGNORE = _Dummy(True, "ANYTHING")
FAIL = _Dummy(False, "NOTHING")
def make_predicate(expr):
"""
common utility for making various expressions into predicates
"""
if isinstance(expr, Predicate):
return expr
elif isinstance(expr, type):
return FunctionPredicate(lambda obj, type=expr: isinstance(obj, type))
elif callable(expr):
return FunctionPredicate(expr)
else:
return Equality(expr)
P = make_predicate
|
usingdir = '/sys/fs/cgroup/memory/memory.max_usage_in_bytes'
totaldir = '/sys/fs/cgroup/memory/memory.limit_in_bytes'
def ram():
try:
using = int(open(usingdir).read())
total = int(open(totaldir).read())
except FileNotFoundError:
return 'Dados não encontrados'
else:
return f"{convert(using)}/{convert(total)}"
def using_ram():
try:
using = int(open(usingdir).read())
except FileNotFoundError:
return 'Dados não encontrados'
else:
return convert(using)
def total_ram():
try:
total = int(open(totaldir).read())
except FileNotFoundError:
return 'Dados não encontrados'
else:
return convert(total)
def convert(membytes):
types = ['Bytes', 'KB', 'MB', 'GB', 'TB']
n = 0
while membytes > 1024:
membytes = membytes/1024
n += 1
return '{0:.2f}'.format(membytes).rstrip('0').rstrip('.') + types[n]
|
# Copyright 2018 Jianfei Gao, Leonardo Teixeira, Bruno Ribeiro.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Summer Time Period
Set summer time period for stratux data to shift time zone.
"""
SUMMER = {
2017: ((3, 12), (11, 5)),
2018: ((3, 11), (11, 4)),
2019: ((3, 10), (11, 3)),
}
"""Minimum Ground Speed
Set minimum ground speed, above which will be regarded as flight.
The default class embedded value is 0.0005, and is empirically designed.
"""
GROUND_SPEED_THRESHOLD = 0.0004
"""Problematic Flights
Set problematic flights which are provided commonly, but in trouble. For instance,
1. There are some flights provided in G1000 records which are not real flight data.
2. Some time stratux will run out of battery, and give partial flight data which will
crash alignment process.
"""
HIZARD_FLIGHTS = ('112017_02', '112817_01', '022718_01', '030418_03')
"""Input Keywords
Necessary keywords of input in short version.
By current, it is defined by five types:
1. GPS
2. Speed of GPS (Not divided by time step)
3. Acceleration of GPS (Not divided by time step)
4. Accelerometer
5. Gyroscope
"""
INPUT_KEYWORDS = (
'alt', 'lat', 'long',
'spd_alt', 'spd_lat', 'spd_long',
'acc_alt', 'acc_lat', 'acc_long',
'accmx', 'accmy', 'accmz',
'gyrox', 'gyroy', 'gyroz',
)
"""Window Configuration
Window configuration for dividing sequences into frames.
It should contain enough information for generating frames. For instance,
1. It should have window length for input and target;
2. It should have information to compute window offset length for input and target;
3. It should have padding method for input and target.
"""
WINDOW_CONFIG = {
'input': {
'length': 32,
'offset_length': None, 'offset_rate': 0.4,
'padding': 'repeat_base',
},
'target': {
'length': 32,
'offset_length': None, 'offset_rate': 0.4,
'padding': 'repeat_base',
},
} |
nota1 = int(input('Digite sua nota da A1 '))
nota2 = int(input('Digite sua nota da A2 '))
media = (nota1+nota2)/2
if media < 5:
print(f'REPROVADO')
elif media == 5 or media < 7 :
print(f'RECUPERAÇÃO')
elif media == 7 or media > 7:
print(f'APROVADO') |
def increment(dictionary, k1, k2):
"""
dictionary[k1][k2]++
:param dictionary: Dictionary of dictionary of integers.
:param k1: First key.
:param k2: Second key.
:return: same dictionary with incremented [k1][k2]
"""
if k1 not in dictionary:
dictionary[k1] = {}
if 0 not in dictionary[k1]:
dictionary[k1][0] = 0
if k2 not in dictionary[k1]:
dictionary[k1][k2] = 0
dictionary[k1][0] += 1 # k1 count
dictionary[k1][k2] += 1 # k1, k2 pair count
return dictionary
def get_tags(input, flatten=False):
"""
Get the tags from an input.
:param input: list of tags, list of tuples (word, tag), list of lists of tags or list of lists of tuples (word, tag)
:param flatten:
:return: list of tags.
"""
if type(input[0]) is str: # The input is a list of tags.
tag_list = input
elif type(input[0]) is tuple: # The input is a list of tuples (word, tag).
tag_list = [tag for (word, tag) in input]
else: # The input is a list of lists.
if type(input[0][0]) is str: # The input is a list of lists of tags.
tag_list = input
elif type(input[0][0]) is tuple: # The input is a list of lists of tuples (word, tag).
tag_list = []
for sentence in input:
tag_list.append([tag for (word, tag) in sentence])
if flatten:
tag_list = [tag for sublist in tag_list for tag in sublist]
return tag_list
def get_words(input, flatten=False):
"""
Get the tags from an input.
:param input: list of tags, list of tuples (word, tag), list of lists of tags or list of lists of tuples (word, tag)
:param flatten:
:return: list of tags.
"""
if type(input[0]) is str: # The input is a list of tags.
word_list = input
elif type(input[0]) is tuple: # The input is a list of tuples (word, tag).
word_list = [word for (word, tag) in input]
else: # The input is a list of lists.
if type(input[0][0]) is str: # The input is a list of lists of tags.
word_list = input
elif type(input[0][0]) is tuple: # The input is a list of lists of tuples (word, tag).
word_list = []
for sentence in input:
word_list.append([word for (word, tag) in sentence])
if flatten:
word_list = [word for sublist in word_list for word in sublist]
return word_list
|
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
sumc = 0
cont = 0
for c in range(1, 7):
print("{}----- {} Number -----{}".format(colors["cian"], c, colors["clean"]))
sum = int(input("Enter a number: "))
if (sum % 2) == 0:
sumc += sum
cont += 1
print("{}You enter {} even {} {} {}{}"
.format(colors["blue"], cont, "numbers" if cont > 1 else "number",
"and the sum between them is" if cont > 1 else "so don´t have a sum",
sumc, colors["clean"]))
|
# -*- coding: utf-8 -*-
"""
Copyright () 2018
All rights reserved
FILE: binary_tree.py
AUTHOR: tianyuningmou
DATE CREATED: @Time : 2018/5/15 上午11:06
DESCRIPTION: .
VERSION: : #1
CHANGED By: : tianyuningmou
CHANGE: :
MODIFIED: : @Time : 2018/5/15 上午11:06
"""
"""
二叉树是每个节点最多有两个子树的树结构,子树有左右之分,二叉树常被用于实现二叉查找树和二叉堆
深度为 k, 且有 2**k-1 个节点称之为满二叉树;
深度为 k,有 n 个节点的二叉树,当且仅当其每一个节点都与深度为 k 的满二叉树中序号为 1 至 n 的节点对应时,称之为完全二叉树。
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Traversal:
def __init__(self):
self.traverse_path = list()
def preorder(self, root):
if root:
self.traverse_path.append(root.val)
self.preorder(root.left)
self.preorder(root.right)
def inorder(self, root):
if root:
self.inorder(root.left)
self.traverse_path.append(root.val)
self.inorder(root.right)
def postorder(self, root):
if root:
self.postorder(root.left)
self.postorder(root.right)
self.traverse_path.append(root.val)
|
# Solution to Advent of Code 2020 day 6
# Read data
with open("input.txt") as inFile:
groups = inFile.read().split("\n\n")
# Part 1
yesAnswers = sum([len(set(group.replace("\n", ""))) for group in groups])
print("Solution for part 1:", yesAnswers)
# Part 2
yesAnswers = 0
for group in groups:
persons = group.split("\n")
sameAnswers = set(persons[0])
for person in persons[1:]:
sameAnswers &= set(person)
yesAnswers += len(sameAnswers)
print("Solution for part 2:", yesAnswers)
|
DOCARRAY_PULL_NAME = "fashion-product-images-clip-all"
DATA_DIR = "../data/images" # Where are the files?
CSV_FILE = "../data/styles.csv" # Where's the metadata?
WORKSPACE_DIR = "../embeddings"
DIMS = 512 # This should be same shape as vector embedding
|
def Instagram_scroller(driver,command):
print('In scroller function')
while True:
while True:
l0 = ["scroll up","call down","call don","scroll down","up","down","exit","roll down","croll down","roll up","croll up"]
if len([i for i in l0 if i in command]) != 0:
break
else:
speak("Please , come again .")
command = takeCommand().lower()
print("in scroller function, while loop")
l = ["scroll down","down","roll down","croll down"]
if len([i for i in l if i in command]) != 0:
print("voice gets recognized")
speak("Scrolling Down the pan")
while True:
driver.execute_script("window.scrollBy(0,500)","")
time.sleep(0)
q = takeCommand().lower()
if "stop" in q or "exit" in q or "top" in q:
speak("Exiting the scroll down")
break
l2 = ["scroll up","croll up","up","roll up","call app"]
if len([i for i in l2 if i in command]) != 0:
speak("Scrolling up the pan")
while True:
driver.execute_script("scrollBy(0,-2000);")
time.sleep(0)
q = takeCommand().lower()
if "stop" in q or "exit" in q or "top" in q:
speak("Exiting the scroll up")
break
command = takeCommand().lower()
if "exit" in command:
speak("exiting from scroller")
break |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def _is_tensor(x):
return hasattr(x, "__len__")
|
# initial based on FreeCAD 0.17dev
#last edit: 2019-08
SourceFolder=[
("Base","Foundamental classes for FreeCAD",
"""import as FreeCAD in Python, see detailed description in later section"""),
("App","nonGUI code: Document, Property and DocumentObject",
"""import as FreeCAD in Python, see detailed description in later section"""),
("Gui","Qt-based GUI code: macro-recording, Workbench",
"""import as FreeCADGui in Python, see detailed description in later section"""),
("CXX","modified PyCXX containing both python 2 and python 3"),
("Ext","Source code for all modules with each module in one subfolder",
"""enable module import from FreeCAD to avoid python module name clashing"""),
("Main","main() function for FreeCADCmd.exe and FreeCADGui.exe",
""""Main() of FreeCADCmd.exe (build up CAD model without GUI but python scripting) and FreeCADGui.exe (Interactive mode)"""),
("Mod","Source code for all modules with each module in one subfolder",
"""Source code of ome modules will be explained in later section"""),
("Tools","Tool to build the source code: fcbt.py",
"""fcbt can generate a basic module from _TEMPLATE_ folder, """),
("Doc","Manual and documentation generated by doxygen"),
("CMakeLists.txt","topmost CMake config file, kind of high level cross-platform makefile generator",
"""
Module developer needs not to care about this file, CMakeLists.txt within module will be automatically included.
"""),
("FCConfig.h","preprocessor shared by all source for portability on diff platforms"),
("fc.sh","export environment variable for CASROOT -> OpenCASCADE",
"""
Module developer needs not to care about this file
"""),
("3rdParty","Third party code integration",
"""boost.CMakeLists.txt CxImage Pivy-0.5 zlib.CMakeLists.txt CMakeLists.txt Pivy salomesmesh"""),
("zipios++","source of zipios++ lib"),
("Build","set the version of FreeCAD"),
("MacAppBundle","config file to generate MacOSX bundle (installer)"),
("XDGData","FreeCAD.desktop file for linux package compliant Linux freedesktop standard"),
("WindowsInstaller","config files to generate windows installer"),
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.