content
stringlengths 7
1.05M
|
---|
#
# PySNMP MIB module ZYXEL-AclV2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-AclV2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:43:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint")
InetAddress, = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress")
EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus")
PortList, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "PortList")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Counter32, Integer32, Counter64, NotificationType, Bits, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, TimeTicks, iso, Gauge32, Unsigned32, IpAddress, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Integer32", "Counter64", "NotificationType", "Bits", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "TimeTicks", "iso", "Gauge32", "Unsigned32", "IpAddress", "ObjectIdentity")
RowStatus, MacAddress, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "MacAddress", "DisplayString", "TextualConvention")
esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt")
zyxelAclV2 = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105))
if mibBuilder.loadTexts: zyxelAclV2.setLastUpdated('201207010000Z')
if mibBuilder.loadTexts: zyxelAclV2.setOrganization('Enterprise Solution ZyXEL')
zyxelAclV2ClassifierStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1))
zyxelAclV2PolicyStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2))
zyxelAclV2TrapInfoObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 3))
zyxelAclV2Notifications = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 4))
zyxelAclV2ClassifierTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 1), )
if mibBuilder.loadTexts: zyxelAclV2ClassifierTable.setStatus('current')
zyxelAclV2ClassifierEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 1, 1), ).setIndexNames((0, "ZYXEL-AclV2-MIB", "zyAclV2ClassifierName"))
if mibBuilder.loadTexts: zyxelAclV2ClassifierEntry.setStatus('current')
zyAclV2ClassifierName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 1, 1, 1), DisplayString())
if mibBuilder.loadTexts: zyAclV2ClassifierName.setStatus('current')
zyAclV2ClassifierState = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 1, 1, 2), EnabledStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierState.setStatus('current')
zyAclV2ClassifierWeight = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierWeight.setStatus('current')
zyAclV2ClassifierCountState = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 1, 1, 4), EnabledStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierCountState.setStatus('current')
zyAclV2ClassifierLogState = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 1, 1, 5), EnabledStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierLogState.setStatus('current')
zyAclV2ClassifierTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 1, 1, 6), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierTimeRange.setStatus('current')
zyAclV2ClassifierMatchCount = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 1, 1, 7), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierMatchCount.setStatus('current')
zyxelAclV2ClassifierEthernetTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2), )
if mibBuilder.loadTexts: zyxelAclV2ClassifierEthernetTable.setStatus('current')
zyxelAclV2ClassifierEthernetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1), ).setIndexNames((0, "ZYXEL-AclV2-MIB", "zyAclV2ClassifierName"))
if mibBuilder.loadTexts: zyxelAclV2ClassifierEthernetEntry.setStatus('current')
zyAclV2ClassifierEthernetSourcePorts = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1, 1), PortList()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierEthernetSourcePorts.setStatus('current')
zyAclV2ClassifierEthernetSourceTrunks = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1, 2), PortList()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierEthernetSourceTrunks.setStatus('current')
zyAclV2ClassifierEthernetPacketFormat = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("all", 1), ("ethernetIIUntagged", 2), ("ethernetIITagged", 3), ("ethernet802dot3Untagged", 4), ("ethernet802dot3Tagged", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierEthernetPacketFormat.setStatus('current')
zyAclV2ClassifierEthernet8021pPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierEthernet8021pPriority.setStatus('current')
zyAclV2ClassifierEthernetInner8021pPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierEthernetInner8021pPriority.setStatus('current')
zyAclV2ClassifierEthernetType = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierEthernetType.setStatus('current')
zyAclV2ClassifierEthernetSourceMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1, 7), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierEthernetSourceMacAddress.setStatus('current')
zyAclV2ClassifierEthernetSourceMACMask = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1, 8), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierEthernetSourceMACMask.setStatus('current')
zyAclV2ClassifierEthernetDestinationMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1, 9), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierEthernetDestinationMacAddress.setStatus('current')
zyAclV2ClassifierEthernetDestinationMACMask = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 2, 1, 10), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierEthernetDestinationMACMask.setStatus('current')
zyxelAclV2ClassifierVlanTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 3), )
if mibBuilder.loadTexts: zyxelAclV2ClassifierVlanTable.setStatus('current')
zyxelAclV2ClassifierVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 3, 1), ).setIndexNames((0, "ZYXEL-AclV2-MIB", "zyAclV2ClassifierName"))
if mibBuilder.loadTexts: zyxelAclV2ClassifierVlanEntry.setStatus('current')
zyAclV2ClassifierVlanMap1k = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 3, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierVlanMap1k.setStatus('current')
zyAclV2ClassifierVlanMap2k = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 3, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierVlanMap2k.setStatus('current')
zyAclV2ClassifierVlanMap3k = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 3, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierVlanMap3k.setStatus('current')
zyAclV2ClassifierVlanMap4k = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 3, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierVlanMap4k.setStatus('current')
zyxelAclV2ClassifierInnerVlanTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 4), )
if mibBuilder.loadTexts: zyxelAclV2ClassifierInnerVlanTable.setStatus('current')
zyxelAclV2ClassifierInnerVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 4, 1), ).setIndexNames((0, "ZYXEL-AclV2-MIB", "zyAclV2ClassifierName"))
if mibBuilder.loadTexts: zyxelAclV2ClassifierInnerVlanEntry.setStatus('current')
zyAclV2ClassifierInnerVlanMap1k = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 4, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierInnerVlanMap1k.setStatus('current')
zyAclV2ClassifierInnerVlanMap2k = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 4, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierInnerVlanMap2k.setStatus('current')
zyAclV2ClassifierInnerVlanMap3k = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 4, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierInnerVlanMap3k.setStatus('current')
zyAclV2ClassifierInnerVlanMap4k = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 4, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierInnerVlanMap4k.setStatus('current')
zyxelAclV2ClassifierIpTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5), )
if mibBuilder.loadTexts: zyxelAclV2ClassifierIpTable.setStatus('current')
zyxelAclV2ClassifierIpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1), ).setIndexNames((0, "ZYXEL-AclV2-MIB", "zyAclV2ClassifierName"))
if mibBuilder.loadTexts: zyxelAclV2ClassifierIpEntry.setStatus('current')
zyAclV2ClassifierIpPacketLenRangeStart = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpPacketLenRangeStart.setStatus('current')
zyAclV2ClassifierIpPacketLenRangeEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpPacketLenRangeEnd.setStatus('current')
zyAclV2ClassifierIpDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpDSCP.setStatus('current')
zyAclV2ClassifierIpPrecedence = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpPrecedence.setStatus('current')
zyAclV2ClassifierIpToS = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpToS.setStatus('current')
zyAclV2ClassifierIpProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpProtocol.setStatus('current')
zyAclV2ClassifierIpEstablishOnly = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 7), EnabledStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpEstablishOnly.setStatus('current')
zyAclV2ClassifierIpSourceIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 8), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpSourceIpAddress.setStatus('current')
zyAclV2ClassifierIpSourceIpMaskBits = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpSourceIpMaskBits.setStatus('current')
zyAclV2ClassifierIpDestinationIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 10), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpDestinationIpAddress.setStatus('current')
zyAclV2ClassifierIpDestinationIpMaskBits = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 11), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpDestinationIpMaskBits.setStatus('current')
zyAclV2ClassifierIpSourceSocketRangeStart = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 12), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpSourceSocketRangeStart.setStatus('current')
zyAclV2ClassifierIpSourceSocketRangeEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 13), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpSourceSocketRangeEnd.setStatus('current')
zyAclV2ClassifierIpDestinationSocketRangeStart = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 14), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpDestinationSocketRangeStart.setStatus('current')
zyAclV2ClassifierIpDestinationSocketRangeEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 5, 1, 15), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIpDestinationSocketRangeEnd.setStatus('current')
zyxelAclV2ClassifierIpv6Table = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 6), )
if mibBuilder.loadTexts: zyxelAclV2ClassifierIpv6Table.setStatus('current')
zyxelAclV2ClassifierIpv6Entry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 6, 1), ).setIndexNames((0, "ZYXEL-AclV2-MIB", "zyAclV2ClassifierName"))
if mibBuilder.loadTexts: zyxelAclV2ClassifierIpv6Entry.setStatus('current')
zyAclV2ClassifierIPv6DSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 6, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIPv6DSCP.setStatus('current')
zyAclV2ClassifierIPv6NextHeader = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 6, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIPv6NextHeader.setStatus('current')
zyAclV2ClassifierIPv6EstablishOnly = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 6, 1, 3), EnabledStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIPv6EstablishOnly.setStatus('current')
zyAclV2ClassifierIPv6SourceIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 6, 1, 4), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIPv6SourceIpAddress.setStatus('current')
zyAclV2ClassifierIPv6SourceIpPrefixLength = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 6, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIPv6SourceIpPrefixLength.setStatus('current')
zyAclV2ClassifierIPv6DestinationIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 6, 1, 6), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIPv6DestinationIpAddress.setStatus('current')
zyAclV2ClassifierIPv6DestinationIpPrefixLength = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 6, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2ClassifierIPv6DestinationIpPrefixLength.setStatus('current')
zyxelAclV2ClassifierMatchOrder = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("auto", 1), ("manual", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyxelAclV2ClassifierMatchOrder.setStatus('current')
zyxelAclV2ClassifierLoggingState = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 8), EnabledStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyxelAclV2ClassifierLoggingState.setStatus('current')
zyxelAclV2ClassifierLoggingInterval = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyxelAclV2ClassifierLoggingInterval.setStatus('current')
zyxelAclV2PolicyTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1), )
if mibBuilder.loadTexts: zyxelAclV2PolicyTable.setStatus('current')
zyxelAclV2PolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1), ).setIndexNames((0, "ZYXEL-AclV2-MIB", "zyAclV2PolicyName"))
if mibBuilder.loadTexts: zyxelAclV2PolicyEntry.setStatus('current')
zyAclV2PolicyName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 1), DisplayString())
if mibBuilder.loadTexts: zyAclV2PolicyName.setStatus('current')
zyAclV2PolicyState = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 2), EnabledStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyState.setStatus('current')
zyAclV2PolicyClassifier = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyClassifier.setStatus('current')
zyAclV2PolicyVid = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyVid.setStatus('current')
zyAclV2PolicyEgressPort = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyEgressPort.setStatus('current')
zyAclV2Policy8021pPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2Policy8021pPriority.setStatus('current')
zyAclV2PolicyDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyDSCP.setStatus('current')
zyAclV2PolicyTOS = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyTOS.setStatus('current')
zyAclV2PolicyBandwidth = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyBandwidth.setStatus('current')
zyAclV2PolicyOutOfProfileDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyOutOfProfileDSCP.setStatus('current')
zyAclV2PolicyForwardingAction = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("noChange", 1), ("discardThePacket", 2), ("doNotDropTheMatchingFramePreviouslyMarkedForDropping", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyForwardingAction.setStatus('current')
zyAclV2PolicyPriorityAction = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("noChange", 1), ("setThePackets802dot1Priority", 2), ("sendThePacketToPriorityQueue", 3), ("replaceThe802dot1PriorityFieldWithTheIpTosValue", 4), ("replaceThe802dot1PriorityByInner802dot1Priority", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyPriorityAction.setStatus('current')
zyAclV2PolicyDiffServAction = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("noChange", 1), ("setThePacketsTosField", 2), ("replaceTheIpTosFieldWithThe802dot1PriorityValue", 3), ("setTheDiffservCodepointFieldInTheFrame", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyDiffServAction.setStatus('current')
zyAclV2PolicyOutgoingAction = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 14), Bits().clone(namedValues=NamedValues(("sendThePacketToTheMirrorPort", 0), ("sendThePacketToTheEgressPort", 1), ("sendTheMatchingFramesToTheEgressPort", 2), ("setThePacketVlanId", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyOutgoingAction.setStatus('current')
zyAclV2PolicyMeteringState = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 15), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyMeteringState.setStatus('current')
zyAclV2PolicyOutOfProfileAction = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 16), Bits().clone(namedValues=NamedValues(("dropThePacket", 0), ("changeTheDscpValue", 1), ("setOutDropPrecedence", 2), ("doNotDropTheMatchingFramePreviouslyMarkedForDropping", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyOutOfProfileAction.setStatus('current')
zyAclV2PolicyRowstatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 17), RowStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyRowstatus.setStatus('current')
zyAclV2PolicyQueueAction = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 2, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("noChange", 1), ("sendThePacketToPriorityQueue", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zyAclV2PolicyQueueAction.setStatus('current')
zyAclV2TrapClassifierLogMatchCount = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 3, 1), Integer32())
if mibBuilder.loadTexts: zyAclV2TrapClassifierLogMatchCount.setStatus('current')
zyAclV2ClassifierLogNotification = NotificationType((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 105, 4, 1)).setObjects(("ZYXEL-AclV2-MIB", "zyAclV2ClassifierName"), ("ZYXEL-AclV2-MIB", "zyAclV2TrapClassifierLogMatchCount"))
if mibBuilder.loadTexts: zyAclV2ClassifierLogNotification.setStatus('current')
mibBuilder.exportSymbols("ZYXEL-AclV2-MIB", zyAclV2ClassifierInnerVlanMap1k=zyAclV2ClassifierInnerVlanMap1k, zyAclV2ClassifierIPv6DSCP=zyAclV2ClassifierIPv6DSCP, zyAclV2ClassifierEthernetInner8021pPriority=zyAclV2ClassifierEthernetInner8021pPriority, zyAclV2ClassifierInnerVlanMap4k=zyAclV2ClassifierInnerVlanMap4k, zyAclV2ClassifierEthernetPacketFormat=zyAclV2ClassifierEthernetPacketFormat, zyAclV2ClassifierVlanMap2k=zyAclV2ClassifierVlanMap2k, zyxelAclV2PolicyStatus=zyxelAclV2PolicyStatus, zyAclV2PolicyClassifier=zyAclV2PolicyClassifier, zyxelAclV2ClassifierInnerVlanTable=zyxelAclV2ClassifierInnerVlanTable, zyAclV2ClassifierIpEstablishOnly=zyAclV2ClassifierIpEstablishOnly, zyAclV2ClassifierEthernetType=zyAclV2ClassifierEthernetType, zyAclV2ClassifierEthernetSourceMacAddress=zyAclV2ClassifierEthernetSourceMacAddress, zyAclV2ClassifierIpSourceIpMaskBits=zyAclV2ClassifierIpSourceIpMaskBits, zyAclV2ClassifierEthernetDestinationMacAddress=zyAclV2ClassifierEthernetDestinationMacAddress, zyAclV2PolicyOutOfProfileDSCP=zyAclV2PolicyOutOfProfileDSCP, zyAclV2ClassifierIpDestinationSocketRangeEnd=zyAclV2ClassifierIpDestinationSocketRangeEnd, zyAclV2PolicyEgressPort=zyAclV2PolicyEgressPort, zyAclV2PolicyRowstatus=zyAclV2PolicyRowstatus, zyAclV2ClassifierEthernetSourceTrunks=zyAclV2ClassifierEthernetSourceTrunks, zyxelAclV2ClassifierInnerVlanEntry=zyxelAclV2ClassifierInnerVlanEntry, zyAclV2ClassifierLogNotification=zyAclV2ClassifierLogNotification, zyAclV2PolicyOutgoingAction=zyAclV2PolicyOutgoingAction, zyAclV2ClassifierIpDestinationIpAddress=zyAclV2ClassifierIpDestinationIpAddress, zyAclV2PolicyMeteringState=zyAclV2PolicyMeteringState, zyAclV2ClassifierInnerVlanMap2k=zyAclV2ClassifierInnerVlanMap2k, zyAclV2ClassifierIpPrecedence=zyAclV2ClassifierIpPrecedence, zyAclV2PolicyVid=zyAclV2PolicyVid, zyxelAclV2ClassifierEntry=zyxelAclV2ClassifierEntry, zyAclV2ClassifierIpDestinationIpMaskBits=zyAclV2ClassifierIpDestinationIpMaskBits, zyxelAclV2Notifications=zyxelAclV2Notifications, zyxelAclV2PolicyTable=zyxelAclV2PolicyTable, zyxelAclV2ClassifierMatchOrder=zyxelAclV2ClassifierMatchOrder, zyAclV2ClassifierIpDSCP=zyAclV2ClassifierIpDSCP, zyAclV2ClassifierWeight=zyAclV2ClassifierWeight, zyAclV2ClassifierMatchCount=zyAclV2ClassifierMatchCount, zyAclV2PolicyPriorityAction=zyAclV2PolicyPriorityAction, zyAclV2TrapClassifierLogMatchCount=zyAclV2TrapClassifierLogMatchCount, zyxelAclV2ClassifierEthernetEntry=zyxelAclV2ClassifierEthernetEntry, zyAclV2ClassifierIpPacketLenRangeStart=zyAclV2ClassifierIpPacketLenRangeStart, zyAclV2ClassifierEthernetSourceMACMask=zyAclV2ClassifierEthernetSourceMACMask, zyAclV2ClassifierEthernetDestinationMACMask=zyAclV2ClassifierEthernetDestinationMACMask, zyAclV2ClassifierVlanMap3k=zyAclV2ClassifierVlanMap3k, zyAclV2ClassifierTimeRange=zyAclV2ClassifierTimeRange, zyxelAclV2ClassifierIpv6Entry=zyxelAclV2ClassifierIpv6Entry, zyAclV2ClassifierIPv6EstablishOnly=zyAclV2ClassifierIPv6EstablishOnly, zyAclV2ClassifierIPv6DestinationIpPrefixLength=zyAclV2ClassifierIPv6DestinationIpPrefixLength, zyxelAclV2ClassifierIpEntry=zyxelAclV2ClassifierIpEntry, zyAclV2ClassifierIpToS=zyAclV2ClassifierIpToS, zyAclV2ClassifierEthernetSourcePorts=zyAclV2ClassifierEthernetSourcePorts, zyAclV2PolicyQueueAction=zyAclV2PolicyQueueAction, zyAclV2ClassifierIPv6NextHeader=zyAclV2ClassifierIPv6NextHeader, zyAclV2ClassifierVlanMap4k=zyAclV2ClassifierVlanMap4k, zyAclV2ClassifierEthernet8021pPriority=zyAclV2ClassifierEthernet8021pPriority, zyxelAclV2TrapInfoObjects=zyxelAclV2TrapInfoObjects, zyxelAclV2ClassifierIpTable=zyxelAclV2ClassifierIpTable, zyAclV2ClassifierIPv6SourceIpAddress=zyAclV2ClassifierIPv6SourceIpAddress, zyxelAclV2ClassifierLoggingState=zyxelAclV2ClassifierLoggingState, zyxelAclV2=zyxelAclV2, zyxelAclV2ClassifierIpv6Table=zyxelAclV2ClassifierIpv6Table, zyAclV2PolicyDiffServAction=zyAclV2PolicyDiffServAction, zyAclV2ClassifierIpDestinationSocketRangeStart=zyAclV2ClassifierIpDestinationSocketRangeStart, zyAclV2ClassifierVlanMap1k=zyAclV2ClassifierVlanMap1k, zyAclV2PolicyDSCP=zyAclV2PolicyDSCP, zyxelAclV2ClassifierEthernetTable=zyxelAclV2ClassifierEthernetTable, zyAclV2ClassifierLogState=zyAclV2ClassifierLogState, zyAclV2ClassifierInnerVlanMap3k=zyAclV2ClassifierInnerVlanMap3k, zyAclV2ClassifierIPv6SourceIpPrefixLength=zyAclV2ClassifierIPv6SourceIpPrefixLength, zyAclV2PolicyBandwidth=zyAclV2PolicyBandwidth, zyxelAclV2ClassifierLoggingInterval=zyxelAclV2ClassifierLoggingInterval, zyAclV2Policy8021pPriority=zyAclV2Policy8021pPriority, zyAclV2PolicyForwardingAction=zyAclV2PolicyForwardingAction, zyAclV2PolicyName=zyAclV2PolicyName, PYSNMP_MODULE_ID=zyxelAclV2, zyAclV2ClassifierName=zyAclV2ClassifierName, zyAclV2ClassifierIPv6DestinationIpAddress=zyAclV2ClassifierIPv6DestinationIpAddress, zyAclV2ClassifierState=zyAclV2ClassifierState, zyxelAclV2ClassifierVlanEntry=zyxelAclV2ClassifierVlanEntry, zyAclV2PolicyState=zyAclV2PolicyState, zyAclV2ClassifierIpSourceIpAddress=zyAclV2ClassifierIpSourceIpAddress, zyxelAclV2ClassifierTable=zyxelAclV2ClassifierTable, zyxelAclV2ClassifierStatus=zyxelAclV2ClassifierStatus, zyAclV2ClassifierIpSourceSocketRangeEnd=zyAclV2ClassifierIpSourceSocketRangeEnd, zyAclV2PolicyTOS=zyAclV2PolicyTOS, zyAclV2ClassifierIpPacketLenRangeEnd=zyAclV2ClassifierIpPacketLenRangeEnd, zyxelAclV2PolicyEntry=zyxelAclV2PolicyEntry, zyAclV2ClassifierIpProtocol=zyAclV2ClassifierIpProtocol, zyxelAclV2ClassifierVlanTable=zyxelAclV2ClassifierVlanTable, zyAclV2PolicyOutOfProfileAction=zyAclV2PolicyOutOfProfileAction, zyAclV2ClassifierIpSourceSocketRangeStart=zyAclV2ClassifierIpSourceSocketRangeStart, zyAclV2ClassifierCountState=zyAclV2ClassifierCountState)
|
class Temperature:
def __init__(self, kelvin=None, celsius=None, fahrenheit=None):
values = [x for x in [kelvin, celsius, fahrenheit] if x]
if len(values) < 1:
raise ValueError('Need argument')
if len(values) > 1:
raise ValueError('Only one argument')
if celsius is not None:
self.kelvin = celsius + 273.15
elif fahrenheit is not None:
self.kelvin = (fahrenheit - 32) * 5 / 9 + 273.15
else:
self.kelvin = kelvin
if self.kelvin < 0:
raise ValueError('Temperature in Kelvin cannot be negative')
def __str__(self):
return f'Temperature = {self.kelvin} Kelvins'
|
print('-+-' *10)
print(' GERADOR DE PA')
print('+-+' * 10)
c = 1
ter = int(input('Insira o primeiro termo - '))
rz = int(input('Insira a razão - '))
while c <= 10:
print(ter, ' → ', end=' ')
ter += rz
c += 1
print('FIM')
|
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
M = float('inf')
# dynamic programming
dp = [0] + [M] * amount
for i in range(1, amount+1):
dp[i] = 1 + min([dp[i-c] for c in coins if i >= c] or [M])
return dp[-1] if dp[-1] < M else -1
|
def removeLoop(head):
ptr = head
ptr2 = head
while True :
if ptr is None or ptr2 is None or ptr2.next is None :
return
ptr = ptr.next
ptr2 = ptr2.next.next
if ptr is ptr2 :
loopNode = ptr
break
ptr = loopNode.next
count = 1
while ptr is not loopNode :
ptr = ptr.next
count += 1
ptr = head
ptr1 = head
ptr2 = head.next
while count > 1 :
ptr2 = ptr2.next
ptr1 = ptr1.next
count -= 1
while ptr is not ptr2 :
ptr = ptr.next
ptr2 = ptr2.next
ptr1 = ptr1.next
ptr1.next = None
|
students = []
def read_file():
try:
f = open("students.txt", "r")
for student in read_students(f):
students.append(student)
f.close()
except Exception:
print("Could not read file")
def read_students(f):
for line in f:
yield line
read_file()
print(students)
|
def extended_euclidean_algorithm(a, b):
# Initial s = 1
s = 1
list_s = []
list_t = []
# Algorithm
while b > 0:
# Find the remainder of a, b
r = a % b
if r > 0:
# The t expression
t = (r - (a * s)) // b
list_t.append(t)
list_s.append(s)
# Use b to be the new a
a = b
if r > 0:
# Use the remainder to be the new b
b = r
else:
break
# Find the coefficients s and t
for i in range(len(list_t)):
if i+1 < len(list_t):
# Find the coefficient t
t = list_t[0] + (list_t[(len(list_t)-1)] * s)
# Find the coefficient s
s = list_s[i] + list_t[i] * list_t[i+1]
return t
|
class Student(object):
# __init__是一个特殊方法用于在创建对象时进行初始化操作
# 通过这个方法我们可以为学生对象绑定name和age两个属性
def __init__(self, name, age):
self.name = name
self.age = age
def study(self, course_name):
print('%s正在学习%s.' % (self.name, course_name))
# PEP 8要求标识符的名字用全小写多个单词用下划线连接
# 但是部分程序员和公司更倾向于使用驼峰命名法(驼峰标识)
def watch_movie(self):
if self.age < 18:
print('%s只能观看《熊出没》.' % self.name)
else:
print('%s正在观看岛国爱情大电影.' % self.name)
def main():
# 创建学生对象并指定姓名和年龄
stu1 = Student('骆昊', 38)
# 给对象发study消息
stu1.study('Python程序设计')
# 给对象发watch_av消息
stu1.watch_movie()
stu2 = Student('王大锤', 15)
stu2.study('思想品德')
stu2.watch_movie()
if __name__ == '__main__':
main()
|
WIDTH = 20
HEIGHT = 14
TITLE = 'Click Ninja'
BACKGROUND = 'board'
def destroy(s):
sound('swoosh')
if s.name == 'taco':
score(50)
else:
score(5)
# draw a splatting image at the center position of the image
image('redsplat', center=s.event_pos, size=2).fade(1.0)
s.fade(0.25)
def failure(s):
score(-20)
if s.name == 'bomb':
s.destroy()
image('explode', center=s.center, size=10).pulse(0.05)
if s.name == 'bomb' or score() < 0:
sound('scream')
text('You Survived %s seconds' % time(), MAROON)
callback(gameover, 0.01)
def spawn():
speed = randint(2, 10)
size = randint(1,4)
target = choice(['bananas', 'cherries',
'olives', 'ham', 'hotdog',
'fries','icee', 'pizza'])
if randint(1, 4) == 2:
target = 'bomb'
if randint(1, 10) == 5:
target = 'taco'
sound('launch')
arc = rand_arc()
s = image(target, arc[0], size=size)
if target == 'bomb':
s.speed(speed).spin(1).clicked(failure)
s.move_to(arc[1], arc[2], callback = s.destroy)
elif target == 'taco':
s.speed(5).spin().clicked(destroy)
s.move_to((-10, -2), (-5, HEIGHT/2), (WIDTH+1, HEIGHT/2), callback = s.destroy)
else:
s.speed(speed).clicked(destroy)
s.move_to(arc[1], arc[2], callback = lambda: failure(s))
callback(spawn, rand(0.1, 3))
score(color = PURPLE)
callback(spawn, 1)
keydown('r', reset)
|
DEPTH = 3
# Action
class Action:
top = [1, 0, 0, 0]
bottom = [0, 1, 0, 0]
left = [0, 0, 1, 0]
right = [0, 0, 0, 1]
actlist = [(-1, 0), (1, 0), (0, -1), (0, 1)]
mapAct = {
actlist[0]: top,
actlist[1]: bottom,
actlist[2]: left,
actlist[3]: right
}
def go(state, action, board_height, board_width):
if action == (-1, 0):
return ((state[0]+board_height-1) % board_height, state[1])
elif action == (1, 0):
return ((state[0]+1) % board_height, state[1])
elif action == (0, 1):
return (state[0], (state[1]+1) % board_width)
elif action == (0, -1):
return (state[0], (state[1]+board_width-1) % board_width)
class GameState:
obs = {}
is_end = False
def __init__(self, observation):
self.obs = {
1: observation[1].copy(),
2: observation[2].copy(),
3: observation[3].copy(),
4: observation[4].copy(),
5: observation[5].copy(),
6: observation[6].copy(),
7: observation[7].copy(),
'board_width': observation['board_width'],
'board_height': observation['board_height'],
}
def generateSuccessor(self, index, action):
successor = GameState(self.obs)
index += 2
head = tuple(successor.obs[index][0])
tar = list(Action.go(head, action, self.obs['board_height'], self.obs['board_width']))
for i in range(1, 8):
for cor in successor.obs[i]:
if cor == tar:
successor.is_end = True
if i == 1:
successor.obs[index].append(successor.obs[index][-1])
else:
successor.obs[index].clear()
successor.obs[index].insert(0, tar)
successor.obs[index].pop()
return successor
def evaluationFunction(self):
ans = 0
for i in range(2, 8):
if i < 5:
ans += len(self.obs[i])
else:
ans -= len(self.obs[i])
return ans
class MinimaxAgent:
def __init__(self, obs):
self.obs = obs
def value(self, gameState, index, depth, a, b):
index %= 6
if index == 0:
return self.maxValue(gameState, index, depth + 1, a, b)[0]
elif index < 3:
return self.maxValue(gameState, index, depth, a, b)[0]
else:
return self.minValue(gameState, index, depth, a, b)[0]
def maxValue(self, gameState, index, depth, a, b):
if gameState.is_end or depth >= DEPTH:
return [gameState.evaluationFunction(), None]
v = -10000
ac = Action.actlist[0]
for action in Action.actlist:
next = gameState.generateSuccessor(index, action)
value = self.value(next, index+1, depth, a, b)
if value > v:
v = value
ac = action
if v >= b:
return [v, ac]
a = max(a, v)
return [v, ac]
def minValue(self, gameState, index, depth, a, b):
if gameState.is_end:
return [gameState.evaluationFunction(), None]
v = 10000
ac = Action.actlist[0]
for action in Action.actlist:
next = gameState.generateSuccessor(index, action)
value = self.value(next, index+1, depth, a, b)
if value < v:
v = value
ac = action
if v <= a:
return [v, ac]
b = min(b, v)
return [v, ac]
def get_action(self, index):
return self.maxValue(GameState(self.obs), index-2, 0, -10000, 10000)[1]
def my_controller(observation, action_space, is_act_continuous=False):
ac = Action.mapAct[MinimaxAgent(observation).get_action(observation['controlled_snake_index'])]
return [ac]
|
def read_csv(root, file_name, keys):
with open('{root}private_static/csv/{file_name}.csv'.format(root=root, file_name=file_name)) as file:
data = file.read()
lines = data.split("\n")
return [dict(zip(keys, line.split(','))) for i, line in enumerate(lines) if i != 0]
|
# -*- coding: utf-8 -*-
'''
Copyright 2012 Rodrigo Pinheiro Matias <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
templates = {
'static_link': '''
\t@$(AR) rcs %(lib)s %(obj)s
\t@echo " [\033[33m\033[1mAR\033[0m] - \033[37m\033[1m%(obj)s\033[0m to \033[37m\033[1m%(lib)s\033[0m"''',
'c_obj_ruler': '''%(obj)s: %(source)s
\t@$(CC) $(CFLAGS) $(INCLUDE) -c %(source)s -o %(obj)s 1>> compile.log 2>> compile.err
\t@echo " [\033[33m\033[1mCC\033[0m] - \033[37m\033[1m%(source)s\033[0m"''',
'asm_obj_ruler': '''%(obj)s: %(source)s
\t@$(AS) $(ASFLAGS) -o %(obj)s %(source)s 1>> compile.log 2>> compile.err
\t@echo " [\033[33m\033[1mAS\033[0m] - \033[37m\033[1m%(source)s\033[0m"''',
'c_asm_ruler': '''%(obj)s: %(source)s
\t@$(CC) $(CFLAGS) $(INCLUDE) -c %(source)s -S -o %(obj)s 1>> compile.log 2>> compile.err
\t@echo " [\033[33m\033[1mCC\033[0m] - \033[37m\033[1m%(source)s\033[0m"''',
'cxx_obj_ruler': '''%(obj)s: %(source)s
\t@$(CXX) $(CXXFLAGS) $(INCLUDE) -c %(source)s -o %(obj)s 1>> compile.log 2>> compile.err
\t@echo " [\033[33m\033[1mCXX\033[0m] - \033[37m\033[1m%(source)s\033[0m"''',
'cxx_asm_ruler': '''%(obj)s: %(source)s
\t@$(CXX) $(CXXFLAGS) $(INCLUDE) -c %(source)s -S -o %(obj)s 1>> compile.log 2>> compile.err
\t@echo " [\033[33m\033[1mCXX\033[0m] - \033[37m\033[1m%(source)s\033[0m"''',
'avr-main.cc': '''/**
* Generated with sketch %(version)s
**/
#include <avr/sleep.h>
int main(void) {
for(;;)
sleep_mode();
return 0;
}''',
'main.cc': '''/**
* Generated with sketch %(version)s
**/
#include <Arduino.h>
/**
* Setup of the firmware
**/
void setup() {
}
/**
* Schedule events for firmware program
**/
void loop() {
delay(250);
}''',
'Makefile': '''##########################################
# Makefile generated with sketch %(version)s
##########################################
# Defines of Arduino
ARDUINO_HOME=%(sdk_home)s
ARDUINO_CORE=$(ARDUINO_HOME)/hardware/arduino/cores
ARDUINO_VARIANT=$(ARDUINO_HOME)/hardware/arduino/variants/%(variant)s
# Define toolchain
CC=%(cc)s
CXX=%(cxx)s
AS=%(asm)s
LD=%(ld)s
AR=%(ar)s
OBJCOPY=%(objcopy)s
SIZE=%(size)s
AVRDUDE=%(avrdude)s
PROGRAMER=%(programer)s
LIB=
INCLUDE=-I$(ARDUINO_CORE)/arduino -I$(ARDUINO_VARIANT) -I$(ARDUINO_CORE) -I lib/
#Define of MCU
MCU=%(mcu)s
CLOCK=%(clock_hz)sUL
ARDUINO=%(sdk_version)s
# Define compiler flags
_CFLAGS=-Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=$(MCU) \\
-DF_CPU=$(CLOCK) -MMD -DARDUINO=$(ARDUINO) \\
-fpermissive -lm -Wl,-u,vfprintf -lprintf_min
CFLAGS=$(_CFLAGS) -std=c99
CXXFLAGS=$(_CFLAGS) -std=c++98
ASFLAGS=-mmcu $(MCU)
# Define compiler rulers
OBJ=%(obj_dep)s
CORE_OBJ=%(core_obj_dep)s
AOUT=binary/%(project_name)s-%(mcu)s.elf
HEX=binary/%(project_name)s-%(mcu)s.hex
EPP=binary/%(project_name)s-%(mcu)s.epp
CORE_LIB=binary/core.a
LIB_DEPS=%(lib_deps)s
LD_FLAGS=-Os -Wl,--gc-sections -mmcu=$(MCU) -lm
AVRDUDE_OPTIONS = -p$(MCU) -c$(PROGRAMER) %(pgrextra)s -Uflash:w:$(HEX):i
SIZE_OPTS=-C --mcu=$(MCU)
CONFIG_EXISTS=$(shell [ -e "Makefile.config" ] && echo 1 || echo 0)
ifeq ($(CONFIG_EXISTS), 1)
include Makefile.config
endif
all: $(HEX) $(EPP)
rebuild: clean all
deploy: $(HEX)
\t$(AVRDUDE) $(AVRDUDE_OPTIONS)
$(HEX): $(EPP)
\t@echo " [\033[33m\033[1mOBJCOPY\033[0m] - \033[37m\033[1mFirmware\033[0m"
\t@$(OBJCOPY) -O ihex -R .eeprom $(AOUT) $(HEX)
$(EPP): $(AOUT)
\t@echo " [\033[33m\033[1mOBJCOPY\033[0m] - \033[37m\033[1mMemory of EEPROM\033[0m"
\t@$(OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(AOUT) $(EPP)
size: $(AOUT)
\t@$(SIZE) $(SIZE_OPTS) $(AOUT)
$(AOUT): clear-compiler $(OBJ) $(CORE_LIB) $(LIB_DEPS)
\t@echo " [\033[33m\033[1mLD\033[0m] - \033[37m\033[1m$(AOUT)\033[0m"
\t@$(CXX) $(LD_FLAGS) $(LIB) $(OBJ) $(CORE_LIB) $(LIB_DEPS) -o $(AOUT)
$(CORE_LIB): $(CORE_OBJ)%(core_ruler)s
%(asm_rulers)s
%(obj_rulers)s
%(libs_rulers)s
%(core_asm_rulers)s
%(core_obj_rulers)s
clear-compiler:
\t@echo " [\033[33m\033[1mRM\033[0m] - Clear compiler logs"
\trm -f compile.*
clean-tmp:
\t@echo " [\033[33m\033[1mRM\033[0m] - Clear temporary files"
\t@rm -f tmp/*
clean-bin:
\t@echo " [\033[33m\033[1mRM\033[0m] - Clear binary files"
\t@rm -f binary/*
clean:
\t@echo " [\033[33m\033[1mRM\033[0m] - Clear temporary files"
\t@rm -f tmp/*
\t@echo " [\033[33m\033[1mRM\033[0m] - Clear binary files"
\t@rm -f binary/*
''',
'avr-Makefile': '''##########################################
# Makefile generated with sketch %(version)s
##########################################
# Define toolchain
CC=%(cc)s
CXX=%(cxx)s
AS=%(asm)s
LD=%(ld)s
AR=%(ar)s
OBJCOPY=%(objcopy)s
SIZE=%(size)s
AVRDUDE=%(avrdude)s
PROGRAMER=%(programer)s
LIB=
INCLUDE=-I lib/
#Define of MCU
MCU=%(mcu)s
CLOCK=%(clock_hz)sUL
# Define compiler flags
_CFLAGS=-Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=$(MCU) \\
-DF_CPU=$(CLOCK) -fpermissive -lm -Wl,-u,vfprintf -lprintf_min
CFLAGS=$(_CFLAGS) -std=c99
CXXFLAGS=$(_CFLAGS) -std=c++98
ASFLAGS=-mmcu $(MCU)
# Define compiler rulers
ASM=%(asm_dep)s
OBJ=%(obj_dep)s
LIB_DEPS=%(lib_deps)s
AOUT=binary/%(project_name)s-%(mcu)s.elf
HEX=binary/%(project_name)s-%(mcu)s.hex
EPP=binary/%(project_name)s-%(mcu)s.epp
LD_FLAGS=-Os -Wl,--gc-sections -mmcu=$(MCU) -lm
AVRDUDE_OPTIONS = -p$(MCU) -c$(PROGRAMER) %(pgrextra)s -Uflash:w:$(HEX):i
SIZE_OPTS=-A
CONFIG_EXISTS=$(shell [ -e "Makefile.config" ] && echo 1 || echo 0)
ifeq ($(CONFIG_EXISTS), 1)
include Makefile.config
endif
all: $(HEX) $(EPP)
rebuild: clean all
deploy: $(HEX)
\t$(AVRDUDE) $(AVRDUDE_OPTIONS)
$(HEX): $(EPP)
\t@echo " [\033[33m\033[1mOBJCOPY\033[0m] - \033[37m\033[1mFirmware\033[0m"
\t@$(OBJCOPY) -O ihex -R .eeprom $(AOUT) $(HEX)
$(EPP): $(AOUT)
\t@echo " [\033[33m\033[1mOBJCOPY\033[0m] - \033[37m\033[1mMemory of EEPROM\033[0m"
\t@$(OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(AOUT) $(EPP)
size: $(AOUT)
\t@$(SIZE) $(SIZE_OPTS) $(AOUT)
$(AOUT): clear-compiler $(OBJ) $(LIB_DEPS)
\t@echo " [\033[33m\033[1mLD\033[0m] - \033[37m\033[1m$(AOUT)\033[0m"
\t@$(CXX) $(LD_FLAGS) $(LIB) $(OBJ) $(LIB_DEPS) -o $(AOUT)
%(asm_rulers)s
%(obj_rulers)s
%(libs_rulers)s
clear-compiler:
\t@echo " [\033[33m\033[1mRM\033[0m] - Clear compiler logs"
\t@rm -f compile.*
clean-tmp:
\t@echo " [\033[33m\033[1mRM\033[0m] - Clear temporary files"
\t@rm -f tmp/*
clean-bin:
\t@echo " [\033[33m\033[1mRM\033[0m] - Clear binary files"
\t@rm -f binary/*
clean:
\t@echo " [\033[33m\033[1mRM\033[0m] - Clear temporary files"
\t@rm -f tmp/*
\t@echo " [\033[33m\033[1mRM\033[0m] - Clear binary files"
\t@rm -f binary/*
'''
}
|
def main():
# input
A = input()
# compute
# output
if A == 'a':
print(-1)
else:
print('a')
if __name__ == '__main__':
main()
|
## mv to //:WORKSPACE.bzl ocaml_configure
load("//ocaml/_bootstrap:ocaml.bzl", _ocaml_configure = "ocaml_configure")
# load("//ocaml/_bootstrap:obazl.bzl", _obazl_configure = "obazl_configure")
load("//ocaml/_rules:ocaml_repository.bzl" , _ocaml_repository = "ocaml_repository")
# load("//ocaml/_rules:opam_configuration.bzl" , _opam_configuration = "opam_configuration")
# load("//ocaml/_toolchains:ocaml_toolchains.bzl",
# _ocaml_toolchain = "ocaml_toolchain",
# _ocaml_register_toolchains = "ocaml_register_toolchains")
# obazl_configure = _obazl_configure
ocaml_configure = _ocaml_configure
ocaml_repository = _ocaml_repository
# ocaml_toolchain = _ocaml_toolchain
# ocaml_register_toolchains = _ocaml_register_toolchains
|
class AthenaError(Exception):
"""base class for all athena exceptions"""
pass
class AthenaMongoError(AthenaError):
"""Class for all mongo related errors"""
pass
|
class MetricsService:
def __init__(self, adc_data, metrics_data):
self._adc_data = adc_data
self._metrics_data = metrics_data
@property
def metrics_data(self):
return self._metrics_data
def update(self):
self._metrics_data.is_new_data_available = False
if self._adc_data.is_new_data_available:
self._metrics_data.update(self._adc_data.trace)
self._metrics_data.is_new_data_available = True
|
#sum(iterable, start=0, /)
#Return the sum of a 'start' value (default: 0) plus an iterable of numbers
#When the iterable is empty, return the start value.
'''This function is intended specifically for use with numeric values and may
reject non-numeric types.'''
a = [1,3,5,7,9,4,6,2,8]
print(sum(a))
print(sum(a,start = 4))
|
class Sign:
"""
符号
"""
def __init__(self, sign_type, sign_str='', sign_line=-1):
"""
构造
:param sign_type: 符号的类型
:param sign_str: 符号的内容(可以为空)
:param sign_line: 符号所在行数(可以为空)
"""
self.type = sign_type
self.str = sign_str
self.line = sign_line
def is_terminal_sign(self):
"""
是不是终结符
:return: True/False
"""
if self.type == 'empty':
return True
else:
for i in terminal_sign_type:
if i == self.type:
return True
return False
def is_non_terminal_sign(self):
"""
是不是非终结符
:return: True/False
"""
for i in non_terminal_sign_type:
if i == self.type:
return True
return False
def is_empty_sign(self):
"""
是不是空字
:return: True/False
"""
return self.type == 'empty'
class Production:
"""
产生式
"""
def __init__(self, left_type, right_types):
"""
产生式左边
:param left_type: 产生式左边的符号类型
:param right_types: 产生式右边的符号类型列表
:param semantic_start: 语义操作关键字 - 开始
:param semantic_children: 语义操作关键字 - 孩子
:param semantic_end: 语义操作关键字 - 结束
"""
self.left = Sign(left_type)
self.right = list()
for i in right_types:
self.right.append(Sign(i))
# 调试用的
SignToChar = {
'else': 'else',
'if': 'if',
'int': 'int',
'return': 'return',
'void': 'void',
'while': 'while',
'addition': '+',
'subtraction': '-',
'multiplication': '*',
'division': '/',
'bigger': '>',
'bigger-equal': '>=',
'smaller': '<',
'smaller-equal': '<=',
'equal': '==',
'not-equal': '!=',
'evaluate': '=',
'semicolon': ';',
'comma': ',',
'left-parentheses': '(',
'right-parentheses': ')',
'left-bracket': '[',
'right-bracket': ']',
'left-brace': '{',
'right-brace': '}',
'id': 'id',
'num': 'num',
'pound': '#'
}
self.str = self.left.type + ' ->'
if len(self.right) == 0:
self.str += 'ϵ'
else:
for i in self.right:
if i.is_non_terminal_sign():
self.str += ' ' + i.type
else:
self.str += ' ' + SignToChar[i.type]
"""
1. program -> define-list
2. define-list -> define define-list
| empty
3. define -> type ID define-type
4. define-type -> var-define-follow
| fun-define-follow
5. var-define-follow -> ;
| [ NUM ] ;
6. type -> int
| void
7. fun-define-follow -> ( params ) code-block
8. params -> param-list
| empty
9. param-list -> param param-follow
10. param-follow -> , param param-follow
| empty
11. param -> type ID array-subscript
12. array-subscript -> [ ]
| empty
13. code-block -> { local-define-list code-list }
14. local-define-list -> local-var-define local-define-list
| empty
15. local-var-define -> type ID var-define-follow
16. code-list -> code code-list
| empty
17. code -> normal-statement
| selection-statement
| iteration-statement
| return-statement
18. normal-statement -> ;
| ID normal-statement-follow
19. normal-statement-follow -> var-follow = expression ;
| call-follow ;
20. call-follow -> ( call-params )
21. call-params -> call-param-list
| empty
22. call-param-list -> expression call-param-follow
23. call-param-follow -> , expression call-param-follow
| empty
24. selection-statement -> if ( expression ) { code-list } selection-follow
25. selection-follow -> else { code-list }
| empty
26. iteration-statement -> while ( expression ) iteration-follow
27. iteration-follow -> { code-list }
| code
28. return-statement -> return return-follow
29. return-follow -> ;
| expression ;
30. var-follow -> [ expression ]
| empty
31. expression -> additive-expr expression-follow
32. expression-follow -> rel-op additive-expr
| empty
33. rel-op -> <=
| <
| >
| >=
| ==
| !=
34. additive-expr -> term additive-expr-follow
35. additive-expr-follow -> add-op term additive-expr-follow
| empty
36. add-op -> +
| -
37. term -> factor term-follow
38. term-follow -> mul-op factor term-follow
| empty
39. mul-op -> *
| /
40. factor -> ( expression )
| ID id-factor-follow | NUM
41. id-factor-follow -> var-follow
| ( args )
42. args -> arg-list
| empty
43. arg-list -> expression arg-list-follow
44. arg-list-follow -> , expression arg-list-follow
| empty
"""
# 所有终结符的类型
terminal_sign_type = [
'else',
'if',
'int',
'return',
'void',
'while',
'addition',
'subtraction',
'multiplication',
'division',
'bigger',
'bigger-equal',
'smaller',
'smaller-equal',
'equal',
'not-equal',
'evaluate',
'semicolon',
'comma',
'left-parentheses',
'right-parentheses',
'left-bracket',
'right-bracket',
'left-brace',
'right-brace',
'id',
'num',
# 在这之前添加非终结符类型,请务必不要动 'pound'
'pound'
]
# 所有非终结符的类型
non_terminal_sign_type = [
'program',
'define-list',
'define',
'define-type',
'var-define-follow',
'type',
'fun-define-follow',
'params',
'param-list',
'param-follow',
'param',
'array-subscript',
'code-block',
'local-define-list',
'local-var-define',
'code-list',
'code',
'normal-statement',
'normal-statement-follow',
'call-follow',
'call-params',
'call-param-list',
'call-param-follow',
'selection-statement',
'selection-follow',
'iteration-statement',
'iteration-follow',
'return-statement',
'return-follow',
# 'eval-statement',
# 'var',
'var-follow',
'expression',
'expression-follow',
'rel-op',
'additive-expr',
'additive-expr-follow',
'add-op',
'term',
'term-follow',
'mul-op',
'factor',
'id-factor-follow',
'args',
'arg-list',
'arg-list-follow'
]
# 文法产生式
productions = [
# 0
Production('program', ['define-list']),
# 1
Production('define-list', ['define', 'define-list']),
Production('define-list', []),
# 2
Production('define', ['type', 'id', 'define-type']),
# 3
Production('define-type', ['var-define-follow']),
Production('define-type', ['fun-define-follow']),
# 4
Production('var-define-follow', ['semicolon']),
Production('var-define-follow', ['left-bracket', 'num', 'right-bracket', 'semicolon']),
# 5
Production('type', ['int']),
Production('type', ['void']),
# 6
Production('fun-define-follow', ['left-parentheses', 'params', 'right-parentheses', 'code-block']),
# 7
Production('params', ['param-list']),
Production('params', []),
# 8
Production('param-list', ['param', 'param-follow']),
# 9
Production('param-follow', ['comma', 'param', 'param-follow']),
Production('param-follow', []),
# 10
Production('param', ['type', 'id', 'array-subscript']),
# 11
Production('array-subscript', ['left-bracket', 'right-bracket']),
Production('array-subscript', []),
# 12
Production('code-block', ['left-brace', 'local-define-list', 'code-list', 'right-brace']),
# 13
Production('local-define-list', ['local-var-define', 'local-define-list']),
Production('local-define-list', []),
# 14
Production('local-var-define', ['type', 'id', 'var-define-follow']),
# 15
Production('code-list', ['code', 'code-list']),
Production('code-list', []),
# 16
Production('code', ['normal-statement']),
Production('code', ['selection-statement']),
Production('code', ['iteration-statement']),
Production('code', ['return-statement']),
# Production('normal-statement', ['eval-statement', 'semicolon']),
# Production('normal-statement', ['semicolon']),
# 17
Production('normal-statement', ['semicolon']),
Production('normal-statement', ['id', 'normal-statement-follow']),
# 18
Production('normal-statement-follow', ['var-follow', 'evaluate', 'expression', 'semicolon']),
Production('normal-statement-follow', ['call-follow', 'semicolon']),
# 19
Production('call-follow', ['left-parentheses', 'call-params', 'right-parentheses']),
# 20
Production('call-params', ['call-param-list']),
Production('call-params', []),
# 21
Production('call-param-list', ['expression', 'call-param-follow']),
# 22
Production('call-param-follow', ['comma', 'expression', 'call-param-follow']),
Production('call-param-follow', []),
# 23
Production('selection-statement',
['if', 'left-parentheses', 'expression', 'right-parentheses', 'left-brace',
'code-list', 'right-brace', 'selection-follow']),
# 24
Production('selection-follow', ['else', 'left-brace', 'code-list', 'right-brace']),
Production('selection-follow', []),
# 25
Production('iteration-statement', ['while', 'left-parentheses', 'expression',
'right-parentheses', 'iteration-follow']),
# 26
Production('iteration-follow', ['left-brace', 'code-list', 'right-brace']),
Production('iteration-follow', ['code']),
# 27
Production('return-statement', ['return', 'return-follow']),
# 28
Production('return-follow', ['semicolon']),
Production('return-follow', ['expression', 'semicolon']),
# Production('eval-statement', ['var', 'evaluate', 'expression']),
# Production('var', ['id', 'var-follow']),
# 29
Production('var-follow', ['left-bracket', 'expression', 'right-bracket']),
Production('var-follow', []),
# 30
Production('expression', ['additive-expr', 'expression-follow']),
# 31
Production('expression-follow', ['rel-op', 'additive-expr']),
Production('expression-follow', []),
# 32
Production('rel-op', ['smaller-equal']),
Production('rel-op', ['smaller']),
Production('rel-op', ['bigger']),
Production('rel-op', ['bigger-equal']),
Production('rel-op', ['equal']),
Production('rel-op', ['not-equal']),
# 33
Production('additive-expr', ['term', 'additive-expr-follow']),
# 34
Production('additive-expr-follow', ['add-op', 'term', 'additive-expr-follow']),
Production('additive-expr-follow', []),
# 35
Production('add-op', ['addition']),
Production('add-op', ['subtraction']),
# 36
Production('term', ['factor', 'term-follow']),
# 37
Production('term-follow', ['mul-op', 'factor', 'term-follow']),
Production('term-follow', []),
# 38
Production('mul-op', ['multiplication']),
Production('mul-op', ['division']),
# 39
Production('factor', ['left-parentheses', 'expression', 'right-parentheses']),
Production('factor', ['id', 'id-factor-follow']),
Production('factor', ['num']),
# 40
Production('id-factor-follow', ['var-follow']),
Production('id-factor-follow', ['left-parentheses', 'args', 'right-parentheses']),
# 41
Production('args', ['arg-list']),
Production('args', []),
# 42
Production('arg-list', ['expression', 'arg-list-follow']),
Production('arg-list-follow', ['comma', 'expression', 'arg-list-follow']),
Production('arg-list-follow', [])
]
# 文法开始符号
grammar_start = Sign('program')
|
def find_accounts(search_text):
# perform search...
if not db_is_available:
return None
# returns a list of account IDs
return db_search(search_text)
accounts = find_accounts('python')
if accounts is None:
print("Error: DB not available")
else:
print("Accounts found: Would list them here...")
def db_search(search_text):
return [1, 11]
db_is_availble = True
|
fruits = ["orange", "banana", "apple", "avocado", "kiwi", "apricot",
"cherry", "grape", "coconut", "lemon", "mango", "peach",
"pear", "strawberry", "pineapple", "apple", "orange", "pear",
"grape", "banana"
]
filters = dict()
for key in fruits:
filters[key] = 1
result = set(filters.keys())
print(result)
|
#module.py
def hello():
print("Hello!")
#if __name__=="__main__":
# print(__name__)
|
class IOEngine(object):
def __init__(self, node):
self.node = node
self.inputs = []
self.outputs = []
def release(self):
self.inputs = None
self.outputs = None
self.node = None
def updateInputs(self, names):
# remove prior outputs
for inputNode in self.inputs:
if not inputNode in names:
if self.node.model.existNode(inputNode):
self.node.model.getNode(inputNode).ioEngine.removeOutput(
self.node.identifier)
newInputs = []
for nodeId in names:
if self.node.model.existNode(nodeId):
newInputs.append(nodeId)
if not nodeId in self.inputs:
self.node.model.getNode(nodeId).ioEngine.addOutput(
self.node.identifier)
self.inputs = newInputs
def removeOutput(self, nodeId):
if nodeId in self.outputs:
self.outputs.remove(nodeId)
def removeInput(self, nodeId):
if nodeId in self.inputs:
self.inputs.remove(nodeId)
def addOutput(self, nodeId):
self.outputs.append(nodeId)
def updateNodeId(self, oldId, newId):
for inputNode in self.inputs:
if self.node.model.existNode(inputNode):
self.node.model.getNode(
inputNode).ioEngine.updateOutputId(oldId, newId)
for outputNode in self.outputs:
if self.node.model.existNode(outputNode):
self.node.model.getNode(
outputNode).ioEngine.updateInputId(oldId, newId)
def updateOnDeleteNode(self):
for inputNode in self.inputs:
if self.node.model.existNode(inputNode):
self.node.model.getNode(inputNode).ioEngine.removeOutput(
self.node.identifier)
for outputNode in self.outputs:
if self.node.model.existNode(outputNode):
self.node.model.getNode(outputNode).ioEngine.removeInput(
self.node.identifier)
def updateOutputId(self, oldId, newId):
if oldId in self.outputs:
self.outputs.remove(oldId)
self.outputs.append(newId)
def updateInputId(self, oldId, newId):
if oldId in self.inputs:
self.inputs.remove(oldId)
self.inputs.append(newId)
self.node.updateDefinitionForChangeId(oldId, newId)
|
class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
class Binary_Tree:
def __init__(self):
self.root = None
def pre_order(self):
""" root-left-right """
try:
self.values=[]
if self.root == None:
return "Tree is Empty"
def tree(node):
self.values+=[node.value]
if node.left:
tree(node.left)
if node.right:
tree(node.right)
return self.values
return tree(self.root)
except:
return "Error"
def in_order(self):
""" left-node-right"""
try:
self.values=[]
if not self.root:
return "Tree is Empty"
def tree(node):
if node.left:
tree(node.left)
self.values+=[node.value]
if node.right:
tree(node.right)
return self.values
return tree(self.root)
except:
return "Error"
def post_order(self):
""" left-right-node"""
try:
self.values=[]
if not self.root:
return "Tree is Empty"
def tree(node):
if node.left:
tree(node.left)
if node.right:
tree(node.right)
self.values+=[node.value]
return self.values
return tree(self.root)
except:
return "Error"
def max(self):
if not self.root:
return "Tree is Empty"
self.max=self.root.value
def tree(node):
if node.value>self.max:
self.max=node.value
if node.left:
tree(node.left)
if node.right:
tree(node.right)
return self.max
return tree(self.root)
class Binary_Search_Tree(Binary_Tree):
def add(self,value):
'''add value to binery tree '''
if self.root == None:
self.root = Node(value)
else:
current=self.root
while current:
if value < current.value :
if current.left == None:
current.left = Node(value)
break
current = current.left
else:
if current.right == None:
current.right = Node(value)
break
current = current.right
def Contains(self,value):
if self.root==None:
return 'Tree is Empty'
else:
current=self.root
while current:
if current.value==value:
return True
elif value < current.value :
if current.left == None:
return False
current = current.left
else:
if current.right == None:
return False
current = current.right
|
#
# Copyright (C) 2018 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
model = Model()
i1 = Input("op1", "TENSOR_FLOAT32", "{1, 3, 3, 2}")
f1 = Input("op2", "TENSOR_FLOAT32", "{1, 2, 2, 4}")
b1 = Input("op3", "TENSOR_FLOAT32", "{4}")
pad0 = Int32Scalar("pad0", 0)
act = Int32Scalar("act", 0)
stride = Int32Scalar("stride", 1)
cm = Int32Scalar("channelMultiplier", 2)
output = Output("op4", "TENSOR_FLOAT32", "{1, 2, 2, 4}")
model = model.Operation("DEPTHWISE_CONV_2D",
i1, f1, b1,
pad0, pad0, pad0, pad0,
stride, stride,
cm, act).To(output)
model = model.RelaxedExecution(True)
# Example 1. Input in operand 0,
input0 = {i1: # input 0
[10, 21, 10, 22, 10, 23,
10, 24, 10, 25, 10, 26,
10, 27, 10, 28, 10, 29],
f1:
[.25, 0, .2, 0,
.25, 0, 0, .3,
.25, 0, 0, 0,
.25, .1, 0, 0],
b1:
[1, 2, 3, 4]}
# (i1 (conv) f1) + b1
# filter usage:
# in_ch1 * f_1 --> output_d1
# in_ch1 * f_2 --> output_d2
# in_ch2 * f_3 --> output_d3
# in_ch3 * f_4 --> output_d4
output0 = {output: # output 0
[11, 3, 7.2, 10.6,
11, 3, 7.4, 10.9,
11, 3, 7.8, 11.5,
11, 3, 8.0, 11.8]}
# Instantiate an example
Example((input0, output0))
|
class Check_Excessive_Current(object):
def __init__(self,chain_name,cf,handlers,irrigation_io,irrigation_hash_control,get_json_object):
self.get_json_object = get_json_object
cf.define_chain(chain_name, False )
#cf.insert.log("check_excessive_current")
cf.insert.assert_function_reset(self.check_excessive_current)
cf.insert.log("excessive_current_found")
cf.insert.send_event("IRI_CLOSE_MASTER_VALVE",False)
cf.insert.send_event( "RELEASE_IRRIGATION_CONTROL")
cf.insert.one_step(irrigation_io.disable_all_sprinklers )
cf.insert.wait_event_count( count = 15 )
cf.insert.reset()
self.handlers = handlers
self.irrigation_hash_control = irrigation_hash_control
def check_excessive_current(self,cf_handle, chainObj, parameters, event):
#print("check excessive current")
return False #TBD
|
# https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L11_Sieve%20of%20Eratosthenes/11.2%20CountSemiprimes.md
def solution(N, P, Q):
"""
返回由数组P、Q的元素组成的区间内,不大于N的半素数的个数, 时间复杂度O(N * log(log(N)) + M)
:param N: 半素数的最大值
:param P: 数组
:param Q: 数组
:return: 每次查询,得到的半素数的个数
"""
# 半素数只有3或4个因子,并且不能是素数的立方,例如(1, 3, 9, 27)(1, 5, 25, 125)这种情况
# 首先计算出不大于N的半素数列表,是半素数的为其值,不是的为0
semi_prime = []
k =0
for i in range(1, N + 1):
factor_count = 0
sign = 0
for j in range(1, int(i ** 0.5) + 1):
if i % j == 0:
factor_count += 1
f = i / j
if f != j:
if f == j ** 2:
sign = 1
semi_prime.append(0)
break
else:
factor_count += 1
if factor_count > 4:
sign = 1
semi_prime.append(0)
break
if sign != 1:
if factor_count >= 3:
semi_prime.append(i)
else:
semi_prime.append(0)
index_dict = {} # 得出当前数值以及前面一共有几个半素数
semi_dict = {} # 如果是半素数,则添加到字典中
count = 0
for index, value in enumerate(semi_prime):
if value != 0:
count += 1
index_dict[value] = count
semi_dict[value] = 0
else:
index_dict[index + 1] = count
# index_dict {1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 3, 10: 4, 11: 4, 12: 4, 13: 4, 14: 5, 15: 6, 16: 6, 17: 6, 18: 6, 19: 6, 20: 6, 21: 7, 22: 8, 23: 8, 24: 8, 25: 9, 26: 10}
#semi_dict {4: 0, 6: 0, 9: 0, 10: 0, 14: 0, 15: 0, 21: 0, 22: 0, 25: 0, 26: 0}
print("index_dict",index_dict)
print("semi_dict",semi_dict)
result_list = [] # 开始计算,在指定区间内有几个半素数
for i, j in zip(P, Q):
if i in semi_dict:
result_list.append(index_dict[j] - index_dict[i] + 1)
else:
result_list.append(index_dict[j] - index_dict[i])
return result_list
if __name__ == '__main__':
solution(26,[1, 4, 16],[26, 10, 20])
|
indexWords = list()
def PreviousWord(_list, _word):
if _list[_list.index(_word)-1] :
return _list[_list.index(_word)-1]
else:
return
phrase = str(input())
phraseList = phrase.split(" ")
length = len(phraseList)
for item in phraseList :
item = item.strip()
if phrase != "" :
for i in range(1, length-1) :
lengthOfWord = len(phraseList[i])
if phraseList[i][0].isupper() :
if PreviousWord(phraseList, phraseList[i])[-1] != "." :
if phraseList[i][-1]=="." or phraseList[i][-1]=="," :
indexWords.append(i + 1)
indexWords.append(phraseList[i][: lengthOfWord-1])
elif phraseList[i][-1]== "]" and phraseList[i][-2]== "'" :
indexWords.append(i + 1)
indexWords.append(phraseList[i][: lengthOfWord-2])
else :
indexWords.append(i + 1)
indexWords.append(phraseList[i])
else:
print("None")
lengthOfIndexWord = len(indexWords)
if lengthOfIndexWord == 0 :
print("None")
else:
for i in range(0, lengthOfIndexWord//2):
print("%i:%s" %(indexWords[2*i],indexWords[(2*i)+1]))
|
city_country = {}
for _ in range(int(input())):
country, *cities = input().split()
for city in cities:
city_country[city] = country
for _ in range(int(input())):
print(city_country[input()])
|
nume1 = int(input("Digite um numero"))
nume2 = int(input("Digite um numero"))
nume3 = int(input("Digite um numero"))
nume4 = int(input("Digite um numero"))
nume5 = int(input("Digite um numero"))
table = [nume1,nume2,nume3,nume4,nume5]
tableM = (float((nume1 + nume2 + nume3 + nume4 + nume5)))
print(float(tableM))
|
class Solution:
def combinationSum(self, candidates, target):
def lookup(candidates, index, target, combine, result):
if target == 0:
result.append(combine)
return
if index >= len(candidates) and target > 0:
return
if target >= candidates[index]:
lookup(candidates, index, target - candidates[index], list(combine) + [candidates[index]], result)
lookup(candidates, index + 1, target, list(combine), result)
sorted(candidates)
result = []
lookup(candidates, 0, target, [], result)
return result
s = Solution()
print(s.combinationSum([2,3,6,7], 7))
print(s.combinationSum([2,3,5], 8))
|
# 英制单位英寸和公制单位厘米互换
value =float(input('请输入长度:'))
unit =input('请输入单位:')
if unit == 'in' or unit == '英寸':
print('%f英寸 = %f厘米' % (value, value * 2.54))
elif unit == '厘米' or unit == 'cm':
print('%f 厘米 = %f英寸' % (value, value / 2.54))
else:
print('请输入有效的单位')
|
# version of the graw package
__version__ = "0.1.0"
|
'''
@author Gabriel Flores
Checks the primality of an integer.
'''
def is_prime(x):
'''
Checks the primality of an integer.
'''
sqrt = int(x ** (1/2))
for i in range(2, sqrt, 1):
if x % i == 0:
return False
return True
def main():
try:
print("\n\n")
a = int(input(" Enter an integer to check if it is prime: "))
if is_prime(a):
print("\n ",a,"is a prime number.\n")
else:
print("\n ",a,"is not a prime number.\n")
except ValueError as e:
print("\n\n Please enter a valid choice.\n")
if __name__ == "__main__":
main()
|
"""
11367. Report Card Time
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 64 ms
해결 날짜: 2020년 9월 18일
"""
def main():
for _ in range(int(input())):
name, score = input().split()
score = int(score)
if score < 60: grade = 'F'
elif score < 67: grade = 'D'
elif score < 70: grade = 'D+'
elif score < 77: grade = 'C'
elif score < 80: grade = 'C+'
elif score < 87: grade = 'B'
elif score < 90: grade = 'B+'
elif score < 97: grade = 'A'
else: grade = 'A+'
print(name + ' ' + grade)
if __name__ == '__main__':
main()
|
"""
Created by akiselev on 2019-06-14
There is a horizontal row of cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if is on top of then
.
When stacking the cubes, you can only pick up either the leftmost or the rightmost cube each time. Print "Yes" if it is possible to stack the cubes. Otherwise, print "No". Do not print the quotation marks.
Input Format
The first line contains a single integer
, the number of test cases.
For each test case, there are lines.
The first line of each test case contains , the number of cubes.
The second line contains
space separated integers, denoting the sideLengths of each cube in that order.
Constraints
Output Format
For each test case, output a single line containing either "Yes" or "No" without the quotes.
Sample Input
2
6
4 3 2 1 3 4
3
1 3 2
Sample Output
Yes
No
"""
for T in range(int(input())):
n = int(input())
cubes_h = list(map(int, input().split()))
i = 0
while i < n - 1 and cubes_h[i] >= cubes_h[i+1]:
i += 1
while i < n - 1 and cubes_h[i] <= cubes_h[i+1]:
i += 1
print("Yes" if i == n - 1 else "No")
|
def fibonacci_iterative(n):
previous = 0
current = 1
for i in range(n - 1):
current_old = current
current = previous + current
previous = current_old
return current
def fibonacci_recursive(n):
if n == 0 or n == 1:
return n
else:
return fibonacci_recursive(n - 2) + fibonacci_recursive(n - 1)
|
__all__ = [
'session',
'event',
'profile',
'consent',
'segment',
'source',
'rule',
'entity'
]
|
def global_alignment(seq1, seq2, score_matrix, penalty):
len1, len2 = len(seq1), len(seq2)
s = [[0] * (len2 + 1) for i in range(len1 + 1)]
backtrack = [[0] * (len2 + 1) for i in range(len1 + 1)]
for i in range(1, len1 + 1):
s[i][0] = - i * penalty
for j in range(1, len2 + 1):
s[0][j] = - j * penalty
for i in range(1, len1 + 1):
for j in range(1, len2 + 1):
score_list = [s[i - 1][j] - penalty, s[i][j - 1] - penalty,
s[i - 1][j - 1] + score_matrix[seq1[i - 1], seq2[j - 1]]]
s[i][j] = max(score_list)
backtrack[i][j] = score_list.index(s[i][j])
indel_insert = lambda seq, i: seq[:i] + '-' + seq[i:]
align1, align2 = seq1, seq2
a, b = len1, len2
max_score = str(s[a][b])
while a * b != 0:
if backtrack[a][b] == 0:
a -= 1
align2 = indel_insert(align2, b)
elif backtrack[a][b] == 1:
b -= 1
align1 = indel_insert(align1, a)
else:
a -= 1
b -= 1
for i in range(a):
align2 = indel_insert(align2, 0)
for j in range(b):
align1 = indel_insert(align1, 0)
return max_score, align1, align2
def mid_column_score(v, w, score_matrix, penalty):
s = [[i * j * penalty for i in range(-1, 1)] for j in range(len(v) + 1)]
s[0][1] = -penalty
backtrack = [0] * (len(v) + 1)
for j in range(1, len(w) // 2 + 1):
for i in range(0, len(v) + 1):
if i == 0:
s[i][1] = -j * penalty
else:
scores = [s[i - 1][0] + score_matrix[v[i - 1], w[j - 1]], s[i][0] - penalty, s[i - 1][1] - penalty]
s[i][1] = max(scores)
backtrack[i] = scores.index(s[i][1])
if j != len(w) // 2:
s = [[row[1]] * 2 for row in s]
return [i[1] for i in s], backtrack
def mid_edge(v, w, score_matrix, penalty):
source = mid_column_score(v, w, score_matrix, penalty)[0]
mid_to_sink, backtrack = list(map(lambda l: l[::-1], mid_column_score(v[::-1], w[::-1] + ['', '$'][
len(w) % 2 == 1 and len(w) > 1], score_matrix, penalty)))
scores = list(map(sum, zip(source, mid_to_sink)))
max_mid = max(range(len(scores)), key = lambda i: scores[i])
if max_mid == len(scores) - 1:
next_node = (max_mid, len(w) // 2 + 1)
else:
next_node = [(max_mid + 1, len(w) // 2 + 1), (max_mid, len(w) // 2 + 1), (max_mid + 1, len(w) // 2), ][
backtrack[max_mid]]
return (max_mid, len(w) // 2), next_node
def linear_space_alignment(top, bottom, left, right, score_matrix):
v = seq1
w = seq2
if left == right:
return [v[top:bottom], '-' * (bottom - top)]
elif top == bottom:
return ['-' * (right - left), w[left:right]]
elif bottom - top == 1 or right - left == 1:
return global_alignment(v[top:bottom], w[left:right], score_matrix, penalty)[1:]
else:
mid_node, next_node = mid_edge(v[top:bottom], w[left:right], score_matrix, penalty)
mid_node = tuple(map(sum, zip(mid_node, [top, left])))
next_node = tuple(map(sum, zip(next_node, [top, left])))
current = [['-', v[mid_node[0] % len(v)]][next_node[0] - mid_node[0]],
['-', w[mid_node[1] % len(w)]][next_node[1] - mid_node[1]]]
a = linear_space_alignment(top, mid_node[0], left, mid_node[1], score_matrix)
b = linear_space_alignment(next_node[0], bottom, next_node[1], right, score_matrix)
return [a[i] + current[i] + b[i] for i in range(2)]
def linear_space_global_alignment(v, w, score_matrix, penalty):
align1, align2 = linear_space_alignment(0, len(v), 0, len(w), score_matrix)
p = []
for i in zip(align1, align2):
if '-' in i:
p.append(-penalty)
else:
p.append(score_matrix[i])
score = sum(p)
return str(score), align1, align2
if __name__ == '__main__':
with open('input.txt') as f:
seq1 = f.readline().strip()
seq2 = f.readline().strip()
with open('BLOSUM62.txt') as f1:
lines = [line.strip().split() for line in f1.readlines()]
matrix = {(i[0], i[1]): int(i[2]) for i in lines}
penalty = 5
alignment = '\n'.join(linear_space_global_alignment(seq1, seq2, matrix, penalty))
print(alignment)
|
def main(file: str) -> None:
depth = 0
distance = 0
aim = 0
with open(f"{file}.in") as f:
for line in f.readlines():
line = line.rstrip().split(" ")
command = line[0]
unit = int(line[1])
if command == "forward":
distance += unit
depth += aim * unit
elif command == "down":
aim += unit
else:
aim -= unit
print(f"{file}: {depth * distance}")
if __name__ == "__main__":
main("test")
main("puzzle")
|
# coding=utf8
class MetaSingleton(type):
def __init__(cls, *args):
type.__init__(cls, *args)
cls.instance = None
def __call__(cls, *args, **kwargs):
if not cls.instance:
cls.instance = type.__call__(cls, *args, **kwargs)
return cls.instance
|
how_many_snakes = 1
snake_string = """
Welcome to Python3!
____
/ . .\\
\\ ---<
\\ /
__________/ /
-=:___________/
<3, Juno
"""
print(snake_string * how_many_snakes)
|
class Person:
olhos = 2
def __init__(self, *children, name=None, year=0):
self.year = year
self.name = name
self.children = list(children)
def cumprimentar(self):
return 'Hello'
@staticmethod
def metodo_estatico():
return 123
@classmethod
def metodo_classe(cls):
return f'{cls} - {cls.olhos}'
if __name__ == '__main__':
p = Person()
eu = Person(name='marcio')
wes = Person(eu, name='Wesley')
print(p.cumprimentar())
print(p.year) # Atributo de instancia
print(p.name) # Atributo de dados
for filhos in wes.children:
print(filhos.year)
p.sobre = 'eu'
print(p.sobre)
del p.sobre
print(p.__dict__)
print(p.olhos)
print(eu.olhos)
print(p.metodo_estatico(), eu.metodo_estatico())
print(p.metodo_classe(), eu.metodo_classe())
|
class Animal:
def __init__(self):
self.name = ""
self.weight = 0
self.sound = ""
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setWeight(self, weight):
self.weight = weight
def getWeight(self):
return self.weight
def setSound(self, sound):
self.sound = sound
def getSound(self):
return self.sound
|
#!/usr/bin/python3
lines = open("inputs/07.in", "r").readlines()
for i,line in enumerate(lines):
lines[i] = line.split("\n")[0]
l = lines.copy();
wires = {}
def func_set(p, i):
if p[0].isdigit():
wires[p[2]] = int(p[0])
lines.pop(i)
elif p[0] in wires.keys():
wires[p[2]] = wires[p[0]]
lines.pop(i)
def func_and(p, i):
if p[0].isdigit() and p[2] in wires.keys():
wires[p[4]] = int(p[0]) & wires[p[2]]
lines.pop(i)
if p[0] in wires.keys() and p[2] in wires.keys():
wires[p[4]] = wires[p[0]] & wires[p[2]]
lines.pop(i)
def func_or(p, i):
if p[0] in wires.keys() and p[2] in wires.keys():
wires[p[4]] = wires[p[0]] | wires[p[2]]
lines.pop(i)
def func_rshift(p, i):
if p[0] in wires.keys():
wires[p[4]] = wires[p[0]] >> int(p[2])
lines.pop(i)
def func_lshift(p, i):
if p[0] in wires.keys():
wires[p[4]] = wires[p[0]] << int(p[2])
lines.pop(i)
def func_not(p, i):
if p[1] in wires.keys():
wires[p[3]] = 65535 - wires[p[1]]
lines.pop(i)
def run():
i = 0
while len(lines) > 0:
parts = lines[i].split(" ")
if "AND" in parts:
func_and(parts, i)
elif "NOT" in parts:
func_not(parts, i)
elif "RSHIFT" in parts:
func_rshift(parts, i)
elif "LSHIFT" in parts:
func_lshift(parts, i)
elif "OR" in parts:
func_or(parts, i)
else:
func_set(parts, i)
i += 1
if i >= len(lines):
i = 0
run()
print("Part 1: " + str(wires["a"]))
lines = l
wires = {"b": wires["a"]}
run()
print("Part 2: " + str(wires["a"]))
|
#Variables
#Working with build 2234
saberPort = "/dev/ttyUSB0"
#Initializing Motorcontroller
saber = Runtime.start("saber", "Sabertooth")
saber.connect(saberPort)
sleep(1)
#Initializing Joystick
joystick = Runtime.start("joystick","Joystick")
print(joystick.getControllers())
python.subscribe("joystick","publishJoystickInput")
joystick.setController(0)
for x in range(0,100):
print("power", x)
saber.driveForwardMotor1(x)
sleep(0.5)
for x in range(100,-1,-1):
print("power", x)
saber.driveForwardMotor1(x)
sleep(0.5)
|
# Author: Guilherme Aldeia
# Contact: [email protected]
# Version: 1.0.0
# Last modified: 08-20-2021 by Guilherme Aldeia
"""
Simple exception that is raised by explainers when they don't support local
or global explanations, or when they are not model agnostic. This should be
catched and handled in the experiments.
"""
class NotApplicableException(Exception):
def __init__(self, message=""):
self.message = message
|
# ASSIGNMENT 3
"""
During a programming contest, each contestant had to solve 3 problems (named P1, P2 and P3).
Afterwards, an evaluation committee graded the solutions to each of the problems using integers between 0 and 10.
The committee needs a program that will allow managing the list of scores and establishing the winners.
Write a program that implements the functionalities exemplified below:
(A) Add the result of a new participant (add, insert)
(B) Modify scores (remove, remove between two postion, replace the score obtained by a certain participant at a
certain problem with other score obtained by other participant)
(C) Display participants whose score has different properties. """
def get(list, position):
""" The function will extract a certain element from a list."""
return list[int(position)]
def set(list, element, position):
""" The functin will set a certain element from a list.
:param list: [ ['2', '4', '8'], ['3', '5', '6'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'] ]
:param element: ['5', '8', '9']
:param position: 1
:return: [ ['2', '4', '8'], ['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10']
"""
list.insert(int(position), element)
list.remove(get(list, int(position) + 1))
def make_a_list(sentence):
""" The function will make a list containing the given scores P1, P2 and P3 that are found in the command."""
list_one_score = []
for i in range(1, 4):
list_one_score.append(sentence[i])
return list_one_score
def add_scores(list, sentence):
""" The function will add to the principal list (with all the scores of all the participants) a list with the
scores of just one participant.
"""
list.append(make_a_list(sentence))
def insert_scores(list, sentence, position):
""" The function will insert in a given position to the principal list (with all the scores of all the participants)
a list with the scores of just one participant
"""
list.insert(int(position), make_a_list(sentence))
def remove_one_part(list, position):
""" The function will set the scores of the participant at a given position to 0.
So that, the participant <position> score P1=P2=P3= 0. """
nul_element = ['0', '0', '0']
set(list, nul_element, position)
def remove_more_part(list, first_position, last_position):
""" The function will set the scores of all the participants between the first position and last position to 0.
For all the participants between <first_position> and <last_position>, P1=P1=P3= 0 """
nul_element = ['0', '0', '0']
for i in range(int(first_position), int(last_position) + 1):
set(list, nul_element, i)
def remove(list, cmd):
if len(cmd) == 2: # The command is remove <position>
remove_one_part(list, get(cmd, 1))
elif len(cmd) == 4: # The command is remove <first pos> to <last pos>
remove_more_part(list, get(cmd, 1), get(cmd, 3))
def replace(list, problem, new_score):
""" The function will replace a score obtained by a participant at a specific problem with a new score.
List represents the list with the scores of a participant, where <problem> ( P1/P2/P3 ) will recive a new score
"""
set(list, new_score, int(problem[1]) - 1)
def calc_average(list):
""" The function will calculate the average of all the integers from a list ( it will calculate the sum of al the
integers, and then it will divide the sum by the value of the len of tne list)
:param list: [ '2', '4', '3' ]
:return: 3
"""
result = 0
for i in range(0, len(list)):
result = result + int(get(list, i))
return result / len(list)
def average_score_lesser(list, number):
""" The function will display all the participants with an average score lesser than the given number.
:param list: [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']]
:param number: 7
:return:['10', '4', '6'], ['9', '3', '2']
"""
l = [] # l is the required list
for i in range(0, len(list)):
if calc_average(get(list, i)) < number:
l.append(get(list, i))
return l
def average_score_equal(list, number):
""" The function will display all the participants with an average score equal with the given number.
:param list: [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']]
:param number: 8
:return:['7', '8', '9']
"""
l = [] # l is the required list
for i in range(0, len(list)):
if calc_average(get(list, i)) == number:
l.append(get(list, i))
return l
def average_score_greater(list, number):
""" The function will return a list with all the participants with an average score greater than the given number.
:param list: [['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']]
:param number: 7
:return: [['10', '10', '10'], ['7', '8', '9']]
"""
l = [] # l is the required list
for i in range(0, len(list)):
if calc_average(get(list, i)) > number:
l.append(get(list, i))
return l
def list_sorted(list):
""" The function will return a list with participants sorted in decreasing order of average score
:param list: [['5', '8', '9'], ['10', '4', '6'], ['10', '10', '10'], ['7', '8', '9'], ['10', '2', '9']]
:return: [['10', '10', '10'], , ['7', '8', '9'], ['5', '8', '9'], ['10', '2', '9'], ['10', '4', '6']]
"""
l = []
for i in range(0, len(list)):
get(list, i).insert(0, calc_average(get(list, i)))
l.append(get(list, i))
l.sort(reverse=True)
for i in range(0, len(l)):
get(l, i)
get(l, i).remove(get(get(l, i), 0))
return l
def list(list, cmd):
if len(cmd) == 1:
l = list
elif get(cmd, 1) == 'sorted':
l = list_sorted(list)
elif get(cmd, 1) == '<':
l = average_score_lesser(list, int(get(cmd, 2)))
elif get(cmd, 1) == '=':
l = average_score_equal(list, int(get(cmd, 2)))
elif get(cmd, 1) == '>':
l = average_score_greater(list, int(get(cmd, 2)))
print(l)
def print_menu():
commands = ['add <P1 score> <P2 score> <P3 score>', 'insert <P1 score> <P2 score> <P3 score> at <position>',
'remove <position>', 'remove <start position> to <end position>',
'replace <position> <P1 | P2 | P3> with <new score>', 'list', 'list sorted', 'list [< | = | >] <score>']
print("The possible comands are:")
print(*commands, sep="\n")
def run_menu():
list_participants_scores = [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9'],
['8', '9', '10'], ['10', '2', '9'], ['2', '4', '6'], ['8', '2', '1'], ['0', '8', '4']]
commands = ['add <P1 score> <P2 score> <P3 score>', 'insert <P1 score> <P2 score> <P3 score> at <position>',
'remove <position>', 'remove <start position> to <end position>',
'replace <position> <P1 | P2 | P3> with <new score>', 'list', 'list sorted', 'list [< | = | >] <score>']
while True:
comand = input()
comand_splited = comand.split()
first_word = get(comand_splited, 0)
if first_word == 'add': # The command is add P1, P2, P3
add_scores(list_participants_scores, comand_splited)
elif first_word == 'insert': # The command is insert [P1, P2, P3] at position
insert_scores(list_participants_scores, comand_splited, comand_splited[5])
elif first_word == 'remove':
remove(list_participants_scores, comand_splited)
elif first_word == 'replace': # The command is replace <old score> P1/P2/P3 with <new score>
replace(get(list_participants_scores, int(get(comand_splited, 1))), get(comand_splited, 2),
(get(comand_splited, 4)))
elif first_word == 'list':
(list(list_participants_scores, comand_splited))
else:
print("Wrong command")
break
if __name__ == '__main__':
print_menu()
run_menu()
|
#===============================================================================
# Copyright 2020-2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#===============================================================================
load("@onedal//dev/bazel:repos.bzl", "repos")
micromkl_repo = repos.prebuilt_libs_repo_rule(
includes = [
"include",
"%{os}/include",
],
libs = [
"%{os}/lib/intel64/libdaal_mkl_thread.a",
"%{os}/lib/intel64/libdaal_mkl_sequential.a",
"%{os}/lib/intel64/libdaal_vmlipp_core.a",
],
build_template = "@onedal//dev/bazel/deps:micromkl.tpl.BUILD",
)
micromkl_dpc_repo = repos.prebuilt_libs_repo_rule(
includes = [
"include",
],
libs = [
"lib/intel64/libdaal_sycl.a",
],
build_template = "@onedal//dev/bazel/deps:micromkldpc.tpl.BUILD",
)
|
guests=int(input())
reservations=set([])
while guests!=0:
reservationCode=input()
reservations.add(reservationCode)
guests-=1
while True:
r=input()
if r!="END":
reservations.discard(r)
else:
print(len(reservations))
VIPS=[]; Regulars=[]
for e in reservations:
if e[0].isnumeric():
VIPS.append(e)
else:
Regulars.append(e)
VIPS.sort(); Regulars.sort()
for k in VIPS:
print(k)
for k in Regulars:
print(k)
break
|
class TestClass:
def __init__(self, list, name):
self.list = list
self.name = name
def func1():
print("func1 print something")
def func2():
print("func2 print something")
integer = 8
return integer
def func3():
print("func3 print something")
s = "func3"
return s
def func4():
print("func4 print something")
listIntegers = [1,2,3,4,5]
return listIntegers
def func5():
print("func5 print something")
listStrings = ["a","b","c","d","e"]
return listStrings
print("Hello World")
# test = TestClass()
|
# // ###########################################################################
# // Queries
# // ###########################################################################
# -> get a single cell of a df (use `iloc` with `row` + `col` as arguments)
df.iloc[0]['staticContextId']
# -> get one column as a list
allFunctionNames = staticContexts[['displayName']].to_numpy().flatten().tolist()
# -> get all rows that match a condition
callLinked = staticTraces[~staticTraces['callId'].isin([0])]
# -> exclude columns
df.drop(['A', 'B'], axis=1)
# -> complex queries
staticTraces.query(f'callId == {callId} or resultCallId == {callId}')
# -> join queries (several examples)
# https://stackoverflow.com/a/40869861
df.set_index('key').join(other.set_index('key'))
B.query('client_id not in @A.client_id')
B[~B.client_id.isin(A.client_id)]
# merging dfs
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html
pd.merge(df1, df2, on=['A', 'B'])
df1.merge(df2, left_on='lkey', right_on='rkey')
# // ###########################################################################
# // Display
# // ###########################################################################
# -> display a groupby object (https://stackoverflow.com/questions/22691010/how-to-print-a-groupby-object)
groups = df.groupby('A')
for key, item in groups:
group = groups.get_group(key)
display(group)
# .to_numpy().flatten().tolist()
|
"""Module to help guess whether a file is binary or text.
Requirements:
Python 2.7+
Recommended:
Python 3
"""
def is_binary_file(fname):
"""Attempt to guess if 'fname' is a binary file heuristically.
This algorithm has many flaws. Use with caution.
It assumes that if a part of the file has NUL bytes
or has more control characters than text characters,
it is a binary file.
Additionally, an ASCII compatible character set is assumed.
Returns True if 'fname' appears to be a binary file.
"""
with open(fname, 'rb') as fh:
chunk = fh.read(1024)
if not chunk: # Empty file
return False
if b'\x00' in chunk: # Has NUL bytes
return True
ncontrol = control_char_count(chunk)
ntext = len(chunk) - ncontrol
return ncontrol > ntext
def is_control_char(c):
"""Return True if 'c' is a control character.
c is considered a control character if
it is outside of the extended ASCII set or
has a code below 32 with some exclusions.
An ASCII compatible character set is assumed.
"""
charcode = 0
# The following assignment
# should make this module compatible with
# at least Python 2.7 (tested on 2.7.9).
try:
charcode = ord(c)
except TypeError:
charcode = c
excludes = ("\t", "\r", "\n")
if charcode in [ord(char) for char in excludes]:
return False
return (charcode < 32 or
charcode > 255)
def control_char_count(data):
"""Return the count of control characters in 'data'."""
n = 0
for c in data:
if is_control_char(c):
n += 1
return n
|
def climbingLeaderboard(ranked, player):
ranked = sorted(list(set(ranked)), reverse=True)
ranks = []
# print(ranked)
for i in range(len(player)):
bi = 0
bs = len(ranked) - 1
index = 0
while (bi <= bs):
mid = (bi+bs) // 2
if (ranked[mid] > player[i]):
index = mid
bi = mid + 1
else:
bs = mid - 1
if (ranked[index] > player[i]):
index += 1
index += 1
ranks.append(index)
return ranks
|
class Auth():
def __init__(self, client):
self.client = client
def get_profiles(self):
return self.client.get('/auth/api/profiles/', {'page_size': 10000})['results']
def get_groups(self):
return self.client.get('/auth/api/groups/')
def get_group_map(self):
return {group['id']: group['name'] for group in self.get_groups()}
def activate_profile(self, pk):
return self.client.put('/auth/api/profiles/%d/activate/' % pk, {})
def update_profile_attributes(self, pk, attributes):
return self.client.patch('/auth/api/profiles/%d/' % pk, {'attributes': attributes})
|
input = """
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in
"""
def validate(passport):
passport_fields = { "byr": False, "iyr": False, "eyr": False, "hgt": False, "hcl": False, "ecl": False, "pid": False }
for line in passport.split("\n"):
values = line.split(" ")
for value in values:
field = value.split(":")[0]
if field == "cid":
continue
passport_fields[field] = True
if False in passport_fields.values():
return False
return True
count = 0
for i in input.strip().split("\n\n"):
if validate(i):
count += 1
print(count)
|
class Solution:
def kthFactor(self, n: int, k: int) -> int:
s1 = set()
s2 = set()
for i in range(1,int(n**0.5)+1):
if n%i ==0:
s1.add(i)
s2.add(int(n/i))
l = list(s1|s2)
l.sort()
if k > len(l):
return -1
return l[k-1]
|
'''
https://resources.urionlinejudge.com.br/gallery/images/problems/UOJ_1000.png
Bem-vindo ao URI Online Judge!
O seu primeiro programa em qualquer linguagem de programação normalmente é o "Hello World!". Neste primeiro problema tudo o que você precisa fazer é imprimir esta mensagem na tela.
Entrada
Este problema não possui nenhuma entrada.
Saída
Você deve imprimir a mensagem "Hello World!" conforme o exemplo abaixo.
'''
print('Hello World!')
|
class Node(object): # Similar to Linked List initial set-up
def __init__(self, value): # Constructor
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preorder_print(tree.root, "") # init
elif traversal_type == "inorder":
return self.in_order_print(tree.root, "") # init
elif traversal_type == "postorder":
return self.post_order_print(tree.root, "") # init
else:
print("Traversal type " + str(traversal_type) + "not valid")
return False
def preorder_print(self, start, traversal):
# Root --> Left --> Right
if start:
traversal += (str(start.value) + "--")
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
def in_order_print(self, start, traversal):
# Very Left --> Root --> Very Right
if start:
traversal = self.in_order_print(start.left, traversal)
traversal += (str(start.value) + '--')
traversal = self.in_order_print(start.right, traversal)
return traversal
def post_order_print(self, start, traversal):
# Very Left --> Very Right --> Root
if start:
traversal = self.post_order_print(start.left, traversal)
traversal = self.post_order_print(start.right, traversal)
traversal += (str(start.value) + '--')
return traversal
"""Try doing Post-Order tomorrow"""
# Visualization of Current Tree
# Pre-Order Output: 1--2--4--9--10--11--5--3--6--7--8--
# In-Order Output: 11--10--9--4--2--5--1--6--3--7--8--
# Pre-Order Output: 11--10--9--4--5--2--6--8--7--3--1--
# 1
# / \
# 2 3
# / | / |
# 4 5 6 7
# / \
# 9 8
# /
# 10
# /
# 11
# Tree Set-Up
# Another implementation
# class BinaryTree(object):
# def __init__(self, root):
# self.root = Node(root)
# def search(self, find_val):
# return self.preorder_search(tree.root, find_val)
# def print_tree(self):
# return self.preorder_print(tree.root, "")[:-1]
# def preorder_search(self, start, find_val):
# if start:
# if start.value == find_val:
# return True
# else:
# return self.preorder_search(start.left, find_val) or self.preorder_search(start.right, find_val)
# return False
# def preorder_print(self, start, traversal):
# if start:
# traversal += (str(start.value) + "-")
# traversal = self.preorder_print(start.left, traversal)
# traversal = self.preorder_print(start.right, traversal)
# return traversal
tree = BinaryTree(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
tree.root.right.right.right = Node(8)
tree.root.left.left.left = Node(9)
tree.root.left.left.left.left = Node(10)
tree.root.left.left.left.left.left = Node(11)
# print(tree.print_tree("preorder"))
# print(tree.print_tree("inorder"))
print(tree.print_tree("postorder"))
|
# _*_ coding: utf-8 _*_
"""
util_config.py by xianhu
"""
__all__ = [
"CONFIG_FETCH_MESSAGE",
"CONFIG_PARSE_MESSAGE",
"CONFIG_MESSAGE_PATTERN",
"CONFIG_URL_LEGAL_PATTERN",
"CONFIG_URL_ILLEGAL_PATTERN",
]
# define the structure of message, used in Fetcher and Parser
CONFIG_FETCH_MESSAGE = "priority=%s, keys=%s, deep=%s, repeat=%s, url=%s"
CONFIG_PARSE_MESSAGE = "priority=%s, keys=%s, deep=%s, url=%s"
CONFIG_MESSAGE_PATTERN = r"priority=(?P<priority>\d+),\s*keys=(?P<keys>.+?),\s*deep=(?P<deep>\d+),\s*(repeat=(?P<repeat>\d+),\s*)?url=(?P<url>.+)$"
# define url_legal_pattern and url_illegal_pattern
CONFIG_URL_LEGAL_PATTERN = r"^https?:[^\s]+?\.[^\s]+?"
CONFIG_URL_ILLEGAL_PATTERN = r"\.(cab|iso|zip|rar|tar|gz|bz2|7z|tgz|apk|exe|app|pkg|bmg|rpm|deb|dmg|jar|jad|bin|msi|" \
"pdf|doc|docx|xls|xlsx|ppt|pptx|txt|md|odf|odt|rtf|py|java|c|cc|js|css|log|csv|tsv|" \
"jpg|jpeg|png|gif|bmp|xpm|xbm|ico|drm|dxf|eps|psd|pcd|pcx|tif|tiff|" \
"mp3|mp4|swf|mkv|avi|flv|mov|wmv|wma|3gp|mpg|mpeg|mp4a|wav|ogg|rmvb)$"
|
__title__ = 'The Onion Box'
__description__ = 'Dashboard to monitor Tor node operations.'
__version__ = '20.2'
__stamp__ = '20200119|095654'
|
# This is the word list from where the answers for the hangman game will come from.
word_list = [
2015,
"Fred Swaniker",
"Rwanda and Mauritius",
2,
"Dr, Gaidi Faraj",
"Sila Ogidi",
"Madagascar",
94,
8,
"Mauritius"
]
# Here we are defining the variables 'Right'(for when they get the question correct) and \n
# 'tries'(for when they get a question wrong).
Right = 0
tries = 0
# This function below after called, will greet the user when they input their name.
def greet(name):
print("Hello " + name + " welcome to hangman and good luck!")
user_name = input("What is your name?")
greet(user_name)
# This functions below when called, will check when guess is returned whether the user's guess is in the word_list\n
# or not and will print out the appropriate responses while consecutively adding to the 'Right' or 'tries' variable.
def alu(guess):
if guess in word_list:
print("congrats!")
def check(guess):
if guess not in word_list:
print("Wrong")
return guess
guess1 = int(input("When was ALU founded?"))
if alu(guess1):
Right += 1
else:
check(guess1)
tries += 1
guess2 = input("Who is the CEO of ALU")
if alu(guess2):
Right += 1
else:
check(guess2)
tries += 1
guess3 = input("Where are ALU campuses?")
if alu(guess3):
Right += 1
else:
check(guess3)
tries += 1
guess4 = int(input("How many campuses does ALU have?"))
if alu(guess4):
Right += 1
else:
check(guess4)
tries += 1
guess5 = input("What is the name of ALU Rwanda's Dean?")
if alu(guess5):
Right += 1
else:
check(guess5)
tries += 1
guess6 = input("Who is in charge of Student Life?")
if alu(guess6):
Right += 1
else:
check(guess6)
tries += 1
if tries == 6:
exit("You lost")
guess7 = input("What is the name of our Lab?")
if alu(guess7):
Right += 1
else:
check(guess7)
tries += 1
if tries == 6:
exit("You lost")
guess8 = int(input("How many students do we have in Year 2 CS?"))
if alu(guess8):
Right += 1
else:
check(guess8)
tries += 1
if tries == 6:
exit("You lost")
guess9 = int(input("How many degrees does ALU offer?"))
if alu(guess9):
Right += 1
else:
check(guess9)
tries += 1
if tries == 6:
exit("You lost")
guess10 = input("Where are the headquarters of ALU?")
if alu(guess10):
Right += 1
else:
check(guess10)
tries += 1
if tries == 6:
exit("You lost")
|
OS_MA_NFVO_IP = '192.168.1.197'
OS_USER_DOMAIN_NAME = 'Default'
OS_USERNAME = 'admin'
OS_PASSWORD = '0000'
OS_PROJECT_DOMAIN_NAME = 'Default'
OS_PROJECT_NAME = 'admin'
|
# Copyright 2016 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
_pub_uri = "https://storage.googleapis.com/pub.dartlang.org/packages"
"""A set of BUILD rules that facilitate using or building on "pub"."""
def _pub_repository_impl(repository_ctx):
package = repository_ctx.attr.package
version = repository_ctx.attr.version
repository_ctx.download_and_extract(
"%s/%s-%s.tar.gz" % (_pub_uri, package, version),
repository_ctx.attr.output,
)
pub_deps = repository_ctx.attr.pub_deps
bazel_deps = ["\"@vendor_%s//:%s\"" % (dep, dep) for dep in pub_deps]
deps = ",\n".join(bazel_deps)
repository_ctx.file(
"%s/BUILD" % (repository_ctx.attr.output),
"""
load("@io_bazel_rules_dart//dart/build_rules:core.bzl", "dart_library")
package(default_visibility = ["//visibility:public"])
filegroup(name = "LICENSE_FILES", srcs=["LICENSE"])
dart_library(
name = "%s",
srcs = glob(["lib/**"]),
license_files = ["LICENSE"],
pub_pkg_name = "%s",
deps = [
%s
],
)
""" % (package, package, deps),
)
pub_repository = repository_rule(
attrs = {
"output": attr.string(),
"package": attr.string(mandatory = True),
"version": attr.string(mandatory = True),
"pub_deps": attr.string_list(default = []),
},
implementation = _pub_repository_impl,
)
|
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
if len(nums) < 1:
raise Exception("Invalid Array")
n = len(nums)
res = []
s = set()
for x in nums:
s.add(x)
for i in range(1, n + 1):
if i not in s:
res.append(i)
return res
|
'''
03 - Multiple arguments
In the previous exercise, the square brackets around imag in the documentation showed us that the
imag argument is optional. But Python also uses a different way to tell users about arguments being
optional.
Have a look at the documentation of sorted() by typing help(sorted) in the IPython Shell.
You'll see that sorted() takes three arguments: iterable, key and reverse.
key=None means that if you don't specify the key argument, it will be None. reverse=False means
that if you don't specify the reverse argument, it will be False.
In this exercise, you'll only have to specify iterable and reverse, not key. The first input you
pass to sorted() will be matched to the iterable argument, but what about the second input? To tell
Python you want to specify reverse without changing anything about key, you can use =:
sorted(___, reverse = ___)
Two lists have been created for you on the right. Can you paste them together and sort them in
descending order?
Note: For now, we can understand an iterable as being any collection of objects, e.g. a List.
Instructions:
- Use + to merge the contents of first and second into a new list: full.
- Call sorted() on full and specify the reverse argument to be True. Save the sorted list as
full_sorted.
- Finish off by printing out full_sorted.
'''
# Create lists first and second
first = [11.25, 18.0, 20.0]
second = [10.75, 9.50]
# Paste together first and second: full
full = first + second
# Sort full in descending order: full_sorted
full_sorted = sorted(full, reverse=True)
# Print out full_sorted
print(full_sorted)
|
"""
Entradas: 3 Valores flotantes que son el valor de diferentes monedas
Chelines autriacos --> float --> x
Dramas griegos --> float --> z
Pesetas --> float --> w
Salidas 4 valores flotantes que es la conversión de las anteriores monedas
Pesetas --> float --> x
Francos franceses --> float --> z
Dolares --> float --> a
Liras italianas --> float --> b
"""
# Entradas
x1 = float(input("Dime los chelines autríacos\n"))
z1 = float(input("Dime los dracmas griegos\n"))
w = float(input("Dime las pesetas\n"))
# Caja negra
x = (x1 * 956871)/100
z = z1/22.64572381
a = w/122499
b = (w*100)/9289
# Salidas
print(f"\n{x1} Chelines austríacos en pesetas son {x}\n{z1} Dracmas griegos en Francos franceses son {z}\n{w} Pesetas en Dolares son {a}\n{w} Pesetas en Liras italianas son {b}\n")
|
parameters = {}
genome = {}
genome_stats = {}
genome_test_stats = []
brain = {}
cortical_list = []
cortical_map = {}
intercortical_mapping = []
block_dic = {}
upstream_neurons = {}
memory_list = {}
activity_stats = {}
temp_neuron_list = []
original_genome_id = []
fire_list = []
termination_flag = False
variation_counter_actual = 0
exposure_counter_actual = 0
mnist_training = {}
mnist_testing = {}
top_10_utf_memory_neurons = {}
top_10_utf_neurons = {}
v1_members = []
prunning_candidates = set()
genome_id = ""
event_id = '_'
blueprint = ""
comprehension_queue = ''
working_directory = ''
connectome_path = ''
paths = {}
watchdog_queue = ''
exit_condition = False
fcl_queue = ''
proximity_queue = ''
last_ipu_activity = ''
last_alertness_trigger = ''
influxdb = ''
mongodb = ''
running_in_container = False
hardware = ''
gazebo = False
stimulation_data = {}
hw_controller_path = ''
hw_controller = None
opu_pub = None
router_address = None
burst_timer = 1
# rules = ""
brain_is_running = False
# live_mode_status can have modes of idle, learning, testing, tbd
live_mode_status = 'idle'
fcl_history = {}
brain_run_id = ""
burst_detection_list = {}
burst_count = 0
fire_candidate_list = {}
previous_fcl = {}
future_fcl = {}
labeled_image = []
training_neuron_list_utf = {}
training_neuron_list_img = {}
empty_fcl_counter = 0
neuron_mp_list = []
pain_flag = False
cumulative_neighbor_count = 0
time_neuron_update = ''
time_apply_plasticity_ext = ''
plasticity_time_total = None
plasticity_time_total_p1 = None
plasticity_dict = {}
tester_test_stats = {}
# Flags
flag_ready_to_inject_image = False
|
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton' , 'Andrew Ng' , 'Sebastian Raschka' , 'Yoshua Bengio']
class_2 = ['Hilary Mason' , 'Carla Gentry' , 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
del new_class[5]
print(new_class)
# Code ends here
# --------------
# Code starts here
courses = {'Math': 65 , 'English': 70 , 'History': 80 , 'French': 70 , 'Science': 60}
total = sum(courses.values())
print(total)
percentage = total/500*100
print(percentage)
# Code ends here
# --------------
# Code starts here
mathematics = { 'Geoffrey Hinton' : 78, 'Andrew Ng' : 95, 'Sebastian Raschka' : 65 ,
'Yoshua Benjio' : 50 , 'Hilary Mason' : 70 , 'Corinna Cortes' : 66 , 'Peter Warden' : 75}
max_marks_scored = max(mathematics, key=mathematics.get)
print(max_marks_scored)
topper = max_marks_scored
print(topper)
# Code ends here
# --------------
# Given string
topper = ' andrew ng'
# Code starts here
first_name = topper.split()[0]
print(first_name)
last_name = topper.split()[1]
print(last_name)
full_name = last_name +' '+ first_name
print(full_name)
certificate_name = full_name.upper()
print(certificate_name)
# Code ends here
|
n = int(input().strip())
items = [
int(A_temp)
for A_temp
in input().strip().split(' ')
]
items_map = {}
result = None
for i, item in enumerate(items):
if item not in items_map:
items_map[item] = [i]
else:
items_map[item].append(i)
for _, item_indexes in items_map.items():
items_indexes_length = len(item_indexes)
if items_indexes_length > 1:
for i in range(items_indexes_length):
for j in range(i + 1, items_indexes_length):
diff = item_indexes[j] - item_indexes[i]
if result is None:
result = diff
elif diff < result:
result = diff
print(result if result else -1)
|
"""A Queryset slicer for Django."""
def slice_queryset(queryset, chunk_size):
"""Slice a queryset into chunks."""
start_pk = 0
queryset = queryset.order_by('pk')
while True:
# No entry left
if not queryset.filter(pk__gt=start_pk).exists():
break
try:
# Fetch chunk_size entries if possible
end_pk = queryset.filter(pk__gt=start_pk).values_list(
'pk', flat=True)[chunk_size - 1]
# Fetch rest entries if less than chunk_size left
except IndexError:
end_pk = queryset.values_list('pk', flat=True).last()
yield queryset.filter(pk__gt=start_pk).filter(pk__lte=end_pk)
start_pk = end_pk
|
def compareMetaboliteDicts(d1, d2):
sorted_d1_keys = sorted(d1.keys())
sorted_d2_keys = sorted(d2.keys())
for i in range(len(sorted_d1_keys)):
if not compareMetabolites(sorted_d1_keys[i], sorted_d2_keys[i], naive=True):
return False
elif not d1[sorted_d1_keys[i]] == d2[sorted_d2_keys[i]]:
return False
else:
return True
def compareMetabolites(met1, met2, naive=False):
if isinstance(met1, set):
return compareReactions(list(met1), list(met2), naive)
if isinstance(met1, list):
if not isinstance(met2, list):
return False
elif len(met1) != len(met2):
return False
else:
for i in range(len(met1)):
if not compareMetabolites(met1[i], met2[i], naive):
return False
else:
return True
else:
if not True:
#can never be entered
pass
elif not met1._bound == met2._bound:
return False
elif not met1._constraint_sense == met2._constraint_sense:
return False
#elif not met1.annotation == met2.annotation:
# return False
elif not met1.charge == met2.charge:
return False
elif not met1.compartment == met2.compartment:
return False
elif not met1.name == met2.name:
return False
elif not met1.compartment == met2.compartment:
return False
#elif not met1.notes == met2.notes:
# return False
elif not naive:
if not compareReactions(met1._reaction, met2._reaction, naive=True):
return False
elif not compareModels(met1._model, met2._model, naive=True):
return False
else:
return True
else:
return True
def compareReactions(r1, r2, naive=False):
if isinstance(r1, set):
return compareReactions(list(r1), list(r2), naive)
if isinstance(r1, list):
if not isinstance(r2, list):
return False
elif len(r1) != len(r2):
return False
else:
for i in range(len(r1)):
if not compareReactions(r1[i], r2[i],naive):
return False
else:
return True
else:
if not True:
#can never be entered
pass
#elif not r1._compartments == r2._compartments:
# return False
#elif not r1._forward_variable == r2._forward_variable:
# return False
elif not r1._gene_reaction_rule == r2._gene_reaction_rule:
return False
elif not r1._id == r2._id:
return False
elif not r1._lower_bound == r2._lower_bound:
return False
#elif not r1._model == r2._model:
# return False
#elif not r1._reverse_variable == r2._reverse_variable:
# return False
elif not r1._upper_bound == r2._upper_bound:
return False
#elif not r1.annotation == r2.annotation:
# return False
elif not r1.name== r2.name:
return False
#elif not r1.notes == r2.notes:
# return False
elif not r1.subsystem == r2.subsystem:
return False
elif not r1.variable_kind == r2.variable_kind:
return False
elif not naive:
if not compareMetaboliteDicts(r1._metabolites, r2._metabolites):
return False
elif not compareGenes(r1._genes,r2._genes, naive=True):
return False
else:
return True
else:
return True
def compareGenes(g1, g2, naive=False):
if isinstance(g1, set):
return compareGenes(list(g1), list(g2), naive)
if isinstance(g1, list):
if not isinstance(g2, list):
return False
elif len(g1) != len(g2):
return False
else:
for i in range(len(g1)):
if not compareGenes(g1[i], g2[i], naive):
return False
else:
return True
else:
if not True:
#can never be entered
pass
elif not g1._functional == g2._functional:
return False
elif not g1._id == g2._id:
return False
#elif not g1._model == g2._model:
# return False
elif not g1.annotation == g2.annotation:
return False
elif not g1.name == g2.name:
return False
#elif not g1.notes == g2.notes:
# return False
elif not naive:
if not compareReactions(g1._reaction,g2._reaction, naive=True):
return False
else:
return True
else:
return True
def compareModels(m1, m2, naive=False):
if not True:
#can never be entered
pass
#elif not m1._compartments == m2._compartments:
# return False
#elif not m1._contexts == m2._contexts:
# return False
#elif not m1._solver == m2._solver:
# return False
elif not m1._id == m2._id:
return False
#elif not m1._trimmed == m2.trimmed:
# return False
#elif not m1._trimmed_genes == m2._trimmed_genes:
# return False
#elif not m1._trimmed_reactions == m2._trimmed_reactions:
# return False
#elif not m1.annotation == m2.annotation:
# return False
elif not m1.bounds == m2.bounds:
return False
elif not m1.name == m2.name:
return False
#elif not m1.notes == m2.notes:
# return False
#elif not m1.quadratic_component == m2.quadratic_component:
# return False
elif not naive:
if not compareGenes(m1.genes, m2.genes):
return False
elif not compareMetabolites(m1.metabolites, m2.metabolites):
return False
elif not compareReactions(m1.reactions,m2.reactions):
return False
else:
return True
else:
return True
|
class Session(list):
"""Abstract Session class"""
def to_strings(self, user_id, session_id):
"""represent session as list of strings (one per event)"""
user_id, session_id = str(user_id), str(session_id)
session_type = self.get_type()
strings = []
for event, product in self:
columns = [user_id, session_type, session_id, event, str(product)]
strings.append(','.join(columns))
return strings
def get_type(self):
raise NotImplemented
class OrganicSessions(Session):
def __init__(self):
super(OrganicSessions, self).__init__()
def next(self, context, product):
self.append(
{
't': context.time(),
'u': context.user(),
'z': 'pageview',
'v': product
}
)
def get_type(self):
return 'organic'
def get_views(self):
return [p for _, _, e, p in self if e == 'pageview']
|
"""Recursive implementations."""
def find_max(A):
"""invoke recursive function to find maximum value in A."""
def rmax(lo, hi):
"""Use recursion to find maximum value in A[lo:hi+1]."""
if lo == hi: return A[lo]
mid = (lo+hi) // 2
L = rmax(lo, mid)
R = rmax(mid+1, hi)
return max(L, R)
return rmax(0, len(A)-1)
def find_max_with_count(A):
"""Count number of comparisons."""
def frmax(lo, hi):
"""Use recursion to find maximum value in A[lo:hi+1] incl. count"""
if lo == hi: return (0, A[lo])
mid = (lo+hi)//2
ctleft,left = frmax(lo, mid)
ctright,right = frmax(mid+1, hi)
return (1+ctleft+ctright, max(left, right))
return frmax(0, len(A)-1)
def count(A,target):
"""invoke recursive function to return number of times target appears in A."""
def rcount(lo, hi, target):
"""Use recursion to find maximum value in A[lo:hi+1]."""
if lo == hi:
return 1 if A[lo] == target else 0
mid = (lo+hi)//2
left = rcount(lo, mid, target)
right = rcount(mid+1, hi, target)
return left + right
return rcount(0, len(A)-1, target)
|
somaIdade = 0
maiorIdade = 0
nomeVelho = ''
totmulher20 = 0
for p in range(1, 3):
print('---- {}ª PESSOA ----'.format(p))
nome = str(input('Nome: ')).strip()
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F]: '))
somaIdade += idade
if p == 1 and sexo in 'Mm':
maiorIdade = idade
nomeVelho = nome
if sexo in 'Mm' and idade > maiorIdade:
maiorIdade = idade
nomeVelho = nome
if sexo in 'Ff' and idade < 20:
totmulher20 += 1
mediaIdade = int(somaIdade / 4)
print('A média de idade do grupo de pessoas é de {} anos.'.format(mediaIdade))
print('O homem mais velho tem {} anos e se chama {}.'.format(maiorIdade, nomeVelho))
print('Ao todo são {} mulher com menos de 20 anos.'.format(totmulher20))
|
"""ssb-pseudonymization - Data pseudonymization functions used by SSB"""
__version__ = '0.0.2'
__author__ = 'Statistics Norway (ssb.no)'
__all__ = []
|
problem_type = "segmentation"
dataset_name = "synthia_rand_cityscapes"
dataset_name2 = None
perc_mb2 = None
model_name = "resnetFCN"
freeze_layers_from = None
show_model = False
load_imageNet = True
load_pretrained = False
weights_file = "weights.hdf5"
train_model = True
test_model = True
pred_model = False
debug = True
debug_images_train = 50
debug_images_valid = 50
debug_images_test = 50
debug_n_epochs = 2
batch_size_train = 2
batch_size_valid = 2
batch_size_test = 2
crop_size_train = (512, 512)
crop_size_valid = None
crop_size_test = None
resize_train = None
resize_valid = None
resize_test = None
shuffle_train = True
shuffle_valid = False
shuffle_test = False
seed_train = 1924
seed_valid = 1924
seed_test = 1924
optimizer = "rmsprop"
learning_rate = 0.0001
weight_decay = 0.0
n_epochs = 1000
save_results_enabled = True
save_results_nsamples = 5
save_results_batch_size = 5
save_results_n_legend_rows = 1
earlyStopping_enabled = True
earlyStopping_monitor = "val_jaccard"
earlyStopping_mode = "max"
earlyStopping_patience = 50
earlyStopping_verbose = 0
checkpoint_enabled = True
checkpoint_monitor = "val_jaccard"
checkpoint_mode = "max"
checkpoint_save_best_only = True
checkpoint_save_weights_only = True
checkpoint_verbose = 0
plotHist_enabled = True
plotHist_verbose = 0
LRScheduler_enabled = True
LRScheduler_batch_epoch = "batch"
LRScheduler_type = "poly"
LRScheduler_M = 75000
LRScheduler_decay = 0.1
LRScheduler_S = 10000
LRScheduler_power = 0.9
TensorBoard_enabled = True
TensorBoard_histogram_freq = 1
TensorBoard_write_graph = True
TensorBoard_write_images = False
TensorBoard_logs_folder = None
norm_imageNet_preprocess = True
norm_fit_dataset = False
norm_rescale = 1
norm_featurewise_center = False
norm_featurewise_std_normalization = False
norm_samplewise_center = False
norm_samplewise_std_normalization = False
norm_gcn = False
norm_zca_whitening = False
cb_weights_method = None
da_rotation_range = 0
da_width_shift_range = 0.0
da_height_shift_range = 0.0
da_shear_range = 0.0
da_zoom_range = 0.5
da_channel_shift_range = 0.0
da_fill_mode = "constant"
da_cval = 0.0
da_horizontal_flip = True
da_vertical_flip = False
da_spline_warp = False
da_warp_sigma = 10
da_warp_grid_size = 3
da_save_to_dir = False
|
{
"targets": [
{
"target_name": "cclust",
"sources": [ "./src/heatmap_clustering_js_module.cpp" ],
'dependencies': ['bonsaiclust']
},
{
'target_name': 'bonsaiclust',
'type': 'static_library',
'sources': [ 'src/cluster.c' ],
'cflags': ['-fPIC', '-I', '-pedantic', '-Wall']
}
]
}
|
#!/usr/bin/env python3.8
table="".maketrans("0123456789","\N{Devanagari digit zero}\N{Devanagari digit one}"
"\N{Devanagari digit two}\N{Devanagari digit three}"
"\N{Devanagari digit four}\N{Devanagari digit five}"
"\N{Devanagari digit six}\N{Devanagari digit seven}"
"\N{Devanagari digit eight}\N{Devanagari digit nine}")
print("0123456789".translate(table))
|
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class AzureCloudCredentials(object):
"""Implementation of the 'AzureCloudCredentials' model.
Specifies the cloud credentials to connect to a Microsoft
Azure service account.
Attributes:
storage_access_key (string): Specifies the access key to use when
accessing a storage tier in a Azure cloud service.
storage_account_name (string): Specifies the account name to use when
accessing a storage tier in a Azure cloud service.
tier_type (TierTypeAzureCloudCredentialsEnum): Specifies the storage
class of Azure. AzureTierType specifies the storage class for
Azure. 'kAzureTierHot' indicates a tier type of Azure properties
that is accessed frequently. 'kAzureTierCool' indicates a tier
type of Azure properties that is accessed less frequently, and
stored for at least 30 days. 'kAzureTierArchive' indicates a tier
type of Azure properties that is accessed rarely and stored for at
least 180 days.
"""
# Create a mapping from Model property names to API property names
_names = {
"storage_access_key":'storageAccessKey',
"storage_account_name":'storageAccountName',
"tier_type":'tierType'
}
def __init__(self,
storage_access_key=None,
storage_account_name=None,
tier_type=None):
"""Constructor for the AzureCloudCredentials class"""
# Initialize members of the class
self.storage_access_key = storage_access_key
self.storage_account_name = storage_account_name
self.tier_type = tier_type
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
storage_access_key = dictionary.get('storageAccessKey')
storage_account_name = dictionary.get('storageAccountName')
tier_type = dictionary.get('tierType')
# Return an object of this model
return cls(storage_access_key,
storage_account_name,
tier_type)
|
__author__ = 'Riccardo Frigerio'
'''
Oggetto HOST
Attributi:
- mac_address: indirizzo MAC
- port: porta a cui e' collegato
- dpid: switch a cui e' collegato
'''
class Host(object):
def __init__(self, mac_address, port, dpid):
self.mac_address = mac_address
self.port = port
self.dpid = dpid
|
"""
Write a function with a list of ints as a paramter. /
Return True if any two nums sum to 0. /
>>> add_to_zero([]) /
False /
>>> add_to_zero([1]) /
False /
>>> add_to_zero([1, 2, 3]) /
False /
>>> add_to_zero([1, 2, 3, -2]) /
True /
"""
|
# nested loops = The "inner loop" will finish all of it's iterations before
# finishing one iteration of the "outer loop"
rows = int(input("How many rows?: "))
columns = int(input("How many columns?: "))
symbol = input("Enter a symbol to use: ")
#symbol = int(input("Enter a symbol to use: "))
for i in range(rows):
for j in range(columns):
print(symbol, end="")
print()
|
# -*- coding: utf-8 -*-
"""Top-level package for Music Downloader Telegram Bot."""
# version as tuple for simple comparisons
VERSION = (0, 9, 16)
__author__ = """George Pchelkin"""
__email__ = '[email protected]'
# string created from tuple to avoid inconsistency
__version__ = ".".join([str(x) for x in VERSION])
|
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py'
]
cudnn_benchmark = True
norm_cfg = dict(type='BN', requires_grad=True)
checkpoint = 'https://download.openmmlab.com/mmclassification/v0/efficientnet/efficientnet-b3_3rdparty_8xb32-aa_in1k_20220119-5b4887a0.pth' # noqa
model = dict(
backbone=dict(
_delete_=True,
type='EfficientNet',
arch='b3',
drop_path_rate=0.2,
out_indices=(3, 4, 5),
frozen_stages=0,
norm_cfg=dict(
type='SyncBN', requires_grad=True, eps=1e-3, momentum=0.01),
norm_eval=False,
init_cfg=dict(
type='Pretrained', prefix='backbone', checkpoint=checkpoint)),
neck=dict(
in_channels=[48, 136, 384],
start_level=0,
out_channels=256,
relu_before_extra_convs=True,
no_norm_on_lateral=True,
norm_cfg=norm_cfg),
bbox_head=dict(type='RetinaSepBNHead', num_ins=5, norm_cfg=norm_cfg),
# training and testing settings
train_cfg=dict(assigner=dict(neg_iou_thr=0.5)))
# dataset settings
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
img_size = (896, 896)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(
type='Resize',
img_scale=img_size,
ratio_range=(0.8, 1.2),
keep_ratio=True),
dict(type='RandomCrop', crop_size=img_size),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size=img_size),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=img_size,
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size=img_size),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=4,
workers_per_gpu=4,
train=dict(pipeline=train_pipeline),
val=dict(pipeline=test_pipeline),
test=dict(pipeline=test_pipeline))
# optimizer
optimizer_config = dict(grad_clip=None)
optimizer = dict(
type='SGD',
lr=0.04,
momentum=0.9,
weight_decay=0.0001,
paramwise_cfg=dict(norm_decay_mult=0, bypass_duplicate=True))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=1000,
warmup_ratio=0.1,
step=[8, 11])
# runtime settings
runner = dict(type='EpochBasedRunner', max_epochs=12)
# NOTE: This variable is for automatically scaling LR,
# USER SHOULD NOT CHANGE THIS VALUE.
default_batch_size = 32 # (8 GPUs) x (4 samples per GPU)
|
'''
1. Write a Python program to access a specific item in a singly linked list using index value.
2. Write a Python program to set a new value of an item in a singly linked list using index value.
3. Write a Python program to delete the first item from a singly linked list.
'''
|
# Generalizando para não repetir o código!
class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
self.nomeclasse = self.__class__.__name__
def falar(self):
print(f'{self.nomeclasse} está falando.')
class Cliente(Pessoa):
def comprar(self):
print(f'{self.nomeclasse} está comprando...')
class Aluno(Pessoa):
def estudar(self):
print(f'{self.nomeclasse} está estudando...')
class ClienteVIP(Cliente):
def __init__(self, nome, idade, sobrenome):
super().__init__(nome, idade)
print(f'{self.nome}, {self.idade} anos, criado com sucesso.')
self.sobrenome = sobrenome
def falar(self):
Pessoa.falar(self)
# Como a classe Cliente não possui o método falar(), o Python busca na superclasse o método.
Cliente.falar(self)
print(f'{self.nome} {self.sobrenome}')
|
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2019 all rights reserved
#
# declaration
class Chain:
"""
A locator that ties together two others in order to express that something in {next}
caused {this} to be recorded
"""
# meta methods
def __init__(self, this, next):
self.this = this
self.next = next
return
def __str__(self):
# if {next} is non-trivial, show the chain
if self.next: return "{0.this}, {0.next}".format(self)
# otherwise don't
return "{0.this}".format(self)
# implementation details
__slots__ = "this", "next"
# end of file
|
"""
.. module:: aws_utilities_cli.iam
:platform: OS X
:synopsis: Small collection of utilities that
use the Amazon Web Services (AWS) SDK
.. moduleauthor:: dataday
"""
__all__ = ['generate_identity', 'generate_policy']
|
class Node:
left = right = None
def __init__(self, data):
self.data = data
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, end=' ')
inorder(root.right)
def insert(root, key):
if root is None:
return Node(key)
if key < root.data:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
def constructBST(keys):
root = None
for key in keys:
root = insert(root, key)
return root
if __name__ == '__main__':
keys = [15, 10, 20, 8, 12, 16, 25]
root = constructBST(keys)
inorder(root)
|
class NoMessageRecipients(Exception):
"""
Raised when Message Recipients are not specified.
"""
pass
class InvalidAmount(Exception):
"""
Raised when an invalid currency amount is specified
"""
pass
|
def something() -> None:
print("Andrew says: `something`.")
|
blacklist=set()
def get_blacklist():
return blacklist
def add_to_blacklist(jti):
return blacklist.add(jti)
|
#unit
#mydict.py
class Dict(dict):
def __init__(self,**kw):
super(Dict,self).__init__(**kw)
def __getattr__(self,key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object han no attribute'%s'" %key)
def __setattr__(self,key,value):
self[key]=value
|
"""Translates validation error messages for the response"""
messages = {
'accepted': 'The :field: must be accepted.',
'after': 'The :field: must be a date after :other:.',
'alpha': 'The :field: may contain only letters.',
'alpha_dash': 'The :field: may only contain letters, numbers, and dashes.',
'alpha_num': 'The :field: may contain only letters and numbers.',
'array': 'The :field: must be an array.',
'before': 'The :field: must be a date before :other:.',
'between': 'The :field: must be between :least: and :most:.',
'between_string': 'The :field: must be between :least: and :most: characters.',
'between_numeric': 'The :field: must be between :least: and :most:.',
'boolean': 'The :field: must be either true or false.',
'confirmed': 'The :field: confirmation does not match.',
'date': 'The :field: is not a valid date.',
'different': 'The :field: and :other: must be different.',
'digits': 'The :field: must be :length: digits.',
'email': 'The :field: must be a valid email address.',
'exists': 'The selected :field: is invalid.',
'found_in': 'The selected :field: is invalid.',
'integer': 'The :field: must be an integer.',
'json': 'The :field: must be valid json format.',
'most_string': 'The :field: must not be greater than :most: characters.',
'most_numeric': 'The :field: must not be greater than :most:.',
'least_string': 'The :field: must be at least :least: characters.',
'least_numeric': 'The :field: must be at least :least:.',
'not_in': 'The selected :field: is invalid.',
'numeric': 'The :field: must be a number.',
'positive': 'The :field: must be a positive number.',
'regex': 'The :field: format is invalid.',
'required': 'The :field: field is required.',
'required_with': 'The :field: field is required when :other: is present.',
'required_without': 'The :field: field is required when :other: si not present.',
'same': 'The :field: and :other: must match.',
'size_string': 'The :field: must be :size: characters.',
'size_numeric': 'The :field: must be :size:.',
'string': 'The :field: must be a string.',
'unique': 'The :field: is already taken.',
'url': 'The :field: format is invalid.',
}
def trans(rule, fields):
message = messages[rule]
for k, v in fields.items():
message = message.replace(k, v).replace('_', ' ')
return message
|
"""
Commom settings to all applications
"""
A = 40.3
TECU = 1.0e16
C = 299792458
F1 = 1.57542e9
F2 = 1.22760e9
factor_1 = (F1 - F2) / (F1 + F2) / C
factor_2 = (F1 * F2) / (F2 - F1) / C
DIFF_TEC_MAX = 0.05
LIMIT_STD = 7.5
plot_it = True
REQUIRED_VERSION = 3.01
CONSTELLATIONS = ['G', 'R']
COLUMNS_IN_RINEX = {'3.03': {'G': {'L1': 'L1C', 'L2': 'L2W', 'C1': 'C1C', 'P1': 'C1W', 'P2': 'C2W'},
'R': {'L1': 'L1C', 'L2': 'L2C', 'C1': 'C1C', 'P1': 'C1P', 'P2': 'C2P'}
},
'3.02': {'G': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1W', 'P2': 'C2W'},
'R': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1P', 'P2': 'C2P'}
},
'3.01': {'G': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1W', 'P2': 'C2W'},
'R': {'L1': 'L1', 'L2': 'L2', 'C1': 'C1C', 'P1': 'C1P', 'P2': 'C2P'}
}
}
|
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dict_1 = {}
for i in s:
if i not in dict_1:
dict_1[i] = 1
else:
dict_1[i] += 1
print(dict_1)
for idx, val in enumerate(s):
if dict_1[val] == 1:
return idx
return -1
|
#
# This is Seisflows
#
# See LICENCE file
#
###############################################################################
raise NotImplementedError
|
# -*- coding: utf-8 -*-
"""
awsecommerceservice
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class ItemLookupRequest(object):
"""Implementation of the 'ItemLookupRequest' model.
TODO: type model description here.
Attributes:
condition (ConditionEnum): TODO: type description here.
id_type (IdTypeEnum): TODO: type description here.
merchant_id (string): TODO: type description here.
item_id (list of string): TODO: type description here.
response_group (list of string): TODO: type description here.
search_index (string): TODO: type description here.
variation_page (object): TODO: type description here.
related_item_page (object): TODO: type description here.
relationship_type (list of string): TODO: type description here.
include_reviews_summary (string): TODO: type description here.
truncate_reviews_at (int): TODO: type description here.
"""
# Create a mapping from Model property names to API property names
_names = {
"condition":'Condition',
"id_type":'IdType',
"merchant_id":'MerchantId',
"item_id":'ItemId',
"response_group":'ResponseGroup',
"search_index":'SearchIndex',
"variation_page":'VariationPage',
"related_item_page":'RelatedItemPage',
"relationship_type":'RelationshipType',
"include_reviews_summary":'IncludeReviewsSummary',
"truncate_reviews_at":'TruncateReviewsAt'
}
def __init__(self,
condition=None,
id_type=None,
merchant_id=None,
item_id=None,
response_group=None,
search_index=None,
variation_page=None,
related_item_page=None,
relationship_type=None,
include_reviews_summary=None,
truncate_reviews_at=None):
"""Constructor for the ItemLookupRequest class"""
# Initialize members of the class
self.condition = condition
self.id_type = id_type
self.merchant_id = merchant_id
self.item_id = item_id
self.response_group = response_group
self.search_index = search_index
self.variation_page = variation_page
self.related_item_page = related_item_page
self.relationship_type = relationship_type
self.include_reviews_summary = include_reviews_summary
self.truncate_reviews_at = truncate_reviews_at
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
condition = dictionary.get('Condition')
id_type = dictionary.get('IdType')
merchant_id = dictionary.get('MerchantId')
item_id = dictionary.get('ItemId')
response_group = dictionary.get('ResponseGroup')
search_index = dictionary.get('SearchIndex')
variation_page = dictionary.get('VariationPage')
related_item_page = dictionary.get('RelatedItemPage')
relationship_type = dictionary.get('RelationshipType')
include_reviews_summary = dictionary.get('IncludeReviewsSummary')
truncate_reviews_at = dictionary.get('TruncateReviewsAt')
# Return an object of this model
return cls(condition,
id_type,
merchant_id,
item_id,
response_group,
search_index,
variation_page,
related_item_page,
relationship_type,
include_reviews_summary,
truncate_reviews_at)
|
#empréstimos bancários. pegue o valor da casa, o salario da pessoa e em quanto tempo ela quer pagar.
#se as parcelas ficarem acima de 30% do salario, negue o imprestimo.
casa = float(input('Informe o valor da casa: R$'))
salario = float(input('informe seu salario: R$'))
tempo = int(input('Em quanto tempo planeja pagar: '))
parcela = casa/(tempo*12)#para fazer a conta com base em anos, levando em conta as parcelas mensais.
print('Para pagar um casa de R${:.2f} e em {}anos, suas parcelas ficariam de R${:.2f}'.format(casa, tempo, parcela))
if parcela >= (salario*30/100):
print('Com seu salário atual, não é possível efetuar esse empréstimo.')
else:
print('Empréstimo aprovado')
|
#Integer division
#You have a shop selling buns for $2.40 each. A customer comes in with $15, and would like to buy as many buns as possible.
#Complete the code to calculate how many buns the customer can afford.
#Note: Your customer won't be happy if you try to sell them part of a bun.
#Print only the result, any other text in the output will cause the checker to fail.
bun_price = 2.40
money = 15
print( money // bun_price )
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.