content
stringlengths 7
1.05M
|
---|
s = input()
hachi = set()
if len(s) < 3:
if int(s) % 8 == 0 or int(s[::-1]) % 8 == 0:
print("Yes")
else:
print("No")
exit()
t = 104
while t < 1000:
hachi.add(str(t))
t += 8
counter = [0 for _ in range(10)]
for i in s:
counter[int(i)] += 1
for h in hachi:
count = [0 for _ in range(10)]
for i in str(h):
count[int(i)] += 1
for i in range(10):
if counter[i] < count[i]:
break
else:
print("Yes")
exit()
print("No")
|
#
# PySNMP MIB module DLINK-3100-BRIDGEMIBOBJECTS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-BRIDGEMIBOBJECTS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:33:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion")
Timeout, BridgeId, dot1dBasePort = mibBuilder.importSymbols("BRIDGE-MIB", "Timeout", "BridgeId", "dot1dBasePort")
rnd, = mibBuilder.importSymbols("DLINK-3100-MIB", "rnd")
InterfaceIndex, ifIndex = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "ifIndex")
PortList, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "PortList")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, Counter64, TimeTicks, ModuleIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, ObjectIdentity, NotificationType, MibIdentifier, Integer32, Gauge32, Unsigned32, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Counter64", "TimeTicks", "ModuleIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "ObjectIdentity", "NotificationType", "MibIdentifier", "Integer32", "Gauge32", "Unsigned32", "Counter32")
RowStatus, TruthValue, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TruthValue", "TextualConvention", "DisplayString")
rlpBridgeMIBObjects = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57))
rlpBridgeMIBObjects.setRevisions(('2007-01-02 00:00',))
if mibBuilder.loadTexts: rlpBridgeMIBObjects.setLastUpdated('200701020000Z')
if mibBuilder.loadTexts: rlpBridgeMIBObjects.setOrganization('Dlink, Inc. Dlink Semiconductor, Inc.')
rldot1dPriority = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 1))
rldot1dPriorityMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dPriorityMibVersion.setStatus('current')
rldot1dPriorityPortGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 1, 2), )
if mibBuilder.loadTexts: rldot1dPriorityPortGroupTable.setStatus('current')
rldot1dPriorityPortGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 1, 2, 1), ).setIndexNames((0, "BRIDGE-MIB", "dot1dBasePort"))
if mibBuilder.loadTexts: rldot1dPriorityPortGroupEntry.setStatus('current')
rldot1dPriorityPortGroupNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dPriorityPortGroupNumber.setStatus('current')
rldot1dStp = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2))
rldot1dStpMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpMibVersion.setStatus('current')
rldot1dStpType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 4))).clone(namedValues=NamedValues(("perDevice", 1), ("mstp", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpType.setStatus('current')
rldot1dStpEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 3), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpEnable.setStatus('current')
rldot1dStpPortMustBelongToVlan = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 4), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpPortMustBelongToVlan.setStatus('current')
rldot1dStpExtendedPortNumberFormat = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 5), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpExtendedPortNumberFormat.setStatus('current')
rldot1dStpVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6), )
if mibBuilder.loadTexts: rldot1dStpVlanTable.setStatus('current')
rldot1dStpVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1), ).setIndexNames((0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1dStpVlan"))
if mibBuilder.loadTexts: rldot1dStpVlanEntry.setStatus('current')
rldot1dStpVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpVlan.setStatus('current')
rldot1dStpVlanEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 2), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpVlanEnable.setStatus('current')
rldot1dStpTimeSinceTopologyChange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpTimeSinceTopologyChange.setStatus('current')
rldot1dStpTopChanges = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpTopChanges.setStatus('current')
rldot1dStpDesignatedRoot = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 5), BridgeId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpDesignatedRoot.setStatus('current')
rldot1dStpRootCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpRootCost.setStatus('current')
rldot1dStpRootPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpRootPort.setStatus('current')
rldot1dStpMaxAge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 8), Timeout()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpMaxAge.setStatus('current')
rldot1dStpHelloTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 9), Timeout()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpHelloTime.setStatus('current')
rldot1dStpHoldTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpHoldTime.setStatus('current')
rldot1dStpForwardDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 6, 1, 11), Timeout()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpForwardDelay.setStatus('current')
rldot1dStpVlanPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7), )
if mibBuilder.loadTexts: rldot1dStpVlanPortTable.setStatus('current')
rldot1dStpVlanPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1), ).setIndexNames((0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1dStpVlanPortVlan"), (0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1dStpVlanPortPort"))
if mibBuilder.loadTexts: rldot1dStpVlanPortEntry.setStatus('current')
rldot1dStpVlanPortVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4095))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpVlanPortVlan.setStatus('current')
rldot1dStpVlanPortPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4096))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpVlanPortPort.setStatus('current')
rldot1dStpVlanPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpVlanPortPriority.setStatus('current')
rldot1dStpVlanPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("disabled", 1), ("blocking", 2), ("listening", 3), ("learning", 4), ("forwarding", 5), ("broken", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpVlanPortState.setStatus('current')
rldot1dStpVlanPortEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpVlanPortEnable.setStatus('current')
rldot1dStpVlanPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpVlanPortPathCost.setStatus('current')
rldot1dStpVlanPortDesignatedRoot = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 7), BridgeId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpVlanPortDesignatedRoot.setStatus('current')
rldot1dStpVlanPortDesignatedCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpVlanPortDesignatedCost.setStatus('current')
rldot1dStpVlanPortDesignatedBridge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 9), BridgeId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpVlanPortDesignatedBridge.setStatus('current')
rldot1dStpVlanPortDesignatedPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 10), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpVlanPortDesignatedPort.setStatus('current')
rldot1dStpVlanPortForwardTransitions = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 7, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpVlanPortForwardTransitions.setStatus('current')
rldot1dStpTrapVariable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 8))
rldot1dStpTrapVrblifIndex = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 8, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpTrapVrblifIndex.setStatus('current')
rldot1dStpTrapVrblVID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 8, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpTrapVrblVID.setStatus('current')
rldot1dStpTypeAfterReset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 4))).clone(namedValues=NamedValues(("perDevice", 1), ("mstp", 4))).clone('perDevice')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpTypeAfterReset.setStatus('current')
rldot1dStpMonitorTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 20)).clone(10)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpMonitorTime.setStatus('current')
rldot1dStpBpduCount = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 60)).clone(10)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpBpduCount.setStatus('current')
rldot1dStpLastChanged = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 12), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpLastChanged.setStatus('current')
rldot1dStpPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13), )
if mibBuilder.loadTexts: rldot1dStpPortTable.setStatus('current')
rldot1dStpPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1), ).setIndexNames((0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1dStpPortPort"))
if mibBuilder.loadTexts: rldot1dStpPortEntry.setStatus('current')
rldot1dStpPortPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4096))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpPortPort.setStatus('current')
rldot1dStpPortDampEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpPortDampEnable.setStatus('current')
rldot1dStpPortDampStable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 3), TruthValue().clone('true')).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpPortDampStable.setStatus('current')
rldot1dStpPortFilterBpdu = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("false", 0), ("true", 1), ("none", 2))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpPortFilterBpdu.setStatus('current')
rldot1dStpPortBpduSent = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpPortBpduSent.setStatus('current')
rldot1dStpPortBpduReceived = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpPortBpduReceived.setStatus('current')
rldot1dStpPortRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("unknown", 0), ("disabled", 1), ("alternate", 2), ("backup", 3), ("root", 4), ("designated", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpPortRole.setStatus('current')
rldot1dStpBpduType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("stp", 0), ("rstp", 1)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpBpduType.setStatus('current')
rldot1dStpPortRestrictedRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 9), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpPortRestrictedRole.setStatus('current')
rldot1dStpPortAutoEdgePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 10), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpPortAutoEdgePort.setStatus('current')
rldot1dStpPortLoopback = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 11), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpPortLoopback.setStatus('current')
rldot1dStpPortBpduOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 13, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("filter", 0), ("flood", 1), ("bridge", 2), ("stp", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpPortBpduOperStatus.setStatus('current')
rldot1dStpPortsEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 14), TruthValue().clone('true')).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpPortsEnable.setStatus('current')
rldot1dStpTaggedFlooding = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 15), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpTaggedFlooding.setStatus('current')
rldot1dStpPortBelongToVlanDefault = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 16), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpPortBelongToVlanDefault.setStatus('current')
rldot1dStpEnableByDefault = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 17), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpEnableByDefault.setStatus('current')
rldot1dStpPortToDefault = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 18), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpPortToDefault.setStatus('current')
rldot1dStpSupportedType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("perDevice", 1), ("perVlan", 2), ("mstp", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpSupportedType.setStatus('current')
rldot1dStpEdgeportSupportInStp = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 20), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dStpEdgeportSupportInStp.setStatus('current')
rldot1dStpFilterBpdu = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 21), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpFilterBpdu.setStatus('current')
rldot1dStpFloodBpduMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("classic", 0), ("bridging", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpFloodBpduMethod.setStatus('current')
rldot1dStpSeparatedBridges = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 23))
rldot1dStpPortBpduGuardTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 24), )
if mibBuilder.loadTexts: rldot1dStpPortBpduGuardTable.setStatus('current')
rldot1dStpPortBpduGuardEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 24, 1), ).setIndexNames((0, "BRIDGE-MIB", "dot1dBasePort"))
if mibBuilder.loadTexts: rldot1dStpPortBpduGuardEntry.setStatus('current')
rldot1dStpPortBpduGuardEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 24, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpPortBpduGuardEnable.setStatus('current')
rldot1dStpLoopbackGuardEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 25), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpLoopbackGuardEnable.setStatus('current')
rldot1dStpSeparatedBridgesTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 23, 1), )
if mibBuilder.loadTexts: rldot1dStpSeparatedBridgesTable.setStatus('current')
rldot1dStpSeparatedBridgesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 23, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: rldot1dStpSeparatedBridgesEntry.setStatus('current')
rldot1dStpSeparatedBridgesPortEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 23, 1, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpSeparatedBridgesPortEnable.setStatus('current')
rldot1dStpSeparatedBridgesEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 23, 2), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpSeparatedBridgesEnable.setStatus('current')
rldot1dStpSeparatedBridgesAutoConfig = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 2, 23, 3), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1dStpSeparatedBridgesAutoConfig.setStatus('current')
rldot1dExtBase = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 3))
rldot1dExtBaseMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 3, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dExtBaseMibVersion.setStatus('current')
rldot1dDeviceCapabilities = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 3, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dDeviceCapabilities.setStatus('current')
rldot1wRStp = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 4))
rldot1wRStpVlanEdgePortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 4, 1), )
if mibBuilder.loadTexts: rldot1wRStpVlanEdgePortTable.setStatus('current')
rldot1wRStpVlanEdgePortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 4, 1, 1), ).setIndexNames((0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1wRStpVlanEdgePortVlan"), (0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1wRStpVlanEdgePortPort"))
if mibBuilder.loadTexts: rldot1wRStpVlanEdgePortEntry.setStatus('current')
rldot1wRStpVlanEdgePortVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4095))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1wRStpVlanEdgePortVlan.setStatus('current')
rldot1wRStpVlanEdgePortPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 4, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1wRStpVlanEdgePortPort.setStatus('current')
rldot1wRStpEdgePortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 4, 1, 1, 3), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1wRStpEdgePortStatus.setStatus('current')
rldot1wRStpForceVersionTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 4, 2), )
if mibBuilder.loadTexts: rldot1wRStpForceVersionTable.setStatus('current')
rldot1wRStpForceVersionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 4, 2, 1), ).setIndexNames((0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1wRStpForceVersionVlan"))
if mibBuilder.loadTexts: rldot1wRStpForceVersionEntry.setStatus('current')
rldot1wRStpForceVersionVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 4, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4095))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1wRStpForceVersionVlan.setStatus('current')
rldot1wRStpForceVersionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 4, 2, 1, 2), Integer32().clone(2)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1wRStpForceVersionState.setStatus('current')
rldot1pPriorityMap = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 5))
rldot1pPriorityMapState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1pPriorityMapState.setStatus('current')
rldot1pPriorityMapTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 5, 2), )
if mibBuilder.loadTexts: rldot1pPriorityMapTable.setStatus('current')
rldot1pPriorityMapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 5, 2, 1), ).setIndexNames((0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1pPriorityMapName"))
if mibBuilder.loadTexts: rldot1pPriorityMapEntry.setStatus('current')
rldot1pPriorityMapName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 5, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 25))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1pPriorityMapName.setStatus('current')
rldot1pPriorityMapPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 5, 2, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 8)).setFixedLength(8)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rldot1pPriorityMapPriority.setStatus('current')
rldot1pPriorityMapPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 5, 2, 1, 3), PortList()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rldot1pPriorityMapPort.setStatus('current')
rldot1pPriorityMapPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 5, 2, 1, 4), PortList()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1pPriorityMapPortList.setStatus('current')
rldot1pPriorityMapStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 5, 2, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rldot1pPriorityMapStatus.setStatus('current')
rldot1sMstp = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6))
rldot1sMstpInstanceTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1), )
if mibBuilder.loadTexts: rldot1sMstpInstanceTable.setStatus('current')
rldot1sMstpInstanceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1), ).setIndexNames((0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1sMstpInstanceId"))
if mibBuilder.loadTexts: rldot1sMstpInstanceEntry.setStatus('current')
rldot1sMstpInstanceId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceId.setStatus('current')
rldot1sMstpInstanceEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 2), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceEnable.setStatus('current')
rldot1sMstpInstanceTimeSinceTopologyChange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceTimeSinceTopologyChange.setStatus('current')
rldot1sMstpInstanceTopChanges = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceTopChanges.setStatus('current')
rldot1sMstpInstanceDesignatedRoot = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 5), BridgeId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceDesignatedRoot.setStatus('current')
rldot1sMstpInstanceRootCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceRootCost.setStatus('current')
rldot1sMstpInstanceRootPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceRootPort.setStatus('current')
rldot1sMstpInstanceMaxAge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 8), Timeout()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceMaxAge.setStatus('current')
rldot1sMstpInstanceHelloTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 9), Timeout()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceHelloTime.setStatus('current')
rldot1sMstpInstanceHoldTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceHoldTime.setStatus('current')
rldot1sMstpInstanceForwardDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 11), Timeout()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceForwardDelay.setStatus('current')
rldot1sMstpInstancePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 61440))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1sMstpInstancePriority.setStatus('current')
rldot1sMstpInstanceRemainingHopes = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 1, 1, 13), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstanceRemainingHopes.setStatus('current')
rldot1sMstpInstancePortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2), )
if mibBuilder.loadTexts: rldot1sMstpInstancePortTable.setStatus('current')
rldot1sMstpInstancePortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1), ).setIndexNames((0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1sMstpInstancePortMstiId"), (0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1sMstpInstancePortPort"))
if mibBuilder.loadTexts: rldot1sMstpInstancePortEntry.setStatus('current')
rldot1sMstpInstancePortMstiId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstancePortMstiId.setStatus('current')
rldot1sMstpInstancePortPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4096))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstancePortPort.setStatus('current')
rldot1sMstpInstancePortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 240))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1sMstpInstancePortPriority.setStatus('current')
rldot1sMstpInstancePortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("disabled", 1), ("blocking", 2), ("listening", 3), ("learning", 4), ("forwarding", 5), ("broken", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstancePortState.setStatus('current')
rldot1sMstpInstancePortEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstancePortEnable.setStatus('current')
rldot1sMstpInstancePortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstancePortPathCost.setStatus('current')
rldot1sMstpInstancePortDesignatedRoot = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 7), BridgeId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstancePortDesignatedRoot.setStatus('current')
rldot1sMstpInstancePortDesignatedCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstancePortDesignatedCost.setStatus('current')
rldot1sMstpInstancePortDesignatedBridge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 9), BridgeId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstancePortDesignatedBridge.setStatus('current')
rldot1sMstpInstancePortDesignatedPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 10), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstancePortDesignatedPort.setStatus('current')
rldot1sMstpInstancePortForwardTransitions = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpInstancePortForwardTransitions.setStatus('current')
rldot1sMStpInstancePortAdminPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1sMStpInstancePortAdminPathCost.setStatus('current')
rldot1sMStpInstancePortRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("unknown", 0), ("disabled", 1), ("alternate", 2), ("backup", 3), ("root", 4), ("designated", 5), ("master", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMStpInstancePortRole.setStatus('current')
rldot1sMstpMaxHopes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 40)).clone(20)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1sMstpMaxHopes.setStatus('current')
rldot1sMstpConfigurationName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 4), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpConfigurationName.setStatus('current')
rldot1sMstpRevisionLevel = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpRevisionLevel.setStatus('current')
rldot1sMstpVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 6), )
if mibBuilder.loadTexts: rldot1sMstpVlanTable.setStatus('current')
rldot1sMstpVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 6, 1), ).setIndexNames((0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1sMstpVlan"))
if mibBuilder.loadTexts: rldot1sMstpVlanEntry.setStatus('current')
rldot1sMstpVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpVlan.setStatus('current')
rldot1sMstpGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 6, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpGroup.setStatus('current')
rldot1sMstpPendingGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 6, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1sMstpPendingGroup.setStatus('current')
rldot1sMstpExtPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 7), )
if mibBuilder.loadTexts: rldot1sMstpExtPortTable.setStatus('current')
rldot1sMstpExtPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 7, 1), ).setIndexNames((0, "DLINK-3100-BRIDGEMIBOBJECTS-MIB", "rldot1sMstpExtPortPort"))
if mibBuilder.loadTexts: rldot1sMstpExtPortEntry.setStatus('current')
rldot1sMstpExtPortPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4096))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpExtPortPort.setStatus('current')
rldot1sMstpExtPortInternalOperPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpExtPortInternalOperPathCost.setStatus('current')
rldot1sMstpExtPortDesignatedRegionalRoot = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 7, 1, 3), BridgeId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpExtPortDesignatedRegionalRoot.setStatus('current')
rldot1sMstpExtPortDesignatedRegionalCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 7, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpExtPortDesignatedRegionalCost.setStatus('current')
rldot1sMstpExtPortBoundary = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 7, 1, 5), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpExtPortBoundary.setStatus('current')
rldot1sMstpExtPortInternalAdminPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 7, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1sMstpExtPortInternalAdminPathCost.setStatus('current')
rldot1sMstpDesignatedMaxHopes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 40))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpDesignatedMaxHopes.setStatus('current')
rldot1sMstpRegionalRoot = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 9), BridgeId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpRegionalRoot.setStatus('current')
rldot1sMstpRegionalRootCost = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpRegionalRootCost.setStatus('current')
rldot1sMstpPendingConfigurationName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 11), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1sMstpPendingConfigurationName.setStatus('current')
rldot1sMstpPendingRevisionLevel = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1sMstpPendingRevisionLevel.setStatus('current')
rldot1sMstpPendingAction = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("copyPendingActive", 1), ("copyActivePending", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rldot1sMstpPendingAction.setStatus('current')
rldot1sMstpRemainingHops = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 6, 14), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1sMstpRemainingHops.setStatus('current')
rldot1dTpAgingTime = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 7))
rldot1dTpAgingTimeMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 7, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dTpAgingTimeMin.setStatus('current')
rldot1dTpAgingTimeMax = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 94, 89, 89, 57, 7, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rldot1dTpAgingTimeMax.setStatus('current')
mibBuilder.exportSymbols("DLINK-3100-BRIDGEMIBOBJECTS-MIB", rldot1dStpVlanPortDesignatedBridge=rldot1dStpVlanPortDesignatedBridge, rldot1pPriorityMapEntry=rldot1pPriorityMapEntry, rldot1sMStpInstancePortRole=rldot1sMStpInstancePortRole, rldot1sMstpInstancePriority=rldot1sMstpInstancePriority, rldot1pPriorityMapPriority=rldot1pPriorityMapPriority, rldot1dStpVlan=rldot1dStpVlan, rldot1sMstpExtPortInternalAdminPathCost=rldot1sMstpExtPortInternalAdminPathCost, rldot1dStpVlanPortPriority=rldot1dStpVlanPortPriority, rldot1sMstpInstancePortPathCost=rldot1sMstpInstancePortPathCost, rlpBridgeMIBObjects=rlpBridgeMIBObjects, rldot1dStpMibVersion=rldot1dStpMibVersion, rldot1sMstpExtPortPort=rldot1sMstpExtPortPort, rldot1sMstpInstanceHoldTime=rldot1sMstpInstanceHoldTime, rldot1dStpPortBpduSent=rldot1dStpPortBpduSent, rldot1sMstpInstancePortPort=rldot1sMstpInstancePortPort, rldot1sMstpConfigurationName=rldot1sMstpConfigurationName, rldot1dStpSeparatedBridgesTable=rldot1dStpSeparatedBridgesTable, rldot1dStpTopChanges=rldot1dStpTopChanges, rldot1dStpTypeAfterReset=rldot1dStpTypeAfterReset, rldot1dStpHoldTime=rldot1dStpHoldTime, rldot1dExtBaseMibVersion=rldot1dExtBaseMibVersion, rldot1dTpAgingTime=rldot1dTpAgingTime, rldot1sMstpInstancePortDesignatedBridge=rldot1sMstpInstancePortDesignatedBridge, rldot1dTpAgingTimeMin=rldot1dTpAgingTimeMin, rldot1dStpVlanPortForwardTransitions=rldot1dStpVlanPortForwardTransitions, rldot1dExtBase=rldot1dExtBase, rldot1dStpBpduType=rldot1dStpBpduType, rldot1sMstpInstanceId=rldot1sMstpInstanceId, rldot1sMstp=rldot1sMstp, rldot1sMstpRegionalRootCost=rldot1sMstpRegionalRootCost, rldot1dStpSeparatedBridgesEntry=rldot1dStpSeparatedBridgesEntry, rldot1dStpPortBpduReceived=rldot1dStpPortBpduReceived, rldot1sMstpGroup=rldot1sMstpGroup, rldot1sMstpPendingGroup=rldot1sMstpPendingGroup, rldot1dStpSeparatedBridgesEnable=rldot1dStpSeparatedBridgesEnable, rldot1dPriorityPortGroupTable=rldot1dPriorityPortGroupTable, rldot1dStpRootPort=rldot1dStpRootPort, rldot1dStpPortsEnable=rldot1dStpPortsEnable, rldot1sMstpInstanceTimeSinceTopologyChange=rldot1sMstpInstanceTimeSinceTopologyChange, rldot1pPriorityMapName=rldot1pPriorityMapName, rldot1pPriorityMap=rldot1pPriorityMap, rldot1sMstpInstanceRootCost=rldot1sMstpInstanceRootCost, rldot1dStpDesignatedRoot=rldot1dStpDesignatedRoot, rldot1dStp=rldot1dStp, rldot1sMstpInstancePortPriority=rldot1sMstpInstancePortPriority, rldot1dDeviceCapabilities=rldot1dDeviceCapabilities, rldot1sMstpPendingConfigurationName=rldot1sMstpPendingConfigurationName, rldot1sMstpInstanceEnable=rldot1sMstpInstanceEnable, rldot1dPriorityPortGroupEntry=rldot1dPriorityPortGroupEntry, rldot1dStpPortLoopback=rldot1dStpPortLoopback, rldot1sMstpRegionalRoot=rldot1sMstpRegionalRoot, rldot1pPriorityMapStatus=rldot1pPriorityMapStatus, rldot1sMstpInstanceTable=rldot1sMstpInstanceTable, rldot1dStpVlanEntry=rldot1dStpVlanEntry, rldot1dStpMaxAge=rldot1dStpMaxAge, rldot1sMstpMaxHopes=rldot1sMstpMaxHopes, rldot1dStpPortPort=rldot1dStpPortPort, rldot1sMStpInstancePortAdminPathCost=rldot1sMStpInstancePortAdminPathCost, rldot1dStpTrapVrblifIndex=rldot1dStpTrapVrblifIndex, rldot1wRStpForceVersionEntry=rldot1wRStpForceVersionEntry, rldot1dTpAgingTimeMax=rldot1dTpAgingTimeMax, rldot1dStpBpduCount=rldot1dStpBpduCount, rldot1sMstpPendingRevisionLevel=rldot1sMstpPendingRevisionLevel, rldot1dStpPortBpduGuardEntry=rldot1dStpPortBpduGuardEntry, rldot1dStpPortTable=rldot1dStpPortTable, rldot1dStpVlanPortDesignatedPort=rldot1dStpVlanPortDesignatedPort, rldot1dStpExtendedPortNumberFormat=rldot1dStpExtendedPortNumberFormat, rldot1dStpVlanPortVlan=rldot1dStpVlanPortVlan, rldot1wRStpForceVersionState=rldot1wRStpForceVersionState, rldot1sMstpInstancePortForwardTransitions=rldot1sMstpInstancePortForwardTransitions, rldot1dStpVlanEnable=rldot1dStpVlanEnable, rldot1sMstpInstanceForwardDelay=rldot1sMstpInstanceForwardDelay, rldot1dStpPortFilterBpdu=rldot1dStpPortFilterBpdu, rldot1dStpPortBpduGuardTable=rldot1dStpPortBpduGuardTable, rldot1dPriorityPortGroupNumber=rldot1dPriorityPortGroupNumber, rldot1dStpTrapVrblVID=rldot1dStpTrapVrblVID, rldot1dStpSeparatedBridges=rldot1dStpSeparatedBridges, rldot1dStpVlanTable=rldot1dStpVlanTable, rldot1dStpMonitorTime=rldot1dStpMonitorTime, rldot1sMstpExtPortInternalOperPathCost=rldot1sMstpExtPortInternalOperPathCost, rldot1pPriorityMapPort=rldot1pPriorityMapPort, rldot1dStpPortRole=rldot1dStpPortRole, rldot1wRStpForceVersionVlan=rldot1wRStpForceVersionVlan, rldot1pPriorityMapTable=rldot1pPriorityMapTable, rldot1dStpVlanPortEntry=rldot1dStpVlanPortEntry, rldot1dStpSeparatedBridgesPortEnable=rldot1dStpSeparatedBridgesPortEnable, rldot1sMstpInstancePortDesignatedRoot=rldot1sMstpInstancePortDesignatedRoot, rldot1sMstpInstanceEntry=rldot1sMstpInstanceEntry, rldot1sMstpVlanTable=rldot1sMstpVlanTable, PYSNMP_MODULE_ID=rlpBridgeMIBObjects, rldot1dPriority=rldot1dPriority, rldot1dStpPortBpduOperStatus=rldot1dStpPortBpduOperStatus, rldot1wRStpVlanEdgePortEntry=rldot1wRStpVlanEdgePortEntry, rldot1pPriorityMapState=rldot1pPriorityMapState, rldot1dStpPortDampEnable=rldot1dStpPortDampEnable, rldot1sMstpExtPortDesignatedRegionalRoot=rldot1sMstpExtPortDesignatedRegionalRoot, rldot1sMstpInstancePortTable=rldot1sMstpInstancePortTable, rldot1dStpType=rldot1dStpType, rldot1dStpPortDampStable=rldot1dStpPortDampStable, rldot1dStpPortEntry=rldot1dStpPortEntry, rldot1dStpVlanPortPathCost=rldot1dStpVlanPortPathCost, rldot1dStpEdgeportSupportInStp=rldot1dStpEdgeportSupportInStp, rldot1sMstpExtPortEntry=rldot1sMstpExtPortEntry, rldot1sMstpInstanceRootPort=rldot1sMstpInstanceRootPort, rldot1sMstpVlanEntry=rldot1sMstpVlanEntry, rldot1wRStp=rldot1wRStp, rldot1sMstpInstanceTopChanges=rldot1sMstpInstanceTopChanges, rldot1dStpVlanPortDesignatedCost=rldot1dStpVlanPortDesignatedCost, rldot1sMstpDesignatedMaxHopes=rldot1sMstpDesignatedMaxHopes, rldot1dStpHelloTime=rldot1dStpHelloTime, rldot1dPriorityMibVersion=rldot1dPriorityMibVersion, rldot1dStpTaggedFlooding=rldot1dStpTaggedFlooding, rldot1dStpPortBpduGuardEnable=rldot1dStpPortBpduGuardEnable, rldot1dStpEnable=rldot1dStpEnable, rldot1wRStpVlanEdgePortPort=rldot1wRStpVlanEdgePortPort, rldot1wRStpVlanEdgePortTable=rldot1wRStpVlanEdgePortTable, rldot1sMstpInstanceRemainingHopes=rldot1sMstpInstanceRemainingHopes, rldot1wRStpVlanEdgePortVlan=rldot1wRStpVlanEdgePortVlan, rldot1dStpPortToDefault=rldot1dStpPortToDefault, rldot1dStpLastChanged=rldot1dStpLastChanged, rldot1sMstpPendingAction=rldot1sMstpPendingAction, rldot1dStpRootCost=rldot1dStpRootCost, rldot1sMstpInstancePortDesignatedPort=rldot1sMstpInstancePortDesignatedPort, rldot1dStpForwardDelay=rldot1dStpForwardDelay, rldot1wRStpEdgePortStatus=rldot1wRStpEdgePortStatus, rldot1sMstpExtPortTable=rldot1sMstpExtPortTable, rldot1sMstpInstanceDesignatedRoot=rldot1sMstpInstanceDesignatedRoot, rldot1sMstpInstancePortEnable=rldot1sMstpInstancePortEnable, rldot1dStpVlanPortDesignatedRoot=rldot1dStpVlanPortDesignatedRoot, rldot1sMstpInstancePortDesignatedCost=rldot1sMstpInstancePortDesignatedCost, rldot1dStpTimeSinceTopologyChange=rldot1dStpTimeSinceTopologyChange, rldot1dStpVlanPortState=rldot1dStpVlanPortState, rldot1pPriorityMapPortList=rldot1pPriorityMapPortList, rldot1sMstpInstancePortMstiId=rldot1sMstpInstancePortMstiId, rldot1sMstpInstanceMaxAge=rldot1sMstpInstanceMaxAge, rldot1sMstpInstancePortEntry=rldot1sMstpInstancePortEntry, rldot1dStpPortBelongToVlanDefault=rldot1dStpPortBelongToVlanDefault, rldot1sMstpExtPortBoundary=rldot1sMstpExtPortBoundary, rldot1dStpEnableByDefault=rldot1dStpEnableByDefault, rldot1sMstpRemainingHops=rldot1sMstpRemainingHops, rldot1dStpFloodBpduMethod=rldot1dStpFloodBpduMethod, rldot1dStpSeparatedBridgesAutoConfig=rldot1dStpSeparatedBridgesAutoConfig, rldot1dStpPortRestrictedRole=rldot1dStpPortRestrictedRole, rldot1dStpTrapVariable=rldot1dStpTrapVariable, rldot1dStpVlanPortEnable=rldot1dStpVlanPortEnable, rldot1sMstpInstanceHelloTime=rldot1sMstpInstanceHelloTime, rldot1dStpSupportedType=rldot1dStpSupportedType, rldot1dStpLoopbackGuardEnable=rldot1dStpLoopbackGuardEnable, rldot1wRStpForceVersionTable=rldot1wRStpForceVersionTable, rldot1sMstpInstancePortState=rldot1sMstpInstancePortState, rldot1sMstpVlan=rldot1sMstpVlan, rldot1dStpPortAutoEdgePort=rldot1dStpPortAutoEdgePort, rldot1sMstpRevisionLevel=rldot1sMstpRevisionLevel, rldot1dStpFilterBpdu=rldot1dStpFilterBpdu, rldot1dStpVlanPortTable=rldot1dStpVlanPortTable, rldot1sMstpExtPortDesignatedRegionalCost=rldot1sMstpExtPortDesignatedRegionalCost, rldot1dStpVlanPortPort=rldot1dStpVlanPortPort, rldot1dStpPortMustBelongToVlan=rldot1dStpPortMustBelongToVlan)
|
def has_doi(bib_info):
return "doi" in bib_info
def get_doi(bib_info):
return bib_info["doi"]
def has_title(bib_info):
return "title" in bib_info
def get_title(bib_info):
return bib_info["title"]
def has_url(bib_info):
return "url" in bib_info
def get_url(bib_info):
if "url" in bib_info:
return bib_info["url"]
else:
return ""
def has_author(bib_info):
return "author" in bib_info
def get_author(bib_info):
return bib_info["author"]
|
payload_mass=5
payload_fairing_height=1
stage1_height=7.5
stage1_burnTime=74
stage1_propellant_mass=15000
stage1_engine_mass=1779
stage1_thrust=469054
stage1_isp=235.88175331294596
stage1_coastTime=51
stage2_height=3.35
stage2_burnTime=64
stage2_propellant_mass=5080
stage2_engine_mass=527
stage2_thrust=220345
stage2_isp=282.97655453618756
stage2_coastTime=164
stage3_height=2.1
stage3_burnTime=46
stage3_propellant_mass=1760
stage3_engine_mass=189
stage3_thrust=106212
stage3_isp=282.97655453618756
stage3_coastTime=50
outside_diameter=1.405
propulsion_modifier=0.02
voltage = 28.8
|
# Problem:
# Write a program that introduces a number n (2 ≤ n ≤ 100) and prints a cot with a size n x n.
n = int(input())
asterisk = "*"
minuses = "-"
for i in range(1, n + 1):
if n % 2 == 0 and i % 2 == 0:
asterisk = i
minuses = (n - i ) // 2
print("-" * minuses + "*" * asterisk + "-" * minuses)
elif n % 2 != 0 and i % 2 != 0:
asterisk = i
minuses = (n - i) // 2
print("-" * minuses + "*" * asterisk + "-" * minuses)
for i in range(0 , n // 2):
print("|" + "*" * (n -2) + "|")
|
digit1 = 999
digit2 = 999
largestpal = 0 #always save the largest palindrome
#nested loop for 3digit product
while digit1 >= 1:
while digit2 >= 1:
#get string from int
p1 = str(digit1 * digit2)
#check string for palindrome by comparing first-last, etc.
for i in range(0, (len(p1) - 1)):
#no pal? go on
if p1[i] != p1[len(p1)-i-1]:
break
#pal? save if larger than current
elif i >= (len(p1)-1)/2:
if largestpal < int(p1):
largestpal = digit1 * digit2
print (largestpal)
digit2 -= 1
digit1 -= 1
digit2 = 999
print (largestpal)
|
class InvalidMoveException(Exception):
pass
class InvalidPlayerException(Exception):
pass
class InvalidGivenBallsException(Exception):
pass
class GameIsOverException(Exception):
pass
|
while True:
try:
dinheiro = []
nota = input()
cent = input()
if(len(cent) < 2):
cent += '0'
cent = cent[::-1]
dinheiro += '.' + cent
print(dinheiro)
except EOFError:
break
|
# import sys
# from io import StringIO
#
# input_1 = """3, 6
# 7, 1, 3, 3, 2, 1
# 1, 3, 9, 8, 5, 6
# 4, 6, 7, 9, 1, 0
# """
#
# sys.stdin = StringIO(input_1)
rows, columns = [int(x) for x in input().split(", ")]
matrix = []
sum_matrix = 0
for _ in range(rows):
row = [int(x) for x in input().split(", ")]
matrix.append(row)
sum_matrix += sum(row)
print(sum_matrix)
print(matrix)
|
'''
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.
Example:
MyHashSet hashSet = new MyHashSet();
hashSet.add(1);
hashSet.add(2);
hashSet.contains(1); // returns true
hashSet.contains(3); // returns false (not found)
hashSet.add(2);
hashSet.contains(2); // returns true
hashSet.remove(2);
hashSet.contains(2); // returns false (already removed)
Note:
All values will be in the range of [0, 1000000].
The number of operations will be in the range of [1, 10000].
Please do not use the built-in HashSet library.
'''
class MyHashSet:
def eval_hash(self, key):
return ((key*1031237) & (1<<20) - 1)>>5
def __init__(self):
self.a = [[] for _ in range(1<<15)]
def add(self, key: int) -> None:
pos = self.eval_hash(key) #calling function foa a key to generate a position using hash formula
if key not in self.a[pos]:
self.a[pos].append(key)
def remove(self, key: int) -> None:
pos = self.eval_hash(key)
if key in self.a[pos]:
self.a[pos].remove(key)
def contains(self, key: int) -> bool:
pos = self.eval_hash(key)
print(pos,self.a[pos])
if key in self.a[pos]:
return True
return False
'''
The idea is to have hash function in the following form.
image
Here we use the following notations:
K is our number (key), we want to hash.
a is some big odd number (sometimes good idea to use prime number) I choose a = 1031237 without any special reason, it is just random odd number.
m is length in bits of output we wan to have. We are given, that we have no more than 10000 operations overall, so we can choose such m, so that 2^m > 10000. I chose m = 15, so in this case we have less collistions.
if you go to wikipedia, you can read that w is size of machine word. Here we do not really matter, what is this size, we can choose any w > m. I chose m = 20.
So, everything is ready for function eval_hash(key): ((key*1031237) & (1<<20) - 1)>>5. Here I also used trick for fast bit operation modulo 2^t: for any s: s % (2^t) = s & (1<<t) - 1.'''
|
# -*- coding: UTF-8 -*-
class MyClass(object):
def __init__(self):
pass
def __eq__(self, other):
return type(self) == type(other)
if __name__ == '__main__':
print (MyClass())
print (MyClass())
print (MyClass() == MyClass())
print (MyClass() == 42)
|
"""pandas-data-dictionary - Pandas extension adding data dictionary accessor for describing and validating data."""
__version__ = '0.1.0'
__author__ = 'Tom Couch <[email protected]>'
__all__ = []
|
# 2020.08.02
# Problem Statement:
# https://leetcode.com/problems/substring-with-concatenation-of-all-words/
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
# check if s is empty or words is empty
if len(s) * len(words) == 0: return []
# length is the total length of words
# word_length is the length per word in words (all the same)
# word_dict is the hash table to store words and their occurance times
length = len(words) * len(words[0])
word_length = len(words[0])
word_dict = {}
# initialize the occurances to all 0
for word in words:
word_dict[word] = 0
# calculate for occurance times
for word in words:
word_dict[word] = word_dict[word] + 1
# do a deep copy for word_dict
word_dict_copy = deepcopy(word_dict)
# initialize answer to return
answer = []
# start index can be any index between [0, len(s)-length]
for start in range(0, len(s)-length+1):
# if this substring is legal
add = True
# check all the potential matched words in substring
for word_index in range(0, len(words)):
# get the single word
word = s[start+word_index*word_length: start+(word_index+1)*word_length]
# not match, this substring should not count
if word not in word_dict.keys():
add = False
break
# match
else:
# check occurance time, should have 1 less occurance time remaining
word_dict[word] = word_dict[word] - 1
# exceed the occurance times
if word_dict[word] < 0:
add = False
break
# add the result
if add:
answer.append(start)
# get back the orginal word_dict
word_dict = deepcopy(word_dict_copy)
return answer
|
print("hello")
print("hello")
print("hello")
print("hello")
print("It's me")
print("I'm here")
|
class CourseType():
__doc__ = "Type of degree, e.g. BA, BEng, BSc"
possibleCourseTypes = ["BA", "BSc"] #TODO extend to values from http://typesofdegrees.org/
def __init__(self, name, accepts, singleHons = 0, jointHons = 0):
if self.checkName(name):
self._name = name
self.accepts = accepts
self.singleHons = singleHons
self.jointHons = jointHons
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if self.checkName(value):
self._name = name # Must be one of possibleCourseTypes
def checkName(self, name):
if (name in self.possibleCourseTypes):
return True
else:
raise ValueError("Name must be one of: ", self.possibleCourseTypes)
|
#Given an array of integers, return the 3rd Maximum Number in this array, if it doesn't exist, return the Maximum Number. The time complexity must be O(n) or less.
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a=b=c=-pow(10, 18)
nums=set(nums)
for i in nums:
if i>=a:
c,b,a=b,a,i
elif i>=b:
c,b=b,i
elif i>=c:
c=i
return c if len(nums)>2 else max(nums)
|
def collatz_len(n):
ct = 1
while n != 1:
if n % 2 == 0:
n = n/2
else:
n = 3*n+1
ct += 1
return ct
len_max = i_max = 0
for i in range(1, 1000001):
current_len = collatz_len(i)
if current_len > len_max:
len_max = current_len
i_max = i
print(i_max)
|
# Sorts a Python list in ascending order using the quick sort
# algorithm
def quickSort(theList):
n = len(theList)
recQuickSort(theList, 0, n-1)
# The recursive "in-place" implementation
def recQuickSort(theList, first, last):
# Check the base case (range is trivially sorted)
if first >= last:
return
else:
# Partition the list and obtain the pivot position
pos = partitionSeq(theList, first, last)
# Repeat the process on the two sublists
recQuickSort(theList, first, pos - 1)
recQuickSort(theList, pos + 1, last)
# Partitions the list using the first key as the pivot
def partitionSeq(theList, first, last):
# Save a copy of the pivot value.
pivot = theList[first] # first element of range is pivot
# Find the pivot position and move the elements around it
left = first + 1 # will scan rightward
right = last # will scan leftward
while left <= right:
# Scan until reaches value equal or larger than pivot (or
# right marker)
while left <= right and theList[left] < pivot:
left += 1
# Scan until reaches value equal or smaller than pivot (or
# left marker)
while left <= right and theList[right] > pivot:
right -= 1
# Scans did not strictly cross
if left <= right:
# swap values
theList[left], theList[right] = theList[right], theList[left]
# Shrink range (Recursion: Progress towards base case)
left += 1
right -= 1
# Put the pivot in the proper position (marked by the right index)
theList[first] , theList[right] = theList[right] , pivot
# Return the index position of the pivot value.
return right
# Test code
list_of_numbers = [12, 7, 9, 24, 7, 29, 5, 3, 11, 7]
print('Input List:', list_of_numbers)
quickSort(list_of_numbers)
print('Sorted List:', list_of_numbers)
|
class Commitment(object):
"""
Abstraction from the messages.Commitment
Purpose: don't mix messaging logic with internal logic
Expect that the `protocol.send()` takes an instance of Commitment and constructs the message by itself.
On incoming messages, the protocol will use the `Commitment.from_message(msg)` to construct a Commitment
Bottom line: don't worry about messages, but use this class instead!
"""
def __init__(self, amount, offer_id, timeout, signature, sender):
self.amount = amount
self.offer = offer_id
self.timeout = timeout
self.sender = sender
self.signature = signature
@classmethod
def from_message(cls, message):
offer_id = message.offer_id
timeout = message.timeout
amount = message.amount
signature = message.signature
sender = message.sender
return cls(amount, offer_id, timeout, signature, sender)
class SwapExecution(object):
"""
Abstraction from the messages.SwapExecution
Purpose: don't mix messaging logic with internal logic
Expect that the `protocol.send()` takes an instance of SwapExecution and constructs the message by itself.
On incoming messages, the protocol will use the `SwapExecution.from_message(msg)` to construct a SwapExecution
Bottom line: don't worry about messages, but use this class instead!
"""
def __init__(self, offer_id, timestamp, sender):
self.offer_id = offer_id
self.timestamp = timestamp
self.sender = sender
@classmethod
def from_message(cls, message):
offer_id = message.offer_id
timestamp = message.timestamp
sender = message.sender
return cls(offer_id, timestamp, sender)
|
class Time:
max_hours = 23
max_minutes = 59
max_seconds = 59
def __init__(self, hours: int, minutes: int, seconds: int):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def set_time(self, hours, minutes, seconds):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def get_time(self):
hh = str(self.hours)
mm = str(self.minutes)
ss = str(self.seconds)
return f"{hh.zfill(2)}:{mm.zfill(2)}:{ss.zfill(2)}"
def next_second(self):
self.seconds = (self.seconds + 1) % 60
self.minutes = (self.minutes + int(self.seconds == 0)) % 60
self.hours = (self.hours + int(self.minutes == 0 and self.seconds == 0)) % 24
return self.get_time()
# time = Time(9, 30, 59)
# print(time.next_second())
# time = Time(10, 59, 59)
# print(time.next_second())
time = Time(24, 59, 59)
print(time.get_time())
print(time.next_second())
print(time.next_second())
print(time.next_second())
print(time.next_second())
print(time.next_second())
print(time.next_second())
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def subfun(root, minimal, maximal):
if not root:
return
if root.val >= maximal or root.val <= minimal:
self.out = False
else:
subfun(root.left, minimal, root.val)
if self.out:
subfun(root.right, root.val, maximal)
self.out = True
subfun(root, -inf, inf)
return self.out
|
# Lambda funkcie
#
# Tato sekcia sluzi na precvicenie si lambda vyrazov
#
# Uloha 1:
def make_square():
return(lambda x: x*x)
# Uloha 2:
def make_upper():
return(lambda x: x.upper())
# Uloha 3:
def make_power():
return(lambda x, N: x ** N)
# Uloha 4:
def make_power2(N):
return(lambda x: x ** N)
# Uloha 5:
def call_name():
return(lambda x, name: getattr(x, name)())
|
def forever2():
pass
forever(forever2)
|
IMU_BUS = 2
# MPU9250 Default I2C slave address
MPU_DEFAULT_I2C_ADDR = 0x68
"""
register offsets
"""
SMPLRT_DIV = 0x19
CONFIG = 0x1A
GYRO_CONFIG = 0x1B
ACCEL_CONFIG = 0x1C
ACCEL_CONFIG_2 = 0x1D
INT_PIN_CFG = 0x37
ACCEL_XOUT_H = 0x3B
ACCEL_XOUT_L = 0x3C
ACCEL_YOUT_H = 0x3D
ACCEL_YOUT_L = 0x3E
ACCEL_ZOUT_H = 0x3F
ACCEL_ZOUT_L = 0x40
TEMP_OUT_H = 0x41
TEMP_OUT_L = 0x42
GYRO_XOUT_H = 0x43
GYRO_XOUT_L = 0x44
GYRO_YOUT_H = 0x45
GYRO_YOUT_L = 0x46
GYRO_ZOUT_H = 0x47
GYRO_ZOUT_L = 0x48
USER_CTRL = 0x6A
PWR_MGMT_1 = 0x6B
PWR_MGMT_2 = 0x6C
WHO_AM_I_MPU9250 = 0x71
"""
CONFIG register bits
"""
FIFO_MODE_REPLACE_OLD = 0
FIFO_MODE_KEEP_OLD = 0x01 << 6
EXT_SYNC_SET_DISABLE = 0
"""
ACCEL_CONFIG register bits
"""
AX_ST_EN = 0x01 << 7
AY_ST_EN = 0x01 << 6
AZ_ST_EN = 0x01 << 5
ACCEL_FSR_CFG_2G = 0x00 << 3
ACCEL_FSR_CFG_4G = 0x01 << 3
ACCEL_FSR_CFG_8G = 0x02 << 3
ACCEL_FSR_CFG_16G = 0x03 << 3
"""
* ACCEL_CONFIG2 register bits
"""
ACCEL_FCHOICE_1KHZ = 0x00 << 3
ACCEL_FCHOICE_4KHZ = 0x01 << 3
"""
INT_PIN_CFG
"""
ACTL_ACTIVE_LOW = 0x01 << 7
ACTL_ACTIVE_HIGH = 0
INT_OPEN_DRAIN = 0
INT_PUSH_PULL = 0x00 << 6
LATCH_INT_EN = 0x01 << 5
INT_ANYRD_CLEAR = 0x01 << 4
ACTL_FSYNC_ACTIVE_LOW = 0x01 << 3
ACTL_FSYNC_ACTIVE_HIGH = 0x00 << 3
FSYNC_INT_MODE_EN = 0x01 << 2
FSYNC_INT_MODE_DIS = 0x00 << 2
BYPASS_EN = 0x01 << 1
"""
GYRO_CONFIG register bits
"""
XGYRO_CTEN = 0x01 << 7
YGYRO_CTEN = 0x01 << 6
ZGYRO_CTEN = 0x01 << 5
GYRO_FSR_CFG_250 = 0x00 << 3
GYRO_FSR_CFG_500 = 0x01 << 3
GYRO_FSR_CFG_1000 = 0x02 << 3
GYRO_FSR_CFG_2000 = 0x03 << 3
FCHOICE_B_DLPF_EN = 0x00
FCHOICE_B_DLPF_DISABLE = 0x01
"""
PWR_MGMT_1 register settings
"""
H_RESET = 0x01 << 7
MPU_SLEEP = 0x01 << 6
MPU_CYCLE = 0x01 << 5
"""
temperature reading constants
"""
ROOM_TEMP_OFFSET = 0x00
TEMP_SENSITIVITY = 333.87
"""
USER_CTRL settings bits
"""
FIFO_EN_BIT = 0x01 << 6
I2C_MST_EN = 0x01 << 5
I2C_IF_DIS = 0x01 << 4
FIFO_RST = 0x01 << 2
I2C_MST_RST = 0x01 << 1
SIG_COND_RST = 0x01
"""
Magnetometer Registers
"""
AK8963_ADDR = 0x0C
WHO_AM_I_AK8963 = 0x48
INFO = 0x01
AK8963_ST1 = 0x02
AK8963_XOUT_L = 0x03
AK8963_XOUT_H = 0x04
AK8963_YOUT_L = 0x05
AK8963_YOUT_H = 0x06
AK8963_ZOUT_L = 0x07
AK8963_ZOUT_H = 0x08
AK8963_ST2 = 0x09
AK8963_CNTL = 0x0A
AK8963_ASTC = 0x0C
AK8963_I2CDIS = 0x0F
AK8963_ASAX = 0x10
AK8963_ASAY = 0x11
AK8963_ASAZ = 0x12
"""
Magnetometer AK8963_CNTL register Settings
"""
MAG_POWER_DN = 0x00
MAG_SINGLE_MES = 0x01
MAG_CONT_MES_1 = 0x02
MAG_CONT_MES_2 = 0x06
MAG_EXT_TRIG = 0x04
MAG_SELF_TEST = 0x08
MAG_FUSE_ROM = 0x0F
MSCALE_16 = 0x01 << 4
MSCALE_14 = 0x00
"""
Magnetometer AK8963_ST2 register definitions
"""
MAGNETOMETER_SATURATION = 0x01 << 3
"""
Magnetometer AK8963_ST1 register definitions
"""
MAG_DATA_READY = 0x01
"""
Magnetometer sensitivity in micro Teslas to LSB
"""
MAG_RAW_TO_uT = 4912.0 / 32760.0
BIT_I2C_MST_VDDIO = 0x80
BIT_FIFO_EN = 0x40
BIT_DMP_EN = 0x80
BIT_FIFO_RST = 0x04
BIT_DMP_RST = 0x08
BIT_FIFO_OVERFLOW = 0x10
BIT_DATA_RDY_EN = 0x01
BIT_DMP_INT_EN = 0x02
BIT_MOT_INT_EN = 0x40
BITS_FSR = 0x18
BITS_LPF = 0x07
BITS_HPF = 0x07
BITS_CLK = 0x07
BIT_FIFO_SIZE_1024 = 0x40
|
def retrieve_page(page):
if page > 3:
return {"next_page": None, "items": []}
return {"next_page": page + 1, "items": ["A", "B", "C"]}
items = []
page = 1
while page is not None:
page_result = retrieve_page(page)
items += page_result["items"]
page = page_result["next_page"]
print(items) # ["A", "B", "C", "A", "B", "C", "A", "B", "C"]
|
# A chess knight has 8 possible moves it can make, as illustrated. It can move to the nearest square but not on the same row, column, or diagonal.
# (e.g., it can move two squares horizontally, then one square vertically, or it can move one square horizontally then two squares vertically - i.e., in an "L" pattern.)
# The knight game is played on a board with dimensions N x N.
# You will receive a board with "K" for knights and "0" for empty cells. Your task is to remove knights until no knights that can attack one another with one move are left.
# Input
# • On the first line, you will receive integer N - the size of the board
# • On the following N lines, you will receive strings with "K" and "0"
# Output
# • Print a single integer with the minimum number of knights that need to be removed
knight_moves = (
(-2, -1),
(-2, 1),
(-1, -2),
(-1, 2),
(1, -2),
(1, 2),
(2, -1),
(2, 1)
)
def allowed_moves(cell:tuple) -> list:
temp_moves = [(x + cell[0], y + cell[1]) for x, y in knight_moves]
return list(filter(lambda item: min(item[0],item[1]) >= 0 and max(item[0],item[1]) < matrix_size,temp_moves))
def update_take_moves(data:dict) -> dict:
for key in data.keys():
data[key] = [x for x in data[key] if x in data.keys()]
return {k:v for k, v in data.items() if v}
matrix_size = int(input())
knights = {}
for i in range(matrix_size):
line = input()
for j in range(matrix_size):
if line[j] == 'K':
knights[(i, j)] = allowed_moves((i,j))
knights = update_take_moves(knights)
removes = 0
while knights:
removes += 1
s = [k for k, v in sorted(knights.items(), key=lambda item: len(item[1]), reverse=True)]
knights.pop(s[0])
knights = update_take_moves(knights)
print(removes)
|
# 1) O que uma pessoa Tem? Quais as caracteristicas?
###### Atributos --- variáveis
# nome
# idade
# telefone
# sexo
# 2) O que uma pessoa faz?
###### Métodos --- (função/procedimento)
# respira
# dorme
# corre
# bebe
# come
# multiplica ###
# 3) Como a pessoa está agora?
###### Atributos de estado ---- Variáveis
# divida
# cansada
# viva
# fome
# sede
class Pessoa:
'''
Essa classe é uma demonstração para aula
'''
def __init__(self,nome1, idade1, telefone1, sexo1):
'''
O__init__é o motor que irá iniciar as variáveis da classe
o self é o que irá conectar toda a classe
'''
#Atributos##########
self.nome = nome1
self.idade = idade1
self.telefone = telefone1
self.sexo = sexo1
####################
self.divida = None
self.cansada = 'não'
self.viva = True
self.fome = 'não'
self.sede = 'não'
### Métodos
def respira (self, respirar):
if self.viva == True:
if respirar == True:
self.viva = True
else:
self.viva = False
def corre (self, distancia):
if self.viva:
if distancia >= 50 and distancia < 100:
self.cansada = 'pouco'
self.sede = 'pouco'
self.fome = 'pouco'
elif distancia >= 100 and distancia < 200:
self.cansada = 'medio'
self.sede = 'medio'
self.fome = 'medio'
elif distancia >=200:
self.cansada = 'muito'
self.sede = 'muito'
self.fome = 'muito'
def dorme (self):
if self.viva:
self.cansada = 'não'
self.bebe()
self.come()
def bebe (self):
if self.viva:
self.sede = 'não'
def come (self):
if self.viva:
self.fome = 'não'
def multiplica (self):
if self.viva:
self.multiplica = 'não'
p = Pessoa('Antonio', 18, '479966995', 'm')
p.respira(True)
p.corre(300)
p.come()
p.dorme()
p.bebe()
print(f'Meu nome é {p.nome}')
print(f'Esta vivo? {p.viva}')
print(f'Está com fome? {p.fome}')
print(f' Está com sede? {p.sede}')
print(f'Esta cansado? {p.cansada}')
|
# Способ сократить код!
a, b = 5, 10
print("Разность:", a - b)
print()
print("StepikPyGEK001113сh02p02st04C02")
B, b = 1, 0
b, B = 2, 10
print("Если возвести", b, "в", B, "степень, то будет", b ** B)
print()
print("StepikPyGEK001113сh02p02st05C03")
a = 4
b = 3
# Выберите все подходящие ответы из списка
# a, b = 3, 4
# a = 4; b = 3
# a = 4, b = 3
# a, b = 4, 3
print(a, b)
a = 4; b = 3
print(a, b)
# a = 4, b = 3
b = 0
c = 1
a = c
c = b
b = a
print(b, c)
|
# SIEL type compliance cases require a specific control code prefixes. currently: (0 to 9)D, (0 to 9)E, ML21, ML22.
COMPLIANCE_CASE_ACCEPTABLE_GOOD_CONTROL_CODES = "(^[0-9][DE].*$)|(^ML21.*$)|(^ML22.*$)"
class ComplianceVisitTypes:
FIRST_CONTACT = "first_contact"
FIRST_VISIT = "first_visit"
ROUTINE_VISIT = "routine_visit"
REVISIT = "revisit"
choices = [
(FIRST_CONTACT, "First contact"),
(FIRST_VISIT, "First visit"),
(ROUTINE_VISIT, "Routine visit"),
(REVISIT, "Revisit"),
]
@classmethod
def to_str(cls, visit_type):
return next(choice[1] for choice in cls.choices if choice[0] == visit_type)
class ComplianceRiskValues:
VERY_LOW = "very_low"
LOWER = "lower"
MEDIUM = "medium"
HIGHER = "higher"
HIGHEST = "highest"
choices = (
(VERY_LOW, "Very low risk"),
(LOWER, "Lower risk"),
(MEDIUM, "Medium risk"),
(HIGHER, "Higher risk"),
(HIGHEST, "Highest risk"),
)
@classmethod
def to_str(cls, risk_value):
for value, label in cls.choices:
if value == risk_value:
return label
return ""
|
'''
Sort the following string alphabetically, from z to a, and assign it to the variable sorted_letters.
'''
letters = "alwnfiwaksuezlaeiajsdl"
sorted_letters = sorted(letters, reverse = True)
'''
Sort the list below, animals, into alphabetical order, a-z. Save the new list as animals_sorted.
'''
animals = ['elephant', 'cat', 'moose', 'antelope', 'elk', 'rabbit', 'zebra', 'yak', 'salamander', 'deer', 'otter', 'minx', 'giraffe', 'goat', 'cow', 'tiger', 'bear']
animals_sorted = sorted(animals)
'''
The dictionary, medals, shows the medal count for six countries during the Rio Olympics.
Sort the country names so they appear alphabetically. Save this list to the variable alphabetical.
'''
medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}
alphabetical = sorted(medals)
'''
Given the same dictionary, medals, now sort by the medal count. Save the three countries with the highest medal count
to the list, top_three.
'''
medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}
top_three = sorted(medals, key = lambda p: medals[p], reverse = True)[:3]
#top_three = top[:3]
'''
We have provided the dictionary groceries. You should return a list of its keys,
but they should be sorted by their values, from highest to lowest. Save the new list as most_needed.
'''
groceries = {'apples': 5, 'pasta': 3, 'carrots': 12, 'orange juice': 2, 'bananas': 8, 'popcorn': 1, 'salsa': 3, 'cereal': 4, 'coffee': 5, 'granola bars': 15, 'onions': 7, 'rice': 1, 'peanut butter': 2, 'spinach': 9}
most_needed = sorted(groceries, key = lambda k: groceries[k], reverse = True)
'''
Create a function called last_four that takes in an ID number and returns the last four digits.
For example, the number 17573005 should return 3005. Then, use this function to sort the list of ids stored in the variable,
ids, from lowest to highest. Save this sorted list in the variable, sorted_ids.
Hint: Remember that only strings can be indexed, so conversions may be needed.
'''
def last_four(x):
return str(x)[-4]
ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329]
sorted_ids = sorted(ids, key = lambda id: last_four(id))
'''
Sort the list ids by the last four digits of each id. Do this using lambda and not using a defined function.
Save this sorted list in the variable sorted_id.
'''
ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329]
sorted_id = sorted(ids, key = lambda id: str(id)[-4])
'''
Sort the following list by each element’s second letter a to z. Do so by using lambda.
Assign the resulting value to the variable lambda_sort.
'''
ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']
lambda_sort = sorted(ex_lst, key = lambda ch: ch[1])
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
k=-1
pre=ListNode(-1000,list1)
x=ListNode()
y=ListNode()
while pre:
if pre.next and k==a-1:
x=pre
while k!=b:
pre=pre.next
k+=1
y=pre.next
k+=1
pre=pre.next
x.next=list2
print(x.val,y.val)
while list2:
if list2.next:
list2=list2.next
else:
list2.next=y
break
return list1
|
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
def get_max(self):
return max(self.items)
def is_correct_bracket_seq(line):
if len(line) % 2 != 0:
return False
stack = Stack()
# opening_brackets = ('{','[','(')
opening_brackets = {
'{': 0,
'[': 1,
'(': 2
}
# closing_brackets = ('}',']',')')
closing_brackets = {
'}': 0,
']': 1,
')': 2
}
for ch in line:
if ch in closing_brackets.keys() and stack.size() == 0:
return False
if ch in opening_brackets.keys():
stack.push(ch)
if ch in closing_brackets.keys():
index_stack = opening_brackets[stack.peek()]
index_new = closing_brackets[ch]
# print(stack.peek(), ch)
if index_new != index_stack:
return False
else:
stack.pop()
return True
def main():
line = input().strip()
print(is_correct_bracket_seq(line))
main()
|
def palindrome(word, index):
left = index
right = len(word) - 1 - index
if left >= right:
return f"{word} is a palindrome"
right_letter = word[len(word)-1-index]
left_letter = word[index]
if left_letter != right_letter:
return f"{word} is not a palindrome"
return palindrome(word, index + 1)
print(palindrome("abcba", 0))
print((palindrome("peter", 0)))
|
#
# PySNMP MIB module CISCO-HEALTH-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-HEALTH-MONITOR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:59:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
entPhysicalIndex, = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalIndex")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
ModuleIdentity, TimeTicks, Bits, iso, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, MibIdentifier, IpAddress, Counter32, Unsigned32, Gauge32, Integer32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "TimeTicks", "Bits", "iso", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "MibIdentifier", "IpAddress", "Counter32", "Unsigned32", "Gauge32", "Integer32", "Counter64")
TruthValue, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "DisplayString", "TextualConvention")
ciscoHealthMonitorMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 243))
ciscoHealthMonitorMIB.setRevisions(('2003-09-12 12:30',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoHealthMonitorMIB.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts: ciscoHealthMonitorMIB.setLastUpdated('200309121230Z')
if mibBuilder.loadTexts: ciscoHealthMonitorMIB.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts: ciscoHealthMonitorMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W. Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: [email protected]')
if mibBuilder.loadTexts: ciscoHealthMonitorMIB.setDescription("Health Monitor MIB module. The Health Monitor uses a model based on events of varying severity and frequency, and predefined rules, to generate a metric that represents a system's (and its subsystems') level of health. The events are typically internally generated notifications in response to detrimental or correctional changes in the state of the hardware or software of the system. Detrimental events are classified under one of the following severity levels: Catastrophic - Causes or leads to system failure Critical - Major subsystem or functionality failure High - Potential for major impact to important functions Medium - Potential for minor impact to functionality Low - Negligible impact to functionality Whilst correctional events fall under the following classification: Positive - Not a fault event. May cause or lead to the return of functionality This MIB module provides information for tracking occurrences of the above events, and presents the associated health metric for the system and its component subsystems.")
ciscoHealthMonitorMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 243, 1))
class HealthLevel(TextualConvention, Gauge32):
description = 'Reflects the health of a system or subsystem based on system events and predefined rules, expressed as a percentage. The UNITS clause associated with each object will indicate the degree of precision.'
status = 'current'
subtypeSpec = Gauge32.subtypeSpec + ValueRangeConstraint(0, 10000)
ciscoHealthMonitorTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1), )
if mibBuilder.loadTexts: ciscoHealthMonitorTable.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorTable.setDescription('This table contains Health Monitor statistics for physical entities and their constituent hardware and/or software subsystems. The Health Monitor statistics present in each row provide information such as the computed health of the indicated subsystem and the number of faults it has experienced.')
ciscoHealthMonitorEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (1, "CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorSubsysName"))
if mibBuilder.loadTexts: ciscoHealthMonitorEntry.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorEntry.setDescription('A Health Monitor statistics entry. The entPhysicalIndex identifies the physical entity (chassis or container), while the ciscoHealthMonitorSubsysName identifies by name the appropriate subsystem for which these statistics apply. If there are other entities such as peer routers or line cards then, in the context of this MIB, these are also defined to be in the same system. If these entities also run an instance of the Health Monitor then the summary information from the distributed Health Monitors is obtained here.')
ciscoHealthMonitorSubsysName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 128)))
if mibBuilder.loadTexts: ciscoHealthMonitorSubsysName.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorSubsysName.setDescription("A textual string containing the name of the hardware or software subsystem. A management station wishing to obtain summary statistics for a physical entity should use a value of 'system' for this object.")
ciscoHealthMonitorHealth = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 2), HealthLevel()).setUnits('0.01 percent').setMaxAccess("readonly")
if mibBuilder.loadTexts: ciscoHealthMonitorHealth.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorHealth.setDescription('The computed current health of this subsystem on the specified entity. This health metric is based on predefined rules that specify how the health should be adjusted in response to certain events of varying severity and frequency. As these events are encountered by each subsystem or physical entity, the appropriate rules are applied and the health is modified accordingly.')
ciscoHealthMonitorHealthNotifyEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 3), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ciscoHealthMonitorHealthNotifyEnable.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorHealthNotifyEnable.setDescription('Enables or disables health level notifications. When set to true(1), the ciscoHealthMonitorHealthLevel notification is enabled. When set to false(0), the ciscoHealthMonitorHealthLevel notification is disabled. If such a notification is desired, it is the responsibility of the management entity to ensure that the SNMP administrative model is configured in such a way as to allow the notification to be delivered.')
ciscoHealthMonitorHealthNotifyHighThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 4), HealthLevel().clone(10000)).setUnits('0.01 percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: ciscoHealthMonitorHealthNotifyHighThreshold.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorHealthNotifyHighThreshold.setDescription('Specifies the health level at which a ciscoHealthMonitorHealthLevel notification will be generated for the specified subsystem and entity. A notification will only be generated if the health level had previously reached the low threshold level prior to reaching this high threshold level. Health levels oscillating within the high and the low threshold levels do not generate notifications. A health level going from low threshold (or below) to high threshold (or above) represents a return to normal health for the specified subsystem. Set your optimal health level to this threshold.')
ciscoHealthMonitorHealthNotifyLowThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 5), HealthLevel()).setUnits('0.01 percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: ciscoHealthMonitorHealthNotifyLowThreshold.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorHealthNotifyLowThreshold.setDescription('Specifies the health level at which a ciscoHealthMonitorHealthLevel notification will be generated for the specified subsystem and entity. A notification will only be generated if the health level had previously reached the high threshold level prior to reaching this low threshold level. Health levels oscillating within the high and the low threshold levels do not generate notifications. A health level going from high threshold (or above) to low threshold (or below) represents a deterioration of the health for the specified subsystem. Set your unacceptable health level to this threshold.')
ciscoHealthMonitorCatastrophicFaults = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciscoHealthMonitorCatastrophicFaults.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorCatastrophicFaults.setDescription('The number of catastrophic faults that have occurred in this subsystem on the specified entity since the system was initialized.')
ciscoHealthMonitorCriticalFaults = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciscoHealthMonitorCriticalFaults.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorCriticalFaults.setDescription('The number of critical faults that have occurred in this subsystem on the specified entity since the system was initialized.')
ciscoHealthMonitorHighSeverityFaults = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciscoHealthMonitorHighSeverityFaults.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorHighSeverityFaults.setDescription('The number of high severity faults that have occurred in this subsystem on the specified entity since the system was initialized.')
ciscoHealthMonitorMediumSeverityFaults = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciscoHealthMonitorMediumSeverityFaults.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorMediumSeverityFaults.setDescription('The number of medium severity faults that have occurred in this subsystem on the specified entity since the system was initialized.')
ciscoHealthMonitorLowSeverityFaults = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciscoHealthMonitorLowSeverityFaults.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorLowSeverityFaults.setDescription('The number of low severity faults that have occurred in this subsystem on the specified entity since the system was initialized.')
ciscoHealthMonitorPositiveEvents = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 243, 1, 1, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciscoHealthMonitorPositiveEvents.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorPositiveEvents.setDescription('The number of positive events that have occurred in this subsystem on the specified entity since the system was initialized.')
ciscoHealthMonitorMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 243, 0))
ciscoHealthMonitorHealthLevel = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 243, 0, 1)).setObjects(("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorHealth"))
if mibBuilder.loadTexts: ciscoHealthMonitorHealthLevel.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorHealthLevel.setDescription('A ciscoHealthMonitorHealthLevel notification is sent when the health of a subsystem reaches either the ciscoHealthMonitorHealthNotifyLowThreshold or ciscoHealthMonitorHealthNotifyHighThreshold threshold as described above.')
ciscoHealthMonitorMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 243, 2))
ciscoHealthMonitorMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 243, 2, 1))
ciscoHealthMonitorMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 243, 2, 2))
ciscoHealthMonitorMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 243, 2, 1, 1)).setObjects(("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoHealthMonitorMIBCompliance = ciscoHealthMonitorMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorMIBCompliance.setDescription('The compliance statement for entities which implement the Cisco Health Monitor MIB')
ciscoHealthMonitorGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 243, 2, 2, 1)).setObjects(("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorHealth"), ("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorHealthNotifyEnable"), ("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorHealthNotifyHighThreshold"), ("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorHealthNotifyLowThreshold"), ("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorCatastrophicFaults"), ("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorCriticalFaults"), ("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorHighSeverityFaults"), ("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorMediumSeverityFaults"), ("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorLowSeverityFaults"), ("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorPositiveEvents"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoHealthMonitorGroup = ciscoHealthMonitorGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorGroup.setDescription('The collection of objects providing health information.')
ciscoHealthMonitorMIBNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 243, 2, 2, 2)).setObjects(("CISCO-HEALTH-MONITOR-MIB", "ciscoHealthMonitorHealthLevel"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoHealthMonitorMIBNotificationGroup = ciscoHealthMonitorMIBNotificationGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoHealthMonitorMIBNotificationGroup.setDescription('Set of notifications implemented in this module.')
mibBuilder.exportSymbols("CISCO-HEALTH-MONITOR-MIB", ciscoHealthMonitorCatastrophicFaults=ciscoHealthMonitorCatastrophicFaults, ciscoHealthMonitorEntry=ciscoHealthMonitorEntry, ciscoHealthMonitorPositiveEvents=ciscoHealthMonitorPositiveEvents, HealthLevel=HealthLevel, ciscoHealthMonitorHealthNotifyHighThreshold=ciscoHealthMonitorHealthNotifyHighThreshold, ciscoHealthMonitorMIBGroups=ciscoHealthMonitorMIBGroups, ciscoHealthMonitorMIBConform=ciscoHealthMonitorMIBConform, ciscoHealthMonitorHighSeverityFaults=ciscoHealthMonitorHighSeverityFaults, ciscoHealthMonitorCriticalFaults=ciscoHealthMonitorCriticalFaults, ciscoHealthMonitorHealth=ciscoHealthMonitorHealth, ciscoHealthMonitorHealthNotifyEnable=ciscoHealthMonitorHealthNotifyEnable, ciscoHealthMonitorMIB=ciscoHealthMonitorMIB, ciscoHealthMonitorGroup=ciscoHealthMonitorGroup, ciscoHealthMonitorMIBNotificationGroup=ciscoHealthMonitorMIBNotificationGroup, PYSNMP_MODULE_ID=ciscoHealthMonitorMIB, ciscoHealthMonitorLowSeverityFaults=ciscoHealthMonitorLowSeverityFaults, ciscoHealthMonitorSubsysName=ciscoHealthMonitorSubsysName, ciscoHealthMonitorMIBNotifs=ciscoHealthMonitorMIBNotifs, ciscoHealthMonitorMIBCompliances=ciscoHealthMonitorMIBCompliances, ciscoHealthMonitorHealthNotifyLowThreshold=ciscoHealthMonitorHealthNotifyLowThreshold, ciscoHealthMonitorMediumSeverityFaults=ciscoHealthMonitorMediumSeverityFaults, ciscoHealthMonitorMIBObjects=ciscoHealthMonitorMIBObjects, ciscoHealthMonitorHealthLevel=ciscoHealthMonitorHealthLevel, ciscoHealthMonitorMIBCompliance=ciscoHealthMonitorMIBCompliance, ciscoHealthMonitorTable=ciscoHealthMonitorTable)
|
class ListNode:
def __init__(self, key=None, value=None, next_node=None):
self.key = key
self.val = value
self.next = next_node
class MyHashMap:
def __init__(self):
self.size = 8
self.used = 0
self.threshold = 0.618
self.buckets = [None] * self.size
def _resize(self):
self.size *= 2
self.used = 0
new_buckets = [None] * self.size
for b in self.buckets:
current = b
while current:
h = self._hash(current.key)
new_buckets[h] = ListNode(current.key, current.val, new_buckets[h])
self.used += 1
current = current.next
self.buckets = new_buckets
# print("Resizing: current size: {} current used: {} new size {}".format(self.size // 2, self.used, self.size))
def _check_capacity_and_resize(self):
capacity = self.used / self.size
if capacity > self.threshold:
self._resize()
def _hash(self, key):
return key % self.size
def _find_node_return_previous_and_current(self, key):
h = self._hash(key)
current = previous = self.buckets[h]
while current and current.key != key:
previous = current
current = current.next
return previous, current
def put(self, key: int, value: int) -> None:
self._check_capacity_and_resize()
previous, current = self._find_node_return_previous_and_current(key)
if current is None and previous is None:
self.buckets[self._hash(key)] = ListNode(key, value)
self.used += 1
elif previous is not None and current is not None:
current.val = value
elif previous is not None and current is None:
previous.next = ListNode(key, value)
self.used += 1
def get(self, key: int) -> int:
previous, current = self._find_node_return_previous_and_current(key)
return -1 if not previous or not current else current.val
def remove(self, key: int) -> None:
previous, current = self._find_node_return_previous_and_current(key)
if current is None:
return
elif previous == current:
self.buckets[self._hash(key)] = current.next
else:
previous.next = current.next
self.used -= 1
op = ["MyHashMap", "put", "put", "put", "remove", "get", "put", "put", "get", "put", "put", "put", "put", "put", "put",
"put", "put", "put", "put", "put", "put", "remove", "put", "remove", "put", "put", "remove", "put", "get", "put",
"get", "put", "put", "put", "put", "put", "get", "put", "remove", "put", "remove", "put", "put", "put", "put",
"put", "remove", "put", "put", "remove", "put", "put", "put", "get", "get", "put", "remove", "put", "put", "put",
"get", "put", "put", "put", "remove", "put", "put", "put", "put", "put", "get", "put", "put", "get", "get", "put",
"remove", "remove", "get", "put", "remove", "put", "remove", "put", "put", "put", "get", "put", "put", "put",
"remove", "put", "put", "get", "put", "put", "get", "remove", "get", "get", "put"]
param = [[], [24, 31], [58, 35], [59, 88], [84], [62], [2, 22], [44, 70], [24], [24, 42], [58, 99], [74, 29], [40, 66],
[55, 83], [21, 27], [31, 25], [78, 19], [86, 70], [71, 73], [39, 95], [6, 96], [76], [62, 22], [78], [53, 51],
[66, 53], [44], [14, 46], [77], [15, 32], [22], [53, 79], [35, 21], [73, 57], [18, 67], [96, 61], [73],
[58, 77], [6], [5, 58], [17], [25, 14], [16, 13], [4, 37], [47, 43], [14, 79], [35], [7, 13], [78, 85], [27],
[73, 33], [95, 87], [31, 21], [20], [64], [90, 22], [16], [77, 50], [55, 41], [33, 62], [44], [73, 16],
[13, 54], [41, 5], [71], [81, 6], [20, 98], [35, 64], [15, 35], [74, 31], [90], [32, 15], [44, 79], [37], [53],
[22, 80], [24], [10], [7], [53, 61], [65], [63, 99], [47], [97, 68], [7, 0], [9, 25], [97], [93, 13], [92, 43],
[83, 73], [74], [41, 78], [39, 28], [52], [34, 16], [93, 63], [82], [77], [16], [50], [68, 47]]
hm = MyHashMap()
for i in range(len(op)):
if op[i] == "MyHashMap":
hm = MyHashMap()
continue
if op[i] == "put":
print(hm.put(param[i][0], param[i][1]))
if op[i] == "get":
print(hm.get(param[i][0]))
if op[i] == "remove":
print(hm.remove(param[i][0]))
print("simple test")
hm = MyHashMap()
for i in range(0, 10):
hm.put(i, i)
hm.remove(2)
hm.remove(11)
print(hm.get(1))
print(hm.get(2))
print("test resizing")
hm = MyHashMap()
for i in range(0, 10):
hm.put(i * 8, i * 8)
print(hm.buckets)
c = hm.buckets[0]
while c:
print(c.val)
c = c.next
c = hm.buckets[8]
while c:
print(c.val)
c = c.next
|
DOC_CHAPTER(
header = 'If statements',
topic = 'Reference',
text = """
There are two main forms of if-statements.
1. Regular if-then with optional else-clause
$DOC_LIST_UNORDERED(
$DOC_WORD( if ) $DOC_QUOTE( [ condition ] ),
$DOC_WORD( if ) $DOC_QUOTE( [ condition ] ) $DOC_WORD( then ) $DOC_QUOTE( [ value ] ),
$DOC_WORD( if ) $DOC_QUOTE( [ condition ] ) $DOC_WORD( then ) $DOC_QUOTE( [ value ] ) $DOC_WORD( else ) $DOC_QUOTE( [ alternative-value ] )
)
2. The if-let statement where the result of the condition, named $DOC_QUOTE( variable ), can be used in the then-clause.
$DOC_LIST_UNORDERED(
$DOC_WORD( if ) $DOC_QUOTE( variable ) $DOC_QUOTE( [ condition ] ),
$DOC_WORD( if ) $DOC_QUOTE( variable ) $DOC_QUOTE( [ condition ] ) $DOC_WORD( then ) $DOC_QUOTE( [ value ] ),
$DOC_WORD( if ) $DOC_QUOTE( variable ) $DOC_QUOTE( [ condition ] ) $DOC_WORD( then ) $DOC_QUOTE( [ value ] ) $DOC_WORD( else ) $DOC_QUOTE( [ alternative-value ] )
)
Notice that there are no booleans.
Instead, the then-clause is evaluated if the condition-clause does not fail,
and if it does fail, the optional else-clause is evaluated.
An if-expression is similar to a try-clause.
The if-statement without either a then-clause or else-clause simply prevents a fail message from propagating.
"""
)
ROOT_SCOPE_METHOD(
MC( ARG( CW( 'if' ), CT( 'WORD', 'word' ), CG( 'LIST', 'if_phrase' ), CW( 'then' ), CG( 'LIST', 'then_phrase' ), CW( 'else' ), CG( 'LIST', 'else_phrase' ) ), """
JUMP__this( $CA(FRAME__CONDITIONALS_IF_0_new( CONTEXT, $CA(PARAM_word), PARAM_if_phrase, PARAM_then_phrase, PARAM_else_phrase )), CONTEXT ) ;
""" ),
MC( ARG( CW( 'if' ), CT( 'WORD', 'word' ), CG( 'LIST', 'if_phrase' ), CW( 'then' ), CG( 'LIST', 'then_phrase' ) ), """
JUMP__this( $CA(FRAME__CONDITIONALS_IF_0_new( CONTEXT, $CA(PARAM_word), PARAM_if_phrase, PARAM_then_phrase, $NONE )), CONTEXT ) ;
""" ),
MC( ARG( CW( 'if' ), CG( 'LIST', 'if_phrase' ), CW( 'then' ), CG( 'LIST', 'then_phrase' ), CW( 'else' ), CG( 'LIST', 'else_phrase' ) ), """
JUMP__this( $CA(FRAME__CONDITIONALS_IF_0_new( CONTEXT, $NONE, PARAM_if_phrase, PARAM_then_phrase, PARAM_else_phrase )), CONTEXT ) ;
""" ),
MC( ARG( CW( 'if' ), CG( 'LIST', 'if_phrase' ), CW( 'then' ), CG( 'LIST', 'then_phrase' ) ), """
JUMP__this( $CA(FRAME__CONDITIONALS_IF_0_new( CONTEXT, $NONE, PARAM_if_phrase, PARAM_then_phrase, $NONE )), CONTEXT ) ;
""" ),
MC( ARG( CW( 'if' ), CG( 'LIST', 'if_phrase' ) ), """
JUMP__this( $CA(FRAME__CONDITIONALS_IF_0_new( CONTEXT, $NONE, PARAM_if_phrase, $NONE, $NONE )), CONTEXT ) ;
""" )
)
TEST( """ if [ . 1 == 2 ] """ )
TEST( """ if [ . 2 == 2 ] """ )
TEST( """ if [ . 1 == 2 ] then [ . 3 ] """ )
TEST( """ if [ . 2 == 2 ] then [ . 3 ] == 3 """ )
TEST( """ if it [ . 7 == 7 ] then [ . 3 * ( it ) ] == 21 """ )
TEST( """ if [ . 1 == 2 ] then [ . 3 ] else [ . 4 ] == 4 """ )
TEST( """ if [ . 2 == 2 ] then [ . 3 ] else [ . 4 ] == 3 """ )
TEST( """ if x [ . 2 == 2 ] then [ x + 3 ] else [ . 4 ] == 5 """ )
TEST( """ if x [ . 1 == 2 ] then [ x + 2 ] else [ . 7 ] == 7 """ )
TEST( """ if [ asdf asdf asdf ] then [ it ] else [ . 123 ] == 123 """ )
FRAME( 'CONDITIONALS_IF_0',
attributes = [
A( 'ANY', 'word' ),
A( 'ANY', 'if_phrase' ),
A( 'ANY', 'then_phrase' ),
A( 'ANY', 'else_phrase' ),
],
methods = [
MS( ARG( CW( 'return' ), CG( 'ANY', 'value' ) ), """
JUMP__evaluate_ANY( $CA(FRAME__CONDITIONALS_IF_1_new( ACTION->parent, PARAM_value, ACTION->word, ACTION->then_phrase, ACTION->else_phrase )), ACTION->if_phrase, PARAM_value ) ;
""" ),
]
)
FRAME( 'CONDITIONALS_IF_1',
attributes = [
A( 'ANY', 'scope' ),
A( 'ANY', 'word' ),
A( 'ANY', 'then_phrase' ),
A( 'ANY', 'else_phrase' ),
],
methods = [
MS( ARG( CW( 'return' ), CG( 'ANY', 'value' ) ), """
if ( ACTION->then_phrase != $NONE ) {
if ( ACTION->word != $NONE ) {
JUMP__evaluate_ANY( ACTION->parent, ACTION->then_phrase, $CA(UNION_new( $LISTNEW( nom_definition( ACTION->word, PARAM_value ), ACTION->scope ) )) ) ;
} else {
JUMP__evaluate_ANY( ACTION->parent, ACTION->then_phrase, ACTION->scope ) ;
}
} else {
JUMP__return_ANY( ACTION->parent, ACTION->parent, $NONE ) ;
}
""" ),
MS( ARG( CW( 'fail' ), CG( 'ANY', 'error' ) ), """
if ( ACTION->else_phrase != $NONE ) {
JUMP__evaluate_ANY( ACTION->parent, ACTION->else_phrase, ACTION->scope ) ;
} else {
JUMP__return_ANY( ACTION->parent, ACTION->parent, $NONE ) ;
}
""" ),
]
)
|
n=int(input());ans=0
def s(x,h):
global ans
for i in range(3):
if i==0 and x==0: continue
if x==n:
if h%3==0: ans+=1;return
else:
s(x+1,h+i)
s(0,0)
print(ans)
|
def BFS(adj, s):
queue = [s]
visited = []
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.append(vertex)
for node in graph[vertex]:
if node not in visited:
queue.append(node)
return visited
#경로탐색
def bfs_path(graph, start, end, path=[]):
path = path + [start]
#목적지에 도달
if start == end:
paths.append(path)
queue = [start]
while queue:
vertext = queue.pop(0)
for node in graph[vertex]:
if node not in path:
bfs_path(graph, node, end, path)
|
# 参考大佬的代码
# 动态规划化法
class Solution:
def isMatch(self, s, p):
len_s = len(s)
# 如果p中的?和字母的数量和大于s的长度
if len(p) - p.count('*') > len_s:
return False
# dp[i]表示字符串s前i个字符是否匹配p
# dp[0]表示字符串和空字符串或者只有*的字符串匹配
dp = [True] + [False] * len_s
for i in p:
# 一次循环确定:s 与 到字符i位置的p的部分 的拼配气矿
if i != '*':
for n in reversed(range(len_s)):
# 倒着循环,len_s-1 到 0
# 从s的最后一个字符往前遍历
if dp[n] and (i in {s[n], "?"}):
dp[n + 1] = True
else:
dp[n + 1] = False
else:
for n in range(1, len_s + 1):
dp[n] = dp[n - 1] or dp[n]
dp[0] = dp[0] and i == '*'
# 返回结果,即s的全部字符是否和模式p匹配
return dp[-1]
if __name__ == '__main__':
s = "mississippi"
p = "m??*ss*?i*pi"
# s = "adceb"
# p = "*a*b"
# s = "abefcdgiescdfimde"
# p = "ab*cd?i*de"
# s = "aaaa"
# p = "***a"
# s = "c"
# p = "*?*"
# s = "hi"
# p = "*?"
res = Solution().isMatch(s, p)
print(res)
|
def slack_escape(text: str) -> str:
"""
Escape special control characters in text formatted for Slack's markup.
This applies escaping rules as documented on
https://api.slack.com/reference/surfaces/formatting#escaping
"""
return text.replace("&", "&").replace("<", "<").replace(">", ">")
def incident_modal_payload():
"""Return the Slack Block Kit payload for the "Create new incident" modal"""
return {
"type": "modal",
"submit": {"type": "plain_text", "text": "Submit", "emoji": True},
"close": {"type": "plain_text", "text": "Cancel", "emoji": True},
"title": {"type": "plain_text", "text": "PagerDuty", "emoji": True},
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Create a new PagerDuty incident",
"emoji": True,
},
},
{
"type": "input",
"block_id": "service",
"element": {
"type": "external_select",
"placeholder": {
"type": "plain_text",
"text": "Select service",
"emoji": True,
},
"action_id": "service_value",
"min_query_length": 0,
},
"label": {
"type": "plain_text",
"text": "Affected service",
"emoji": True,
},
},
{
"type": "input",
"block_id": "title",
"element": {"type": "plain_text_input", "action_id": "title_value"},
"label": {"type": "plain_text", "text": "Title", "emoji": True},
},
{
"type": "input",
"block_id": "description",
"optional": True,
"element": {
"type": "plain_text_input",
"multiline": True,
"action_id": "description_value",
},
"label": {
"type": "plain_text",
"text": "Description",
"emoji": True,
},
},
],
}
def incident_created_modal_payload(pd_api_response):
"""Return the Slack Block Kit payload for the "Incident created" modal"""
safe_summary = slack_escape(pd_api_response["summary"])
return {
"response_action": "update",
"view": {
"type": "modal",
"title": {"type": "plain_text", "text": "Success"},
"close": {"type": "plain_text", "text": "Close"},
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"*The incident <{pd_api_response['html_url']}|{safe_summary}> was successfully created*",
},
},
],
},
}
|
class NoChoice(Exception):
def __init__(self):
super().__init__("Took too long.")
class PaginationError(Exception):
pass
class CannotEmbedLinks(PaginationError):
def __init__(self):
super().__init__("Bot cannot embed links in this channel.")
|
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
def isStringHTML(s):
if not isinstance(s, str):
return False
s = s.lower()
return any(tag in s for tag in ('<p>', '<p ', '<br', '<li>'))
|
def notas(*num,sit = False):
"""
Esse função recebe a nota de vários alunos e as armazena em uma biblioteca
:param num: Notas dos alunos
:param sit: Situação opcional para verificar o desempenho geral da turma
:return: Retorna a biblioteca contendo a maior e menor nota, média, etc
"""
bibli = {}
maior = media = menor = 0
bibli['Total'] = len(num)
for c in range(0,len(num)):
if c == 0:
maior = num[c]
menor = num[c]
if num[c] > maior:
maior = num[c]
if num[c] < menor:
menor = num[c]
media += num[c]
bibli['Maior'] = maior
bibli['Menor'] = menor
bibli['Média'] = media/len(num)
if sit == True:
if bibli['Média'] >= 7:
bibli['Situação'] = 'Boa'
elif bibli['Média'] >= 5:
bibli['Situação'] = 'Razoavel'
else:
bibli['Situação'] = 'Ruim'
return bibli
resp = notas(5.5,2.5,1.5,sit = True)
print(resp)
help(notas)
|
def assert_dict_equal(expected, actual):
message = []
equal = True
for k, v in expected.items():
if actual[k] != v:
message.append(f"For key {k} want {v}, got {actual[k]}")
equal = False
for k, v in actual.items():
if not k in expected:
message.append(f"Got extra key {k} with value {v}")
equal = False
assert equal, "\n".join(message)
|
"""
:copyright: (c) 2020 Yotam Rechnitz
:license: MIT, see LICENSE for more details
"""
class Assists:
def __init__(self, js: dict):
self._defensive_assists = js["defensiveAssists"] if "defensiveAssists" in js else 0
self._healing_done = js["healing_done"] if "healing_done" in js else 0
self._offensive_assists = js["offensive_assists"] if "offensive_assists" in js else 0
self._recon_assists = js["recon_assists"] if "recon_assists" in js else 0
@property
def defensive_assists(self) -> int:
return self._defensive_assists
@property
def healing_done(self) -> int:
return self._healing_done
@property
def offensive_assists(self) -> int:
return self._offensive_assists
@property
def recon_assists(self) -> int:
return self._recon_assists
|
x = int(input())
for j in range(x):
q = int(input())
print("Case", j + 1, end=": ")
for t in range(1, int(q / 2 + 1)):
if q % t == 0:
print(t, end=" ")
print(q)
|
"""
Write a Python program to replace last element in a list with another list.
"""
num1 = [1, 3, 5, 7, 9]
num2 = [2, 4, 6, 8, 0]
num1[-1:] = num2
print(num1)
|
class RobotStatus:
def __init__(self):
self.status = 'init'
self.position = ''
def isAvailable(self):
if self.status == 'available':
return True
else:
return False
def isWaitEV(self):
if self.status == 'waitEV':
return True
else:
return False
def isInEV(self):
if self.status == 'inEV':
return True
else:
return False
def setAvailable(self):
self.status = 'available'
def setMoving(self):
self.status = 'moving'
def setWaitEV(self):
self.status = 'waitEV'
def setInEV(self):
self.status = 'inEV'
def getPosition(self):
return self.position
def setPosition(self,newPose):
self.position = newPose
|
# The language mapping for 2 and 3 character language code.
language_dict = {
"kn": "kannada",
"kan": "kannada",
"hi": "hindi",
"hin": "hindi",
}
|
# Recursive Functions
def iterTest(low, high):
while low <= high:
print(low)
low=low+1
def recurTest(low,high):
if low <= high:
print(low)
recurTest(low+1, high)
|
#!/usr/bin/env python3
"""
Bradley N. Miller, David L. Ranum
Problem Solving with Algorithms and Data Structures using Python
Copyright 2005
Updated by Roman Yasinovskyy, 2017
"""
class BinaryHeap:
"""Minimal Binary Heap"""
def __init__(self):
"""Create a heap"""
self._heap = []
def _perc_up(self, cur_idx):
"""Move a node up"""
while (cur_idx - 1) // 2 >= 0:
parent_idx = (cur_idx - 1) // 2
if self._heap[cur_idx] < self._heap[parent_idx]:
self._heap[cur_idx], self._heap[parent_idx] = (
self._heap[parent_idx],
self._heap[cur_idx],
)
cur_idx = parent_idx
def _perc_down(self, cur_idx):
"""Move a node down"""
while 2 * cur_idx + 1 < len(self._heap):
min_child_idx = self._get_min_child(cur_idx)
if self._heap[cur_idx] > self._heap[min_child_idx]:
self._heap[cur_idx], self._heap[min_child_idx] = (
self._heap[min_child_idx],
self._heap[cur_idx],
)
else:
return
cur_idx = min_child_idx
def _get_min_child(self, parent_idx):
"""Get a smaller child"""
if 2 * parent_idx + 2 > len(self._heap) - 1:
return 2 * parent_idx + 1
if self._heap[2 * parent_idx + 1] < self._heap[2 * parent_idx + 2]:
return 2 * parent_idx + 1
return 2 * parent_idx + 2
def heapify(self, not_a_heap, show_details=False):
"""Build a heap from any list"""
self._heap = not_a_heap[:]
cur_idx = len(self._heap) // 2 - 1
while cur_idx >= 0:
self._perc_down(cur_idx)
cur_idx = cur_idx - 1
if show_details:
print(self._heap)
def insert(self, item):
"""Add a new item"""
self._heap.append(item)
self._perc_up(len(self._heap) - 1)
def delete(self):
"""Remove an item"""
self._heap[0], self._heap[-1] = self._heap[-1], self._heap[0]
result = self._heap.pop()
self._perc_down(0)
return result
def is_empty(self):
"""Check if the heap is empty"""
return not bool(self._heap)
def __len__(self):
"""Get heap size"""
return len(self._heap)
def __str__(self):
"""Heap as a string"""
return str(self._heap)
def __contains__(self, item):
"""__contains__in method override"""
return item in self._heap
|
# find min. no. of sets an array (awards) can be divided into such that couple-wise difference of each element is at most k
# ex: awards=[1,5,4,6,8,9,2], k=3, o/p=3
# [1,2][4,5,6][8,9] with max diff 1,2,1 respectively
# int minimumGroups(int awards[n],int k) => o/p
def max_diff(arr):
return max(arr) - min(arr)
def minimumGroups(awards, k):
awards.sort()
count = 1
n = len(awards)
i, j = 0, 1
while j != n:
# print(awards[i : j + 1], max_diff(awards[i : j + 1]))
if max_diff(awards[i : j + 1]) >= k:
count += 1
i = j
j = i + 1
j = j + 1
return count
def main():
awards = [1, 5, 4, 6, 8, 9, 2]
k = 3
print(minimumGroups(awards, k))
if __name__ == "__main__":
main()
|
class Solution:
def countBits(self, n: int) -> List[int]:
arr = []
for i in range(n+1):
i_b = int(bin(i)[2:])
arr.append(self.calculate1(i_b))
return arr
def calculate1(self, i):
count = 0
while i >= 1:
res = i%10
if res == 1:
count += 1
i //= 10
return count
|
class Heap:
def __init__(self, arr):
self.arr = arr
self.size = len(self.arr)
def max_heapify(self, current_index):
if not self.is_leaf(current_index):
left_child = (2 * current_index) + 1
right_child = (2 * current_index) + 2
if right_child < self.size:
if self.arr[left_child] > self.arr[current_index] or self.arr[right_child] > self.arr[current_index]:
if self.arr[left_child] > self.arr[right_child]:
self.arr[left_child], self.arr[current_index] = self.arr[current_index], self.arr[left_child]
self.max_heapify(left_child)
else:
self.arr[right_child], self.arr[current_index] = self.arr[current_index], self.arr[right_child]
self.max_heapify(right_child)
else:
if self.arr[left_child] > self.arr[current_index]:
self.arr[left_child], self.arr[current_index] = self.arr[current_index], self.arr[left_child]
self.max_heapify(left_child)
def build_heap(self):
for index in range((self.size//2) - 1, -1, -1):
self.max_heapify(index)
def is_leaf(self, current_index):
if current_index >= self.size // 2 and current_index <= self.size - 1:
return True
return False
def return_arr(self):
return self.arr
if __name__ == '__main__':
heap = Heap([3, 6, 5, 0, 8, 2, 1, 9])
heap.build_heap()
print(heap.return_arr())
|
# -*- coding: utf-8 -*-
# @Author: Wenwen Yu
# @Created Time: 7/8/2020 9:34 PM
Entities_list = [
"date_echeance",
"date_facture",
"methode_payement",
"numero_facture",
"rib",
"adresse",
"contact",
"nom_fournisseur",
"matricule_fiscale",
"total_ht",
"total_ttc"
]
# Entities_list = [
# "ticket_num",
# "starting_station",
# "train_num",
# "destination_station",
# "date",
# "ticket_rates",
# "seat_category",
# "name"
# ]
|
""" Script to specify the config
@author: AbinayaM02
"""
# Gunicorn config
bind = '0.0.0.0:5069'
workers = 1
timeout = 0
max_requests = 1
|
data = (
'Guo ', # 0x00
'Yin ', # 0x01
'Hun ', # 0x02
'Pu ', # 0x03
'Yu ', # 0x04
'Han ', # 0x05
'Yuan ', # 0x06
'Lun ', # 0x07
'Quan ', # 0x08
'Yu ', # 0x09
'Qing ', # 0x0a
'Guo ', # 0x0b
'Chuan ', # 0x0c
'Wei ', # 0x0d
'Yuan ', # 0x0e
'Quan ', # 0x0f
'Ku ', # 0x10
'Fu ', # 0x11
'Yuan ', # 0x12
'Yuan ', # 0x13
'E ', # 0x14
'Tu ', # 0x15
'Tu ', # 0x16
'Tu ', # 0x17
'Tuan ', # 0x18
'Lue ', # 0x19
'Hui ', # 0x1a
'Yi ', # 0x1b
'Yuan ', # 0x1c
'Luan ', # 0x1d
'Luan ', # 0x1e
'Tu ', # 0x1f
'Ya ', # 0x20
'Tu ', # 0x21
'Ting ', # 0x22
'Sheng ', # 0x23
'Pu ', # 0x24
'Lu ', # 0x25
'Iri ', # 0x26
'Ya ', # 0x27
'Zai ', # 0x28
'Wei ', # 0x29
'Ge ', # 0x2a
'Yu ', # 0x2b
'Wu ', # 0x2c
'Gui ', # 0x2d
'Pi ', # 0x2e
'Yi ', # 0x2f
'Di ', # 0x30
'Qian ', # 0x31
'Qian ', # 0x32
'Zhen ', # 0x33
'Zhuo ', # 0x34
'Dang ', # 0x35
'Qia ', # 0x36
'Akutsu ', # 0x37
'Yama ', # 0x38
'Kuang ', # 0x39
'Chang ', # 0x3a
'Qi ', # 0x3b
'Nie ', # 0x3c
'Mo ', # 0x3d
'Ji ', # 0x3e
'Jia ', # 0x3f
'Zhi ', # 0x40
'Zhi ', # 0x41
'Ban ', # 0x42
'Xun ', # 0x43
'Tou ', # 0x44
'Qin ', # 0x45
'Fen ', # 0x46
'Jun ', # 0x47
'Keng ', # 0x48
'Tun ', # 0x49
'Fang ', # 0x4a
'Fen ', # 0x4b
'Ben ', # 0x4c
'Tan ', # 0x4d
'Kan ', # 0x4e
'Pi ', # 0x4f
'Zuo ', # 0x50
'Keng ', # 0x51
'Bi ', # 0x52
'Xing ', # 0x53
'Di ', # 0x54
'Jing ', # 0x55
'Ji ', # 0x56
'Kuai ', # 0x57
'Di ', # 0x58
'Jing ', # 0x59
'Jian ', # 0x5a
'Tan ', # 0x5b
'Li ', # 0x5c
'Ba ', # 0x5d
'Wu ', # 0x5e
'Fen ', # 0x5f
'Zhui ', # 0x60
'Po ', # 0x61
'Pan ', # 0x62
'Tang ', # 0x63
'Kun ', # 0x64
'Qu ', # 0x65
'Tan ', # 0x66
'Zhi ', # 0x67
'Tuo ', # 0x68
'Gan ', # 0x69
'Ping ', # 0x6a
'Dian ', # 0x6b
'Gua ', # 0x6c
'Ni ', # 0x6d
'Tai ', # 0x6e
'Pi ', # 0x6f
'Jiong ', # 0x70
'Yang ', # 0x71
'Fo ', # 0x72
'Ao ', # 0x73
'Liu ', # 0x74
'Qiu ', # 0x75
'Mu ', # 0x76
'Ke ', # 0x77
'Gou ', # 0x78
'Xue ', # 0x79
'Ba ', # 0x7a
'Chi ', # 0x7b
'Che ', # 0x7c
'Ling ', # 0x7d
'Zhu ', # 0x7e
'Fu ', # 0x7f
'Hu ', # 0x80
'Zhi ', # 0x81
'Chui ', # 0x82
'La ', # 0x83
'Long ', # 0x84
'Long ', # 0x85
'Lu ', # 0x86
'Ao ', # 0x87
'Tay ', # 0x88
'Pao ', # 0x89
'[?] ', # 0x8a
'Xing ', # 0x8b
'Dong ', # 0x8c
'Ji ', # 0x8d
'Ke ', # 0x8e
'Lu ', # 0x8f
'Ci ', # 0x90
'Chi ', # 0x91
'Lei ', # 0x92
'Gai ', # 0x93
'Yin ', # 0x94
'Hou ', # 0x95
'Dui ', # 0x96
'Zhao ', # 0x97
'Fu ', # 0x98
'Guang ', # 0x99
'Yao ', # 0x9a
'Duo ', # 0x9b
'Duo ', # 0x9c
'Gui ', # 0x9d
'Cha ', # 0x9e
'Yang ', # 0x9f
'Yin ', # 0xa0
'Fa ', # 0xa1
'Gou ', # 0xa2
'Yuan ', # 0xa3
'Die ', # 0xa4
'Xie ', # 0xa5
'Ken ', # 0xa6
'Jiong ', # 0xa7
'Shou ', # 0xa8
'E ', # 0xa9
'Ha ', # 0xaa
'Dian ', # 0xab
'Hong ', # 0xac
'Wu ', # 0xad
'Kua ', # 0xae
'[?] ', # 0xaf
'Tao ', # 0xb0
'Dang ', # 0xb1
'Kai ', # 0xb2
'Gake ', # 0xb3
'Nao ', # 0xb4
'An ', # 0xb5
'Xing ', # 0xb6
'Xian ', # 0xb7
'Huan ', # 0xb8
'Bang ', # 0xb9
'Pei ', # 0xba
'Ba ', # 0xbb
'Yi ', # 0xbc
'Yin ', # 0xbd
'Han ', # 0xbe
'Xu ', # 0xbf
'Chui ', # 0xc0
'Cen ', # 0xc1
'Geng ', # 0xc2
'Ai ', # 0xc3
'Peng ', # 0xc4
'Fang ', # 0xc5
'Que ', # 0xc6
'Yong ', # 0xc7
'Xun ', # 0xc8
'Jia ', # 0xc9
'Di ', # 0xca
'Mai ', # 0xcb
'Lang ', # 0xcc
'Xuan ', # 0xcd
'Cheng ', # 0xce
'Yan ', # 0xcf
'Jin ', # 0xd0
'Zhe ', # 0xd1
'Lei ', # 0xd2
'Lie ', # 0xd3
'Bu ', # 0xd4
'Cheng ', # 0xd5
'Gomi ', # 0xd6
'Bu ', # 0xd7
'Shi ', # 0xd8
'Xun ', # 0xd9
'Guo ', # 0xda
'Jiong ', # 0xdb
'Ye ', # 0xdc
'Nian ', # 0xdd
'Di ', # 0xde
'Yu ', # 0xdf
'Bu ', # 0xe0
'Ya ', # 0xe1
'Juan ', # 0xe2
'Sui ', # 0xe3
'Pi ', # 0xe4
'Cheng ', # 0xe5
'Wan ', # 0xe6
'Ju ', # 0xe7
'Lun ', # 0xe8
'Zheng ', # 0xe9
'Kong ', # 0xea
'Chong ', # 0xeb
'Dong ', # 0xec
'Dai ', # 0xed
'Tan ', # 0xee
'An ', # 0xef
'Cai ', # 0xf0
'Shu ', # 0xf1
'Beng ', # 0xf2
'Kan ', # 0xf3
'Zhi ', # 0xf4
'Duo ', # 0xf5
'Yi ', # 0xf6
'Zhi ', # 0xf7
'Yi ', # 0xf8
'Pei ', # 0xf9
'Ji ', # 0xfa
'Zhun ', # 0xfb
'Qi ', # 0xfc
'Sao ', # 0xfd
'Ju ', # 0xfe
'Ni ', # 0xff
)
|
# faça um programa que leia um numero inteiro qualquer e mostre na tela a sua tabuada.
numero = int(input("Digite um numero inteiro: "))
print("A tabuada do {} é: ". format(numero))
print("{} x 1 = {}".format(numero, (numero*1)))
print("{} x 2 = {}".format(numero, (numero*2)))
print("{} x 3 = {}".format(numero, (numero*3)))
print("{} x 4 = {}".format(numero, (numero*4)))
print("{} x 5 = {}".format(numero, (numero*5)))
print("{} x 6 = {}".format(numero, (numero*6)))
print("{} x 7 = {}".format(numero, (numero*7)))
print("{} x 8 = {}".format(numero, (numero*8)))
print("{} x 9 = {}".format(numero, (numero*9)))
print("{} x 10 = {}".format(numero, (numero*10)))
|
FEATURES = {"DEBUG_MODE": False}
def feature(feature_id: str) -> bool:
if feature_id not in FEATURES:
raise ValueError("Key not a valid feature")
return FEATURES[feature_id]
|
team_names = ['LA Chargers', 'LA Rams', 'NE Patriots', 'NY Giants',
'Chicago Bears']
locations = ['LA', 'NY', 'SF', 'CH', 'NE']
weeks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
|
def any_lowercase(s):
""" incorrect - only checks whether first letter is lower case"""
for c in s:
if c.islower():
return True
else:
return False
def any_lowercase_fixed(s):
for c in s:
if c.islower():
return True
return False
def any_lowercase2(s):
""" incorrect - checks if 'c' is lower case, which is
always True, and returns a string not a Boolean"""
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
def any_lowercase3(s):
""" incorrect - only returns the value of the final character of s"""
for c in s:
flag = c.islower()
return flag
def any_lowercase4(s):
""" correct """
flag = False
for c in s:
flag = flag or c.islower()
return flag
def any_lowercase5(s):
""" incorrect - returns whether false if s contains any capital letters"""
for c in s:
if not c.islower():
return False
return True
|
"""
53. Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one
number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Examples
--------
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
Constraints
-----------
* 1 <= nums.length <= 105
* -104 <= nums[i] <= 104
"""
def initial_pass(nums: list[int]) -> int:
# Check each subarray from size 1 to size n
max_sum = -105 * 106 # Ensures we start at a value that can be overwritten
for i in range(1, len(nums)+1):
start_index = 0
end_index = i
while end_index <= len(nums):
max_sum = max(max_sum, sum(nums[start_index:end_index]))
start_index += 1
end_index += 1
return max_sum
|
x = int(input(""))
y = int(input(""))
div = int(x/y)
print(div)
mod = int(x % y)
print(mod)
z = divmod(x, y)
print(z)
|
red = 'Red'
blue = 'Blue'
green = 'Green'
spring_green = 'SpringGreen'
hot_pink = 'HotPink'
blue_violet = 'BlueViolet'
cadet_blue = 'CadetBlue'
chocolate = 'Chocolate'
coral = 'Coral'
dodger_blue = 'DodgerBlue'
firebrick = 'Firebrick'
golden_rod = 'GoldenRod'
orange_red = 'OrangeRed'
yellow_green = 'YellowGreen'
sea_green = 'SeaGreen'
|
# -*- coding: utf8 -*-
__author__ = 'wangqiang'
if __name__ == "__main__":
# 四舍五入方式保留2位小数(3.14)
print("{:.2f}".format(3.1415926))
# 带符号保留2位小数(+3.14)
print("{:+.2f}".format(3.1415926))
# (-1.00)
print("{:+.2f}".format(-1))
# 四舍五入取整
print("{:.0f}".format(2.7182))
# 整数左边补零,宽度为2
print("{:0>2d}".format(5))
# 整数右边补x,宽度为4
print("{:x<4d}".format(4))
# 以逗号分隔数字
print("{:,}".format(10000000))
# 百分号表示,并且保留2位小数
print("{:.2%}".format(0.25678))
# 指数表示,并保留2位小数(1.35e+09)
print("{:.2e}".format(1345600000))
# 右对齐,宽度为5
print("{:>5d}".format(23))
# 左对齐
print("{:<5d}".format(23))
# 中间对齐
print("{:^5d}".format(23))
# 进制输出
# 2进制(1011)
print("{:b}".format(11))
# 16进制
print("{:x}".format(11))
# 8进制
print("{:o}".format(11))
# 10进制
print("{:d}".format(11))
# 16进制带标志(0xb)
print("{:#x}".format(11))
# 16进制带标志(大写表示)(0XB)
print("{:#X}".format(11))
# 通过集合进行格式化
info = [(1, "A"), (2, "B")]
print("{0[1]},{0[0]}".format(info[1]))
|
class Solution:
def numSub(self, s: str) -> int:
l = [int(i) for i in s]
res = 0
i = 0
while i < len(l):
if l[i] != 1:
i += 1
continue
count = 0
curr = 0
while i < len(l) and l[i] == 1:
i += 1
count += 1
curr += count
res += curr
res %= 10**9+7
return res
|
class conta_corrente:
def __Init__(self, nome):
self.nome = nome
self.email = None
self.telefone = None
self._saldo = 0
def _checar_saldo(self, valor):
return self._saldo >= valor
def depositar(self, valor):
self._saldo += valor
def sacar(self, valor):
if self._checar_saldo(valor):
self._saldo -= valor
return True
else:
return False
def obter_saldo(self):
return self._saldo
|
chromedriver_path='***'
from_station='***'
to_station='***'
email='***'
phone_num='***'
full_name='***'
card_num='***'
exp='***'
cvv='***'
|
# terrascript/data/camptocamp/jwt.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:19:50 UTC)
__all__ = []
|
mon_fichier = open("mdp.txt" , "r")
crypt = mon_fichier.read()
mon_fichier.close()
mon_fichier = open("encrypt.txt" , "r")
decrypt1 = mon_fichier.read()
mon_fichier.close()
def encrypt(crypt):
number=input("donner une cle de cryptage (numero)")
b=list(crypt)
str(b)
c=[ord(x)for x in(b)]
d=[]
for i in c:
d.append(i+number)
e=[chr(i) for i in (d)]
e="".join(e)
print ("ta cle est:", number,)
mon_fichier = open("encrypt.txt" , "w")
mon_fichier.write(e)
mon_fichier.close()
def decrypt(decrypt1):
number=input("quelle est la cle de cryptage ?")
b=list(decrypt1)
str(b)
c=[ord(x)for x in(b)]
d=[]
for i in c:
d.append(i-number)
e=[chr(i) for i in (d)]
e="".join(e)
mon_fichier = open("decrypt.txt" , "w")
mon_fichier.write(e)
mon_fichier.close()
def menu():
print ("Que veut-tu faire ??")
print ("1 pour Encrypter un document")
print ("2 pour Decrypter un ducoment")
choice=input("fait ton choix:")
if choice=="1":
run = encrypt(crypt)
run
menu()
elif choice=="2":
derun=decrypt(decrypt1)
derun
menu()
menu()
|
#1
Transformers={"Оптімус Прайм":"Грузовик Peterbilt 379","Бамблбі":"Chevrolet Camaro","Джаз":"Porsche 935 Turbo"}
for i, x in Transformers.items():
print(i,"-",x)
#2
for i in Transformers:
if i=="Оптімус Прайм":
print("Оптімус Прайм прибув")
break
#3
TransformersWeight={ "Оптімус":5000,"Бамблбі":2500,"Джаз":3000}
x = 0
for i in TransformersWeight.values():
x += i
print(x)
#4
megatron=("Megatron","Кібертронський винищувач","Танк","Кібертронський Зорельот.","Десептикон")
for i in megatron:
if i=="Десептикон":
print("Мегатрон - ворог")
#5
x={"Сентінел Прайм":"Пожежна машина"}
Transformers.update(x)
print(Transformers)
|
'''dom.py contains all referenced dom elements. Gathering all fragile dom elements in one config file makes it easier to maintain the code'''
def dom():
dom = {
'loginButton': 'html/body/div[3]/header/div/div/div/div[2]/button/span',
'einverstandenButton': 'div.c-button--bold',
'usernameInput': 'Username'
}
return dom
|
def template_expand(tool, template, output, subs, executable = False, execution_requirements = None):
"""Powerful template expansion rule.
template_expand uses the powerful golang text/template engine to expand an input template
into an output file. The subs dict provide keys and values, where the values can either be
plain strings, or File objects that end up read from disk.
The full documentation of text/template syntax can be found here:
https://golang.org/pkg/text/template/
Args:
template: a File object, the template to expand. The template can use any syntax supported
by the golang text/template library.
output: a File object, the file to create with the expanded template.
subs: a dict, {"key": value}, with key being a string, and value being either a string, or
a file object. If the value is a file, the corresponding file will be read and expanded
every time key is used.
If the key is set to "myKey", you can reference it in the template by either using
{{.myKey}}, or by using {{.Get "myKey"}}. Using ".Get" allows to access keys that use
invalid go syntax (for example, "my-key:next"), and causes the substitution to fail if
the key is not present.
Returns:
A dict that can be simply passed as **kwarg to ctx.actions.run(), or mangled before it is
passed over.
Example:
my_rule_implementation(ctx):
...
expander = template_expand(ctx.file._tool, template = ctx.file.config, output = output, subs = subs)
ctx.actions.run(**expander)
In the rule definition:
...
attrs = {
"_tool": template_tool,
}
"""
args = [
"-template",
template.path,
"-output",
output.path,
]
if executable:
args.append("-executable")
inputs = [template]
for key, value in subs.items():
args.extend(["-key", key])
if type(value) == "string":
args.extend(["-value", value])
else:
inputs.append(value)
args.extend(["-valuefile", value.path])
return dict(
executable = tool,
arguments = args,
inputs = inputs,
outputs = [output],
execution_requirements = execution_requirements,
)
# Use template_tool in your rule definition, and pass the corresponding attribute
# to template_execute as the first parameter.
#
# For example:
#
# example_rule = rule(
# implementation = _example_rule_impl,
# attrs = {
# "output": attr.string(...),
# [...]
# "_expander": template_tool,
# }
# )
#
# def _example_rule_impl(ctx):
# [...]
# expander = template_expand(ctx.attr._expander, ...)
# ctx.actions.run(**expander)
#
template_tool = attr.label(
default = Label("//bazel/utils/template"),
cfg = "host",
executable = True,
allow_single_file = True,
)
|
'''
2. Write a Python Program to read the contents of a file and find how many upper case letters,
lower case letters and digits existed in the file.
'''
file = open('SampleCount.txt','r')
data = file.read()
print('Contents of a file is')
print(data)
digit = upper = lower = special = 0
for ch in data:
if ch.islower():
lower += 1
elif ch.isupper():
upper += 1
elif ch.isdigit():
digit += 1
else:
special += 1
print('Number of Upper Case Letters in a file is',upper)
print('Number of Lower Case Letters in a file is',lower)
print('Number of digits in a file is',digit)
print('Number of Special Characters in a file is',special)
file.close()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 数値読み込み
a,b = [int(i) for i in input().split()]
if a <= 0 and b >=0:
print("Zero")
elif a<0 and b<0 and (a-b)%2==0:
print("Negative")
else:
print("Positive")
|
# Specialization: Google IT Automation with Python
# Course 01: Crash Course with Python
# Week 5 Module Part 2 Exercise 02
# Student: Shawn Solomon
# Learning Platform: Coursera.org
# Want to see this in action?
# In this code, there's a Person class that has an attribute name, which gets set when constructing
# the object. Fill in the blanks so that 1) when an instance of the class is created, the attribute
# gets set correctly, and 2) when the greeting() method is called, the greeting states the assigned name.
# class Person:
# def __init__(self, name):
# self.name = ___
# def greeting(self):
# # Should return "hi, my name is " followed by the name of the Person.
# return ___
# # Create a new instance with a name of your choice
# some_person = ___
# # Call the greeting method
# print(some_person.___)
class Person:
def __init__(self, name):
self.name = name
def greeting(self):
# Should return "hi, my name is " followed by the name of the Person.
return "hi, my name is {}".format(self.name)
# Create a new instance with a name of your choice
some_person = Person("Nobody")
# Call the greeting method
print(some_person.greeting())
|
def solve(data):
result = 0
# Declares an unordered collection of unique elements
unique_frequencies = set()
while True:
for number in data:
result += number
# Checks if current sum(result) already exists in the collection
if result in unique_frequencies:
# Breaks out of the function and returns the result
return result
# Adds current sum(result) to the collection
unique_frequencies.add(result)
|
class InMemoryStorage:
__instance = None
def __init__(self):
self.room_data = dict()
self.user_data = dict()
@classmethod
def __getInstance(cls):
return cls.__instance
@classmethod
def instance(cls, *args, **kargs):
cls.__instance = cls(*args, **kargs)
cls.instance = cls.__getInstance
return cls.__instance
def join_user(self, user_id, room_id, user_info):
self.room_data[room_id]['users'][user_id] = {
'score': 0,
'nickname': user_info['nickname'],
'character': user_info['character']
}
storage = InMemoryStorage.instance()
"""
{
room_id: {
'round': int,
'problem': str,
'host': int
'paint': ???(ask to SH),
'remaining_time': int,
'status': Enum,
'is_public': bool,
'users': {
session_id: {
'score': int,
'nickname: str,
'character': str
}
}
'correct_users': [session_id],
'drawer': session_id
}
}
"""
|
class Carro:
def __init__(self, vel_max): # construtor padrão do objeto
self.vel_max = vel_max
self.vel_atual = 0
def acelerar(self, delta=5):
maxima = self.vel_max
nova = self.vel_atual + delta
self.vel_atual = nova if nova <= maxima else maxima
return self.vel_atual
def frear(self, delta=5):
nova = self.vel_atual - delta
self.vel_atual = nova if nova >= 0 else 0
return self.vel_atual
if __name__ == '__main__':
c1 = Carro(180)
for i in range(25):
print(c1.acelerar(8))
for i in range(10):
print(c1.frear(delta=20))
|
def next_13_numbers_product(num, start):
if start + 13 > len(num):
return 0
x = 1
for index in range(start, start + 13):
x *= int(num[index])
return x
number = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450"
maxValue = 0
for i in range(0, len(number)):
value = next_13_numbers_product(number, i)
maxValue = value if value > maxValue else maxValue
print(maxValue)
|
class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
ans = []
i = 0
j = 0
while i < len(A) and j < len(B):
if A[i][0] <= B[j][0] and A[i][1] >= B[j][1]:
C = []
C.append(B[j][0])
C.append(B[j][1])
ans.append(C)
elif B[j][0] <= A[i][0] and B[j][1] >= A[i][1]:
C = []
C.append(A[i][0])
C.append(A[i][1])
ans.append(C)
elif A[i][0] <= B[j][0] and B[j][0] <= A[i][1] and A[i][1] <= B[j][1]:
C = []
C.append(B[j][0])
C.append(A[i][1])
ans.append(C)
elif B[j][0] <= A[i][0] and A[i][0] <= B[j][1] and B[j][1] <= A[i][1]:
C = []
C.append(A[i][0])
C.append(B[j][1])
ans.append(C)
if A[i][1] < B[j][1]:
i += 1
else:
j += 1
return ans
|
def fibonacci():
a = 0
b = 1
while True: # keep going...
yield a # report value, a, during this pass
future = a + b
a = b # this will be next value reported
b = future # and subsequently this
|
X = int(input())
Y = int(input())
print(int(input())*60 + int(input()))
a = int(input())
print(a//60)
print(a%60)
x=int(input())
h=int(input())
m=int(input())
print(h+(x+m)//60)
print((x+m)%60)
|
"""Warnings.
"""
__author__ = 'Md Jahidul Hamid <[email protected]>'
__copyright__ = 'Copyright © Md Jahidul Hamid <https://github.com/neurobin/>'
__license__ = '[BSD](http://www.opensource.org/licenses/bsd-license.php)'
__version__ = '0.0.1'
class UnsupportedWarning(DeprecationWarning):
"""Base class for warnings about unsupported features."""
def __init__(self, msg):
self.message = msg
super(UnsupportedWarning, self).__init__()
def __str__(self):
msg = self.message
return msg
class DeprecatedWarning(DeprecationWarning):
def __init__(self, msg):
self.message = msg
super(DeprecatedWarning, self).__init__()
def __str__(self):
msg = self.message
return msg
|
"""Exercício Python 060: Faça um programa que leia um número qualquer e mostre o seu fatorial.
Exemplo: 5! = 5 x 4 x 3 x 2 x 1 = 120"""
"""
from math import factorial
num = int(input("Digite um nomero para calcular seu fatorial: "))
print(f"O fatorial de {num} é {factorial(num)}")"""
"""
num = int(input("Digite um nomero para calcular seu fatorial: "))
fatorial = 1
print(f"Calculando {num}! = ", end='')
while num != 0:
print(f"{num}", end='')
print(" x " if num > 1 else " = ", end='')
fatorial *= num
num -= 1
print(f"{fatorial}")"""
def fatorial(x):
f = 1
while x != 0:
print(f"{x}", end='')
print(" x " if x > 1 else " = ", end='')
f *= x
x -= 1
print(f"{f}")
num = int(input("Digite um nomero para calcular seu fatorial: "))
fatorial(num)
|
def confusion_matrix(yreal, ypred):
n_classes = len(set(yreal))
new_matrix = []
print("len yreal: ", len(yreal))
print("len ypred: ", len(ypred))
print("n classes: ", n_classes)
for i_class in range(n_classes):
new_matrix.append([])
for _ in range(n_classes): #i_ypred
new_matrix[i_class].append(0.0)
for i_yreal in range(len(yreal)):
new_matrix[yreal[i_yreal]][ypred[i_yreal]] += 1
return new_matrix
def normalize(confusion_matrix):
new_matrix = []
for irow in range(len(confusion_matrix)):
new_matrix.append([])
sum_row = sum(confusion_matrix[irow])
for idata in range(len(confusion_matrix[irow])):
if sum_row == 0:
new_matrix[irow].append(0.0)
else:
new_matrix[irow].append(confusion_matrix[irow][idata]/float(sum_row))
return new_matrix
|
#Задача 4
#Найти произведение ряда чисел от 1 до 10. Полученный результат вывести на экран.
n = 1
for i in range(1,11):
n *= i
print(n)
|
#primeira solução
sexo = input('Informe seu sexo: [M/F] ').strip().upper()[0]# o zero é para pegar
cont = 1
while cont == 1:
if sexo not in 'FfMm':
sexo = input('Dados Inválidos. Por favor informe seu sexo: ').strip().upper()[0]
cont = 1
else:
cont = 0
print('\nSexo {} registrado com sucesso'.format(sexo))
#segunda solução
# sexo = input('Informe seu sexo: [M/F] ')
# while sexo not in 'FfMm':
# sexo = input('Dados Inválidos. Por favor informe seu sexo: ').upper()
# print('\nSexo {} registrado com sucesso'.format(sexo))
|
def find_file(filename):
"""
尝试读取文件,将其内容打印到屏幕上。
并在文件不存在时,捕获异常,打印一
条友好的消息。
"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " does not exist."
print(message)
else:
print(contents.rstrip())
filenames = ['cats.txt', 'dogs.txt']
for filename in filenames:
find_file(filename)
|
def quicksort(array):
if len(array) < 2:
return array
print(quicksort([ ]))
|
'''
A non-empty array A consisting of N numbers is given. The array is sorted in non-decreasing order. The absolute distinct count of this array is the number of distinct absolute values among the elements of the array.
For example, consider array A such that:
A[0] = -5
A[1] = -3
A[2] = -1
A[3] = 0
A[4] = 3
A[5] = 6
The absolute distinct count of this array is 5, because there are 5 distinct absolute values among the elements of this array, namely 0, 1, 3, 5 and 6.
Write a function:
def solution(A)
that, given a non-empty array A consisting of N numbers, returns absolute distinct count of array A.
For example, given array A such that:
A[0] = -5
A[1] = -3
A[2] = -1
A[3] = 0
A[4] = 3
A[5] = 6
the function should return 5, as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647];
array A is sorted in non-decreasing order.
'''
def solution(N):
list_of_absolute_values = list(map(lambda x:abs(x), N))
return len(set(list_of_absolute_values))
|
"""Generate a file.
In this example, the content is passed via an attribute. If you generate
large files with a lot of static content, consider using
`ctx.actions.expand_template` instead.
"""
def file(**kwargs):
_file(out = "{name}.txt".format(**kwargs), **kwargs)
def _impl(ctx):
output = ctx.outputs.out
ctx.actions.write(output = output, content = ctx.attr.content)
_file = rule(
implementation = _impl,
attrs = {"content": attr.string(), "out": attr.output()},
)
|
# Assign String to a Variable
a = 'Hello'
print (a,'\n')
# Multiline Strings
# using three double quotes:
b = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt."""
print(b,'\n')
# using three single quotes:
b = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(b,'\n')
# Strings are Arrays
a = 'I Love Bangladesh'
print(a[2],'\n') # at index 2 we will get 'L', beecause array index start from 0.
# Looping Through a String
for x in "Bangladesh":
print(x)
print('\n')
# String Length
p = 'I Love Bangladesh'
print('length of p: ',len(p),'\n') # The len() function returns the length of a string
# Check String
""" To check if a certain phrase or character is present in a string, we can use the keyword 'in'.
it will returns Boolean(true/false). """
txt = "I Love Bangladesh"
print("my" in txt," 'my' is not present in txt ") # it will print False
print("I" in txt," 'I' is present in txt ") # it will print True
if "Love" in txt:
print("Yes, 'Love' is present in txt.\n")
# Check if NOT
""" To check if a certain phrase or character is NOT present in a string, we can use the keyword 'not in'. """
print("my" not in txt," 'my' is not present in txt ") # it will print True
print("I" not in txt," 'I' is present in txt ") # it will print False
if 'base' not in txt:
print("No, 'base' is NOT present in txt.")
|
#
# PySNMP MIB module Unisphere-Data-SONET-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-SONET-CONF
# Produced by pysmi-0.3.4 at Wed May 1 15:32:59 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, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint")
ModuleCompliance, NotificationGroup, AgentCapabilities = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "AgentCapabilities")
iso, ModuleIdentity, TimeTicks, Integer32, ObjectIdentity, Counter64, Gauge32, Unsigned32, Counter32, NotificationType, Bits, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "ModuleIdentity", "TimeTicks", "Integer32", "ObjectIdentity", "Counter64", "Gauge32", "Unsigned32", "Counter32", "NotificationType", "Bits", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
sonetLineStuff2, sonetSectionStuff, sonetVTStuff2, sonetMediumTimeElapsed, sonetVTStuff, sonetMediumLineType, sonetMediumValidIntervals, sonetSectionStuff2, sonetPathStuff2, sonetFarEndPathStuff2, sonetFarEndVTStuff2, sonetFarEndLineStuff2, sonetMediumStuff2, sonetMediumStuff, sonetPathStuff, sonetLineStuff, sonetMediumLoopbackConfig, sonetMediumLineCoding = mibBuilder.importSymbols("SONET-MIB", "sonetLineStuff2", "sonetSectionStuff", "sonetVTStuff2", "sonetMediumTimeElapsed", "sonetVTStuff", "sonetMediumLineType", "sonetMediumValidIntervals", "sonetSectionStuff2", "sonetPathStuff2", "sonetFarEndPathStuff2", "sonetFarEndVTStuff2", "sonetFarEndLineStuff2", "sonetMediumStuff2", "sonetMediumStuff", "sonetPathStuff", "sonetLineStuff", "sonetMediumLoopbackConfig", "sonetMediumLineCoding")
usDataAgents, = mibBuilder.importSymbols("Unisphere-Data-Agents", "usDataAgents")
usdSonetGroup, usdSonetVirtualTributaryGroup, usdSonetPathGroup = mibBuilder.importSymbols("Unisphere-Data-SONET-MIB", "usdSonetGroup", "usdSonetVirtualTributaryGroup", "usdSonetPathGroup")
usdSonetAgent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 40))
usdSonetAgent.setRevisions(('2002-02-04 21:35', '2001-04-03 22:35',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: usdSonetAgent.setRevisionsDescriptions(('Separate out the SONET VT support.', 'The initial release of this management information module.',))
if mibBuilder.loadTexts: usdSonetAgent.setLastUpdated('200202042135Z')
if mibBuilder.loadTexts: usdSonetAgent.setOrganization('Unisphere Networks, Inc.')
if mibBuilder.loadTexts: usdSonetAgent.setContactInfo(' Unisphere Networks, Inc. Postal: 10 Technology Park Drive Westford, MA 01886 USA Tel: +1 978 589 5800 E-mail: [email protected]')
if mibBuilder.loadTexts: usdSonetAgent.setDescription('The agent capabilities definitions for the SONET component of the SNMP agent in the Unisphere Routing Switch family of products.')
usdSonetAgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 40, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetAgentV1 = usdSonetAgentV1.setProductRelease('Version 1 of the SONET component of the Unisphere Routing Switch SNMP\n agent. This version of the SONET component was supported in the\n Unisphere RX 1.x system releases.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetAgentV1 = usdSonetAgentV1.setStatus('obsolete')
if mibBuilder.loadTexts: usdSonetAgentV1.setDescription('The MIBs supported by the SNMP agent for the SONET application in the Unisphere Routing Switch. These capabilities became obsolete when support for the standard VT group was added.')
usdSonetAgentV2 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 40, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetAgentV2 = usdSonetAgentV2.setProductRelease('Version 2 of the SONET component of the Unisphere Routing Switch SNMP\n agent. This version of the SONET component was supported in the\n Unisphere RX 2.x system releases.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetAgentV2 = usdSonetAgentV2.setStatus('obsolete')
if mibBuilder.loadTexts: usdSonetAgentV2.setDescription('The MIBs supported by the SNMP agent for the SONET application in the Unisphere Routing Switch. These capabilities became obsolete when support for the proprietary path and VT groups were added.')
usdSonetAgentV3 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 40, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetAgentV3 = usdSonetAgentV3.setProductRelease('Version 3 of the SONET component of the Unisphere Routing Switch SNMP\n agent. This version of the SONET component was supported in the\n Unisphere RX 3.0 and 3.1 system releases.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetAgentV3 = usdSonetAgentV3.setStatus('obsolete')
if mibBuilder.loadTexts: usdSonetAgentV3.setDescription('The MIBs supported by the SNMP agent for the SONET application in the Unisphere Routing Switch. These capabilities became obsolete when support for the RFC-2558 version of the SONET-MIB and far-end statistics were added.')
usdSonetAgentV4 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 40, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetAgentV4 = usdSonetAgentV4.setProductRelease('Version 4 of the SONET component of the Unisphere Routing Switch SNMP\n agent. This version of the SONET component was supported in the\n Unisphere RX 3.2 system release.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetAgentV4 = usdSonetAgentV4.setStatus('obsolete')
if mibBuilder.loadTexts: usdSonetAgentV4.setDescription('The MIBs supported by the SNMP agent for the SONET application in the Unisphere Routing Switch. These capabilities became obsolete when Virtual Tributary (VT) support was searated out into a separate capabilities statement.')
usdSonetBasicAgent = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 5, 2, 40, 5))
usdSonetBasicAgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 40, 5, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetBasicAgentV1 = usdSonetBasicAgentV1.setProductRelease('Version 1 of the basic SONET component of the Unisphere Routing Switch\n SNMP agent. It does not include Virtual Tributary (VT) support. This\n version of the basic SONET component is supported in the Unisphere RX\n 3.3 and subsequent system releases.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetBasicAgentV1 = usdSonetBasicAgentV1.setStatus('current')
if mibBuilder.loadTexts: usdSonetBasicAgentV1.setDescription('The MIB conformance groups supported by the SNMP agent for the SONET application in the Unisphere Routing Switch.')
usdSonetVTAgent = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 5, 2, 40, 6))
usdSonetVTAgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 40, 6, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetVTAgentV1 = usdSonetVTAgentV1.setProductRelease('Version 1 of the SONET VT component of the Unisphere Routing Switch\n SNMP agent. This version of the SONET component is supported in the\n Unisphere RX 3.3 and subsequent system releases.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
usdSonetVTAgentV1 = usdSonetVTAgentV1.setStatus('current')
if mibBuilder.loadTexts: usdSonetVTAgentV1.setDescription('The MIB conformance groups supported by the SNMP agent for the SONET application in the Unisphere Routing Switch.')
mibBuilder.exportSymbols("Unisphere-Data-SONET-CONF", usdSonetVTAgentV1=usdSonetVTAgentV1, usdSonetAgentV3=usdSonetAgentV3, usdSonetAgentV4=usdSonetAgentV4, usdSonetAgentV1=usdSonetAgentV1, usdSonetVTAgent=usdSonetVTAgent, usdSonetBasicAgent=usdSonetBasicAgent, usdSonetAgentV2=usdSonetAgentV2, usdSonetAgent=usdSonetAgent, PYSNMP_MODULE_ID=usdSonetAgent, usdSonetBasicAgentV1=usdSonetBasicAgentV1)
|
name1=["ales","Mark","Deny","Hendry"]
name2=name1
name3=name1[:]
name1=["Anand"]
name3=["Murugan"]
sum=0
for ls in (name1,name2,name3):
if ls[0]=="Anand":
sum+=1
pass
if ls[1]=="Murugan":
sum+=5
print(sum)
pass
|
def solution():
def integers():
x = 1
while True:
yield x
x += 1
def halves():
for x in integers():
yield x / 2
def take(n, seq):
result = []
for i in range(n):
result.append(next(seq))
return result
return take, halves, integers
take = solution()[0]
halves = solution()[1]
print(take(5, halves()))
|
"""Classes for stateful data stream sampling
"""
def create_sampler(mode, **kwargs):
"""Creates a specified sampler instance
"""
if mode == 'uniform':
return UniformSampler(**kwargs)
elif mode == 'contiguous':
return ContiguousSampler(**kwargs)
else:
raise ValueError('Unknown sampling mode: %s' % mode)
class UniformSampler(object):
"""Uniform samples from a stream to maintain a certain
ratio of validation data
"""
def __init__(self, rate):
self.rate = rate
self.num_all = 0
self.num_val = 0
def reset(self):
self.num_all = 0
self.num_val = 0
def sample(self):
"""Returns whether to pull the sample for validation
"""
pull_val = self.num_val <= self.num_all * self.rate
self.num_all += 1
if pull_val:
self.num_val += 1
return pull_val
class ContiguousSampler(object):
"""Samples fixed-lengths of data to maintain a ratio of validation data
"""
def __init__(self, rate, segment_length):
self.rate = rate
self.seg_len = segment_length
self.num_all = 0
self.num_val = 0
self.is_pulling = False
self.num_pulled = 0
def reset(self):
self.num_all = 0
self.num_val = 0
self.is_pulling = False
self.num_pulled = 0
def sample(self):
"""Returns whether to pull the sample for validation
"""
if not self.is_pulling:
self.is_pulling = self.num_val < self.num_all * self.rate
self.num_all += 1
if self.is_pulling:
self.num_pulled += 1
if self.num_pulled >= self.seg_len:
self.is_pulling = False
self.num_pulled = 0
self.num_val += 1
return True
else:
return False
|
# Copyright (c) 2017 Pieter Wuille
# Copyright (c) 2018 Oskar Hladky
# Copyright (c) 2018 Pavol Rusnak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
ADDRESS_TYPE_P2KH = 0
ADDRESS_TYPE_P2SH = 8
def cashaddr_polymod(values):
generator = [0x98F2BC8E61, 0x79B76D99E2, 0xF33E5FB3C4, 0xAE2EABE2A8, 0x1E4F43E470]
chk = 1
for value in values:
top = chk >> 35
chk = ((chk & 0x07FFFFFFFF) << 5) ^ value
for i in range(5):
chk ^= generator[i] if (top & (1 << i)) else 0
return chk ^ 1
def prefix_expand(prefix):
return [ord(x) & 0x1F for x in prefix] + [0]
def calculate_checksum(prefix, payload):
poly = cashaddr_polymod(prefix_expand(prefix) + payload + [0, 0, 0, 0, 0, 0, 0, 0])
out = list()
for i in range(8):
out.append((poly >> 5 * (7 - i)) & 0x1F)
return out
def verify_checksum(prefix, payload):
return cashaddr_polymod(prefix_expand(prefix) + payload) == 0
def b32decode(inputs):
out = list()
for letter in inputs:
out.append(CHARSET.find(letter))
return out
def b32encode(inputs):
out = ""
for char_code in inputs:
out += CHARSET[char_code]
return out
def convertbits(data, frombits, tobits, pad=True):
acc = 0
bits = 0
ret = []
maxv = (1 << tobits) - 1
max_acc = (1 << (frombits + tobits - 1)) - 1
for value in data:
if value < 0 or (value >> frombits):
return None
acc = ((acc << frombits) | value) & max_acc
bits += frombits
while bits >= tobits:
bits -= tobits
ret.append((acc >> bits) & maxv)
if pad:
if bits:
ret.append((acc << (tobits - bits)) & maxv)
elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
return None
return ret
def encode(prefix, version, payload):
payload = bytes([version]) + payload
payload = convertbits(payload, 8, 5)
checksum = calculate_checksum(prefix, payload)
return prefix + ":" + b32encode(payload + checksum)
def decode(prefix, addr):
addr = addr.lower()
decoded = b32decode(addr)
if not verify_checksum(prefix, decoded):
raise ValueError("Bad cashaddr checksum")
data = bytes(convertbits(decoded, 5, 8))
return data[0], data[1:-6]
|
#_*_ coding: utf-8 _*_
#Python3 실습
print("hh")
def sum(a,b):
return (a+b)
print(sum(4,5))
print(sum("han"," jaegyu"))
def no_return():
print("안녕하세요")
return
print(no_return())
print(type(None))
a=None
print(a)
print(range(10))
print(list(range(10)))
def daily_sleeping_hours(hours=None):
if hours == None:
print("인자 값 세팅을 잊으셨군요..")
return hours
print(daily_sleeping_hours(6))
print(daily_sleeping_hours())
def introduce_my_car(manufacturer, seats=4, type='sedan'):
print("내 차는", manufacturer, "의", seats, "인승", type,"이다.")
introduce_my_car("ㄹㄹ")
def fun(a='1',b='2',c='3'):
print(a,b,c)
fun(1)
fun(1,1,1)
fun(10,20)
fun(10,c="30")
fun(a='10')
def introduce_your_family(name, *family_names, **family_info):
print("제 이름은", name," 입니다.")
print("제 가족들의 이름은 아래와 같아요. ")
print("-"*40)
for name in family_names:
print(name)
print("-"*40)
for key in family_info.keys():
print(key, ":", family_info[key])
introduce_your_family("홍길동","홍길비","홍길수", 집="용인", 가훈="행복하게 살자!")
def ff(**n):
print(n)
ff(a='aa',b='bb')
def concat(*args, sep='/'):
return sep.join(args)
print(concat("a","b","c"))
print(concat("a","b","c",sep="."))
|
class Iec6205621Exception(Exception):
"""General IEC62056-21 Exception"""
class Iec6205621ClientError(Iec6205621Exception):
"""Client error"""
class Iec6205621ParseError(Iec6205621Exception):
"""Error in parsing IEC62056-21 data"""
class ValidationError(Iec6205621Exception):
"""Not valid data error"""
class TooManyValuesReturned(Iec6205621Exception):
"""If a request for a single value returned more than one value"""
class NoDataReturned(Iec6205621Exception):
"""No data was returned"""
class Iec6206521BaseErrorParser:
"""
Error messages are contained in DataSets and values without unit. Their format is
manufacturer specific so the library can only define a way to handle them not the
exact implementation.
The DummyErrorParser will we used as standard that ignores all errors.
An ErrorParser should take an answer response and parse each data set in it to see
if there is any errors. It should raise appropriate exceptions.
"""
def __init__(self):
pass
def check_for_errors(self, answer_response):
raise NotImplementedError("check_for_errors must be implemented in subclass")
class DummyErrorParser(Iec6206521BaseErrorParser):
"""
A Dummy parser that fits in as default. Should be overridden if you want to define
an error parser.
"""
def check_for_errors(self, answer_response):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.