content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: for.py
edibles = ['ham', 'spam', 'eggs', 'nuts']
for food in edibles:
if food == 'spam':
print('No more spam please!')
break
print('Great, delicious ' + food)
else:
print('I am so glad: No spam!')
print('Finally, I finished stuffing myself')
| edibles = ['ham', 'spam', 'eggs', 'nuts']
for food in edibles:
if food == 'spam':
print('No more spam please!')
break
print('Great, delicious ' + food)
else:
print('I am so glad: No spam!')
print('Finally, I finished stuffing myself') |
class QuoteLine:
def __init__(self, lineText, lineNumber, origin):
self.lineText = lineText
self.lineNumber = lineNumber
self.origin = origin
self.renderedLine = None
def renderLine(self, font, color):
'''
Renders the line using the given font and color.
'''
self.renderedLine = font.render(self.lineText, False, color)
def discardRenderedLine(self):
'''
Discards the rendered line (self.renderedLine = None)
'''
self.renderedLine = None | class Quoteline:
def __init__(self, lineText, lineNumber, origin):
self.lineText = lineText
self.lineNumber = lineNumber
self.origin = origin
self.renderedLine = None
def render_line(self, font, color):
"""
Renders the line using the given font and color.
"""
self.renderedLine = font.render(self.lineText, False, color)
def discard_rendered_line(self):
"""
Discards the rendered line (self.renderedLine = None)
"""
self.renderedLine = None |
first_str = input()
second_str = input()
while first_str in second_str:
second_str = second_str.replace(first_str, '')
print(second_str) | first_str = input()
second_str = input()
while first_str in second_str:
second_str = second_str.replace(first_str, '')
print(second_str) |
#
# PySNMP MIB module CHIPFDDINET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHIPFDDINET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:48:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection")
DisplayString, = mibBuilder.importSymbols("RFC1155-SMI", "DisplayString")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
IpAddress, Gauge32, enterprises, TimeTicks, iso, Counter64, NotificationType, ObjectIdentity, MibIdentifier, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Integer32, ModuleIdentity, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Gauge32", "enterprises", "TimeTicks", "iso", "Counter64", "NotificationType", "ObjectIdentity", "MibIdentifier", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Integer32", "ModuleIdentity", "Unsigned32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
chipcom = MibIdentifier((1, 3, 6, 1, 4, 1, 49))
chipmib02 = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2))
chipGen = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 1))
chipEcho = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 2))
chipProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3))
chipExperiment = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 4))
chipTTY = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 5))
chipTFTP = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 6))
chipDownload = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 7))
online = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1))
oebm = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 2))
midnight = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 3))
workGroupHub = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4))
emm = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 5))
chipBridge = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 6))
trmm = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 7))
fmm = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 8))
focus1 = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 9))
oeim = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 10))
chipExpTokenRing = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 4, 1))
dot1dBridge = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 4, 14))
dot5 = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 4, 1, 1))
olAgents = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 1))
olConc = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 2))
olEnv = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 3))
olModules = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4))
olNets = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5))
olGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 6))
olAlarm = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 7))
olSpecMods = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4))
ol50nnMCTL = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 3))
ol51nnMMGT = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 4))
ol51nnMFIB = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 5))
ol51nnMUTP = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 6))
ol51nnMTP = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 7))
ol51nnMBNC = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 8))
ol51nnBEE = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 9))
ol51nnRES = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 10))
ol51nnREE = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 11))
ol51nnMAUIF = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 12))
ol51nnMAUIM = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 13))
ol5208MTP = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 14))
ol51nnMFP = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 15))
ol51nnMFBP = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 16))
ol51nnMTPL = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 17))
ol51nnMTPPL = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 18))
ol52nnMTP = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 19))
ol52nnMFR = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 20))
ol51nnMTS = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 21))
ol51nnMFL = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 22))
ol50nnMRCTL = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 23))
ol51nnMFB = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 24))
ol53nnMMGT = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 25))
ol53nnMFBMIC = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 26))
ol53nnMFIBST = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 27))
ol53nnMSTP = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 28))
ol51nnMTPCL = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 29))
ol52nnBTT = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 30))
ol51nnIx = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 31))
ol52nnMMGT = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 32))
ol50nnMHCTL = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 33))
olNet = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 1))
olEnet = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 2))
olTRnet = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 3))
olFDDInet = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4))
hubSysGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 1))
hardwareGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 2))
softwareGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 3))
hubGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 4))
boardGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 5))
portGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 6))
alarmGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 7))
olThresh = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 7, 1))
olThreshControl = MibIdentifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 7, 1, 1))
olFDDIStatsModTable = MibTable((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2), )
if mibBuilder.loadTexts: olFDDIStatsModTable.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsModTable.setDescription('A table of statistical information counted for each module in each FDDI network.')
olFDDIStatsModEntry = MibTableRow((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1), ).setIndexNames((0, "CHIPFDDINET-MIB", "olFDDIStatsModSlotIndex"))
if mibBuilder.loadTexts: olFDDIStatsModEntry.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsModEntry.setDescription('A list of statistical information for each module on each FDDI network in the concentrator.')
olFDDIStatsModSlotIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsModSlotIndex.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsModSlotIndex.setDescription('The slot number that contains this module.')
olFDDIStatsModMgtRcvErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsModMgtRcvErrs.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsModMgtRcvErrs.setDescription('The number of errors encountered while receiving data on the Management Channel.')
olFDDIStatsModMgtXmitErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsModMgtXmitErrs.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsModMgtXmitErrs.setDescription('The number of errors encountered while transmitting data on the Management Channel.')
olFDDIStatsModBackplaneErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsModBackplaneErrs.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsModBackplaneErrs.setDescription('The number of errors while receiving and transmitting network data on the backplane.')
olFDDIStatsModPllUnlockErrs = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsModPllUnlockErrs.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsModPllUnlockErrs.setDescription('The number of times the phased lock loop on the backplane network data channel was lost.')
olFDDIStatsPortTable = MibTable((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3), )
if mibBuilder.loadTexts: olFDDIStatsPortTable.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsPortTable.setDescription('A table of statistical information counted for each Port in each FDDI network.')
olFDDIStatsPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1), ).setIndexNames((0, "CHIPFDDINET-MIB", "olFDDIStatsPortSlotIndex"), (0, "CHIPFDDINET-MIB", "olFDDIStatsPortIndex"))
if mibBuilder.loadTexts: olFDDIStatsPortEntry.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsPortEntry.setDescription('A list of statistical information for each Port on each FDDI network in the concentrator.')
olFDDIStatsPortSlotIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsPortSlotIndex.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsPortSlotIndex.setDescription('The slot number that contains this Port.')
olFDDIStatsPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsPortIndex.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsPortIndex.setDescription('The Port number of this port')
olFDDIStatsPortLCTFailCts = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsPortLCTFailCts.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsPortLCTFailCts.setDescription('The count of the consecutive times the link confidence test (LCT) has failed during connection management. Once the connection has been established, the count is zeroed. (refer to ANSI 9.4.1).')
olFDDIStatsPortLerEstimate = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsPortLerEstimate.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsPortLerEstimate.setDescription('A long term average link error rate. It ranges from 10**-4 to 10**-15 and is reported as the absolute value of the exponent of the estimate (the larger the number, the smaller the value).')
olFDDIStatsPortLemRejectCts = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsPortLemRejectCts.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsPortLemRejectCts.setDescription('A link error monitoring count of the times that a link has been removed from the ring due to the LerCutOff threshold being exceeded.')
olFDDIStatsPortLemCts = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDIStatsPortLemCts.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDIStatsPortLemCts.setDescription("The aggregate link error monitor error count, set to zero only on station power up. This variable's long term rate average is lerEstimate.")
olFDDInetStatsTable = MibTable((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4), )
if mibBuilder.loadTexts: olFDDInetStatsTable.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDInetStatsTable.setDescription('A table of statistical information counted for each FDDI network in the concentrator')
olFDDInetStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1), ).setIndexNames((0, "CHIPFDDINET-MIB", "olFDDInetStatsNetID"))
if mibBuilder.loadTexts: olFDDInetStatsEntry.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDInetStatsEntry.setDescription('A list of statistical information for each FDDI network in the concentrator.')
olFDDInetStatsNetID = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 16, 17, 18, 19))).clone(namedValues=NamedValues(("isolated", 2), ("fddi-1", 16), ("fddi-2", 17), ("fddi-3", 18), ("fddi-4", 19)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDInetStatsNetID.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDInetStatsNetID.setDescription('The network index that uniquely identifies this network. One of isolated, fddi-1, fddi-2, fddi-3, or fddi-4.')
olFDDInetStatsRingOpCounts = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDInetStatsRingOpCounts.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDInetStatsRingOpCounts.setDescription('The number times the ring transitioned to operational.')
olFDDInetStatsFrameCounts = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDInetStatsFrameCounts.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDInetStatsFrameCounts.setDescription('Frame_Ct (refer to ANSI MAC 2.2.1).')
olFDDInetStatsErrorCounts = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDInetStatsErrorCounts.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDInetStatsErrorCounts.setDescription('Error_Ct (refer to ANSI MAC 2.2.1).')
olFDDInetStatsLostCounts = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDInetStatsLostCounts.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDInetStatsLostCounts.setDescription('Lost_Ct (refer to ANSI MAC 2.2.1).')
olFDDInetStatsFrameErrorRatio = MibTableColumn((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: olFDDInetStatsFrameErrorRatio.setStatus('mandatory')
if mibBuilder.loadTexts: olFDDInetStatsFrameErrorRatio.setDescription('This attribute is the actual ratio, ((delta snmpFddiMACLostCt + delta snmpFddiMACErrorCt) / (delta snmpFddiMACFrameCt + delta snmpFddiMACLostCt)) x 2**16.')
mibBuilder.exportSymbols("CHIPFDDINET-MIB", olFDDIStatsModSlotIndex=olFDDIStatsModSlotIndex, olNets=olNets, ol50nnMRCTL=ol50nnMRCTL, softwareGroup=softwareGroup, hubSysGroup=hubSysGroup, olFDDInetStatsRingOpCounts=olFDDInetStatsRingOpCounts, olThresh=olThresh, olFDDInetStatsLostCounts=olFDDInetStatsLostCounts, dot1dBridge=dot1dBridge, oeim=oeim, olFDDIStatsModMgtRcvErrs=olFDDIStatsModMgtRcvErrs, olThreshControl=olThreshControl, chipTTY=chipTTY, ol53nnMMGT=ol53nnMMGT, ol52nnMFR=ol52nnMFR, ol51nnMAUIF=ol51nnMAUIF, olFDDIStatsModPllUnlockErrs=olFDDIStatsModPllUnlockErrs, online=online, chipExpTokenRing=chipExpTokenRing, olConc=olConc, ol51nnREE=ol51nnREE, ol53nnMFIBST=ol53nnMFIBST, ol51nnMTPL=ol51nnMTPL, olFDDIStatsModEntry=olFDDIStatsModEntry, ol51nnMBNC=ol51nnMBNC, ol51nnMTPPL=ol51nnMTPPL, trmm=trmm, ol51nnBEE=ol51nnBEE, ol51nnMAUIM=ol51nnMAUIM, chipEcho=chipEcho, olEnv=olEnv, chipProducts=chipProducts, olFDDIStatsPortTable=olFDDIStatsPortTable, ol51nnMFP=ol51nnMFP, olFDDIStatsPortLemRejectCts=olFDDIStatsPortLemRejectCts, chipDownload=chipDownload, olFDDInet=olFDDInet, olSpecMods=olSpecMods, dot5=dot5, ol51nnMTPCL=ol51nnMTPCL, olFDDInetStatsFrameErrorRatio=olFDDInetStatsFrameErrorRatio, fmm=fmm, chipmib02=chipmib02, olFDDIStatsModMgtXmitErrs=olFDDIStatsModMgtXmitErrs, olFDDInetStatsErrorCounts=olFDDInetStatsErrorCounts, ol51nnMFL=ol51nnMFL, chipGen=chipGen, olFDDIStatsPortEntry=olFDDIStatsPortEntry, midnight=midnight, olGroups=olGroups, ol51nnRES=ol51nnRES, olFDDIStatsPortSlotIndex=olFDDIStatsPortSlotIndex, ol53nnMFBMIC=ol53nnMFBMIC, olFDDInetStatsFrameCounts=olFDDInetStatsFrameCounts, olFDDIStatsPortLemCts=olFDDIStatsPortLemCts, emm=emm, olFDDInetStatsEntry=olFDDInetStatsEntry, olEnet=olEnet, ol52nnMMGT=ol52nnMMGT, olFDDIStatsPortLCTFailCts=olFDDIStatsPortLCTFailCts, olNet=olNet, chipcom=chipcom, ol51nnMFBP=ol51nnMFBP, ol51nnIx=ol51nnIx, olFDDIStatsModBackplaneErrs=olFDDIStatsModBackplaneErrs, olModules=olModules, olFDDInetStatsTable=olFDDInetStatsTable, alarmGroup=alarmGroup, ol51nnMTP=ol51nnMTP, olFDDIStatsModTable=olFDDIStatsModTable, ol51nnMFIB=ol51nnMFIB, ol51nnMTS=ol51nnMTS, focus1=focus1, chipTFTP=chipTFTP, olTRnet=olTRnet, workGroupHub=workGroupHub, hardwareGroup=hardwareGroup, ol51nnMUTP=ol51nnMUTP, ol53nnMSTP=ol53nnMSTP, olFDDInetStatsNetID=olFDDInetStatsNetID, ol51nnMMGT=ol51nnMMGT, chipExperiment=chipExperiment, chipBridge=chipBridge, boardGroup=boardGroup, ol52nnBTT=ol52nnBTT, olAlarm=olAlarm, olFDDIStatsPortIndex=olFDDIStatsPortIndex, ol5208MTP=ol5208MTP, ol50nnMHCTL=ol50nnMHCTL, portGroup=portGroup, oebm=oebm, ol51nnMFB=ol51nnMFB, hubGroup=hubGroup, olFDDIStatsPortLerEstimate=olFDDIStatsPortLerEstimate, ol50nnMCTL=ol50nnMCTL, ol52nnMTP=ol52nnMTP, olAgents=olAgents)
| (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection')
(display_string,) = mibBuilder.importSymbols('RFC1155-SMI', 'DisplayString')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(ip_address, gauge32, enterprises, time_ticks, iso, counter64, notification_type, object_identity, mib_identifier, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, integer32, module_identity, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Gauge32', 'enterprises', 'TimeTicks', 'iso', 'Counter64', 'NotificationType', 'ObjectIdentity', 'MibIdentifier', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'Integer32', 'ModuleIdentity', 'Unsigned32')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
chipcom = mib_identifier((1, 3, 6, 1, 4, 1, 49))
chipmib02 = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2))
chip_gen = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 1))
chip_echo = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 2))
chip_products = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3))
chip_experiment = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 4))
chip_tty = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 5))
chip_tftp = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 6))
chip_download = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 7))
online = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1))
oebm = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 2))
midnight = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 3))
work_group_hub = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4))
emm = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 5))
chip_bridge = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 6))
trmm = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 7))
fmm = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 8))
focus1 = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 9))
oeim = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 10))
chip_exp_token_ring = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 4, 1))
dot1d_bridge = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 4, 14))
dot5 = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 4, 1, 1))
ol_agents = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 1))
ol_conc = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 2))
ol_env = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 3))
ol_modules = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4))
ol_nets = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5))
ol_groups = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 6))
ol_alarm = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 7))
ol_spec_mods = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4))
ol50nn_mctl = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 3))
ol51nn_mmgt = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 4))
ol51nn_mfib = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 5))
ol51nn_mutp = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 6))
ol51nn_mtp = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 7))
ol51nn_mbnc = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 8))
ol51nn_bee = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 9))
ol51nn_res = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 10))
ol51nn_ree = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 11))
ol51nn_mauif = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 12))
ol51nn_mauim = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 13))
ol5208_mtp = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 14))
ol51nn_mfp = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 15))
ol51nn_mfbp = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 16))
ol51nn_mtpl = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 17))
ol51nn_mtppl = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 18))
ol52nn_mtp = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 19))
ol52nn_mfr = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 20))
ol51nn_mts = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 21))
ol51nn_mfl = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 22))
ol50nn_mrctl = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 23))
ol51nn_mfb = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 24))
ol53nn_mmgt = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 25))
ol53nn_mfbmic = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 26))
ol53nn_mfibst = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 27))
ol53nn_mstp = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 28))
ol51nn_mtpcl = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 29))
ol52nn_btt = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 30))
ol51nn_ix = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 31))
ol52nn_mmgt = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 32))
ol50nn_mhctl = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 4, 4, 33))
ol_net = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 1))
ol_enet = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 2))
ol_t_rnet = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 3))
ol_fdd_inet = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4))
hub_sys_group = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 1))
hardware_group = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 2))
software_group = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 3))
hub_group = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 4))
board_group = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 5))
port_group = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 6))
alarm_group = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 4, 7))
ol_thresh = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 7, 1))
ol_thresh_control = mib_identifier((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 7, 1, 1))
ol_fddi_stats_mod_table = mib_table((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2))
if mibBuilder.loadTexts:
olFDDIStatsModTable.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsModTable.setDescription('A table of statistical information counted for each module in each FDDI network.')
ol_fddi_stats_mod_entry = mib_table_row((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1)).setIndexNames((0, 'CHIPFDDINET-MIB', 'olFDDIStatsModSlotIndex'))
if mibBuilder.loadTexts:
olFDDIStatsModEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsModEntry.setDescription('A list of statistical information for each module on each FDDI network in the concentrator.')
ol_fddi_stats_mod_slot_index = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsModSlotIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsModSlotIndex.setDescription('The slot number that contains this module.')
ol_fddi_stats_mod_mgt_rcv_errs = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsModMgtRcvErrs.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsModMgtRcvErrs.setDescription('The number of errors encountered while receiving data on the Management Channel.')
ol_fddi_stats_mod_mgt_xmit_errs = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsModMgtXmitErrs.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsModMgtXmitErrs.setDescription('The number of errors encountered while transmitting data on the Management Channel.')
ol_fddi_stats_mod_backplane_errs = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsModBackplaneErrs.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsModBackplaneErrs.setDescription('The number of errors while receiving and transmitting network data on the backplane.')
ol_fddi_stats_mod_pll_unlock_errs = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 2, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsModPllUnlockErrs.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsModPllUnlockErrs.setDescription('The number of times the phased lock loop on the backplane network data channel was lost.')
ol_fddi_stats_port_table = mib_table((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3))
if mibBuilder.loadTexts:
olFDDIStatsPortTable.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsPortTable.setDescription('A table of statistical information counted for each Port in each FDDI network.')
ol_fddi_stats_port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1)).setIndexNames((0, 'CHIPFDDINET-MIB', 'olFDDIStatsPortSlotIndex'), (0, 'CHIPFDDINET-MIB', 'olFDDIStatsPortIndex'))
if mibBuilder.loadTexts:
olFDDIStatsPortEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsPortEntry.setDescription('A list of statistical information for each Port on each FDDI network in the concentrator.')
ol_fddi_stats_port_slot_index = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsPortSlotIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsPortSlotIndex.setDescription('The slot number that contains this Port.')
ol_fddi_stats_port_index = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsPortIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsPortIndex.setDescription('The Port number of this port')
ol_fddi_stats_port_lct_fail_cts = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsPortLCTFailCts.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsPortLCTFailCts.setDescription('The count of the consecutive times the link confidence test (LCT) has failed during connection management. Once the connection has been established, the count is zeroed. (refer to ANSI 9.4.1).')
ol_fddi_stats_port_ler_estimate = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 4), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsPortLerEstimate.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsPortLerEstimate.setDescription('A long term average link error rate. It ranges from 10**-4 to 10**-15 and is reported as the absolute value of the exponent of the estimate (the larger the number, the smaller the value).')
ol_fddi_stats_port_lem_reject_cts = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsPortLemRejectCts.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsPortLemRejectCts.setDescription('A link error monitoring count of the times that a link has been removed from the ring due to the LerCutOff threshold being exceeded.')
ol_fddi_stats_port_lem_cts = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 3, 1, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDIStatsPortLemCts.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDIStatsPortLemCts.setDescription("The aggregate link error monitor error count, set to zero only on station power up. This variable's long term rate average is lerEstimate.")
ol_fdd_inet_stats_table = mib_table((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4))
if mibBuilder.loadTexts:
olFDDInetStatsTable.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDInetStatsTable.setDescription('A table of statistical information counted for each FDDI network in the concentrator')
ol_fdd_inet_stats_entry = mib_table_row((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1)).setIndexNames((0, 'CHIPFDDINET-MIB', 'olFDDInetStatsNetID'))
if mibBuilder.loadTexts:
olFDDInetStatsEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDInetStatsEntry.setDescription('A list of statistical information for each FDDI network in the concentrator.')
ol_fdd_inet_stats_net_id = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(2, 16, 17, 18, 19))).clone(namedValues=named_values(('isolated', 2), ('fddi-1', 16), ('fddi-2', 17), ('fddi-3', 18), ('fddi-4', 19)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDInetStatsNetID.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDInetStatsNetID.setDescription('The network index that uniquely identifies this network. One of isolated, fddi-1, fddi-2, fddi-3, or fddi-4.')
ol_fdd_inet_stats_ring_op_counts = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDInetStatsRingOpCounts.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDInetStatsRingOpCounts.setDescription('The number times the ring transitioned to operational.')
ol_fdd_inet_stats_frame_counts = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDInetStatsFrameCounts.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDInetStatsFrameCounts.setDescription('Frame_Ct (refer to ANSI MAC 2.2.1).')
ol_fdd_inet_stats_error_counts = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDInetStatsErrorCounts.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDInetStatsErrorCounts.setDescription('Error_Ct (refer to ANSI MAC 2.2.1).')
ol_fdd_inet_stats_lost_counts = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDInetStatsLostCounts.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDInetStatsLostCounts.setDescription('Lost_Ct (refer to ANSI MAC 2.2.1).')
ol_fdd_inet_stats_frame_error_ratio = mib_table_column((1, 3, 6, 1, 4, 1, 49, 2, 3, 1, 5, 4, 4, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
olFDDInetStatsFrameErrorRatio.setStatus('mandatory')
if mibBuilder.loadTexts:
olFDDInetStatsFrameErrorRatio.setDescription('This attribute is the actual ratio, ((delta snmpFddiMACLostCt + delta snmpFddiMACErrorCt) / (delta snmpFddiMACFrameCt + delta snmpFddiMACLostCt)) x 2**16.')
mibBuilder.exportSymbols('CHIPFDDINET-MIB', olFDDIStatsModSlotIndex=olFDDIStatsModSlotIndex, olNets=olNets, ol50nnMRCTL=ol50nnMRCTL, softwareGroup=softwareGroup, hubSysGroup=hubSysGroup, olFDDInetStatsRingOpCounts=olFDDInetStatsRingOpCounts, olThresh=olThresh, olFDDInetStatsLostCounts=olFDDInetStatsLostCounts, dot1dBridge=dot1dBridge, oeim=oeim, olFDDIStatsModMgtRcvErrs=olFDDIStatsModMgtRcvErrs, olThreshControl=olThreshControl, chipTTY=chipTTY, ol53nnMMGT=ol53nnMMGT, ol52nnMFR=ol52nnMFR, ol51nnMAUIF=ol51nnMAUIF, olFDDIStatsModPllUnlockErrs=olFDDIStatsModPllUnlockErrs, online=online, chipExpTokenRing=chipExpTokenRing, olConc=olConc, ol51nnREE=ol51nnREE, ol53nnMFIBST=ol53nnMFIBST, ol51nnMTPL=ol51nnMTPL, olFDDIStatsModEntry=olFDDIStatsModEntry, ol51nnMBNC=ol51nnMBNC, ol51nnMTPPL=ol51nnMTPPL, trmm=trmm, ol51nnBEE=ol51nnBEE, ol51nnMAUIM=ol51nnMAUIM, chipEcho=chipEcho, olEnv=olEnv, chipProducts=chipProducts, olFDDIStatsPortTable=olFDDIStatsPortTable, ol51nnMFP=ol51nnMFP, olFDDIStatsPortLemRejectCts=olFDDIStatsPortLemRejectCts, chipDownload=chipDownload, olFDDInet=olFDDInet, olSpecMods=olSpecMods, dot5=dot5, ol51nnMTPCL=ol51nnMTPCL, olFDDInetStatsFrameErrorRatio=olFDDInetStatsFrameErrorRatio, fmm=fmm, chipmib02=chipmib02, olFDDIStatsModMgtXmitErrs=olFDDIStatsModMgtXmitErrs, olFDDInetStatsErrorCounts=olFDDInetStatsErrorCounts, ol51nnMFL=ol51nnMFL, chipGen=chipGen, olFDDIStatsPortEntry=olFDDIStatsPortEntry, midnight=midnight, olGroups=olGroups, ol51nnRES=ol51nnRES, olFDDIStatsPortSlotIndex=olFDDIStatsPortSlotIndex, ol53nnMFBMIC=ol53nnMFBMIC, olFDDInetStatsFrameCounts=olFDDInetStatsFrameCounts, olFDDIStatsPortLemCts=olFDDIStatsPortLemCts, emm=emm, olFDDInetStatsEntry=olFDDInetStatsEntry, olEnet=olEnet, ol52nnMMGT=ol52nnMMGT, olFDDIStatsPortLCTFailCts=olFDDIStatsPortLCTFailCts, olNet=olNet, chipcom=chipcom, ol51nnMFBP=ol51nnMFBP, ol51nnIx=ol51nnIx, olFDDIStatsModBackplaneErrs=olFDDIStatsModBackplaneErrs, olModules=olModules, olFDDInetStatsTable=olFDDInetStatsTable, alarmGroup=alarmGroup, ol51nnMTP=ol51nnMTP, olFDDIStatsModTable=olFDDIStatsModTable, ol51nnMFIB=ol51nnMFIB, ol51nnMTS=ol51nnMTS, focus1=focus1, chipTFTP=chipTFTP, olTRnet=olTRnet, workGroupHub=workGroupHub, hardwareGroup=hardwareGroup, ol51nnMUTP=ol51nnMUTP, ol53nnMSTP=ol53nnMSTP, olFDDInetStatsNetID=olFDDInetStatsNetID, ol51nnMMGT=ol51nnMMGT, chipExperiment=chipExperiment, chipBridge=chipBridge, boardGroup=boardGroup, ol52nnBTT=ol52nnBTT, olAlarm=olAlarm, olFDDIStatsPortIndex=olFDDIStatsPortIndex, ol5208MTP=ol5208MTP, ol50nnMHCTL=ol50nnMHCTL, portGroup=portGroup, oebm=oebm, ol51nnMFB=ol51nnMFB, hubGroup=hubGroup, olFDDIStatsPortLerEstimate=olFDDIStatsPortLerEstimate, ol50nnMCTL=ol50nnMCTL, ol52nnMTP=ol52nnMTP, olAgents=olAgents) |
# class Solution(object):
# def generateParenthesis(self, n):
# """
# :type n: int
# :rtype: List[str]
# """
class Solution(object):
def generateParenthesis(self, n):
if n == 1:
return ['()']
last_list = self.generateParenthesis(n - 1)
res = []
for t in last_list:
curr = t + ')'
for index in range(len(curr)):
if curr[index] == ')':
res.append(curr[:index] + '(' + curr[index:])
return list(set(res))
# def generateParenthesis(self, n):
# def generate(leftnum, rightnum, s, result):
# if leftnum == 0 and rightnum == 0:
# result.append(s)
# if leftnum > 0:
# generate(leftnum - 1, rightnum, s + '(', result)
# if rightnum > 0 and leftnum < rightnum:
# generate(leftnum, rightnum - 1, s + ')', result)
#
# result = []
# s = ''
# generate(n, n, s, result)
# return result
| class Solution(object):
def generate_parenthesis(self, n):
if n == 1:
return ['()']
last_list = self.generateParenthesis(n - 1)
res = []
for t in last_list:
curr = t + ')'
for index in range(len(curr)):
if curr[index] == ')':
res.append(curr[:index] + '(' + curr[index:])
return list(set(res)) |
# MIT License
#
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
def pretty_dict(d, indent=0):
"""Pretty the output format of a dictionary.
Parameters
----------
d
dict, the input dictionary instance.
indent
int, indent level, non-negative.
Returns
-------
res
str, the output string
"""
res = ""
for k, v in d.items():
res += "\t" * indent + str(k)
if isinstance(v, dict):
res += "\n" + pretty_dict(v, indent + 1)
else:
res += ": " + str(v) + "\n"
return res
| def pretty_dict(d, indent=0):
"""Pretty the output format of a dictionary.
Parameters
----------
d
dict, the input dictionary instance.
indent
int, indent level, non-negative.
Returns
-------
res
str, the output string
"""
res = ''
for (k, v) in d.items():
res += '\t' * indent + str(k)
if isinstance(v, dict):
res += '\n' + pretty_dict(v, indent + 1)
else:
res += ': ' + str(v) + '\n'
return res |
print(10/3)
print(10//3)
print()
kue = 16
anak = 4
kuePerAnak = kue // anak
print ("Setiap anak akan mendapatkan kue sebanyak ", kuePerAnak)
| print(10 / 3)
print(10 // 3)
print()
kue = 16
anak = 4
kue_per_anak = kue // anak
print('Setiap anak akan mendapatkan kue sebanyak ', kuePerAnak) |
class ExportUnit(Enum,IComparable,IFormattable,IConvertible):
"""
An enumerated type listing possible target units for CAD Export.
enum ExportUnit,values: Centimeter (4),Default (0),Foot (2),Inch (1),Meter (5),Millimeter (3)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
Centimeter=None
Default=None
Foot=None
Inch=None
Meter=None
Millimeter=None
value__=None
| class Exportunit(Enum, IComparable, IFormattable, IConvertible):
"""
An enumerated type listing possible target units for CAD Export.
enum ExportUnit,values: Centimeter (4),Default (0),Foot (2),Inch (1),Meter (5),Millimeter (3)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self, *args):
pass
def __gt__(self, *args):
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args):
pass
def __lt__(self, *args):
pass
def __ne__(self, *args):
pass
def __reduce_ex__(self, *args):
pass
def __str__(self, *args):
pass
centimeter = None
default = None
foot = None
inch = None
meter = None
millimeter = None
value__ = None |
while True:
X, M = map(int, input().split())
if X == 0 and M == 0:
break
Y = X * M
print(Y) | while True:
(x, m) = map(int, input().split())
if X == 0 and M == 0:
break
y = X * M
print(Y) |
age = 5+(8%3)-3+(3*10)/2
greetings = "Welcome to IEEE Python Workshop 2018 edition. It's my pleasure to conduct today's workshop for you."
name = "Saurabh Mudgal"
major = "mechanical engineering"
print(greetings)
print("My name is " + name + ".")
print("I am " + str(age) + " years old and am majoring in " + major + ".")
| age = 5 + 8 % 3 - 3 + 3 * 10 / 2
greetings = "Welcome to IEEE Python Workshop 2018 edition. It's my pleasure to conduct today's workshop for you."
name = 'Saurabh Mudgal'
major = 'mechanical engineering'
print(greetings)
print('My name is ' + name + '.')
print('I am ' + str(age) + ' years old and am majoring in ' + major + '.') |
# -*- coding: utf-8 -*-
__title__ = 'exp_mixture_model'
__version__ = '1.0.0'
__description__ = 'Maximum likelihood estimation and model selection of EMMs'
__copyright__ = 'Copyright (C) 2019 Makoto Okada and Naoki Masuda'
__license__ = 'MIT License'
__author__ = 'Makoto Okada, Kenji Yamanishi and Naoki Masuda'
__author_email__ = 'naoki.masuda@bristol.ac.uk'
__url__ = 'https://github.com/naokimas/exp_mixture_model'
| __title__ = 'exp_mixture_model'
__version__ = '1.0.0'
__description__ = 'Maximum likelihood estimation and model selection of EMMs'
__copyright__ = 'Copyright (C) 2019 Makoto Okada and Naoki Masuda'
__license__ = 'MIT License'
__author__ = 'Makoto Okada, Kenji Yamanishi and Naoki Masuda'
__author_email__ = 'naoki.masuda@bristol.ac.uk'
__url__ = 'https://github.com/naokimas/exp_mixture_model' |
class Product:
def __init__(self, name, category_name, unit_price):
self.name = name
self.category_name = category_name
self.unit_price = unit_price
def __str__(self):
return f"Nazwa: {self.name} | Kategoria: {self.category_name} | Cena: {self.unit_price} PLN/szt"
| class Product:
def __init__(self, name, category_name, unit_price):
self.name = name
self.category_name = category_name
self.unit_price = unit_price
def __str__(self):
return f'Nazwa: {self.name} | Kategoria: {self.category_name} | Cena: {self.unit_price} PLN/szt' |
class Shape:
def __init__(self):
self.data = ['_' for _ in range(10)]
def print_out(self):
print(''.join(self.data))
class Even(Shape):
def draw_func(self, x):
if x % 2 == 0:
return True
else:
return False
class ThirdBiggerFive(Shape):
def draw_func(self, x):
if x % 3 == 0 or x > 5:
return True
else:
return False
def draw(Obj):
o = Obj()
for x in range(0, 10):
if o.draw_func(x):
o.data[x] = 'X'
return o
even = draw(Even)
even.print_out()
third = draw(ThirdBiggerFive)
third.print_out()
| class Shape:
def __init__(self):
self.data = ['_' for _ in range(10)]
def print_out(self):
print(''.join(self.data))
class Even(Shape):
def draw_func(self, x):
if x % 2 == 0:
return True
else:
return False
class Thirdbiggerfive(Shape):
def draw_func(self, x):
if x % 3 == 0 or x > 5:
return True
else:
return False
def draw(Obj):
o = obj()
for x in range(0, 10):
if o.draw_func(x):
o.data[x] = 'X'
return o
even = draw(Even)
even.print_out()
third = draw(ThirdBiggerFive)
third.print_out() |
#!/usr/bin/python3
# steinkirch at gmail.com
# astro.sunysb.edu/steinkirch
class Node(object):
def __init__(self, value=None):
self.value = value
self.next = None
class Stack(object):
def __init__(self):
self.top = None
def push(self, item):
node = Node(item)
node.next = self.top
self.top = node
def pop(self):
if self.top:
node = self.top
self.top = node.next
return node.value
raise Exception('Stack is empty.')
def isEmpty(self):
return bool(self.top)
def seeTop(self):
if self.top:
return self.top.value
raise Exception('Stack is empty.')
def size(self):
node = self.top
count = 0
while node:
count +=1
node = node.next
return count
class StackList(list):
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if self.items:
return self.items.pop()
raise Exception('Stack is empty.')
def seeTop(self):
if self.items:
return self.items[-1]
raise Exception('Stack is empty.')
def size(self):
return len(self.items)
def isEmpty(self):
return bool(self.items)
def main():
s1 = StackList()
print(s1.isEmpty())
for i in range(1, 10):
s1.push(i)
print(s1.isEmpty())
print(s1.size())
print(s1.seeTop())
s1.pop()
print(s1.size())
print(s1.seeTop())
s2 = Stack()
print(s2.isEmpty())
for i in range(1, 10):
s2.push(i)
print(s2.isEmpty())
print(s2.size())
print(s2.seeTop())
s2.pop()
print(s2.size())
print(s2.seeTop())
if __name__ == '__main__':
main()
| class Node(object):
def __init__(self, value=None):
self.value = value
self.next = None
class Stack(object):
def __init__(self):
self.top = None
def push(self, item):
node = node(item)
node.next = self.top
self.top = node
def pop(self):
if self.top:
node = self.top
self.top = node.next
return node.value
raise exception('Stack is empty.')
def is_empty(self):
return bool(self.top)
def see_top(self):
if self.top:
return self.top.value
raise exception('Stack is empty.')
def size(self):
node = self.top
count = 0
while node:
count += 1
node = node.next
return count
class Stacklist(list):
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if self.items:
return self.items.pop()
raise exception('Stack is empty.')
def see_top(self):
if self.items:
return self.items[-1]
raise exception('Stack is empty.')
def size(self):
return len(self.items)
def is_empty(self):
return bool(self.items)
def main():
s1 = stack_list()
print(s1.isEmpty())
for i in range(1, 10):
s1.push(i)
print(s1.isEmpty())
print(s1.size())
print(s1.seeTop())
s1.pop()
print(s1.size())
print(s1.seeTop())
s2 = stack()
print(s2.isEmpty())
for i in range(1, 10):
s2.push(i)
print(s2.isEmpty())
print(s2.size())
print(s2.seeTop())
s2.pop()
print(s2.size())
print(s2.seeTop())
if __name__ == '__main__':
main() |
# coding: utf-8
def naive_square_matrix_product(A, B):
""" Implementation of naive squre matrix multiplication algorithm """
n = len(A)
C = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C
def print_mx(matrix):
""" pretty print of matrix """
for line in matrix:
print("\t".join(map(str, line)))
def subtract(A, B):
return [[x - y for x, y in zip(a, b)] for a, b in zip(A, B)]
def add(A, B):
return [[x + y for x, y in zip(a, b)] for a, b in zip(A, B)]
def strassen_square_matrix_product(A, B, leaf_size=64):
""" Implementation of the strassen algorithm for square matrixes"""
n = len(A)
# leaf size determine
# the size of matrix when we start using naive square matrix product
if n <= leaf_size:
return naive_square_matrix_product(A, B)
# initializing the new sub-matrices
new_size = n // 2
a11 = list(map(lambda x: x[:new_size], A[:new_size])) # top left
a12 = list(map(lambda x: x[new_size:], A[:new_size])) # top right
a21 = list(map(lambda x: x[:new_size], A[new_size:])) # bottom left
a22 = list(map(lambda x: x[new_size:], A[new_size:])) # bottom right
b11 = list(map(lambda x: x[:new_size], B[:new_size])) # top left
b12 = list(map(lambda x: x[new_size:], B[:new_size])) # top right
b21 = list(map(lambda x: x[:new_size], B[new_size:])) # bottom left
b22 = list(map(lambda x: x[new_size:], B[new_size:])) # bottom right
# Calculating p1 to p7:
# p1 = (a11) * (b12 - b22)
p1 = strassen_square_matrix_product(a11, subtract(b12, b22))
# p2 = (a11 + a12) * (b22)
p2 = strassen_square_matrix_product(add(a11, a12), b22)
# p3 = (a21 + a22) * (b11)
p3 = strassen_square_matrix_product(add(a21, a22), b11)
# p4 = (a22) * (b21 - b11)
p4 = strassen_square_matrix_product(a22, subtract(b21, b11))
# p5 = (a11 + a22) * (b11 + b22)
p5 = strassen_square_matrix_product(add(a11, a22), add(b11, b22))
# p6 = (a12 - a22) * (b21 + b22)
p6 = strassen_square_matrix_product(subtract(a12, a22), add(b21, b22))
# p7 = (a11 - a21) * (b11 + b12)
p7 = strassen_square_matrix_product(subtract(a11, a21), add(b11, b12))
# calculating c11 to c22:
# c11 = p5 + p4 - p2 + p6
c11 = add(subtract(add(p5, p4), p2), p6)
# c12 = p1 + p2
c12 = add(p1, p2)
# c21 = p3 + p4
c21 = add(p3, p4)
# c22 = p5 + p1 - p3 - p7
c22 = subtract(subtract(add(p5, p1), p3), p7)
cl = c11 + c21
cr = c12 + c22
return [cl[i] + cr[i] for i in range(len(cl))]
if __name__ in "__main__":
a = [[1, 2, 7, 0], [2, 3, 4, 2], [4, 5, 1, 0], [2, 6, 3, 8]]
b = [[4, 5, 6, 1], [7, 6, 8, 0], [1, 0, 3, 6], [7, 4, 7, 5]]
print('A:')
print_mx(a)
print('B:')
print_mx(b)
naive = naive_square_matrix_product(a, b)
print('naive algorithm')
print_mx(naive)
print('Strassen algorithm')
strassen = strassen_square_matrix_product(a, b)
print_mx(strassen)
| def naive_square_matrix_product(A, B):
""" Implementation of naive squre matrix multiplication algorithm """
n = len(A)
c = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C
def print_mx(matrix):
""" pretty print of matrix """
for line in matrix:
print('\t'.join(map(str, line)))
def subtract(A, B):
return [[x - y for (x, y) in zip(a, b)] for (a, b) in zip(A, B)]
def add(A, B):
return [[x + y for (x, y) in zip(a, b)] for (a, b) in zip(A, B)]
def strassen_square_matrix_product(A, B, leaf_size=64):
""" Implementation of the strassen algorithm for square matrixes"""
n = len(A)
if n <= leaf_size:
return naive_square_matrix_product(A, B)
new_size = n // 2
a11 = list(map(lambda x: x[:new_size], A[:new_size]))
a12 = list(map(lambda x: x[new_size:], A[:new_size]))
a21 = list(map(lambda x: x[:new_size], A[new_size:]))
a22 = list(map(lambda x: x[new_size:], A[new_size:]))
b11 = list(map(lambda x: x[:new_size], B[:new_size]))
b12 = list(map(lambda x: x[new_size:], B[:new_size]))
b21 = list(map(lambda x: x[:new_size], B[new_size:]))
b22 = list(map(lambda x: x[new_size:], B[new_size:]))
p1 = strassen_square_matrix_product(a11, subtract(b12, b22))
p2 = strassen_square_matrix_product(add(a11, a12), b22)
p3 = strassen_square_matrix_product(add(a21, a22), b11)
p4 = strassen_square_matrix_product(a22, subtract(b21, b11))
p5 = strassen_square_matrix_product(add(a11, a22), add(b11, b22))
p6 = strassen_square_matrix_product(subtract(a12, a22), add(b21, b22))
p7 = strassen_square_matrix_product(subtract(a11, a21), add(b11, b12))
c11 = add(subtract(add(p5, p4), p2), p6)
c12 = add(p1, p2)
c21 = add(p3, p4)
c22 = subtract(subtract(add(p5, p1), p3), p7)
cl = c11 + c21
cr = c12 + c22
return [cl[i] + cr[i] for i in range(len(cl))]
if __name__ in '__main__':
a = [[1, 2, 7, 0], [2, 3, 4, 2], [4, 5, 1, 0], [2, 6, 3, 8]]
b = [[4, 5, 6, 1], [7, 6, 8, 0], [1, 0, 3, 6], [7, 4, 7, 5]]
print('A:')
print_mx(a)
print('B:')
print_mx(b)
naive = naive_square_matrix_product(a, b)
print('naive algorithm')
print_mx(naive)
print('Strassen algorithm')
strassen = strassen_square_matrix_product(a, b)
print_mx(strassen) |
def lmap(f, it):
return list(map(f, it))
def ints(it):
return lmap(int, it)
def solve(input):
l = len(input.split()[0])
xs = lmap(lambda x: int(x, 2), input.split())
a = 0
for i in range(l):
cnt = [0, 0]
for x in xs:
cnt[(x >> i) & 1] += 1
if cnt[1] > cnt[0]:
a |= 1 << i
return a * (~a & ((1 << l) - 1))
| def lmap(f, it):
return list(map(f, it))
def ints(it):
return lmap(int, it)
def solve(input):
l = len(input.split()[0])
xs = lmap(lambda x: int(x, 2), input.split())
a = 0
for i in range(l):
cnt = [0, 0]
for x in xs:
cnt[x >> i & 1] += 1
if cnt[1] > cnt[0]:
a |= 1 << i
return a * (~a & (1 << l) - 1) |
#!/usr/bin/env python3
#
# Author:
# Tamas Jos (@skelsec)
#
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
PROCESS_VM_WRITE = 0x0020
PROCESS_VM_OPERATION = 0x0008
PROCESS_CREATE_THREAD = 0x0002
# Standard access rights
DELETE = 0x00010000
READ_CONTROL = 0x00020000
WRITE_DAC = 0x00040000
WRITE_OWNER = 0x00080000
SYNCHRONIZE = 0x00100000
STANDARD_RIGHTS_REQUIRED = 0x000F0000
STANDARD_RIGHTS_READ = READ_CONTROL
STANDARD_RIGHTS_WRITE = READ_CONTROL
STANDARD_RIGHTS_EXECUTE = READ_CONTROL
STANDARD_RIGHTS_ALL = 0x001F0000
SPECIFIC_RIGHTS_ALL = 0x0000FFFF
#--- Constants ----------------------------------------------------------------
privnames = {
"SE_ASSIGNPRIMARYTOKEN_NAME" : "SeAssignPrimaryTokenPrivilege",
"SE_AUDIT_NAME" : "SeAuditPrivilege",
"SE_BACKUP_NAME" : "SeBackupPrivilege",
"SE_CHANGE_NOTIFY_NAME" : "SeChangeNotifyPrivilege",
"SE_CREATE_GLOBAL_NAME" : "SeCreateGlobalPrivilege",
"SE_CREATE_PAGEFILE_NAME" : "SeCreatePagefilePrivilege",
"SE_CREATE_PERMANENT_NAME" : "SeCreatePermanentPrivilege",
"SE_CREATE_SYMBOLIC_LINK_NAME" : "SeCreateSymbolicLinkPrivilege",
"SE_CREATE_TOKEN_NAME" : "SeCreateTokenPrivilege",
"SE_DEBUG_NAME" : "SeDebugPrivilege",
"SE_ENABLE_DELEGATION_NAME" : "SeEnableDelegationPrivilege",
"SE_IMPERSONATE_NAME" : "SeImpersonatePrivilege",
"SE_INC_BASE_PRIORITY_NAME" : "SeIncreaseBasePriorityPrivilege",
"SE_INCREASE_QUOTA_NAME" : "SeIncreaseQuotaPrivilege",
"SE_INC_WORKING_SET_NAME" : "SeIncreaseWorkingSetPrivilege",
"SE_LOAD_DRIVER_NAME" : "SeLoadDriverPrivilege",
"SE_LOCK_MEMORY_NAME" : "SeLockMemoryPrivilege",
"SE_MACHINE_ACCOUNT_NAME" : "SeMachineAccountPrivilege",
"SE_MANAGE_VOLUME_NAME" : "SeManageVolumePrivilege",
"SE_PROF_SINGLE_PROCESS_NAME" : "SeProfileSingleProcessPrivilege",
"SE_RELABEL_NAME" : "SeRelabelPrivilege",
"SE_REMOTE_SHUTDOWN_NAME" : "SeRemoteShutdownPrivilege",
"SE_RESTORE_NAME" : "SeRestorePrivilege",
"SE_SECURITY_NAME" : "SeSecurityPrivilege",
"SE_SHUTDOWN_NAME" : "SeShutdownPrivilege",
"SE_SYNC_AGENT_NAME" : "SeSyncAgentPrivilege",
"SE_SYSTEM_ENVIRONMENT_NAME" : "SeSystemEnvironmentPrivilege",
"SE_SYSTEM_PROFILE_NAME" : "SeSystemProfilePrivilege",
"SE_SYSTEMTIME_NAME" : "SeSystemtimePrivilege",
"SE_TAKE_OWNERSHIP_NAME" : "SeTakeOwnershipPrivilege",
"SE_TCB_NAME" : "SeTcbPrivilege",
"SE_TIME_ZONE_NAME" : "SeTimeZonePrivilege",
"SE_TRUSTED_CREDMAN_ACCESS_NAME" : "SeTrustedCredManAccessPrivilege",
"SE_UNDOCK_NAME" : "SeUndockPrivilege",
"SE_UNSOLICITED_INPUT_NAME" : "SeUnsolicitedInputPrivilege"
}
# Privilege constants
SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"
SE_AUDIT_NAME = "SeAuditPrivilege"
SE_BACKUP_NAME = "SeBackupPrivilege"
SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege"
SE_CREATE_GLOBAL_NAME = "SeCreateGlobalPrivilege"
SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege"
SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege"
SE_CREATE_SYMBOLIC_LINK_NAME = "SeCreateSymbolicLinkPrivilege"
SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege"
SE_DEBUG_NAME = "SeDebugPrivilege"
SE_ENABLE_DELEGATION_NAME = "SeEnableDelegationPrivilege"
SE_IMPERSONATE_NAME = "SeImpersonatePrivilege"
SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege"
SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"
SE_INC_WORKING_SET_NAME = "SeIncreaseWorkingSetPrivilege"
SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege"
SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege"
SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege"
SE_MANAGE_VOLUME_NAME = "SeManageVolumePrivilege"
SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege"
SE_RELABEL_NAME = "SeRelabelPrivilege"
SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege"
SE_RESTORE_NAME = "SeRestorePrivilege"
SE_SECURITY_NAME = "SeSecurityPrivilege"
SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
SE_SYNC_AGENT_NAME = "SeSyncAgentPrivilege"
SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege"
SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege"
SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege"
SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege"
SE_TCB_NAME = "SeTcbPrivilege"
SE_TIME_ZONE_NAME = "SeTimeZonePrivilege"
SE_TRUSTED_CREDMAN_ACCESS_NAME = "SeTrustedCredManAccessPrivilege"
SE_UNDOCK_NAME = "SeUndockPrivilege"
SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege"
SE_CREATE_TOKEN = 2
SE_ASSIGNPRIMARYTOKEN = 3
SE_LOCK_MEMORY=4
SE_INCREASE_QUOTA=5
SE_UNSOLICITED_INPUT=6
SE_TCB=7
SE_SECURITY=8
SE_TAKE_OWNERSHIP=9
SE_LOAD_DRIVER=10
SE_SYSTEM_PROFILE=11
SE_SYSTEMTIME=12
SE_PROF_SINGLE_PROCESS=13
SE_INC_BASE_PRIORITY=14
SE_CREATE_PAGEFILE=15
SE_CREATE_PERMANENT=16
SE_BACKUP=17
SE_RESTORE=18
SE_SHUTDOWN=19
SE_DEBUG=20
SE_AUDIT=21
SE_SYSTEM_ENVIRONMENT=22
SE_CHANGE_NOTIFY=23
SE_REMOTE_SHUTDOWN=24
SE_UNDOCK=25
SE_SYNC_AGENT=26
SE_ENABLE_DELEGATION=27
SE_MANAGE_VOLUME=28
SE_IMPERSONATE=29
SE_CREATE_GLOBAL=30
SE_TRUSTED_CREDMAN_ACCESS=31
SE_RELABEL=32
SE_INC_WORKING_SET=33
SE_TIME_ZONE=34
SE_CREATE_SYMBOLIC_LINK=35
SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001
SE_PRIVILEGE_ENABLED = 0x00000002
SE_PRIVILEGE_REMOVED = 0x00000004
SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000
TOKEN_ADJUST_PRIVILEGES = 0x00000020
LOGON_WITH_PROFILE = 0x00000001
LOGON_NETCREDENTIALS_ONLY = 0x00000002
# Token access rights
TOKEN_ASSIGN_PRIMARY = 0x0001
TOKEN_DUPLICATE = 0x0002
TOKEN_IMPERSONATE = 0x0004
TOKEN_QUERY = 0x0008
TOKEN_QUERY_SOURCE = 0x0010
TOKEN_ADJUST_PRIVILEGES = 0x0020
TOKEN_ADJUST_GROUPS = 0x0040
TOKEN_ADJUST_DEFAULT = 0x0080
TOKEN_ADJUST_SESSIONID = 0x0100
TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY)
TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID)
#dont ask me...
TOKEN_MANIP_ACCESS = (TOKEN_QUERY | TOKEN_READ | TOKEN_IMPERSONATE | TOKEN_QUERY_SOURCE | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | (131072 | 4))
# typedef enum _SECURITY_IMPERSONATION_LEVEL {
# SecurityAnonymous,
# SecurityIdentification,
# SecurityImpersonation,
# SecurityDelegation
# } SECURITY_IMPERSONATION_LEVEL, *PSECURITY_IMPERSONATION_LEVEL;
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
TokenPrimary = 1
TokenImpersonation = 2
# Predefined HKEY values
HKEY_CLASSES_ROOT = 0x80000000
HKEY_CURRENT_USER = 0x80000001
HKEY_LOCAL_MACHINE = 0x80000002
HKEY_USERS = 0x80000003
HKEY_PERFORMANCE_DATA = 0x80000004
HKEY_CURRENT_CONFIG = 0x80000005
# Registry access rights
KEY_ALL_ACCESS = 0xF003F
KEY_CREATE_LINK = 0x0020
KEY_CREATE_SUB_KEY = 0x0004
KEY_ENUMERATE_SUB_KEYS = 0x0008
KEY_EXECUTE = 0x20019
KEY_NOTIFY = 0x0010
KEY_QUERY_VALUE = 0x0001
KEY_READ = 0x20019
KEY_SET_VALUE = 0x0002
KEY_WOW64_32KEY = 0x0200
KEY_WOW64_64KEY = 0x0100
KEY_WRITE = 0x20006
# Registry value types
REG_NONE = 0
REG_SZ = 1
REG_EXPAND_SZ = 2
REG_BINARY = 3
REG_DWORD = 4
REG_DWORD_LITTLE_ENDIAN = REG_DWORD
REG_DWORD_BIG_ENDIAN = 5
REG_LINK = 6
REG_MULTI_SZ = 7
REG_RESOURCE_LIST = 8
REG_FULL_RESOURCE_DESCRIPTOR = 9
REG_RESOURCE_REQUIREMENTS_LIST = 10
REG_QWORD = 11
REG_QWORD_LITTLE_ENDIAN = REG_QWORD | process_query_information = 1024
process_vm_read = 16
process_vm_write = 32
process_vm_operation = 8
process_create_thread = 2
delete = 65536
read_control = 131072
write_dac = 262144
write_owner = 524288
synchronize = 1048576
standard_rights_required = 983040
standard_rights_read = READ_CONTROL
standard_rights_write = READ_CONTROL
standard_rights_execute = READ_CONTROL
standard_rights_all = 2031616
specific_rights_all = 65535
privnames = {'SE_ASSIGNPRIMARYTOKEN_NAME': 'SeAssignPrimaryTokenPrivilege', 'SE_AUDIT_NAME': 'SeAuditPrivilege', 'SE_BACKUP_NAME': 'SeBackupPrivilege', 'SE_CHANGE_NOTIFY_NAME': 'SeChangeNotifyPrivilege', 'SE_CREATE_GLOBAL_NAME': 'SeCreateGlobalPrivilege', 'SE_CREATE_PAGEFILE_NAME': 'SeCreatePagefilePrivilege', 'SE_CREATE_PERMANENT_NAME': 'SeCreatePermanentPrivilege', 'SE_CREATE_SYMBOLIC_LINK_NAME': 'SeCreateSymbolicLinkPrivilege', 'SE_CREATE_TOKEN_NAME': 'SeCreateTokenPrivilege', 'SE_DEBUG_NAME': 'SeDebugPrivilege', 'SE_ENABLE_DELEGATION_NAME': 'SeEnableDelegationPrivilege', 'SE_IMPERSONATE_NAME': 'SeImpersonatePrivilege', 'SE_INC_BASE_PRIORITY_NAME': 'SeIncreaseBasePriorityPrivilege', 'SE_INCREASE_QUOTA_NAME': 'SeIncreaseQuotaPrivilege', 'SE_INC_WORKING_SET_NAME': 'SeIncreaseWorkingSetPrivilege', 'SE_LOAD_DRIVER_NAME': 'SeLoadDriverPrivilege', 'SE_LOCK_MEMORY_NAME': 'SeLockMemoryPrivilege', 'SE_MACHINE_ACCOUNT_NAME': 'SeMachineAccountPrivilege', 'SE_MANAGE_VOLUME_NAME': 'SeManageVolumePrivilege', 'SE_PROF_SINGLE_PROCESS_NAME': 'SeProfileSingleProcessPrivilege', 'SE_RELABEL_NAME': 'SeRelabelPrivilege', 'SE_REMOTE_SHUTDOWN_NAME': 'SeRemoteShutdownPrivilege', 'SE_RESTORE_NAME': 'SeRestorePrivilege', 'SE_SECURITY_NAME': 'SeSecurityPrivilege', 'SE_SHUTDOWN_NAME': 'SeShutdownPrivilege', 'SE_SYNC_AGENT_NAME': 'SeSyncAgentPrivilege', 'SE_SYSTEM_ENVIRONMENT_NAME': 'SeSystemEnvironmentPrivilege', 'SE_SYSTEM_PROFILE_NAME': 'SeSystemProfilePrivilege', 'SE_SYSTEMTIME_NAME': 'SeSystemtimePrivilege', 'SE_TAKE_OWNERSHIP_NAME': 'SeTakeOwnershipPrivilege', 'SE_TCB_NAME': 'SeTcbPrivilege', 'SE_TIME_ZONE_NAME': 'SeTimeZonePrivilege', 'SE_TRUSTED_CREDMAN_ACCESS_NAME': 'SeTrustedCredManAccessPrivilege', 'SE_UNDOCK_NAME': 'SeUndockPrivilege', 'SE_UNSOLICITED_INPUT_NAME': 'SeUnsolicitedInputPrivilege'}
se_assignprimarytoken_name = 'SeAssignPrimaryTokenPrivilege'
se_audit_name = 'SeAuditPrivilege'
se_backup_name = 'SeBackupPrivilege'
se_change_notify_name = 'SeChangeNotifyPrivilege'
se_create_global_name = 'SeCreateGlobalPrivilege'
se_create_pagefile_name = 'SeCreatePagefilePrivilege'
se_create_permanent_name = 'SeCreatePermanentPrivilege'
se_create_symbolic_link_name = 'SeCreateSymbolicLinkPrivilege'
se_create_token_name = 'SeCreateTokenPrivilege'
se_debug_name = 'SeDebugPrivilege'
se_enable_delegation_name = 'SeEnableDelegationPrivilege'
se_impersonate_name = 'SeImpersonatePrivilege'
se_inc_base_priority_name = 'SeIncreaseBasePriorityPrivilege'
se_increase_quota_name = 'SeIncreaseQuotaPrivilege'
se_inc_working_set_name = 'SeIncreaseWorkingSetPrivilege'
se_load_driver_name = 'SeLoadDriverPrivilege'
se_lock_memory_name = 'SeLockMemoryPrivilege'
se_machine_account_name = 'SeMachineAccountPrivilege'
se_manage_volume_name = 'SeManageVolumePrivilege'
se_prof_single_process_name = 'SeProfileSingleProcessPrivilege'
se_relabel_name = 'SeRelabelPrivilege'
se_remote_shutdown_name = 'SeRemoteShutdownPrivilege'
se_restore_name = 'SeRestorePrivilege'
se_security_name = 'SeSecurityPrivilege'
se_shutdown_name = 'SeShutdownPrivilege'
se_sync_agent_name = 'SeSyncAgentPrivilege'
se_system_environment_name = 'SeSystemEnvironmentPrivilege'
se_system_profile_name = 'SeSystemProfilePrivilege'
se_systemtime_name = 'SeSystemtimePrivilege'
se_take_ownership_name = 'SeTakeOwnershipPrivilege'
se_tcb_name = 'SeTcbPrivilege'
se_time_zone_name = 'SeTimeZonePrivilege'
se_trusted_credman_access_name = 'SeTrustedCredManAccessPrivilege'
se_undock_name = 'SeUndockPrivilege'
se_unsolicited_input_name = 'SeUnsolicitedInputPrivilege'
se_create_token = 2
se_assignprimarytoken = 3
se_lock_memory = 4
se_increase_quota = 5
se_unsolicited_input = 6
se_tcb = 7
se_security = 8
se_take_ownership = 9
se_load_driver = 10
se_system_profile = 11
se_systemtime = 12
se_prof_single_process = 13
se_inc_base_priority = 14
se_create_pagefile = 15
se_create_permanent = 16
se_backup = 17
se_restore = 18
se_shutdown = 19
se_debug = 20
se_audit = 21
se_system_environment = 22
se_change_notify = 23
se_remote_shutdown = 24
se_undock = 25
se_sync_agent = 26
se_enable_delegation = 27
se_manage_volume = 28
se_impersonate = 29
se_create_global = 30
se_trusted_credman_access = 31
se_relabel = 32
se_inc_working_set = 33
se_time_zone = 34
se_create_symbolic_link = 35
se_privilege_enabled_by_default = 1
se_privilege_enabled = 2
se_privilege_removed = 4
se_privilege_used_for_access = 2147483648
token_adjust_privileges = 32
logon_with_profile = 1
logon_netcredentials_only = 2
token_assign_primary = 1
token_duplicate = 2
token_impersonate = 4
token_query = 8
token_query_source = 16
token_adjust_privileges = 32
token_adjust_groups = 64
token_adjust_default = 128
token_adjust_sessionid = 256
token_read = STANDARD_RIGHTS_READ | TOKEN_QUERY
token_all_access = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID
token_manip_access = TOKEN_QUERY | TOKEN_READ | TOKEN_IMPERSONATE | TOKEN_QUERY_SOURCE | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | (131072 | 4)
security_anonymous = 0
security_identification = 1
security_impersonation = 2
security_delegation = 3
token_primary = 1
token_impersonation = 2
hkey_classes_root = 2147483648
hkey_current_user = 2147483649
hkey_local_machine = 2147483650
hkey_users = 2147483651
hkey_performance_data = 2147483652
hkey_current_config = 2147483653
key_all_access = 983103
key_create_link = 32
key_create_sub_key = 4
key_enumerate_sub_keys = 8
key_execute = 131097
key_notify = 16
key_query_value = 1
key_read = 131097
key_set_value = 2
key_wow64_32_key = 512
key_wow64_64_key = 256
key_write = 131078
reg_none = 0
reg_sz = 1
reg_expand_sz = 2
reg_binary = 3
reg_dword = 4
reg_dword_little_endian = REG_DWORD
reg_dword_big_endian = 5
reg_link = 6
reg_multi_sz = 7
reg_resource_list = 8
reg_full_resource_descriptor = 9
reg_resource_requirements_list = 10
reg_qword = 11
reg_qword_little_endian = REG_QWORD |
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
d = collections.defaultdict(int)
for c in s:
d[c] += 1
l = [[-d[key],key] for key in d]
l.sort()
# print l
res = ''.join([(-n)*c for n,c in l])
return res | class Solution(object):
def frequency_sort(self, s):
"""
:type s: str
:rtype: str
"""
d = collections.defaultdict(int)
for c in s:
d[c] += 1
l = [[-d[key], key] for key in d]
l.sort()
res = ''.join([-n * c for (n, c) in l])
return res |
class Helper:
@staticmethod
def is_Empty(obj):
flag = False
if obj is None:
flag = True
elif not obj.strip():
flag = True
else:
flag = False
return flag
if __name__ == '__main__':
print(Helper.is_Empty(None))
| class Helper:
@staticmethod
def is__empty(obj):
flag = False
if obj is None:
flag = True
elif not obj.strip():
flag = True
else:
flag = False
return flag
if __name__ == '__main__':
print(Helper.is_Empty(None)) |
'''
Lambda expressions are quick way of creating the anonymous functions:
'''
#function without lamda expression:
def square(num):
return num ** 2
print(square(5))
#converting it into lambda expression:
lambda num : num ** 2
#if we want we can assign this to variable like
square2 = lambda num : num ** 2. # we are not going to use this very often, cause lamda function are anonymous
print(square2(5))
print(list(map(lambda num : num **2, [1,2,3,4])))
'''
Map: map() --> map(func, *iterables) --> map object
'''
def square(num):
return num ** 2
my_nums = [1,2,3,4,5]
#if I wanna get sqaure for all the list items, we can use map function, instead of for loop, for loop is costly
#Method 1:
for item in map(square, my_nums):
print(item)
#method 2:
list(map(square, my_nums))
def splicer(mystring):
if len(mystring) % 2 == 0:
return 'EVEN'
else:
return mystring[0]
names = ['andy', 'sally', 'eve']
print(list(map(splicer, names)))
'''
Filter: iterate function that returns either true or false
'''
def check_even(num):
return num % 2 == 0
my_numbers = [1,2,3,4,5,6]
print(list(filter(check_even, my_numbers))) | """
Lambda expressions are quick way of creating the anonymous functions:
"""
def square(num):
return num ** 2
print(square(5))
lambda num: num ** 2
square2 = lambda num: num ** 2.0
print(square2(5))
print(list(map(lambda num: num ** 2, [1, 2, 3, 4])))
'\nMap: map() --> map(func, *iterables) --> map object\n'
def square(num):
return num ** 2
my_nums = [1, 2, 3, 4, 5]
for item in map(square, my_nums):
print(item)
list(map(square, my_nums))
def splicer(mystring):
if len(mystring) % 2 == 0:
return 'EVEN'
else:
return mystring[0]
names = ['andy', 'sally', 'eve']
print(list(map(splicer, names)))
'\nFilter: iterate function that returns either true or false\n'
def check_even(num):
return num % 2 == 0
my_numbers = [1, 2, 3, 4, 5, 6]
print(list(filter(check_even, my_numbers))) |
# Builds the Netty fork of Tomcat Native. See http://netty.io/wiki/forked-tomcat-native.html
{
'targets': [
{
'target_name': 'netty-tcnative-so',
'product_name': 'netty-tcnative',
'type': 'shared_library',
'sources': [
'src/c/address.c',
'src/c/bb.c',
'src/c/dir.c',
'src/c/error.c',
'src/c/file.c',
'src/c/info.c',
'src/c/jnilib.c',
'src/c/lock.c',
'src/c/misc.c',
'src/c/mmap.c',
'src/c/multicast.c',
'src/c/network.c',
'src/c/os.c',
'src/c/os_unix_system.c',
'src/c/os_unix_uxpipe.c',
'src/c/poll.c',
'src/c/pool.c',
'src/c/proc.c',
'src/c/shm.c',
'src/c/ssl.c',
'src/c/sslcontext.c',
'src/c/sslinfo.c',
'src/c/sslnetwork.c',
'src/c/ssl_private.h',
'src/c/sslutils.c',
'src/c/stdlib.c',
'src/c/tcn_api.h',
'src/c/tcn.h',
'src/c/tcn_version.h',
'src/c/thread.c',
'src/c/user.c',
],
'include_dirs': [
'../apache-portable-runtime/src/include',
],
'defines': [
'HAVE_OPENSSL',
],
'cflags': [
'-w',
],
'dependencies': [
'../apache-portable-runtime/apr.gyp:apr',
'../boringssl/boringssl.gyp:boringssl',
],
'variables': {
'use_native_jni_exports': 1,
},
},
{
'target_name': 'netty-tcnative',
'type': 'none',
'variables': {
'java_in_dir': 'src/java',
'javac_includes': [ '**/org/apache/tomcat/jni/*.java' ],
'run_findbugs': 0,
},
'includes': [ '../../build/java.gypi' ],
'dependencies': [
'netty-tcnative-so',
'rename_netty_tcnative_so_file',
],
'export_dependent_settings': [
'rename_netty_tcnative_so_file',
],
},
{
# libnetty-tcnative shared library should have a specific name when
# it is copied to the test APK. This target renames (actually makes
# a copy of) the 'so' file if it has a different name.
'target_name': 'rename_netty_tcnative_so_file',
'type': 'none',
'conditions': [
['component=="shared_library"', {
'actions': [
{
'action_name': 'copy',
'inputs': ['<(PRODUCT_DIR)/lib/libnetty-tcnative.cr.so'],
'outputs': ['<(PRODUCT_DIR)/lib/libnetty-tcnative.so'],
'action': [
'cp',
'<@(_inputs)',
'<@(_outputs)',
],
}],
}],
],
'dependencies': [
'netty-tcnative-so',
],
'direct_dependent_settings': {
'variables': {
'netty_tcnative_so_file_location': '<(PRODUCT_DIR)/lib/libnetty-tcnative.so',
},
},
},
],
} | {'targets': [{'target_name': 'netty-tcnative-so', 'product_name': 'netty-tcnative', 'type': 'shared_library', 'sources': ['src/c/address.c', 'src/c/bb.c', 'src/c/dir.c', 'src/c/error.c', 'src/c/file.c', 'src/c/info.c', 'src/c/jnilib.c', 'src/c/lock.c', 'src/c/misc.c', 'src/c/mmap.c', 'src/c/multicast.c', 'src/c/network.c', 'src/c/os.c', 'src/c/os_unix_system.c', 'src/c/os_unix_uxpipe.c', 'src/c/poll.c', 'src/c/pool.c', 'src/c/proc.c', 'src/c/shm.c', 'src/c/ssl.c', 'src/c/sslcontext.c', 'src/c/sslinfo.c', 'src/c/sslnetwork.c', 'src/c/ssl_private.h', 'src/c/sslutils.c', 'src/c/stdlib.c', 'src/c/tcn_api.h', 'src/c/tcn.h', 'src/c/tcn_version.h', 'src/c/thread.c', 'src/c/user.c'], 'include_dirs': ['../apache-portable-runtime/src/include'], 'defines': ['HAVE_OPENSSL'], 'cflags': ['-w'], 'dependencies': ['../apache-portable-runtime/apr.gyp:apr', '../boringssl/boringssl.gyp:boringssl'], 'variables': {'use_native_jni_exports': 1}}, {'target_name': 'netty-tcnative', 'type': 'none', 'variables': {'java_in_dir': 'src/java', 'javac_includes': ['**/org/apache/tomcat/jni/*.java'], 'run_findbugs': 0}, 'includes': ['../../build/java.gypi'], 'dependencies': ['netty-tcnative-so', 'rename_netty_tcnative_so_file'], 'export_dependent_settings': ['rename_netty_tcnative_so_file']}, {'target_name': 'rename_netty_tcnative_so_file', 'type': 'none', 'conditions': [['component=="shared_library"', {'actions': [{'action_name': 'copy', 'inputs': ['<(PRODUCT_DIR)/lib/libnetty-tcnative.cr.so'], 'outputs': ['<(PRODUCT_DIR)/lib/libnetty-tcnative.so'], 'action': ['cp', '<@(_inputs)', '<@(_outputs)']}]}]], 'dependencies': ['netty-tcnative-so'], 'direct_dependent_settings': {'variables': {'netty_tcnative_so_file_location': '<(PRODUCT_DIR)/lib/libnetty-tcnative.so'}}}]} |
#!/usr/bin/python3
def set_dependencies(source_nodes):
"""Sets contract node dependencies.
Arguments:
source_nodes: list of SourceUnit objects.
Returns: SourceUnit objects where all ContractDefinition nodes contain
'dependencies' and 'libraries' attributes."""
symbol_map = get_symbol_map(source_nodes)
contract_list = [x for i in source_nodes for x in i if x.nodeType == "ContractDefinition"]
# add immediate dependencies
for contract in contract_list:
contract.dependencies = set()
contract.libraries = dict(
(_get_type_name(i.typeName), i.libraryName.name)
for i in contract.nodes
if i.nodeType == "UsingForDirective"
)
# listed dependencies
for key in contract.contractDependencies:
contract.dependencies.add(symbol_map[key])
# using .. for libraries
for node in contract.children(filters={"nodeType": "UsingForDirective"}):
ref_node = symbol_map[node.libraryName.referencedDeclaration]
contract.libraries[_get_type_name(node.typeName)] = ref_node
contract.dependencies.add(ref_node)
# imported contracts used as types in assignment
for node in contract.children(filters={"nodeType": "UserDefinedTypeName"}):
ref_id = node.referencedDeclaration
if ref_id in symbol_map:
contract.dependencies.add(symbol_map[ref_id])
# imported contracts as types, no assignment
for node in contract.children(
filters={"nodeType": "FunctionCall", "expression.nodeType": "Identifier"}
):
if node.typeDescriptions["typeString"].startswith("contract "):
ref_id = node.expression.referencedDeclaration
if ref_id in symbol_map:
contract.dependencies.add(symbol_map[ref_id])
# unlinked libraries
for node in contract.children(filters={"nodeType": "Identifier"}):
ref_node = symbol_map.get(node.referencedDeclaration)
if ref_node is None:
continue
if ref_node.nodeType in ("EnumDefinition", "StructDefinition"):
contract.dependencies.add(ref_node)
if ref_node.nodeType == "ContractDefinition" and ref_node.contractKind == "library":
contract.dependencies.add(ref_node)
# prevent recursion errors from self-dependency
contract.dependencies.discard(contract)
# add dependencies of dependencies
for contract in contract_list:
current_deps = contract.dependencies
while True:
expanded_deps = set(x for i in current_deps for x in getattr(i, "dependencies", []))
expanded_deps |= current_deps
expanded_deps.discard(contract)
if current_deps == expanded_deps:
break
current_deps = expanded_deps
current_deps |= {symbol_map[i] for i in contract.linearizedBaseContracts}
contract.dependencies = current_deps
# convert dependency sets to lists
for contract in contract_list:
if contract in contract.dependencies:
# a contract should not list itself as a dependency
contract.dependencies.remove(contract)
contract.dependencies = sorted(contract.dependencies, key=lambda k: k.name)
return source_nodes
def get_symbol_map(source_nodes):
"""Generates a dict of {'id': SourceUnit} used for linking nodes.
Arguments:
source_nodes: list of SourceUnit objects."""
symbol_map = {}
for node in source_nodes:
for key, value in ((k, x) for k, v in node.exportedSymbols.items() for x in v):
try:
symbol_map[value] = node[key]
except KeyError:
# solc >=0.7.2 may include exported symbols that reference
# other contracts, handle this gracefully
pass
return symbol_map
def _get_type_name(node):
if node is None:
return None
if hasattr(node, "name"):
return node.name
if hasattr(node, "typeDescriptions"):
return node.typeDescriptions["typeString"]
return None
| def set_dependencies(source_nodes):
"""Sets contract node dependencies.
Arguments:
source_nodes: list of SourceUnit objects.
Returns: SourceUnit objects where all ContractDefinition nodes contain
'dependencies' and 'libraries' attributes."""
symbol_map = get_symbol_map(source_nodes)
contract_list = [x for i in source_nodes for x in i if x.nodeType == 'ContractDefinition']
for contract in contract_list:
contract.dependencies = set()
contract.libraries = dict(((_get_type_name(i.typeName), i.libraryName.name) for i in contract.nodes if i.nodeType == 'UsingForDirective'))
for key in contract.contractDependencies:
contract.dependencies.add(symbol_map[key])
for node in contract.children(filters={'nodeType': 'UsingForDirective'}):
ref_node = symbol_map[node.libraryName.referencedDeclaration]
contract.libraries[_get_type_name(node.typeName)] = ref_node
contract.dependencies.add(ref_node)
for node in contract.children(filters={'nodeType': 'UserDefinedTypeName'}):
ref_id = node.referencedDeclaration
if ref_id in symbol_map:
contract.dependencies.add(symbol_map[ref_id])
for node in contract.children(filters={'nodeType': 'FunctionCall', 'expression.nodeType': 'Identifier'}):
if node.typeDescriptions['typeString'].startswith('contract '):
ref_id = node.expression.referencedDeclaration
if ref_id in symbol_map:
contract.dependencies.add(symbol_map[ref_id])
for node in contract.children(filters={'nodeType': 'Identifier'}):
ref_node = symbol_map.get(node.referencedDeclaration)
if ref_node is None:
continue
if ref_node.nodeType in ('EnumDefinition', 'StructDefinition'):
contract.dependencies.add(ref_node)
if ref_node.nodeType == 'ContractDefinition' and ref_node.contractKind == 'library':
contract.dependencies.add(ref_node)
contract.dependencies.discard(contract)
for contract in contract_list:
current_deps = contract.dependencies
while True:
expanded_deps = set((x for i in current_deps for x in getattr(i, 'dependencies', [])))
expanded_deps |= current_deps
expanded_deps.discard(contract)
if current_deps == expanded_deps:
break
current_deps = expanded_deps
current_deps |= {symbol_map[i] for i in contract.linearizedBaseContracts}
contract.dependencies = current_deps
for contract in contract_list:
if contract in contract.dependencies:
contract.dependencies.remove(contract)
contract.dependencies = sorted(contract.dependencies, key=lambda k: k.name)
return source_nodes
def get_symbol_map(source_nodes):
"""Generates a dict of {'id': SourceUnit} used for linking nodes.
Arguments:
source_nodes: list of SourceUnit objects."""
symbol_map = {}
for node in source_nodes:
for (key, value) in ((k, x) for (k, v) in node.exportedSymbols.items() for x in v):
try:
symbol_map[value] = node[key]
except KeyError:
pass
return symbol_map
def _get_type_name(node):
if node is None:
return None
if hasattr(node, 'name'):
return node.name
if hasattr(node, 'typeDescriptions'):
return node.typeDescriptions['typeString']
return None |
# https://www.acmicpc.net/problem/9020
if __name__ == '__main__':
input = __import__('sys').stdin.readline
N = 10_001
T = int(input())
is_prime = [True for _ in range(N)]
sqrt = int(N ** (1 / 2))
is_prime[0] = is_prime[1] = False
for idx in range(2, sqrt + 1):
if not is_prime[idx]:
continue
for num in range(idx + idx, N, idx):
is_prime[num] = False
for _ in range(T):
N = int(input())
for num in range(N // 2, -1, -1):
if is_prime[num] and is_prime[N - num]:
print(num, N - num)
break
| if __name__ == '__main__':
input = __import__('sys').stdin.readline
n = 10001
t = int(input())
is_prime = [True for _ in range(N)]
sqrt = int(N ** (1 / 2))
is_prime[0] = is_prime[1] = False
for idx in range(2, sqrt + 1):
if not is_prime[idx]:
continue
for num in range(idx + idx, N, idx):
is_prime[num] = False
for _ in range(T):
n = int(input())
for num in range(N // 2, -1, -1):
if is_prime[num] and is_prime[N - num]:
print(num, N - num)
break |
def bin_value(num):
return bin(num) [2:]
def remove0b(num):
return num [2:]
numberA = int(input(""))
numberB = int(input(""))
binaryA = bin_value(numberA)
binaryB = bin_value(numberB)
sum = bin(int(binaryA,2) + int(binaryB,2))
cleaned = remove0b(sum)
binaryA = str(binaryA)
binaryB = str(binaryB)
sum = str(cleaned)
answer = binaryA + " + " + binaryB + " = " + sum
print(answer)
| def bin_value(num):
return bin(num)[2:]
def remove0b(num):
return num[2:]
number_a = int(input(''))
number_b = int(input(''))
binary_a = bin_value(numberA)
binary_b = bin_value(numberB)
sum = bin(int(binaryA, 2) + int(binaryB, 2))
cleaned = remove0b(sum)
binary_a = str(binaryA)
binary_b = str(binaryB)
sum = str(cleaned)
answer = binaryA + ' + ' + binaryB + ' = ' + sum
print(answer) |
# HEAD
# Classes - Setters are shallow
# DESCRIPTION
# Describes how setting of inherited attributes and values function
# RESOURCES
#
# Creating Parent class
class Parent():
par_cent = "parent"
# Parent Init method
def __init__(self, val):
self.par_cent = val
print("Parent Instantiated with ", self.par_cent)
# Creating ParentTwo class
class Child(Parent):
# Child Init method
def __init__(self, val_two):
print("Child Instantiated with ", val_two)
# Explicit Instantiation of parent init
# Instantiate parent once and passing args
# Parent assigns value storing it in object to access
# Parent default value remains
self.p = super()
self.p.__init__(val_two)
obj = Child(10)
print("""
Value of par_cent is assigned &
fetched from Child class &
default refs of parent remains
""")
print("obj.par_cent", obj.par_cent)
print("obj.p.par_cent, id(obj.p), id(obj)", obj.p.par_cent, id(obj.p), id(obj))
| class Parent:
par_cent = 'parent'
def __init__(self, val):
self.par_cent = val
print('Parent Instantiated with ', self.par_cent)
class Child(Parent):
def __init__(self, val_two):
print('Child Instantiated with ', val_two)
self.p = super()
self.p.__init__(val_two)
obj = child(10)
print('\n Value of par_cent is assigned & \n fetched from Child class & \n default refs of parent remains\n')
print('obj.par_cent', obj.par_cent)
print('obj.p.par_cent, id(obj.p), id(obj)', obj.p.par_cent, id(obj.p), id(obj)) |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_31.py
@time: 2019/4/23 16:09
@desc:
'''
class Solution:
def FindGreatestSumOfSubArray(self, array):
if not array:
return 0
f = array
for i in range(1, len(array)):
if f[i-1] <= 0:
f[i] = array[i]
else:
f[i] = f[i-1] + array[i]
return max(f)
if __name__ == '__main__':
res = Solution()
array = [6,-3,-2,7,-15,1,2,2]
b = res.FindGreatestSumOfSubArray(array)
print(b)
| """
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_31.py
@time: 2019/4/23 16:09
@desc:
"""
class Solution:
def find_greatest_sum_of_sub_array(self, array):
if not array:
return 0
f = array
for i in range(1, len(array)):
if f[i - 1] <= 0:
f[i] = array[i]
else:
f[i] = f[i - 1] + array[i]
return max(f)
if __name__ == '__main__':
res = solution()
array = [6, -3, -2, 7, -15, 1, 2, 2]
b = res.FindGreatestSumOfSubArray(array)
print(b) |
def get_eig_Jacobian(pars, fp):
"""
Simulate the Wilson-Cowan equations
Args:
pars : Parameter dictionary
fp : fixed point (E, I), array
Returns:
evals : 2x1 vector of eigenvalues of the Jacobian matrix
"""
#get the parameters
tau_E, a_E, theta_E = pars['tau_E'], pars['a_E'], pars['theta_E']
tau_I, a_I, theta_I = pars['tau_I'], pars['a_I'], pars['theta_I']
wEE, wEI = pars['wEE'], pars['wEI']
wIE, wII = pars['wIE'], pars['wII']
I_ext_E, I_ext_I = pars['I_ext_E'], pars['I_ext_I']
#initialization
E = fp[0]
I = fp[1]
J = np.zeros((2,2))
#Jacobian matrix
J[0,0] = (-1 + wEE*dF(wEE*E-wEI*I+I_ext_E,a_E,theta_E))/tau_E #dGE_dE
J[0,1] = (-wEI*dF(wEE*E-wEI*I+I_ext_E,a_E,theta_E))/tau_E #dGE_dI
J[1,0] = (wIE*dF(wIE*E-wII*I+I_ext_I,a_I,theta_I))/tau_I #dGI_dE
J[1,1] = (-1 - wII*dF(wIE*E-wII*I,a_I+I_ext_I,theta_I))/tau_I #dGI_dI
# Eigenvalues
evals = np.linalg.eig(J)[0]
return evals
eig_1 = get_eig_Jacobian(pars, x_fp_1)
eig_2 = get_eig_Jacobian(pars, x_fp_2)
eig_3 = get_eig_Jacobian(pars, x_fp_3)
print(eig_1, 'Stable point')
print(eig_2, 'Unstable point')
print(eig_3, 'Stable point') | def get_eig__jacobian(pars, fp):
"""
Simulate the Wilson-Cowan equations
Args:
pars : Parameter dictionary
fp : fixed point (E, I), array
Returns:
evals : 2x1 vector of eigenvalues of the Jacobian matrix
"""
(tau_e, a_e, theta_e) = (pars['tau_E'], pars['a_E'], pars['theta_E'])
(tau_i, a_i, theta_i) = (pars['tau_I'], pars['a_I'], pars['theta_I'])
(w_ee, w_ei) = (pars['wEE'], pars['wEI'])
(w_ie, w_ii) = (pars['wIE'], pars['wII'])
(i_ext_e, i_ext_i) = (pars['I_ext_E'], pars['I_ext_I'])
e = fp[0]
i = fp[1]
j = np.zeros((2, 2))
J[0, 0] = (-1 + wEE * d_f(wEE * E - wEI * I + I_ext_E, a_E, theta_E)) / tau_E
J[0, 1] = -wEI * d_f(wEE * E - wEI * I + I_ext_E, a_E, theta_E) / tau_E
J[1, 0] = wIE * d_f(wIE * E - wII * I + I_ext_I, a_I, theta_I) / tau_I
J[1, 1] = (-1 - wII * d_f(wIE * E - wII * I, a_I + I_ext_I, theta_I)) / tau_I
evals = np.linalg.eig(J)[0]
return evals
eig_1 = get_eig__jacobian(pars, x_fp_1)
eig_2 = get_eig__jacobian(pars, x_fp_2)
eig_3 = get_eig__jacobian(pars, x_fp_3)
print(eig_1, 'Stable point')
print(eig_2, 'Unstable point')
print(eig_3, 'Stable point') |
k, n, w = map(int, input().split())
x = 1
money = 0
while x <= w and money != -1:
money += k * x
x += 1
money_toborrow = money - n
if money_toborrow >= 0:
print(money_toborrow)
else:
print(0) | (k, n, w) = map(int, input().split())
x = 1
money = 0
while x <= w and money != -1:
money += k * x
x += 1
money_toborrow = money - n
if money_toborrow >= 0:
print(money_toborrow)
else:
print(0) |
def fatorial (n):
r = 1
for num in range (n, 1, -1):
r *= num
return r
def dobro (n):
num = n * 2
return num
def triplo (n):
num = n * 3
return num | def fatorial(n):
r = 1
for num in range(n, 1, -1):
r *= num
return r
def dobro(n):
num = n * 2
return num
def triplo(n):
num = n * 3
return num |
#####################################Data class
class RealNews(object):
def __init__(self, date, headline, description,distype, url="", imageurl="",location=""):
self.date = date
self.headline = headline
self.description = description
self.url = url
self.distype = distype
self.imageurl = imageurl
self.location = location
@staticmethod
def from_dict(source):
self.date = source['date']
self.headline = source['headline']
self.description = source['description']
self.url = source['url']
self.distype = source['distype']
self.imageurl = source['imageurl']
self.location = source['location']
def to_dict(self):
return {
'date': self.date,
'headline' : self.headline,
'description' : self.description,
'url' : self.url,
'distype' : self.distype,
'imageurl' : self.imageurl,
'location' : self.location,
}
def __repr__(self):
return(f"News( date: {self.date}, headline : {self.headline}, description : {self.description}, url : {self.url}, distype : {self.distype}, imageurl : {self.imageurl}, location : {self.location})")
#####################################write Data
# date = input('Enter date: ')
# headline = input('Enter headlines: ')
# description = input('Enter description: ')
# distype = input('Enter disaster type: ')
# url = input('Enter url: ')
# imageurl = input('Enter image url: ')
# location = input('Enter location: ')
| class Realnews(object):
def __init__(self, date, headline, description, distype, url='', imageurl='', location=''):
self.date = date
self.headline = headline
self.description = description
self.url = url
self.distype = distype
self.imageurl = imageurl
self.location = location
@staticmethod
def from_dict(source):
self.date = source['date']
self.headline = source['headline']
self.description = source['description']
self.url = source['url']
self.distype = source['distype']
self.imageurl = source['imageurl']
self.location = source['location']
def to_dict(self):
return {'date': self.date, 'headline': self.headline, 'description': self.description, 'url': self.url, 'distype': self.distype, 'imageurl': self.imageurl, 'location': self.location}
def __repr__(self):
return f'News( date: {self.date}, headline : {self.headline}, description : {self.description}, url : {self.url}, distype : {self.distype}, imageurl : {self.imageurl}, location : {self.location})' |
bicicleta=["bike","cannon","cargo", "CALOI"]
#Armazenamento de farias mensagens/lista em uma string
print(bicicleta[0].title())
print(bicicleta[1])
print(bicicleta[2])
print(bicicleta[3])
print(bicicleta[-1])
print(bicicleta[-2])
print(bicicleta[-3])
print(bicicleta[-4].title())
#como imprimir uma mensagem especifica de uma strings que contem varias mensagens/listas
mensagem="Minha Primeira Bicicleta foi uma " + bicicleta[3].title() + "!"
print(mensagem)
| bicicleta = ['bike', 'cannon', 'cargo', 'CALOI']
print(bicicleta[0].title())
print(bicicleta[1])
print(bicicleta[2])
print(bicicleta[3])
print(bicicleta[-1])
print(bicicleta[-2])
print(bicicleta[-3])
print(bicicleta[-4].title())
mensagem = 'Minha Primeira Bicicleta foi uma ' + bicicleta[3].title() + '!'
print(mensagem) |
class Subtract:
def __init__(self,fnum,snum):
self.fnum=fnum
self.snum=snum
def allSub(self):
self.sub=self.fnum-self.snum
return self.sub | class Subtract:
def __init__(self, fnum, snum):
self.fnum = fnum
self.snum = snum
def all_sub(self):
self.sub = self.fnum - self.snum
return self.sub |
model = Sequential()
model.add(LSTM(50, return_sequences = True, input_shape = (x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences = False))
model.add(Dense(25))
model.add(Dense(1))
#Compiling the model
model.compile(optimizer = 'adam', loss = 'mean_squared_error')
#using rmse
| model = sequential()
model.add(lstm(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(lstm(50, return_sequences=False))
model.add(dense(25))
model.add(dense(1))
model.compile(optimizer='adam', loss='mean_squared_error') |
DEFAULT_REDIS_PORT = 6379
# Number of seconds to sleep upon successful end to allow graceful termination of subprocesses.
TERMINATION_TIME = 3
# Max caps on parameters
MAX_NUM_STEPS = 10000
MAX_OBSERVATION_DELTA = 5000
MAX_VIDEO_FPS = 60
| default_redis_port = 6379
termination_time = 3
max_num_steps = 10000
max_observation_delta = 5000
max_video_fps = 60 |
# -*- coding: utf-8 -*-
"""Utils for celery."""
def init_celery(celery, app):
celery.conf.update(app.config)
celery.conf.update(
task_serializer='json',
accept_content=['json'], # Ignore other content
result_serializer='json',
timezone='Europe/Berlin',
enable_utc=True
)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
| """Utils for celery."""
def init_celery(celery, app):
celery.conf.update(app.config)
celery.conf.update(task_serializer='json', accept_content=['json'], result_serializer='json', timezone='Europe/Berlin', enable_utc=True)
task_base = celery.Task
class Contexttask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask |
key = input().strip()
value = input().strip()
count = int(input())
result = ''
for entry in range(count):
keys, values = input().split(' => ')
if key in keys:
result += f'{keys}:\n'
if value in values:
all_values = '\n'.join([f'-{v}' for v in values.split(';') if value in v])
result += f'{all_values}\n'
print(result) | key = input().strip()
value = input().strip()
count = int(input())
result = ''
for entry in range(count):
(keys, values) = input().split(' => ')
if key in keys:
result += f'{keys}:\n'
if value in values:
all_values = '\n'.join([f'-{v}' for v in values.split(';') if value in v])
result += f'{all_values}\n'
print(result) |
"""
Written by Jesse Evers
Finds the factorial of a number.
"""
def factorial(num):
# While num > 1, multiply num by num - 1
if num > 1:
return num * factorial(num - 1)
return num
print(factorial(10)) | """
Written by Jesse Evers
Finds the factorial of a number.
"""
def factorial(num):
if num > 1:
return num * factorial(num - 1)
return num
print(factorial(10)) |
'''
Author : MiKueen
Level : Medium
Problem Statement : Product of Array Except Self
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
'''
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# Time Complexity - O(n)
# Space Complexity - O(1)
res = [1] * len(nums)
left = right = 1
for i in range(len(nums)):
j = -(i+1)
res[i] *= left
res[j] *= right
left *= nums[i]
right *= nums[j]
return res
| """
Author : MiKueen
Level : Medium
Problem Statement : Product of Array Except Self
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
"""
class Solution:
def product_except_self(self, nums: List[int]) -> List[int]:
res = [1] * len(nums)
left = right = 1
for i in range(len(nums)):
j = -(i + 1)
res[i] *= left
res[j] *= right
left *= nums[i]
right *= nums[j]
return res |
name = str(input())
salary = float(input())
sales = float(input())
total = salary + (sales * 0.15)
print(f'TOTAL = R$ {total:.2f}') | name = str(input())
salary = float(input())
sales = float(input())
total = salary + sales * 0.15
print(f'TOTAL = R$ {total:.2f}') |
class Parameters:
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 600
BASE_HEIGHT = 100
BASE_IMAGE = "base.png"
BACKGROUND_IMAGE = "bg.png"
BIRD_IMAGES = ["bird1.png", "bird2.png", "bird3.png"]
PIPE_IMAGES = ["pipe.png"]
| class Parameters:
window_width = 500
window_height = 600
base_height = 100
base_image = 'base.png'
background_image = 'bg.png'
bird_images = ['bird1.png', 'bird2.png', 'bird3.png']
pipe_images = ['pipe.png'] |
# It make a node
class node:
def __init__(self, symbol):
self.symbol = symbol
self.edges = []
self.shortest_distance = float('inf')
self.shortest_path_via = None
# Adds another node as a weighted edge
def add_edge(self, node, distance):
self.edges.append([node, distance])
# Checks every node it has an edge to, and updates it if neccessary
def update_edges(self):
for edge in self.edges:
distance_via = self.shortest_distance + edge[1]
if distance_via < edge[0].shortest_distance:
edge[0].shortest_distance = distance_via
edge[0].shortest_path_via = self
def get_node(nodes, symbol):
"""
Searches "nodes" for node with symbol "symbol" and returns it if found.
PARAMS:\n
nodes (array): array of nodes to search from
symbol (str): string to search matches for
RETURNS:\n
node: if match is found
None: if no match found
"""
for node in nodes:
if node.symbol == symbol:
return node
return None
def make_nodes(edge_data, *args):
"""
Takes an array of edges and makes them into node objects.
PARAMS:
edge_data (arr): array of edges with format [start_node (str), end_node (str), distance (int)]
*args (boolean): True if you want digraph, False if not (default is True) Can save time when entering edges by hand.
*args (array[str]): array of symbols to use for nodes that may not have edges and are not included in "edge_data"
RETURNS:
array: array of the nodes that it created
"""
nodes = []
# Decide if digraph or not
if len(args) > 0:
digraph = args[0]
else:
digraph = False
# Fill in empty nodes
if len(args) > 1:
for symbol in args[1]:
nodes.append(node(symbol))
# Make edges into nodes and couple them
for edge in edge_data:
node1 = get_node(nodes, edge[0])
node2 = get_node(nodes, edge[1])
if node1 == None:
node1 = node(edge[0])
if node2 == None:
node2 = node(edge[1])
node1.add_edge(node2, edge[2])
if not digraph: node2.add_edge(node1, edge[2]) # REMOVE THIS IF YOU WANT DIGRAPH 2/2
if node1 not in nodes: nodes.append(node1)
if node2 not in nodes: nodes.append(node2)
return nodes
def get_path_array(node):
"""
Takes an end node and gives you every node (in order) for the shortest path to it.
PARAMS:
node (node): end node
RETURNS:
array[nodes]: every note you need to visit (in order)
"""
if node.shortest_path_via == None:
return [node]
else:
return get_path_array(node.shortest_path_via) + [node]
def dijkstra(nodes, start, end):
"""
Finds the fastest way from "start" to "end" (usually what dijkstra does).
PARAMS:
nodes (array): array of nodes
start (node): start of path
end (node): end of path
RETURNS
array[node]: path of nodes from "start" to "end" (inclusive) if one is found
None: if no path is found
"""
queue = []
path = []
# Setup
queue = nodes.copy()
start.shortest_distance = 0
queue.sort(key=lambda node: node.shortest_distance)
# Exploration loop
while queue[0] != end:
node = queue[0]
node.update_edges()
path.append(queue.pop(0))
queue.sort(key=lambda node: node.shortest_distance)
# Test if there actually was a path found
if end.shortest_distance == float('inf'):
print("End has not been found")
return None
return get_path_array(end) | class Node:
def __init__(self, symbol):
self.symbol = symbol
self.edges = []
self.shortest_distance = float('inf')
self.shortest_path_via = None
def add_edge(self, node, distance):
self.edges.append([node, distance])
def update_edges(self):
for edge in self.edges:
distance_via = self.shortest_distance + edge[1]
if distance_via < edge[0].shortest_distance:
edge[0].shortest_distance = distance_via
edge[0].shortest_path_via = self
def get_node(nodes, symbol):
"""
Searches "nodes" for node with symbol "symbol" and returns it if found.
PARAMS:
nodes (array): array of nodes to search from
symbol (str): string to search matches for
RETURNS:
node: if match is found
None: if no match found
"""
for node in nodes:
if node.symbol == symbol:
return node
return None
def make_nodes(edge_data, *args):
"""
Takes an array of edges and makes them into node objects.
PARAMS:
edge_data (arr): array of edges with format [start_node (str), end_node (str), distance (int)]
*args (boolean): True if you want digraph, False if not (default is True) Can save time when entering edges by hand.
*args (array[str]): array of symbols to use for nodes that may not have edges and are not included in "edge_data"
RETURNS:
array: array of the nodes that it created
"""
nodes = []
if len(args) > 0:
digraph = args[0]
else:
digraph = False
if len(args) > 1:
for symbol in args[1]:
nodes.append(node(symbol))
for edge in edge_data:
node1 = get_node(nodes, edge[0])
node2 = get_node(nodes, edge[1])
if node1 == None:
node1 = node(edge[0])
if node2 == None:
node2 = node(edge[1])
node1.add_edge(node2, edge[2])
if not digraph:
node2.add_edge(node1, edge[2])
if node1 not in nodes:
nodes.append(node1)
if node2 not in nodes:
nodes.append(node2)
return nodes
def get_path_array(node):
"""
Takes an end node and gives you every node (in order) for the shortest path to it.
PARAMS:
node (node): end node
RETURNS:
array[nodes]: every note you need to visit (in order)
"""
if node.shortest_path_via == None:
return [node]
else:
return get_path_array(node.shortest_path_via) + [node]
def dijkstra(nodes, start, end):
"""
Finds the fastest way from "start" to "end" (usually what dijkstra does).
PARAMS:
nodes (array): array of nodes
start (node): start of path
end (node): end of path
RETURNS
array[node]: path of nodes from "start" to "end" (inclusive) if one is found
None: if no path is found
"""
queue = []
path = []
queue = nodes.copy()
start.shortest_distance = 0
queue.sort(key=lambda node: node.shortest_distance)
while queue[0] != end:
node = queue[0]
node.update_edges()
path.append(queue.pop(0))
queue.sort(key=lambda node: node.shortest_distance)
if end.shortest_distance == float('inf'):
print('End has not been found')
return None
return get_path_array(end) |
d=dict()
for _ in range(int(input())):
s=input().split(' ',1)
d[s[0]]=list(map(int,s[1].split()))
d=dict(sorted(d.items(), key=lambda x: x[0]))
d=dict(sorted(d.items(), key=lambda x: x[1][2],reverse=True))
d=dict(sorted(d.items(), key=lambda x: x[1][1],reverse=True))
d=dict(sorted(d.items(), key=lambda x: x[1][0],reverse=True))
for i,j in d.items():print(i,*j,sep=" ")
| d = dict()
for _ in range(int(input())):
s = input().split(' ', 1)
d[s[0]] = list(map(int, s[1].split()))
d = dict(sorted(d.items(), key=lambda x: x[0]))
d = dict(sorted(d.items(), key=lambda x: x[1][2], reverse=True))
d = dict(sorted(d.items(), key=lambda x: x[1][1], reverse=True))
d = dict(sorted(d.items(), key=lambda x: x[1][0], reverse=True))
for (i, j) in d.items():
print(i, *j, sep=' ') |
def my_func(count=4):
for i in range (1, 5):
print("count", count)
if count == 2:
print("count", count)
count = count - 1
my_func()
| def my_func(count=4):
for i in range(1, 5):
print('count', count)
if count == 2:
print('count', count)
count = count - 1
my_func() |
"""
217. Contains Duplicate
https://leetcode.com/problems/contains-duplicate/
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.
Example:
Input: [1,2,3,1]
Output: true
"""
# Runtime: 128ms
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
hash_map = {}
for num in nums:
if num not in hash_map:
hash_map[num] = hash_map.get(0, num,) + 1
else:
return True
return False
| """
217. Contains Duplicate
https://leetcode.com/problems/contains-duplicate/
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.
Example:
Input: [1,2,3,1]
Output: true
"""
class Solution:
def contains_duplicate(self, nums: List[int]) -> bool:
hash_map = {}
for num in nums:
if num not in hash_map:
hash_map[num] = hash_map.get(0, num) + 1
else:
return True
return False |
s = str(input())
ss = ''.join(list(reversed(s)))
sss = ss[:2]
ssss = ''.join(list(reversed(sss)))
print(ssss)
| s = str(input())
ss = ''.join(list(reversed(s)))
sss = ss[:2]
ssss = ''.join(list(reversed(sss)))
print(ssss) |
num=5
for i in range(1,num+1):
toPrint=""
end=int(i*(i+1)/2)
a=list(j for j in range(end+1-i,end+1))
for x in a:
toPrint+=" "+str(x)
print(toPrint)
toPrint=""
#output
'''
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
''' | num = 5
for i in range(1, num + 1):
to_print = ''
end = int(i * (i + 1) / 2)
a = list((j for j in range(end + 1 - i, end + 1)))
for x in a:
to_print += ' ' + str(x)
print(toPrint)
to_print = ''
'\n1\n2 3\n4 5 6\n7 8 9 10\n11 12 13 14 15\n' |
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
ar = []
#p=0
for i in range(x+1):
for j in range(y+1):
for k in range(z+1):
if (i+j+k) != n:
ar.append([i,j,k])
print(ar)
"""for i in range ( x + 1 ):
for j in range( y + 1):
if i+j != n:
ar.append([])
ar[p] = [ i , j ]
p+=1
print ar """
| if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
ar = []
for i in range(x + 1):
for j in range(y + 1):
for k in range(z + 1):
if i + j + k != n:
ar.append([i, j, k])
print(ar)
'for i in range ( x + 1 ):\n for j in range( y + 1):\n if i+j != n:\n ar.append([])\n ar[p] = [ i , j ]\n p+=1\n print ar ' |
expected_output = {
'mstp': {
'mst_instances': {
0: {
'mst_id': 0,
'bridge_priority': 32768,
'bridge_sysid': 0,
'bridge_address': '00e3.04ff.ad03',
'topology_change_flag': False,
'topology_detected_flag': False,
'topology_changes': 0,
'time_since_topology_change': '142:22:13',
'times': {
'hold': 1,
'topology_change': 70,
'notification': 10,
'max_age': 40,
'hello': 10,
'forwarding_delay': 30,
},
'timers' : {
'hello': 0,
'topology_change': 0,
'notification': 0,
},
'root_of_the_spanning_tree': True,
'interfaces': {
'Port-channel30': {
'name': 'Port-channel30',
'bridge_assurance_inconsistent': True,
'vpc_peer_link_inconsistent': True,
'port_num': 4125,
'status': 'broken',
'cost': 500,
'port_priority': 128,
'port_identifier': '128.4125',
'designated_root_priority': 32768,
'designated_root_address': '0023.04ff.ad03',
'designated_bridge_priority': 61440,
'designated_bridge_address': '4055.39ff.fee7',
'designated_port_id': '128.4125',
'designated_path_cost': 0,
'timers': {
'message_age': 0,
'forward_delay': 0,
'hold': 0,
},
'port_type' : 'network',
'number_of_forward_transitions': 0,
'link_type': 'point-to-point',
'internal': True,
'peer_type': 'STP',
'pvst_simulation': True,
'counters': {
'bpdu_sent': 110,
'bpdu_received': 0
}
}
}
}
},
'hello_time': 10,
'max_age': 40,
'forwarding_delay': 30
}
}
| expected_output = {'mstp': {'mst_instances': {0: {'mst_id': 0, 'bridge_priority': 32768, 'bridge_sysid': 0, 'bridge_address': '00e3.04ff.ad03', 'topology_change_flag': False, 'topology_detected_flag': False, 'topology_changes': 0, 'time_since_topology_change': '142:22:13', 'times': {'hold': 1, 'topology_change': 70, 'notification': 10, 'max_age': 40, 'hello': 10, 'forwarding_delay': 30}, 'timers': {'hello': 0, 'topology_change': 0, 'notification': 0}, 'root_of_the_spanning_tree': True, 'interfaces': {'Port-channel30': {'name': 'Port-channel30', 'bridge_assurance_inconsistent': True, 'vpc_peer_link_inconsistent': True, 'port_num': 4125, 'status': 'broken', 'cost': 500, 'port_priority': 128, 'port_identifier': '128.4125', 'designated_root_priority': 32768, 'designated_root_address': '0023.04ff.ad03', 'designated_bridge_priority': 61440, 'designated_bridge_address': '4055.39ff.fee7', 'designated_port_id': '128.4125', 'designated_path_cost': 0, 'timers': {'message_age': 0, 'forward_delay': 0, 'hold': 0}, 'port_type': 'network', 'number_of_forward_transitions': 0, 'link_type': 'point-to-point', 'internal': True, 'peer_type': 'STP', 'pvst_simulation': True, 'counters': {'bpdu_sent': 110, 'bpdu_received': 0}}}}}, 'hello_time': 10, 'max_age': 40, 'forwarding_delay': 30}} |
#THIS IS HANGMAN
print('"Hangman"\nA game where you will try to guess which the hidden word is!')
print('\n')
word = input('Input the word to guess:\n')
while True:
if word.isalpha():
break
else:
word = input('Wrong input, type a valid word:\n')
number_of_letters = len(word)
word_listed_letters = list(word)
print('\n'*15 + 'This space is given for hiding the word\n')
print('_ '*(number_of_letters - 1) + '_')
letters = [letter for letter in bytearray(range(97, 123)).decode("utf-8")]
letters_left = letters
#Function to check if the letter to use is valid
def isletter():
letter = input('')
while True:
if letter in letters_left:
break
else:
letter = input('Wrong input, type a valid letter:\n')
return letter
#Function to display the hangman according to the chances remaining
def hangman_display(c):
if c == 1:
print('-'*10)
elif c == 2:
print('|\n'*10)
hangman_display(1)
elif c == 3:
print('_'*6)
hangman_display(2)
elif c == 4:
print('_'*6)
print('| |\n'*3 + '|\n'*7)
elif c == 5:
print('_'*6)
print('| |\n'*3 + '| O\n' + '|\n'*6)
elif c == 6:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '| |' + '|\n' * 5)
elif c == 7:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '| |\n' + '| /|\n' + '|\n' * 5)
elif c == 8:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '| |\n' + '| /|\\\n' + '|\n' * 5)
elif c == 9:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '| |\n' + '| /|\\\n' + '/\n' + '|\n' * 4)
elif c == 10:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '| |\n' + '| /|\\\n' + '/\\\n' + '|\n' * 4)
'''count = 0
if try in word:
ind = [i for i in range(number_of_letters) if word[i] == try]
else:
letters_left.remove(try)
count += 1
hangman_display(count)
'''
while True:
#To check if the input is a valid letter
while True:
letter = input('\nInput letter to guess:\n')
if letter in letters_left:
break
else:
letter = input('Wrong input, type a valid letter:\n')
if letter in word:
position = [p for p in range(number_of_letters) if word[p] == letter]
for times in range(len(position)):
blanks = position[0]
print('_ ' * blanks + word[position[0]] + ' ', end='')
if len(position) > 1:
blanks = position[1] - position[0] - 1
position = position[1:]
| print('"Hangman"\nA game where you will try to guess which the hidden word is!')
print('\n')
word = input('Input the word to guess:\n')
while True:
if word.isalpha():
break
else:
word = input('Wrong input, type a valid word:\n')
number_of_letters = len(word)
word_listed_letters = list(word)
print('\n' * 15 + 'This space is given for hiding the word\n')
print('_ ' * (number_of_letters - 1) + '_')
letters = [letter for letter in bytearray(range(97, 123)).decode('utf-8')]
letters_left = letters
def isletter():
letter = input('')
while True:
if letter in letters_left:
break
else:
letter = input('Wrong input, type a valid letter:\n')
return letter
def hangman_display(c):
if c == 1:
print('-' * 10)
elif c == 2:
print('|\n' * 10)
hangman_display(1)
elif c == 3:
print('_' * 6)
hangman_display(2)
elif c == 4:
print('_' * 6)
print('| |\n' * 3 + '|\n' * 7)
elif c == 5:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '|\n' * 6)
elif c == 6:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '| |' + '|\n' * 5)
elif c == 7:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '| |\n' + '| /|\n' + '|\n' * 5)
elif c == 8:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '| |\n' + '| /|\\\n' + '|\n' * 5)
elif c == 9:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '| |\n' + '| /|\\\n' + '/\n' + '|\n' * 4)
elif c == 10:
print('_' * 6)
print('| |\n' * 3 + '| O\n' + '| |\n' + '| /|\\\n' + '/\\\n' + '|\n' * 4)
'count = 0 \nif try in word:\n ind = [i for i in range(number_of_letters) if word[i] == try]\n else:\n letters_left.remove(try)\n count += 1\n hangman_display(count)\n'
while True:
while True:
letter = input('\nInput letter to guess:\n')
if letter in letters_left:
break
else:
letter = input('Wrong input, type a valid letter:\n')
if letter in word:
position = [p for p in range(number_of_letters) if word[p] == letter]
for times in range(len(position)):
blanks = position[0]
print('_ ' * blanks + word[position[0]] + ' ', end='')
if len(position) > 1:
blanks = position[1] - position[0] - 1
position = position[1:] |
dataset_type = "SuperviselyDataset"
data_root = '/data/slyproject'
class_names = ['Car', 'Pedestrian', 'Cyclist', 'DontCare']
point_cloud_range = [0, -40, -3, 70.4, 40, 1]
input_modality = dict(use_lidar=True, use_camera=False)
file_client_args = dict(backend='disk')
# db_sampler = dict(
# data_root=data_root,
# info_path=data_root + 'train/dataset.npy',
# rate=1.0,
# prepare=dict(
# filter_by_difficulty=[-1],
# filter_by_min_points=dict(Car=5, Pedestrian=10, Cyclist=10)),
# classes=class_names,
# sample_groups=dict(Car=1, Pedestrian=1, Cyclist=1),
# points_loader=dict(
# type='LoadPointsFromSlyFile',
# coord_type='LIDAR',
# load_dim=4,
# use_dim=[0, 1, 2, 3],
# file_client_args=file_client_args))
train_pipeline = [
dict(
type='LoadPointsFromSlyFile'),
dict(
type='LoadAnnotations3D', with_bbox_3d=True, with_label_3d=True),
#dict(type='ObjectSample', db_sampler=db_sampler),
dict(type='RandomFlip3D', flip_ratio_bev_horizontal=0.5),
dict(
type='GlobalRotScaleTrans',
rot_range=[-0.78539816, 0.78539816],
scale_ratio_range=[0.95, 1.05]),
dict(type='PointsRangeFilter', point_cloud_range=point_cloud_range),
dict(type='ObjectRangeFilter', point_cloud_range=point_cloud_range),
dict(type='PointShuffle'),
dict(type='DefaultFormatBundle3D', class_names=class_names),
dict(type='Collect3D', keys=['points', 'gt_bboxes_3d', 'gt_labels_3d'])
]
test_pipeline = [
dict(type='LoadPointsFromSlyFile')]
# construct a pipeline for data and gt loading in show function
# please keep its loading function consistent with test_pipeline (e.g. client)
eval_pipeline = [
dict(
type='LoadPointsFromSlyFile'),
dict(
type='DefaultFormatBundle3D',
class_names=class_names,
with_label=False),
dict(type='Collect3D', keys=['points'])
]
data = dict(
samples_per_gpu=1,
workers_per_gpu=1,
train=dict(
type='RepeatDataset',
times=2,
dataset=dict(
type=dataset_type,
data_root=data_root)),
val=dict(
type=dataset_type,
data_root=data_root),
test=dict(
type=dataset_type,
data_root=data_root))
evaluation = dict(interval=1, pipeline=eval_pipeline)
| dataset_type = 'SuperviselyDataset'
data_root = '/data/slyproject'
class_names = ['Car', 'Pedestrian', 'Cyclist', 'DontCare']
point_cloud_range = [0, -40, -3, 70.4, 40, 1]
input_modality = dict(use_lidar=True, use_camera=False)
file_client_args = dict(backend='disk')
train_pipeline = [dict(type='LoadPointsFromSlyFile'), dict(type='LoadAnnotations3D', with_bbox_3d=True, with_label_3d=True), dict(type='RandomFlip3D', flip_ratio_bev_horizontal=0.5), dict(type='GlobalRotScaleTrans', rot_range=[-0.78539816, 0.78539816], scale_ratio_range=[0.95, 1.05]), dict(type='PointsRangeFilter', point_cloud_range=point_cloud_range), dict(type='ObjectRangeFilter', point_cloud_range=point_cloud_range), dict(type='PointShuffle'), dict(type='DefaultFormatBundle3D', class_names=class_names), dict(type='Collect3D', keys=['points', 'gt_bboxes_3d', 'gt_labels_3d'])]
test_pipeline = [dict(type='LoadPointsFromSlyFile')]
eval_pipeline = [dict(type='LoadPointsFromSlyFile'), dict(type='DefaultFormatBundle3D', class_names=class_names, with_label=False), dict(type='Collect3D', keys=['points'])]
data = dict(samples_per_gpu=1, workers_per_gpu=1, train=dict(type='RepeatDataset', times=2, dataset=dict(type=dataset_type, data_root=data_root)), val=dict(type=dataset_type, data_root=data_root), test=dict(type=dataset_type, data_root=data_root))
evaluation = dict(interval=1, pipeline=eval_pipeline) |
LIST_ASSIGNED_USER_ROLE_RESPONSE = """
[
{
"id": "IFIFAX2BIRGUSTQ",
"label": "Application Administrator",
"type": "APP_ADMIN",
"status": "ACTIVE",
"created": "2019-02-06T16:17:40.000Z",
"lastUpdated": "2019-02-06T16:17:40.000Z",
"assignmentType": "USER",
"_links": {
"assignee": {
"href": "http://{yourOktaDomain}/api/v1/users/00ur32Vg0fvpyHZeQ0g3"
}
}
},
{
"id": "JBCUYUC7IRCVGS27IFCE2SKO",
"label": "Help Desk Administrator",
"type": "HELP_DESK_ADMIN",
"status": "ACTIVE",
"created": "2019-02-06T16:17:40.000Z",
"lastUpdated": "2019-02-06T16:17:40.000Z",
"assignmentType": "USER",
"_links": {
"assignee": {
"href": "http://{yourOktaDomain}/api/v1/users/00ur32Vg0fvpyHZeQ0g3"
}
}
}
]
"""
LIST_ASSIGNED_GROUP_ROLE_RESPONSE = """
[
{
"id": "IFIFAX2BIRGUSTQ",
"label": "Application Administrator",
"type": "APP_ADMIN",
"status": "ACTIVE",
"created": "2019-02-27T14:48:59.000Z",
"lastUpdated": "2019-02-27T14:48:59.000Z",
"assignmentType": "GROUP",
"_links": {
"assignee": {
"href": "http://{yourOktaDomain}/api/v1/groups/00gsr2IepS8YhHRFf0g3"
}
}
},
{
"id": "JBCUYUC7IRCVGS27IFCE2SKO",
"label": "Help Desk Administrator",
"type": "HELP_DESK_ADMIN",
"status": "ACTIVE",
"created": "2019-02-06T16:17:40.000Z",
"lastUpdated": "2019-02-06T16:17:40.000Z",
"assignmentType": "GROUP",
"_links": {
"assignee": {
"href": "http://{yourOktaDomain}/api/v1/users/00ur32Vg0fvpyHZeQ0g3"
}
}
}
]
"""
| list_assigned_user_role_response = '\n[\n {\n "id": "IFIFAX2BIRGUSTQ",\n "label": "Application Administrator",\n "type": "APP_ADMIN",\n "status": "ACTIVE",\n "created": "2019-02-06T16:17:40.000Z",\n "lastUpdated": "2019-02-06T16:17:40.000Z",\n "assignmentType": "USER",\n "_links": {\n "assignee": {\n "href": "http://{yourOktaDomain}/api/v1/users/00ur32Vg0fvpyHZeQ0g3"\n }\n }\n },\n {\n "id": "JBCUYUC7IRCVGS27IFCE2SKO",\n "label": "Help Desk Administrator",\n "type": "HELP_DESK_ADMIN",\n "status": "ACTIVE",\n "created": "2019-02-06T16:17:40.000Z",\n "lastUpdated": "2019-02-06T16:17:40.000Z",\n "assignmentType": "USER",\n "_links": {\n "assignee": {\n "href": "http://{yourOktaDomain}/api/v1/users/00ur32Vg0fvpyHZeQ0g3"\n }\n }\n }\n]\n'
list_assigned_group_role_response = '\n[\n {\n "id": "IFIFAX2BIRGUSTQ",\n "label": "Application Administrator",\n "type": "APP_ADMIN",\n "status": "ACTIVE",\n "created": "2019-02-27T14:48:59.000Z",\n "lastUpdated": "2019-02-27T14:48:59.000Z",\n "assignmentType": "GROUP",\n "_links": {\n "assignee": {\n "href": "http://{yourOktaDomain}/api/v1/groups/00gsr2IepS8YhHRFf0g3"\n }\n }\n },\n {\n "id": "JBCUYUC7IRCVGS27IFCE2SKO",\n "label": "Help Desk Administrator",\n "type": "HELP_DESK_ADMIN",\n "status": "ACTIVE",\n "created": "2019-02-06T16:17:40.000Z",\n "lastUpdated": "2019-02-06T16:17:40.000Z",\n "assignmentType": "GROUP",\n "_links": {\n "assignee": {\n "href": "http://{yourOktaDomain}/api/v1/users/00ur32Vg0fvpyHZeQ0g3"\n }\n }\n }\n]\n' |
while True:
num = int(input("Enter a number: "))
if num % 2 == 0:
print(num, "is an even number")
else:
print(f"{num} is a odd number")
| while True:
num = int(input('Enter a number: '))
if num % 2 == 0:
print(num, 'is an even number')
else:
print(f'{num} is a odd number') |
__package_name__ = 'python-utils'
__version__ = '2.5.0'
__author__ = 'Rick van Hattem'
__author_email__ = 'Wolph@wol.ph'
__description__ = (
'Python Utils is a module with some convenient utilities not included '
'with the standard Python install')
__url__ = 'https://github.com/WoLpH/python-utils'
| __package_name__ = 'python-utils'
__version__ = '2.5.0'
__author__ = 'Rick van Hattem'
__author_email__ = 'Wolph@wol.ph'
__description__ = 'Python Utils is a module with some convenient utilities not included with the standard Python install'
__url__ = 'https://github.com/WoLpH/python-utils' |
class BBUtil(object):
def __init__(self,width,height):
super(BBUtil, self).__init__()
self.width=width
self.height=height
def xywh_to_tlwh(self, bbox_xywh):
x,y,w,h = bbox_xywh
xmin = max(int(round(x - (w / 2))),0)
ymin = max(int(round(y - (h / 2))),0)
return [xmin,ymin,int(w),int(h)]
def tlwh_to_xyxy(self, bbox_tlwh):
x,y,w,h = bbox_tlwh
x1 = max(int(x),0)
x2 = min(int(x+w),self.width-1)
y1 = max(int(y),0)
y2 = min(int(y+h),self.height-1)
return [x1,y1,x2,y2]
def xywh_to_xyxy(self, bbox_xywh):
x,y,w,h = bbox_xywh
x1 = max(int(x-w/2),0)
x2 = min(int(x+w/2),self.width-1)
y1 = max(int(y-h/2),0)
y2 = min(int(y+h/2),self.height-1)
return [x1,y1,x2,y2]
def xyxy_to_tlwh(self, bbox_xyxy):
x1,y1,x2,y2 = bbox_xyxy
t = x1
l = y1
w = int(x2-x1)
h = int(y2-y1)
return [t,l,w,h]
def float_to_int(self,bbox_xyxy):
x1,y1,x2,y2 = bbox_xyxy
return [int(x1*self.width), int(y1*self.height), int(x2*self.width), int(y2*self.height)]
def int_to_float(self,bbox_xyxy):
x1,y1,x2,y2 = [float(item) for item in bbox_xyxy]
return [x1/self.width, y1/self.height, x2/self.width, y2/self.height]
| class Bbutil(object):
def __init__(self, width, height):
super(BBUtil, self).__init__()
self.width = width
self.height = height
def xywh_to_tlwh(self, bbox_xywh):
(x, y, w, h) = bbox_xywh
xmin = max(int(round(x - w / 2)), 0)
ymin = max(int(round(y - h / 2)), 0)
return [xmin, ymin, int(w), int(h)]
def tlwh_to_xyxy(self, bbox_tlwh):
(x, y, w, h) = bbox_tlwh
x1 = max(int(x), 0)
x2 = min(int(x + w), self.width - 1)
y1 = max(int(y), 0)
y2 = min(int(y + h), self.height - 1)
return [x1, y1, x2, y2]
def xywh_to_xyxy(self, bbox_xywh):
(x, y, w, h) = bbox_xywh
x1 = max(int(x - w / 2), 0)
x2 = min(int(x + w / 2), self.width - 1)
y1 = max(int(y - h / 2), 0)
y2 = min(int(y + h / 2), self.height - 1)
return [x1, y1, x2, y2]
def xyxy_to_tlwh(self, bbox_xyxy):
(x1, y1, x2, y2) = bbox_xyxy
t = x1
l = y1
w = int(x2 - x1)
h = int(y2 - y1)
return [t, l, w, h]
def float_to_int(self, bbox_xyxy):
(x1, y1, x2, y2) = bbox_xyxy
return [int(x1 * self.width), int(y1 * self.height), int(x2 * self.width), int(y2 * self.height)]
def int_to_float(self, bbox_xyxy):
(x1, y1, x2, y2) = [float(item) for item in bbox_xyxy]
return [x1 / self.width, y1 / self.height, x2 / self.width, y2 / self.height] |
class Storage:
__storage = 0
def __init__(self, capacity):
self.capacity = capacity
self.storage = []
def add_product(self, product):
if not Storage.__storage == self.capacity:
self.storage.append(product)
Storage.__storage += 1
def get_products(self):
return self.storage | class Storage:
__storage = 0
def __init__(self, capacity):
self.capacity = capacity
self.storage = []
def add_product(self, product):
if not Storage.__storage == self.capacity:
self.storage.append(product)
Storage.__storage += 1
def get_products(self):
return self.storage |
# A CAN bus.
class Bus(object):
"""A CAN bus.
"""
def __init__(self,
name,
comment=None,
baudrate=None,
fd_baudrate=None,
autosar_specifics=None):
self._name = name
# If the 'comment' argument is a string, we assume that is an
# English comment. This is slightly hacky, because the
# function's behavior depends on the type of the passed
# argument, but it is quite convenient...
if isinstance(comment, str):
# use the first comment in the dictionary as "The" comment
self._comments = { None: comment }
else:
# assume that we have either no comment at all or a
# multi-lingual dictionary
self._comments = comment
self._baudrate = baudrate
self._fd_baudrate = fd_baudrate
self._autosar = autosar_specifics
@property
def name(self):
"""The bus name as a string.
"""
return self._name
@property
def comment(self):
"""The bus' comment, or ``None`` if unavailable.
Note that we implicitly try to return the English comment if
multiple languages were specified.
"""
if self._comments is None:
return None
elif self._comments.get(None) is not None:
return self._comments.get(None)
elif self._comments.get("FOR-ALL") is not None:
return self._comments.get("FOR-ALL")
return self._comments.get('EN')
@property
def comments(self):
"""The dictionary with the descriptions of the bus in multiple
languages. ``None`` if unavailable.
"""
return self._comments
@property
def baudrate(self):
"""The bus baudrate, or ``None`` if unavailable.
"""
return self._baudrate
@property
def fd_baudrate(self):
"""The baudrate used for the payload of CAN-FD frames, or ``None`` if
unavailable.
"""
return self._fd_baudrate
@property
def autosar(self):
"""An object containing AUTOSAR specific properties of the bus.
"""
return self._autosar
@autosar.setter
def autosar(self, value):
self._autosar = value
def __repr__(self):
return "bus('{}', {})".format(
self._name,
"'" + self.comment + "'" if self.comment is not None else None)
| class Bus(object):
"""A CAN bus.
"""
def __init__(self, name, comment=None, baudrate=None, fd_baudrate=None, autosar_specifics=None):
self._name = name
if isinstance(comment, str):
self._comments = {None: comment}
else:
self._comments = comment
self._baudrate = baudrate
self._fd_baudrate = fd_baudrate
self._autosar = autosar_specifics
@property
def name(self):
"""The bus name as a string.
"""
return self._name
@property
def comment(self):
"""The bus' comment, or ``None`` if unavailable.
Note that we implicitly try to return the English comment if
multiple languages were specified.
"""
if self._comments is None:
return None
elif self._comments.get(None) is not None:
return self._comments.get(None)
elif self._comments.get('FOR-ALL') is not None:
return self._comments.get('FOR-ALL')
return self._comments.get('EN')
@property
def comments(self):
"""The dictionary with the descriptions of the bus in multiple
languages. ``None`` if unavailable.
"""
return self._comments
@property
def baudrate(self):
"""The bus baudrate, or ``None`` if unavailable.
"""
return self._baudrate
@property
def fd_baudrate(self):
"""The baudrate used for the payload of CAN-FD frames, or ``None`` if
unavailable.
"""
return self._fd_baudrate
@property
def autosar(self):
"""An object containing AUTOSAR specific properties of the bus.
"""
return self._autosar
@autosar.setter
def autosar(self, value):
self._autosar = value
def __repr__(self):
return "bus('{}', {})".format(self._name, "'" + self.comment + "'" if self.comment is not None else None) |
def signFinder (s):
plus = s.count("-")
minus = s.count("+")
total = plus+minus
if total == 1:
return True
else:
return False | def sign_finder(s):
plus = s.count('-')
minus = s.count('+')
total = plus + minus
if total == 1:
return True
else:
return False |
"""Postgres Connector error classes."""
class PostgresConnectorError(Exception):
"""Base class for all errors."""
class PostgresClientError(PostgresConnectorError):
"""An error specific to the PostgreSQL driver."""
| """Postgres Connector error classes."""
class Postgresconnectorerror(Exception):
"""Base class for all errors."""
class Postgresclienterror(PostgresConnectorError):
"""An error specific to the PostgreSQL driver.""" |
def binary_search(arr, target):
low, high = 0, len(arr)-1
while low < high:
mid = (low + high)/2
if arr[mid] == target:
return mid
elif arr[mid] > target:
high = mid - 1
else:
low = mid + 1
return high
if __name__ == "__main__":
lst = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(binary_search(lst,15))
| def binary_search(arr, target):
(low, high) = (0, len(arr) - 1)
while low < high:
mid = (low + high) / 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
high = mid - 1
else:
low = mid + 1
return high
if __name__ == '__main__':
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
print(binary_search(lst, 15)) |
#EP1
'''
def getPentagonalNumber(n):
i = 1
for i in range(1,n+1):
s = (i*(3*i-1)*1.0)/2
print (str(s)+' ',end='')
if i%10==0:
print()
getPentagonalNumber(100)
'''
#EP2
'''
def sum(n):
s= 0
while(n%10!=0):
a=n%10
b=n//10
s=s+a
n=b
print(s)
a= eval(raw_input("enter a int:"))
sum(a)
'''
#EP3
'''
def display(n1,n2,n3):
b=[n1,n2,n3]
b.sort()
print(b)
a1,a2,a3=eval(raw_input("enter three numbers:"))
display(a1,a2,a3)
'''
#EP4
'''
inves = eval(input("the amount inversted:"))
monthly = eval(input("annual interest rate:"))
print("annual\tfuture value")
def funtureinver(inves,monthly,years):
return inves*pow((1+monthly/100/12),years*12)
for i in range(1,31):
c=funtureinver(inves,monthly,i)
print("%d\t%.2f"%(i,c),end=" ")
print()
'''
#EP5
'''
def printchars(c1,c2,number):
m=0
a=ord(c1)
b=ord(c2)+1
for i in range(a,b):
print(chr(i),end='')
m=m+1
if(m%number==0):
print("")
a,b=input("enter start to end ascii:").split(',')
c = eval(input("enter number:"))
printchars('1','Z',10)
'''
#EP6
'''
def number(year):
if((year%4==0)&(year%100!=0))|(year%400==0):
print("%d:366"%(i))
else:
print("%d:365"%(i))
for i in range(2010,2021):
number(i)
'''
#EP7
'''
def distance(a1,b1,a2,b2):
print(((a1-a2)*(a1-a2)+(b1-b2)*(b1-b2))**0.5)
a1,b1=eval(raw_input("enter a1 and a2 for point1: "))
a2,b2=eval(raw_input("enter a1 and a2 for point2: "))
distance(a1,b1,a2,b2)
'''
#EP8
'''
import math
print ("p\t2^p-1")
def n(a):
f=0
for j in range(2,int(math.sqrt(a)+1)):
if a%j==0 :
f = 0
else :
f = 1
return f
print("2\t3")
for i in range(1,32):
c=pow(2,i)-1
if(n(c)):
print("%d\t%d"%(i,c))
'''
#EP9
'''
from time import *
print(ctime(time()))
'''
#EP10
'''
import random
n = random.randint(1,6)
m = random.randint(1,6)
s = n+m
if (s==2)|(s==3)|(s==12):
print("you rolled {} + {} = {}\nyou lose".format(n,m,s))
elif (s==7)|(s==11):
print("you rolled {} + {} = {}\nyou win".format(n,m,s))
else :
print("you rolled {} + {} = {}\nyou is {}".format(n,m,s,s))
n1 = random.randint(1,6)
m1 = random.randint(1,6)
s1 = n1+m1
if(s1!=s):
print("you rolled {} + {} = {}\nyou lose".format(n1,m1,s1))
else :
print("you rolled {} + {} = {}\nyou win".format(n1,m1,s1))
'''
#EP11
| """
def getPentagonalNumber(n):
i = 1
for i in range(1,n+1):
s = (i*(3*i-1)*1.0)/2
print (str(s)+' ',end='')
if i%10==0:
print()
getPentagonalNumber(100)
"""
'\ndef sum(n):\n s= 0\n while(n%10!=0):\n a=n%10\n b=n//10\n s=s+a\n n=b\n print(s)\na= eval(raw_input("enter a int:"))\nsum(a)\n\n'
'\ndef display(n1,n2,n3):\n b=[n1,n2,n3]\n b.sort()\n print(b)\na1,a2,a3=eval(raw_input("enter three numbers:"))\ndisplay(a1,a2,a3)\n'
'\ninves = eval(input("the amount inversted:"))\nmonthly = eval(input("annual interest rate:"))\nprint("annual\tfuture value")\ndef funtureinver(inves,monthly,years):\n return inves*pow((1+monthly/100/12),years*12)\nfor i in range(1,31):\n c=funtureinver(inves,monthly,i)\n print("%d\t%.2f"%(i,c),end=" ")\n print()\n'
'\ndef printchars(c1,c2,number):\n m=0\n a=ord(c1)\n b=ord(c2)+1\n for i in range(a,b):\n print(chr(i),end=\'\')\n m=m+1\n if(m%number==0):\n print("")\na,b=input("enter start to end ascii:").split(\',\')\nc = eval(input("enter number:"))\nprintchars(\'1\',\'Z\',10)\n'
'\ndef number(year):\n if((year%4==0)&(year%100!=0))|(year%400==0):\n print("%d:366"%(i))\n else:\n print("%d:365"%(i))\nfor i in range(2010,2021):\n number(i)\n'
'\ndef distance(a1,b1,a2,b2):\n print(((a1-a2)*(a1-a2)+(b1-b2)*(b1-b2))**0.5)\na1,b1=eval(raw_input("enter a1 and a2 for point1: "))\na2,b2=eval(raw_input("enter a1 and a2 for point2: "))\ndistance(a1,b1,a2,b2)\n'
'\nimport math\nprint ("p\t2^p-1")\ndef n(a):\n f=0\n for j in range(2,int(math.sqrt(a)+1)):\n if a%j==0 :\n f = 0\n else :\n f = 1\n return f\nprint("2\t3")\nfor i in range(1,32):\n c=pow(2,i)-1\n if(n(c)):\n print("%d\t%d"%(i,c))\n'
'\nfrom time import *\nprint(ctime(time()))\n'
'\nimport random\n\nn = random.randint(1,6)\nm = random.randint(1,6)\ns = n+m\n\nif (s==2)|(s==3)|(s==12):\n print("you rolled {} + {} = {}\nyou lose".format(n,m,s))\nelif (s==7)|(s==11):\n print("you rolled {} + {} = {}\nyou win".format(n,m,s))\nelse :\n print("you rolled {} + {} = {}\nyou is {}".format(n,m,s,s))\n n1 = random.randint(1,6)\n m1 = random.randint(1,6)\n s1 = n1+m1\n if(s1!=s):\n print("you rolled {} + {} = {}\nyou lose".format(n1,m1,s1))\n else :\n print("you rolled {} + {} = {}\nyou win".format(n1,m1,s1))\n' |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 13:45:46 2021
@author: Lakhan Kumawat
"""
mylist=input().split()
k=int(input())
k1=k
mylist1=mylist
mylist1.sort()
mylist.sort()
max1=max(mylist1)
#print(mylist,mylist1)
#remove k-1th max from list1 and print max
while(k1-1!=0):
while(max(mylist1)==max1):
mylist1.remove(max(mylist1))
max1=max(mylist1)
k1-=1
#remove k-1th min from list and print min
min2=min(mylist)
while(k-1!=0):
while(min(mylist)==min2):
mylist.remove(min(mylist))
min2=min(mylist1)
k-=1
#finally sum of kth max and kth min
print(int(max(mylist1))+int(min(mylist))) | """
Created on Fri Feb 19 13:45:46 2021
@author: Lakhan Kumawat
"""
mylist = input().split()
k = int(input())
k1 = k
mylist1 = mylist
mylist1.sort()
mylist.sort()
max1 = max(mylist1)
while k1 - 1 != 0:
while max(mylist1) == max1:
mylist1.remove(max(mylist1))
max1 = max(mylist1)
k1 -= 1
min2 = min(mylist)
while k - 1 != 0:
while min(mylist) == min2:
mylist.remove(min(mylist))
min2 = min(mylist1)
k -= 1
print(int(max(mylist1)) + int(min(mylist))) |
# coding=utf-8
__author__ = 'co2y'
__email__ = 'co2y@foxmail.com'
__version__ = '0.0.1'
| __author__ = 'co2y'
__email__ = 'co2y@foxmail.com'
__version__ = '0.0.1' |
"""
Errors relating to partitioning
"""
# Partitioning
partitionWarning = ("Partitioning suggests no partitions.\n"
"Recommend running with different partitioning method or disable partitioning")
| """
Errors relating to partitioning
"""
partition_warning = 'Partitioning suggests no partitions.\nRecommend running with different partitioning method or disable partitioning' |
def main():
full_name = get_full_name()
print()
password = get_password()
print()
first_name = get_first_name(full_name)
print("Hi " + first_name + ", thanks for creating an account.")
def get_full_name():
while True:
name = input("Enter full name: ").strip()
if " " in name:
return name
else:
print("You must enter your full name.")
def get_first_name(full_name):
index1 = full_name.find(" ")
first_name = full_name[:index1]
return first_name
def get_password():
while True:
digit = False
cap_letter = False
password = input("Enter password: ").strip()
for char in password:
if char.isdigit():
digit = True
elif char.isupper():
cap_letter = True
if digit == False or cap_letter == False or len(password) < 8:
print("Password must be 8 characters or more \n" +
"with at least one digit and one uppercase letter.")
else:
return password
if __name__ == "__main__":
main()
| def main():
full_name = get_full_name()
print()
password = get_password()
print()
first_name = get_first_name(full_name)
print('Hi ' + first_name + ', thanks for creating an account.')
def get_full_name():
while True:
name = input('Enter full name: ').strip()
if ' ' in name:
return name
else:
print('You must enter your full name.')
def get_first_name(full_name):
index1 = full_name.find(' ')
first_name = full_name[:index1]
return first_name
def get_password():
while True:
digit = False
cap_letter = False
password = input('Enter password: ').strip()
for char in password:
if char.isdigit():
digit = True
elif char.isupper():
cap_letter = True
if digit == False or cap_letter == False or len(password) < 8:
print('Password must be 8 characters or more \n' + 'with at least one digit and one uppercase letter.')
else:
return password
if __name__ == '__main__':
main() |
#EVALUATION OF THE MODEL
def evaluate_model(model, X_test, y_test):
_, score = model.evaluate(X_test, y_test, verbose = 0)
print(score)
def predict_model(model, X):
y = model.predict(X)
print(y)
def predict_class_model(model, X):
y = model.predict_classes(X)
print(y) | def evaluate_model(model, X_test, y_test):
(_, score) = model.evaluate(X_test, y_test, verbose=0)
print(score)
def predict_model(model, X):
y = model.predict(X)
print(y)
def predict_class_model(model, X):
y = model.predict_classes(X)
print(y) |
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
if len(num) == 0 and len(num) <= k :
return "0"
st = [num[0]]
i = 1
while i < len(num):
while len(st) > 0 and int(st[-1]) > int(num[i]) and k > 0:
st.pop()
k-=1
st.append(num[i])
i+=1
while k > 0 :
st.pop()
k-=1
while len(st) > 0 and st[0] == "0" :
st.pop(0)
if len(st) == 0 :
return "0"
else :
return "".join(st)
#python special
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
stack = []
for n in num:
while k > 0 and stack and stack[-1] > n:
stack.pop()
k -= 1
stack.append(n)
ans = stack[:-k] if k else stack
return "".join(ans).lstrip('0') or "0"
| class Solution:
def remove_kdigits(self, num: str, k: int) -> str:
if len(num) == 0 and len(num) <= k:
return '0'
st = [num[0]]
i = 1
while i < len(num):
while len(st) > 0 and int(st[-1]) > int(num[i]) and (k > 0):
st.pop()
k -= 1
st.append(num[i])
i += 1
while k > 0:
st.pop()
k -= 1
while len(st) > 0 and st[0] == '0':
st.pop(0)
if len(st) == 0:
return '0'
else:
return ''.join(st)
class Solution:
def remove_kdigits(self, num: str, k: int) -> str:
stack = []
for n in num:
while k > 0 and stack and (stack[-1] > n):
stack.pop()
k -= 1
stack.append(n)
ans = stack[:-k] if k else stack
return ''.join(ans).lstrip('0') or '0' |
file_input = open("motivation.txt",'w')
file_input.write("Never give up")
file_input.write("\nRise above hate")
file_input.write("\nNo body remember second place")
file_input.close() | file_input = open('motivation.txt', 'w')
file_input.write('Never give up')
file_input.write('\nRise above hate')
file_input.write('\nNo body remember second place')
file_input.close() |
__title__ = "django-kindeditor"
__description__ = "Django admin KindEditor integration."
__url__ = "https://github.com/waketzheng/django-kindeditor"
__version__ = "0.3.0"
__author__ = "Waket Zheng"
__author_email__ = "waketzheng@gmail.com"
__license__ = "MIT"
__copyright__ = "Copyright 2019 Waket Zheng"
| __title__ = 'django-kindeditor'
__description__ = 'Django admin KindEditor integration.'
__url__ = 'https://github.com/waketzheng/django-kindeditor'
__version__ = '0.3.0'
__author__ = 'Waket Zheng'
__author_email__ = 'waketzheng@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019 Waket Zheng' |
class BoundingBox:
x: int
y: int
x2: int
y2: int
cx: int
cy: int
width: int
height: int
def __init__(self, x: int, y: int, width: int, height: int):
self.x = x
self.y = y
self.width = width
self.height = height
self.x2 = x + width - 1
self.y2 = y + height - 1
self.cx = round(x + width / 2)
self.cy = round(y + height / 2)
| class Boundingbox:
x: int
y: int
x2: int
y2: int
cx: int
cy: int
width: int
height: int
def __init__(self, x: int, y: int, width: int, height: int):
self.x = x
self.y = y
self.width = width
self.height = height
self.x2 = x + width - 1
self.y2 = y + height - 1
self.cx = round(x + width / 2)
self.cy = round(y + height / 2) |
#!/usr/bin/env python3
def convert_to_celsius(fahrenheit: float) -> float:
return (fahrenheit - 32.0) * 5.0 / 9.0
def above_freezing(celsius: float) -> bool:
return celsius > 0
fahrenheit = float(input('Enter the temperature in degrees Fahrenheit: '))
celsius = convert_to_celsius(fahrenheit)
print(celsius)
if above_freezing(celsius):
print('It is above freezing.')
else:
print('It is below freezing.') | def convert_to_celsius(fahrenheit: float) -> float:
return (fahrenheit - 32.0) * 5.0 / 9.0
def above_freezing(celsius: float) -> bool:
return celsius > 0
fahrenheit = float(input('Enter the temperature in degrees Fahrenheit: '))
celsius = convert_to_celsius(fahrenheit)
print(celsius)
if above_freezing(celsius):
print('It is above freezing.')
else:
print('It is below freezing.') |
numero = str(input('digite um numero'))
print('unidade: {}'.format(numero[1]))
print('dezena: {}'.format(numero[2]))
print('centena: {} '.format(numero[3]))
print('unidade de milhar: {}'.format(numero[4]))
| numero = str(input('digite um numero'))
print('unidade: {}'.format(numero[1]))
print('dezena: {}'.format(numero[2]))
print('centena: {} '.format(numero[3]))
print('unidade de milhar: {}'.format(numero[4])) |
def floydwarshall(G):
"""
Compute and return the all pairs shortest paths solution.
Notice the returned path cost matrix P has modified entries. For
example, P[i][j] contains a tuple (c, v1) where c is the cost of the
shortest path from i to j, and v1 is the first vertex along said path
after i. If there is no such vertex, then it is -1.
"""
N = len(G)
P = [[(G[i][j],j) for j in range(N)] for i in range(N)]
for i in range(N):
P[i][i] = (0, -1)
for k in range(N):
for i in range(N):
for j in range(N):
alt = P[i][k][0] + P[k][j][0]
if P[i][j][0] > alt:
P[i][j] = (alt, P[i][k][1])
return P
def printpath(P, u, w):
"""
Given modified path cost matrix (see floydwarshall) return shortest path
from i to j.
"""
path = [u]
while P[u][w][1] != -1:
path.append(P[u][w][1])
u = P[u][w][1]
return path
def pprint(matrix): #https://stackoverflow.com/questions/13214809/
"""
Pretty print matrix with proper spacing. Don't worry about this.
"""
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print('\n'.join(table))
'''
Let us create the following weighted graph (graph art stolen from g4g)
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3
'''
inf = float('inf')
G = [ [inf , 5 , inf, 10 ],
[inf , inf, 3 , inf],
[inf , inf, inf, 1 ],
[inf , inf, inf, inf]]
print('Edge Cost Matrix')
pprint(G)
P = floydwarshall(G)
print('Path Cost Matrix')
pprint(P)
print(printpath(P, 0, 2))
| def floydwarshall(G):
"""
Compute and return the all pairs shortest paths solution.
Notice the returned path cost matrix P has modified entries. For
example, P[i][j] contains a tuple (c, v1) where c is the cost of the
shortest path from i to j, and v1 is the first vertex along said path
after i. If there is no such vertex, then it is -1.
"""
n = len(G)
p = [[(G[i][j], j) for j in range(N)] for i in range(N)]
for i in range(N):
P[i][i] = (0, -1)
for k in range(N):
for i in range(N):
for j in range(N):
alt = P[i][k][0] + P[k][j][0]
if P[i][j][0] > alt:
P[i][j] = (alt, P[i][k][1])
return P
def printpath(P, u, w):
"""
Given modified path cost matrix (see floydwarshall) return shortest path
from i to j.
"""
path = [u]
while P[u][w][1] != -1:
path.append(P[u][w][1])
u = P[u][w][1]
return path
def pprint(matrix):
"""
Pretty print matrix with proper spacing. Don't worry about this.
"""
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join(('{{:{}}}'.format(x) for x in lens))
table = [fmt.format(*row) for row in s]
print('\n'.join(table))
'\nLet us create the following weighted graph (graph art stolen from g4g)\n 10 \n (0)------->(3) \n | /|\\ \n 5 | | \n | | 1 \n \\|/ | \n (1)------->(2) \n 3 \n'
inf = float('inf')
g = [[inf, 5, inf, 10], [inf, inf, 3, inf], [inf, inf, inf, 1], [inf, inf, inf, inf]]
print('Edge Cost Matrix')
pprint(G)
p = floydwarshall(G)
print('Path Cost Matrix')
pprint(P)
print(printpath(P, 0, 2)) |
"""
Tema: Arrays
Curso: Estructura de Datos Lineales (Python).
Plataforma: Platzi.
Profesor: Hector Vega.
Alumno: @edinsonrequena.
"""
class Array(object):
"""A simple array"""
def __init__(self, capacity: int, fill_value=None) -> None:
self.items = list()
for i in range(capacity):
self.items.append(fill_value)
def __len__(self) -> int:
"""
Method to Know the array's lenght
"""
count = 0
for i in self.items:
count += 1
return count
def __str__(self) -> str:
"""Returns string representation of the array"""
return str(self.items)
def __iter__(self):
"""
Method to iter the array
"""
current = 0
while current < len(self.items):
yield current
current += 1
def __getitem__(self, index: any) -> any:
"""
returns a specific index
"""
return self.items[index]
def __setitem__(self, index, new_item):
"""
set item in a specific index
"""
self.items[index] = new_item
return self.items
def __fillslots__(self):
"""
return a sequence of numbers according to the array's length
"""
slots = self.items
for i in range(len(slots)):
slots[i] = i + 1
return slots
def __sumlements__(self) -> list or None:
"""
return the sum of all array's elements if and only if the elements are integers
"""
arr = self.items
try:
for i in range(len(arr)):
if type(arr[i]) != int:
raise TypeError('Solo se pueden sumar enteros')
return sum(arr)
except TypeError as e:
print(e)
def __add__(self, index, item):
"""
returns the array with de new element
"""
arr = self.items
return arr[:index] + [item] + arr[index:]
def __append__(self, item):
"""
returns the array with de new element at the end
"""
arr = self.items
return arr[:] + [item]
def __pop__(self, index):
"""
returns the array without the select element
"""
arr = self.items
arr.pop()
return arr
| """
Tema: Arrays
Curso: Estructura de Datos Lineales (Python).
Plataforma: Platzi.
Profesor: Hector Vega.
Alumno: @edinsonrequena.
"""
class Array(object):
"""A simple array"""
def __init__(self, capacity: int, fill_value=None) -> None:
self.items = list()
for i in range(capacity):
self.items.append(fill_value)
def __len__(self) -> int:
"""
Method to Know the array's lenght
"""
count = 0
for i in self.items:
count += 1
return count
def __str__(self) -> str:
"""Returns string representation of the array"""
return str(self.items)
def __iter__(self):
"""
Method to iter the array
"""
current = 0
while current < len(self.items):
yield current
current += 1
def __getitem__(self, index: any) -> any:
"""
returns a specific index
"""
return self.items[index]
def __setitem__(self, index, new_item):
"""
set item in a specific index
"""
self.items[index] = new_item
return self.items
def __fillslots__(self):
"""
return a sequence of numbers according to the array's length
"""
slots = self.items
for i in range(len(slots)):
slots[i] = i + 1
return slots
def __sumlements__(self) -> list or None:
"""
return the sum of all array's elements if and only if the elements are integers
"""
arr = self.items
try:
for i in range(len(arr)):
if type(arr[i]) != int:
raise type_error('Solo se pueden sumar enteros')
return sum(arr)
except TypeError as e:
print(e)
def __add__(self, index, item):
"""
returns the array with de new element
"""
arr = self.items
return arr[:index] + [item] + arr[index:]
def __append__(self, item):
"""
returns the array with de new element at the end
"""
arr = self.items
return arr[:] + [item]
def __pop__(self, index):
"""
returns the array without the select element
"""
arr = self.items
arr.pop()
return arr |
def f():
'''f'''
pass
def f1(): pass
f2 = f
if True:
def g(): pass
else:
def h(): pass
class C:
def i(self): pass
def j(self):
def j2(self):
pass
class C2:
def k(self): pass
| def f():
"""f"""
pass
def f1():
pass
f2 = f
if True:
def g():
pass
else:
def h():
pass
class C:
def i(self):
pass
def j(self):
def j2(self):
pass
class C2:
def k(self):
pass |
# 450. Delete_Node_in_a_BST
# ttungl@gmail.com
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
# // search key in the tree, if key is found, return root.
# // if key found at node n:
# // + node has no left/right: return null
# // + node has either left/right: return right/left
# // + node has both left and right:
# // + find minval of right.
# // + set minval to current node found
# // + delete min in right.
# // time complexity: O(height of tree)
# // space complexity: O(n)
if root is None:
return None
# search the key
if root.val > key:
root.left = self.deleteNode(root.left, key)
elif root.val < key:
root.right = self.deleteNode(root.right, key)
else: # key is found
if root.left is None:
return root.right
elif root.right is None:
return root.left
minValue = root.right
while minValue.left: # find min value
minValue = minValue.left
# replace current found
minValue.left = root.left
return root.right
return root
| class Solution(object):
def delete_node(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if root is None:
return None
if root.val > key:
root.left = self.deleteNode(root.left, key)
elif root.val < key:
root.right = self.deleteNode(root.right, key)
else:
if root.left is None:
return root.right
elif root.right is None:
return root.left
min_value = root.right
while minValue.left:
min_value = minValue.left
minValue.left = root.left
return root.right
return root |
"""
Day 8 - Part 1
https://adventofcode.com/2021/day/8
By NORXND @ 08.12.2021
(C) NORXND 2021 - Under The MIT License
"""
input_file = open('Day8/input.txt', 'r')
entries = []
for entry in input_file.readlines():
entry = entry.strip().split(" | ")
patterns = entry[0].split(" ")
output = entry[1].split(" ")
entries.append({
"Patterns": patterns,
"Output": output,
})
segments = {
1: 2,
4: 4,
7: 3,
8: 7,
}
matches = []
for entry in entries:
for output in entry["Output"]:
if len(output) in segments.values():
matches.append(output)
print(len(matches)) | """
Day 8 - Part 1
https://adventofcode.com/2021/day/8
By NORXND @ 08.12.2021
(C) NORXND 2021 - Under The MIT License
"""
input_file = open('Day8/input.txt', 'r')
entries = []
for entry in input_file.readlines():
entry = entry.strip().split(' | ')
patterns = entry[0].split(' ')
output = entry[1].split(' ')
entries.append({'Patterns': patterns, 'Output': output})
segments = {1: 2, 4: 4, 7: 3, 8: 7}
matches = []
for entry in entries:
for output in entry['Output']:
if len(output) in segments.values():
matches.append(output)
print(len(matches)) |
IPlist = ['209.85.238.4','216.239.51.98','64.233.173.198','64.3.17.208','64.233.173.238']
# for address in range(len(IPlist)):
# IPlist[address] = '%3s.%3s.%3s.%3s' % tuple(IPlist[address].split('.'))
# IPlist.sort(reverse=False)
# for address in range(len(IPlist)):
# IPlist[address] = IPlist[address].replace(' ', '')
# IPlist.sort(key=lambda address: list(map(int, address.split('.'))))
IPlist.sort(key=lambda address: list(map(str, address.split('.'))))
print(IPlist) | i_plist = ['209.85.238.4', '216.239.51.98', '64.233.173.198', '64.3.17.208', '64.233.173.238']
IPlist.sort(key=lambda address: list(map(str, address.split('.'))))
print(IPlist) |
class Base1:
def FuncA(self):
print("Base1::FuncA")
class Base2:
def FuncA(self):
print("Base2::FuncA")
class Child(Base1, Base2):
pass
def main():
obj=Child()
obj.FuncA()
if __name__ == "__main__":
main()
| class Base1:
def func_a(self):
print('Base1::FuncA')
class Base2:
def func_a(self):
print('Base2::FuncA')
class Child(Base1, Base2):
pass
def main():
obj = child()
obj.FuncA()
if __name__ == '__main__':
main() |
KIND_RETRIEVE_DATA = {
"_embedded": {
"naam": {
"_embedded": {
"inOnderzoek": {
"_embedded": {
"datumIngangOnderzoek": {
"dag": None,
"datum": None,
"jaar": None,
"maand": None,
}
},
"geslachtsnaam": False,
"voornamen": False,
"voorvoegsel": False,
}
},
"geslachtsnaam": "Maykin Kind",
"voorletters": "K",
"voornamen": "Media Kind",
"voorvoegsel": "van",
},
"geboorte": {
"_embedded": {
"datum": {"dag": 15, "datum": "1999-06-15", "jaar": 1999, "maand": 6},
"land": {"code": "6030", "omschrijving": "Nederland"},
"plaats": {"code": "624", "omschrijving": "Amsterdam"},
"inOnderzoek": {
"_embedded": {
"datumIngangOnderzoek": {
"dag": None,
"datum": None,
"jaar": None,
"maand": None,
}
},
"datum": False,
"land": False,
"plaats": False,
},
}
},
"inOnderzoek": {
"_embedded": {
"datumIngangOnderzoek": {
"dag": None,
"datum": None,
"jaar": None,
"maand": None,
}
},
"burgerservicenummer": False,
},
},
"burgerservicenummer": "456789123",
"geheimhoudingPersoonsgegevens": True,
"leeftijd": 21,
}
KIND_RETRIEVE_DATA_NO_DATES = {
"_embedded": {
"naam": {
"_embedded": {
"inOnderzoek": {
"_embedded": {
"datumIngangOnderzoek": {
"dag": None,
"datum": None,
"jaar": None,
"maand": None,
}
},
"geslachtsnaam": False,
"voornamen": False,
"voorvoegsel": False,
}
},
"geslachtsnaam": "Maykin Kind",
"voorletters": "K",
"voornamen": "Media Kind",
"voorvoegsel": "van",
},
"geboorte": {
"_embedded": {
"datum": {"dag": None, "datum": None, "jaar": None, "maand": None},
"land": {"code": "6030", "omschrijving": "Nederland"},
"plaats": {"code": "624", "omschrijving": "Amsterdam"},
"inOnderzoek": {
"_embedded": {
"datumIngangOnderzoek": {
"dag": None,
"datum": None,
"jaar": None,
"maand": None,
}
},
"datum": False,
"land": False,
"plaats": False,
},
}
},
"inOnderzoek": {
"_embedded": {
"datumIngangOnderzoek": {
"dag": None,
"datum": None,
"jaar": None,
"maand": None,
}
},
"burgerservicenummer": False,
},
},
"burgerservicenummer": "456789123",
"geheimhoudingPersoonsgegevens": True,
"leeftijd": 0,
}
| kind_retrieve_data = {'_embedded': {'naam': {'_embedded': {'inOnderzoek': {'_embedded': {'datumIngangOnderzoek': {'dag': None, 'datum': None, 'jaar': None, 'maand': None}}, 'geslachtsnaam': False, 'voornamen': False, 'voorvoegsel': False}}, 'geslachtsnaam': 'Maykin Kind', 'voorletters': 'K', 'voornamen': 'Media Kind', 'voorvoegsel': 'van'}, 'geboorte': {'_embedded': {'datum': {'dag': 15, 'datum': '1999-06-15', 'jaar': 1999, 'maand': 6}, 'land': {'code': '6030', 'omschrijving': 'Nederland'}, 'plaats': {'code': '624', 'omschrijving': 'Amsterdam'}, 'inOnderzoek': {'_embedded': {'datumIngangOnderzoek': {'dag': None, 'datum': None, 'jaar': None, 'maand': None}}, 'datum': False, 'land': False, 'plaats': False}}}, 'inOnderzoek': {'_embedded': {'datumIngangOnderzoek': {'dag': None, 'datum': None, 'jaar': None, 'maand': None}}, 'burgerservicenummer': False}}, 'burgerservicenummer': '456789123', 'geheimhoudingPersoonsgegevens': True, 'leeftijd': 21}
kind_retrieve_data_no_dates = {'_embedded': {'naam': {'_embedded': {'inOnderzoek': {'_embedded': {'datumIngangOnderzoek': {'dag': None, 'datum': None, 'jaar': None, 'maand': None}}, 'geslachtsnaam': False, 'voornamen': False, 'voorvoegsel': False}}, 'geslachtsnaam': 'Maykin Kind', 'voorletters': 'K', 'voornamen': 'Media Kind', 'voorvoegsel': 'van'}, 'geboorte': {'_embedded': {'datum': {'dag': None, 'datum': None, 'jaar': None, 'maand': None}, 'land': {'code': '6030', 'omschrijving': 'Nederland'}, 'plaats': {'code': '624', 'omschrijving': 'Amsterdam'}, 'inOnderzoek': {'_embedded': {'datumIngangOnderzoek': {'dag': None, 'datum': None, 'jaar': None, 'maand': None}}, 'datum': False, 'land': False, 'plaats': False}}}, 'inOnderzoek': {'_embedded': {'datumIngangOnderzoek': {'dag': None, 'datum': None, 'jaar': None, 'maand': None}}, 'burgerservicenummer': False}}, 'burgerservicenummer': '456789123', 'geheimhoudingPersoonsgegevens': True, 'leeftijd': 0} |
# -*- coding: utf-8 -*-
#from pkg_resources import resource_filename
class dlib_model:
def pose_predictor_model_location():
return "./models/dlib/shape_predictor_68_face_landmarks.dat"
def pose_predictor_five_point_model_location():
return "./models/dlib/shape_predictor_5_face_landmarks.dat"
def face_recognition_model_location():
return "./models/dlib/dlib_face_recognition_resnet_model_v1_for_asian.dat"
def cnn_face_detector_model_location():
return "./models/dlib/mmod_human_face_detector.dat"
class opencv_model:
def caff_model_location():
return "./models/opencv/res10_300x300_ssd_iter_140000_fp16.caffemodel"
def caff_cfgfile_location():
return "./models/opencv/deploy.prototxt"
def tensorflow_model_location():
return "./models/opencv/opencv_face_detector_uint8.pb"
def tensorflow_cfgfile_location():
return "./models/opencv/opencv_face_detector.pbtxt"
class classifier_model:
def classifier_location():
return "./models/classifier/face_classifier.pkl"
| class Dlib_Model:
def pose_predictor_model_location():
return './models/dlib/shape_predictor_68_face_landmarks.dat'
def pose_predictor_five_point_model_location():
return './models/dlib/shape_predictor_5_face_landmarks.dat'
def face_recognition_model_location():
return './models/dlib/dlib_face_recognition_resnet_model_v1_for_asian.dat'
def cnn_face_detector_model_location():
return './models/dlib/mmod_human_face_detector.dat'
class Opencv_Model:
def caff_model_location():
return './models/opencv/res10_300x300_ssd_iter_140000_fp16.caffemodel'
def caff_cfgfile_location():
return './models/opencv/deploy.prototxt'
def tensorflow_model_location():
return './models/opencv/opencv_face_detector_uint8.pb'
def tensorflow_cfgfile_location():
return './models/opencv/opencv_face_detector.pbtxt'
class Classifier_Model:
def classifier_location():
return './models/classifier/face_classifier.pkl' |
# %% [705. Design HashSet](https://leetcode.com/problems/design-hashset/)
class MyHashSet(set):
remove = set.discard
contains = set.__contains__
| class Myhashset(set):
remove = set.discard
contains = set.__contains__ |
words_count = int(input())
words_dict = {}
def add_word(word,definition):
words_dict[word] = definition
def translate_sentence(words_list):
sentence = ""
for word in words_list:
if word in words_dict:
sentence += words_dict[word] + " "
else:
sentence += word + " "
return sentence
for i in range(words_count + 1):
text = input()
words = text.split(" ")
if len(words) == 2:
add_word(words[0] ,words[1])
else:
print(translate_sentence(words))
| words_count = int(input())
words_dict = {}
def add_word(word, definition):
words_dict[word] = definition
def translate_sentence(words_list):
sentence = ''
for word in words_list:
if word in words_dict:
sentence += words_dict[word] + ' '
else:
sentence += word + ' '
return sentence
for i in range(words_count + 1):
text = input()
words = text.split(' ')
if len(words) == 2:
add_word(words[0], words[1])
else:
print(translate_sentence(words)) |
''' Control Structures
A statement used to control the flow of execution in a program is called a control structure.
Types of control structures
1. Sequence ******************************************************
In a sequential structure the statements are executed in the same order in which they are specified in the program, the control flows from one statement to the other in a logical sequence, all sequences are executed exactly as run.
It means that no statement is kept and no statement is executed more than once.
Statement # 1
Statement # 2
Statement # 3
Statement # 4
An example
Start
|
input base
|
input height
|
input height
|
calculate area
Area = 1/2 * base * height
|
Display Area
|
End
2. Selection ******************************************************
A selection structure selects a statement or set of statements to execute on the basis of a condition.
In this structure, a statement or set of statements is executed when the condition is True. And ignored when the condition is False.
An example
Suppose a program that imputs the temperature and then displays the message on the screen.
If the temperature is greater than 35, the it displays the message "Hot day".
When the temperature is between 25 and 35 the it displays the message "Pleasant day".
If it is less than 25, then it displays the message "cool day".
Flowchart of simple selection.
Condition
T or F
T F
(if True) (if False)
Statement #1 Statement #2
3. Repetition
A repetition structure executes a statement or set of statements repeadadly.
It is also known as iterations or loops.
An example.
Suspose we want to display a message to the screen "Hello World" one thousand times!
It takes huge time to write that code and it takes more space as well. (lenghty awkward looking code)
It is very easy to perform this task usig loops or repetition structure.
Flowchart of Repetition
_______
| |
| |
| Condition = F
| T or F |
| | T |
| | |
| Statement |
|_______| |
|
End of loop
4. Relational or Comparision Operators.
Less than, greater than or equal to.
Sometime we need to do a lot of comparisions in order to see whether a specific command should be executed.
The conditional statements are used to specify conditions in programs.
A relatinal operator compares two values. It produces a result as True or False.
The relation operators are sometimes called the conditional operators as they test conditions that are tru or false.
RELATIONAL OR COMPARISION OPERATORS
> Greater than returns true if the value on the left side of > is greater than the value on the righr side. Otherwise, it returns false.
>>> # greator than operator (>)
>>> 10 > 3
True
>>> 10 > 13
False
< Less than operator returns true if the value on the left side < is less than the value on the rught side. Otherwise it returns false.
>>> # Less Than operator (<)
>>> 3 < 7
True
>>> 10 < 7
False
== Equals operator returns true if the value on both sides of == are equal. Otherwise returns false. == The assignment operator is used to assign the value on the right hand side of any expression to the variable on the left hand side while the equal equal operator which is Gradley comparision operator is used to compare the two to values on the left and right hand side of this operator.
>>> 10 == 10
True
>>> 10 == 11
False
>= Greater that or equal to operator returns true if the value on the left side of >= us greator than or equal to the value on the right hand side. Otherwise returns false.
>>> # Greater that or equal to operator (>=)
>>> 10 >= 9
True
>>> 10 >= 10
True
>>> 10 >= 11
False
<= Less that or equal to operator returns true if the value on the left of <= is less than or equal to value on right side. Otherwise returns false.
>>> # Lesser than or equal to operator
>>> 10 <= 10
True
>>> 10 <= 11
True
>>> 10 <= 9
False
!= The not equal to operator. Returns true if the value on the left side of != is not equal to the value on the right. Otherwise returns false.
>>> # not equal to operator
>>> 10 != 10
False
>>> 10 == 10
True
>>> 3 != 5
True
'''
| """ Control Structures
A statement used to control the flow of execution in a program is called a control structure.
Types of control structures
1. Sequence ******************************************************
In a sequential structure the statements are executed in the same order in which they are specified in the program, the control flows from one statement to the other in a logical sequence, all sequences are executed exactly as run.
It means that no statement is kept and no statement is executed more than once.
Statement # 1
Statement # 2
Statement # 3
Statement # 4
An example
Start
|
input base
|
input height
|
input height
|
calculate area
Area = 1/2 * base * height
|
Display Area
|
End
2. Selection ******************************************************
A selection structure selects a statement or set of statements to execute on the basis of a condition.
In this structure, a statement or set of statements is executed when the condition is True. And ignored when the condition is False.
An example
Suppose a program that imputs the temperature and then displays the message on the screen.
If the temperature is greater than 35, the it displays the message "Hot day".
When the temperature is between 25 and 35 the it displays the message "Pleasant day".
If it is less than 25, then it displays the message "cool day".
Flowchart of simple selection.
Condition
T or F
T F
(if True) (if False)
Statement #1 Statement #2
3. Repetition
A repetition structure executes a statement or set of statements repeadadly.
It is also known as iterations or loops.
An example.
Suspose we want to display a message to the screen "Hello World" one thousand times!
It takes huge time to write that code and it takes more space as well. (lenghty awkward looking code)
It is very easy to perform this task usig loops or repetition structure.
Flowchart of Repetition
_______
| |
| |
| Condition = F
| T or F |
| | T |
| | |
| Statement |
|_______| |
|
End of loop
4. Relational or Comparision Operators.
Less than, greater than or equal to.
Sometime we need to do a lot of comparisions in order to see whether a specific command should be executed.
The conditional statements are used to specify conditions in programs.
A relatinal operator compares two values. It produces a result as True or False.
The relation operators are sometimes called the conditional operators as they test conditions that are tru or false.
RELATIONAL OR COMPARISION OPERATORS
> Greater than returns true if the value on the left side of > is greater than the value on the righr side. Otherwise, it returns false.
>>> # greator than operator (>)
>>> 10 > 3
True
>>> 10 > 13
False
< Less than operator returns true if the value on the left side < is less than the value on the rught side. Otherwise it returns false.
>>> # Less Than operator (<)
>>> 3 < 7
True
>>> 10 < 7
False
== Equals operator returns true if the value on both sides of == are equal. Otherwise returns false. == The assignment operator is used to assign the value on the right hand side of any expression to the variable on the left hand side while the equal equal operator which is Gradley comparision operator is used to compare the two to values on the left and right hand side of this operator.
>>> 10 == 10
True
>>> 10 == 11
False
>= Greater that or equal to operator returns true if the value on the left side of >= us greator than or equal to the value on the right hand side. Otherwise returns false.
>>> # Greater that or equal to operator (>=)
>>> 10 >= 9
True
>>> 10 >= 10
True
>>> 10 >= 11
False
<= Less that or equal to operator returns true if the value on the left of <= is less than or equal to value on right side. Otherwise returns false.
>>> # Lesser than or equal to operator
>>> 10 <= 10
True
>>> 10 <= 11
True
>>> 10 <= 9
False
!= The not equal to operator. Returns true if the value on the left side of != is not equal to the value on the right. Otherwise returns false.
>>> # not equal to operator
>>> 10 != 10
False
>>> 10 == 10
True
>>> 3 != 5
True
""" |
#33
# Time: O(logn)
# Space: O(1)
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
#
# You are given a target value to search. If found in the array return its index, otherwise return -1.
#
# You may assume no duplicate exists in the array.
class binarySearchSol():
def searchInRotatedArrayI(self,nums,target):
left,right=0,len(nums)-1
while left<=right:
mid=(left+right)//2
if nums[mid]==target:
return mid
elif (nums[mid]>nums[left] and nums[left]<=target<nums[mid]) or \
(nums[mid]<nums[left] and not (nums[mid]<target<=nums[right])):
right=mid-1
else:
left=mid+1
return -1
| class Binarysearchsol:
def search_in_rotated_array_i(self, nums, target):
(left, right) = (0, len(nums) - 1)
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] > nums[left] and nums[left] <= target < nums[mid] or (nums[mid] < nums[left] and (not nums[mid] < target <= nums[right])):
right = mid - 1
else:
left = mid + 1
return -1 |
"""Chapter 8 Practice Question 3
Draw the complete truth tables for the and, or, and not operators.
"""
def notTruthTable() -> None:
"""Not truth table.
Prints a truth table for the not operator.
Returns:
None. Only prints out a table.
"""
print(" _________________________\n",
"|not A | Evaluates to:|\n",
"|_________|______________|\n",
"|not False| True |\n",
"|not True | False |\n",
"|_________|______________|\n")
return None
def andTruthTable() -> None:
"""And truth table.
Prints a truth table for the and operator.
Returns:
None. Only prints out a table.
"""
print(" _______________________________\n",
"|A and B | Evaluates to:|\n",
"|_______________|______________|\n",
"|False and False| False |\n",
"|False and True | False |\n",
"|True and False | False |\n",
"|True and True | True |\n",
"|_______________|______________|\n")
return None
def orTruthTable() -> None:
"""Or truth table.
Prints a truth table for the or operator.
Returns:
None. Only prints out a table.
"""
print(" ______________________________\n",
"|A or B | Evaluates to:|\n",
"|______________|______________|\n",
"|False or False| False |\n",
"|False or True | True |\n",
"|True or False | True |\n",
"|True or True | True |\n",
"|______________|______________|\n")
return None
def main():
notTruthTable()
andTruthTable()
orTruthTable()
# If Question3.py is run (instead of imported as a module), call
# the main() function:
if __name__ == '__main__':
main()
| """Chapter 8 Practice Question 3
Draw the complete truth tables for the and, or, and not operators.
"""
def not_truth_table() -> None:
"""Not truth table.
Prints a truth table for the not operator.
Returns:
None. Only prints out a table.
"""
print(' _________________________\n', '|not A | Evaluates to:|\n', '|_________|______________|\n', '|not False| True |\n', '|not True | False |\n', '|_________|______________|\n')
return None
def and_truth_table() -> None:
"""And truth table.
Prints a truth table for the and operator.
Returns:
None. Only prints out a table.
"""
print(' _______________________________\n', '|A and B | Evaluates to:|\n', '|_______________|______________|\n', '|False and False| False |\n', '|False and True | False |\n', '|True and False | False |\n', '|True and True | True |\n', '|_______________|______________|\n')
return None
def or_truth_table() -> None:
"""Or truth table.
Prints a truth table for the or operator.
Returns:
None. Only prints out a table.
"""
print(' ______________________________\n', '|A or B | Evaluates to:|\n', '|______________|______________|\n', '|False or False| False |\n', '|False or True | True |\n', '|True or False | True |\n', '|True or True | True |\n', '|______________|______________|\n')
return None
def main():
not_truth_table()
and_truth_table()
or_truth_table()
if __name__ == '__main__':
main() |
"""
-*- coding: utf-8 -*-
Time : 2019/7/19 8:25
Author : Hansybx
"""
class Res:
code = 200
msg = ''
info = {}
def __init__(self, code, msg, info):
self.code = code
self.msg = msg
self.info = info
| """
-*- coding: utf-8 -*-
Time : 2019/7/19 8:25
Author : Hansybx
"""
class Res:
code = 200
msg = ''
info = {}
def __init__(self, code, msg, info):
self.code = code
self.msg = msg
self.info = info |
class Task:
def __init__(self,name,due_date):
self.name = name
self.due_date = due_date
self.comments=[]
self.completed=False
def change_name(self,new_name:str):
if self.name==new_name:
return f"Name cannot be the same."
self.name=new_name
return self.name
def change_due_date(self,new_date:str):
if self.due_date==new_date:
return "Date cannot be the same."
self.due_date=new_date
return self.due_date
def add_comment(self,comment:str):
self.comments.append(comment)
def edit_comment(self,comment_number:int,new_comment:str):
if 0<comment_number>=len(self.comments):
return "Cannot find comment."
self.comments[comment_number]=new_comment
return f"{', '.join([x for x in self.comments])}"
def details(self):
return f"Name: {self.name} - Due Date: {self.due_date}"
| class Task:
def __init__(self, name, due_date):
self.name = name
self.due_date = due_date
self.comments = []
self.completed = False
def change_name(self, new_name: str):
if self.name == new_name:
return f'Name cannot be the same.'
self.name = new_name
return self.name
def change_due_date(self, new_date: str):
if self.due_date == new_date:
return 'Date cannot be the same.'
self.due_date = new_date
return self.due_date
def add_comment(self, comment: str):
self.comments.append(comment)
def edit_comment(self, comment_number: int, new_comment: str):
if 0 < comment_number >= len(self.comments):
return 'Cannot find comment.'
self.comments[comment_number] = new_comment
return f"{', '.join([x for x in self.comments])}"
def details(self):
return f'Name: {self.name} - Due Date: {self.due_date}' |
class BITree:
def __init__(self, nums):
self.n = len(nums)
self.arr = [0 for _ in range(self.n)]
self.bitree = [0 for _ in range(self.n + 1)]
for i in range(self.n):
self.update(i, nums[i])
def update(self, i, val):
diff = val - self.arr[i]
self.arr[i] = val
i += 1
while i <= self.n:
self.bitree[i] += diff
i += i & (-i)
def sumRange(self, i, j):
return self._getSum(j) - self._getSum(i - 1)
def _getSum(self, i):
i += 1
sum = 0
while i > 0:
sum += self.bitree[i]
i -= i & (-i)
return sum
class Solution:
"""
@param: A: An integer array
"""
def __init__(self, A):
self.bitree = BITree(A)
"""
@param: start: An integer
@param: end: An integer
@return: The sum from start to end
"""
def query(self, start, end):
return self.bitree.sumRange(start, end)
"""
@param: index: An integer
@param: value: An integer
@return: nothing
"""
def modify(self, index, value):
self.bitree.update(index, value) | class Bitree:
def __init__(self, nums):
self.n = len(nums)
self.arr = [0 for _ in range(self.n)]
self.bitree = [0 for _ in range(self.n + 1)]
for i in range(self.n):
self.update(i, nums[i])
def update(self, i, val):
diff = val - self.arr[i]
self.arr[i] = val
i += 1
while i <= self.n:
self.bitree[i] += diff
i += i & -i
def sum_range(self, i, j):
return self._getSum(j) - self._getSum(i - 1)
def _get_sum(self, i):
i += 1
sum = 0
while i > 0:
sum += self.bitree[i]
i -= i & -i
return sum
class Solution:
"""
@param: A: An integer array
"""
def __init__(self, A):
self.bitree = bi_tree(A)
'\n @param: start: An integer\n @param: end: An integer\n @return: The sum from start to end\n '
def query(self, start, end):
return self.bitree.sumRange(start, end)
'\n @param: index: An integer\n @param: value: An integer\n @return: nothing\n '
def modify(self, index, value):
self.bitree.update(index, value) |
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
res = 0
while n:
res += 1
n &= (n-1)
return res
def hammingWeight(self, n):
for i in range(33):
if not n: return i
n &= (n - 1)
# cheat
def hammingWeight(self, n):
return bin(n).count('1')
| class Solution(object):
def hamming_weight(self, n):
"""
:type n: int
:rtype: int
"""
res = 0
while n:
res += 1
n &= n - 1
return res
def hamming_weight(self, n):
for i in range(33):
if not n:
return i
n &= n - 1
def hamming_weight(self, n):
return bin(n).count('1') |
"""
133 / 133 test cases passed.
Runtime: 56 ms
Memory Usage: 15.1 MB
"""
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
l, r = 0, m * n - 1
while l < r:
mid = (l + r + 1) >> 1
if matrix[mid // n][mid % n] <= target:
l = mid
else:
r = mid - 1
return matrix[r // n][r % n] == target
| """
133 / 133 test cases passed.
Runtime: 56 ms
Memory Usage: 15.1 MB
"""
class Solution:
def search_matrix(self, matrix: List[List[int]], target: int) -> bool:
(m, n) = (len(matrix), len(matrix[0]))
(l, r) = (0, m * n - 1)
while l < r:
mid = l + r + 1 >> 1
if matrix[mid // n][mid % n] <= target:
l = mid
else:
r = mid - 1
return matrix[r // n][r % n] == target |
class ManuscriptSubjectAreaService:
def __init__(self, df):
self._df = df
self._subject_areas_by_id_map = df.groupby(
'version_id')['subject_area'].apply(sorted).to_dict()
@staticmethod
def from_database(db, valid_version_ids=None):
df = db.manuscript_subject_area.read_frame()
if valid_version_ids is not None:
df = df[df['version_id'].isin(valid_version_ids)]
return ManuscriptSubjectAreaService(df)
def get_ids_by_subject_areas(self, subject_areas):
df = self._df[self._df['subject_area'].str.lower().isin(
[s.lower() for s in subject_areas]
)]
return set(df['version_id'])
def get_subject_areas_by_id(self, manuscript_version_id):
return self._subject_areas_by_id_map.get(manuscript_version_id, [])
def get_all_subject_areas(self):
return set(self._df['subject_area'].unique())
| class Manuscriptsubjectareaservice:
def __init__(self, df):
self._df = df
self._subject_areas_by_id_map = df.groupby('version_id')['subject_area'].apply(sorted).to_dict()
@staticmethod
def from_database(db, valid_version_ids=None):
df = db.manuscript_subject_area.read_frame()
if valid_version_ids is not None:
df = df[df['version_id'].isin(valid_version_ids)]
return manuscript_subject_area_service(df)
def get_ids_by_subject_areas(self, subject_areas):
df = self._df[self._df['subject_area'].str.lower().isin([s.lower() for s in subject_areas])]
return set(df['version_id'])
def get_subject_areas_by_id(self, manuscript_version_id):
return self._subject_areas_by_id_map.get(manuscript_version_id, [])
def get_all_subject_areas(self):
return set(self._df['subject_area'].unique()) |
def _cc_stamp_header(ctx):
out = ctx.outputs.out
args = ctx.actions.args()
args.add("--stable_status", ctx.info_file)
args.add("--volatile_status", ctx.version_file)
args.add("--output_header", out)
ctx.actions.run(
outputs = [out],
inputs = [ctx.info_file, ctx.version_file],
arguments = [args],
executable = ctx.executable.tool,
)
return DefaultInfo(files = depset([out]))
cc_stamp_header = rule(
implementation = _cc_stamp_header,
attrs = {
"out": attr.output(
doc = "C++ header file to generate",
mandatory = True,
),
"tool": attr.label(
default = Label("@rules_cc_stamp//cc_stamp_header_generator"),
cfg = "exec",
executable = True,
),
},
)
| def _cc_stamp_header(ctx):
out = ctx.outputs.out
args = ctx.actions.args()
args.add('--stable_status', ctx.info_file)
args.add('--volatile_status', ctx.version_file)
args.add('--output_header', out)
ctx.actions.run(outputs=[out], inputs=[ctx.info_file, ctx.version_file], arguments=[args], executable=ctx.executable.tool)
return default_info(files=depset([out]))
cc_stamp_header = rule(implementation=_cc_stamp_header, attrs={'out': attr.output(doc='C++ header file to generate', mandatory=True), 'tool': attr.label(default=label('@rules_cc_stamp//cc_stamp_header_generator'), cfg='exec', executable=True)}) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 11 11:47:23 2021
@author: Claire He
Selecting Topics : paper suggest topic selection policy-wise using Meade (2017)
work on dissent in policies. We may want to use the same method to select
Using Lasso regression shrinkage
"""
| """
Created on Mon Oct 11 11:47:23 2021
@author: Claire He
Selecting Topics : paper suggest topic selection policy-wise using Meade (2017)
work on dissent in policies. We may want to use the same method to select
Using Lasso regression shrinkage
""" |
def permute(obj_list, l, r, level):
"""Helper function to implement the nAr permutation operation
Arguments:
obj_list -- the list of objects from which the permutation should be generated
l -- left end point of current permutation
r -- right end point (exclusive) of current permutation
level -- used to stop the recursion prematruely according to r
"""
if level == 0:
print(obj_list[:l])
else:
for i in range(l, r):
obj_list[l], obj_list[i] = obj_list[i], obj_list[l]
permute(obj_list, l + 1, r, level - 1)
obj_list[l], obj_list[i] = obj_list[i], obj_list[l]
def nAr(obj_list, n, r):
"""Implement the nAr permutation operation
Arguments:
obj_list -- the list of objects from which the permutation should be generated
n -- number of elements in object list
r -- number of chosen elements
"""
assert len(obj_list) == n and r <= n, "incorrect input!"
permute(obj_list, 0, n, r)
obj_list = [1, 2, 3]
nAr(obj_list, len(obj_list), 2)
| def permute(obj_list, l, r, level):
"""Helper function to implement the nAr permutation operation
Arguments:
obj_list -- the list of objects from which the permutation should be generated
l -- left end point of current permutation
r -- right end point (exclusive) of current permutation
level -- used to stop the recursion prematruely according to r
"""
if level == 0:
print(obj_list[:l])
else:
for i in range(l, r):
(obj_list[l], obj_list[i]) = (obj_list[i], obj_list[l])
permute(obj_list, l + 1, r, level - 1)
(obj_list[l], obj_list[i]) = (obj_list[i], obj_list[l])
def n_ar(obj_list, n, r):
"""Implement the nAr permutation operation
Arguments:
obj_list -- the list of objects from which the permutation should be generated
n -- number of elements in object list
r -- number of chosen elements
"""
assert len(obj_list) == n and r <= n, 'incorrect input!'
permute(obj_list, 0, n, r)
obj_list = [1, 2, 3]
n_ar(obj_list, len(obj_list), 2) |
print('Challenge 14: WAF to check if a number is present in a list or not.')
test_list = [ 1, 6, 3, 5, 3, 4 ]
print("Checking if 6 exists in list: ")
# Checking if 6 exists in list
# using loop
for i in test_list:
if(i == 6) :
print ("Element Exists") | print('Challenge 14: WAF to check if a number is present in a list or not.')
test_list = [1, 6, 3, 5, 3, 4]
print('Checking if 6 exists in list: ')
for i in test_list:
if i == 6:
print('Element Exists') |
# dictionaries
friends = ["john", "andre", "mark", "robert"]
ages = [23, 43, 54, 12]
biodatas_dict = dict(zip(friends, ages))
print(biodatas_dict)
# list
biodatas_list = list(zip(friends, ages))
print(biodatas_list)
# tuple
biodatas_tuple = tuple(zip(friends, ages))
print(biodatas_tuple)
| friends = ['john', 'andre', 'mark', 'robert']
ages = [23, 43, 54, 12]
biodatas_dict = dict(zip(friends, ages))
print(biodatas_dict)
biodatas_list = list(zip(friends, ages))
print(biodatas_list)
biodatas_tuple = tuple(zip(friends, ages))
print(biodatas_tuple) |
#!/usr/bin/env python
def count_fish(lanternfish: list, repro_day: int) -> int:
return len([x for x in lanternfish if x == repro_day])
def pass_one_day(fish_age_hash: dict, day: int, lanternfish: list=None):
if day == 0:
if not lanternfish:
raise AttributeError("Error: lanternfish list must be passed as arg")
new_fish_age_hash = {
'zero': count_fish(lanternfish, 1),
'one': count_fish(lanternfish, 2),
'two': count_fish(lanternfish, 3),
'three': count_fish(lanternfish, 4),
'four': count_fish(lanternfish, 5),
'five': count_fish(lanternfish, 6),
'six': count_fish(lanternfish, 0) + count_fish(lanternfish, 7),
'seven': count_fish(lanternfish, 8),
'eight': count_fish(lanternfish, 0),
}
else:
new_fish_age_hash = {
'zero': fish_age_hash['one'],
'one': fish_age_hash['two'],
'two': fish_age_hash['three'],
'three': fish_age_hash['four'],
'four': fish_age_hash['five'],
'five': fish_age_hash['six'],
'six': fish_age_hash['zero'] + fish_age_hash['seven'],
'seven': fish_age_hash['eight'],
'eight': fish_age_hash['zero'],
}
return new_fish_age_hash
# Import data
with open('/home/agaspari/aoc2021/dec_6/dec6_input.txt') as f:
lanternfish = [int(x) for x in f.read().split(',')]
# Task 1
fish_age_hash = dict()
for day in range(0, 80):
fish_age_hash = pass_one_day(fish_age_hash, day, lanternfish)
print(sum([v for v in fish_age_hash.values()]))
# Task 2
fish_age_hash = dict()
for day in range(0, 256):
fish_age_hash = pass_one_day(fish_age_hash, day, lanternfish)
print(sum([v for v in fish_age_hash.values()]))
| def count_fish(lanternfish: list, repro_day: int) -> int:
return len([x for x in lanternfish if x == repro_day])
def pass_one_day(fish_age_hash: dict, day: int, lanternfish: list=None):
if day == 0:
if not lanternfish:
raise attribute_error('Error: lanternfish list must be passed as arg')
new_fish_age_hash = {'zero': count_fish(lanternfish, 1), 'one': count_fish(lanternfish, 2), 'two': count_fish(lanternfish, 3), 'three': count_fish(lanternfish, 4), 'four': count_fish(lanternfish, 5), 'five': count_fish(lanternfish, 6), 'six': count_fish(lanternfish, 0) + count_fish(lanternfish, 7), 'seven': count_fish(lanternfish, 8), 'eight': count_fish(lanternfish, 0)}
else:
new_fish_age_hash = {'zero': fish_age_hash['one'], 'one': fish_age_hash['two'], 'two': fish_age_hash['three'], 'three': fish_age_hash['four'], 'four': fish_age_hash['five'], 'five': fish_age_hash['six'], 'six': fish_age_hash['zero'] + fish_age_hash['seven'], 'seven': fish_age_hash['eight'], 'eight': fish_age_hash['zero']}
return new_fish_age_hash
with open('/home/agaspari/aoc2021/dec_6/dec6_input.txt') as f:
lanternfish = [int(x) for x in f.read().split(',')]
fish_age_hash = dict()
for day in range(0, 80):
fish_age_hash = pass_one_day(fish_age_hash, day, lanternfish)
print(sum([v for v in fish_age_hash.values()]))
fish_age_hash = dict()
for day in range(0, 256):
fish_age_hash = pass_one_day(fish_age_hash, day, lanternfish)
print(sum([v for v in fish_age_hash.values()])) |
class MyClass:
def __call__(self): print('__call__')
c = MyClass()
c()
c.__call__()
print()
c.__call__ = lambda: print('overriding call')
c()
c.__call__()
| class Myclass:
def __call__(self):
print('__call__')
c = my_class()
c()
c.__call__()
print()
c.__call__ = lambda : print('overriding call')
c()
c.__call__() |
token = 'Ndhhfghfgh'
firebase = {
"apiKey": "AIzaSyBYHMxJYFVWP6xH55gAY1TJpVECq4KRjKM",
"authDomain": "test24-13912.firebaseapp.com",
"databaseURL": "https://test24-13912-default-rtdb.firebaseio.com",
"projectId": "test24-13912",
"storageBucket": "test24-13912.appspot.com",
"messagingSenderId": "939334214645",
"appId": "1:939334214645:web:3d8f56ea422989878f76bc",
"measurementId": "G-C95H67C4ZD"
} | token = 'Ndhhfghfgh'
firebase = {'apiKey': 'AIzaSyBYHMxJYFVWP6xH55gAY1TJpVECq4KRjKM', 'authDomain': 'test24-13912.firebaseapp.com', 'databaseURL': 'https://test24-13912-default-rtdb.firebaseio.com', 'projectId': 'test24-13912', 'storageBucket': 'test24-13912.appspot.com', 'messagingSenderId': '939334214645', 'appId': '1:939334214645:web:3d8f56ea422989878f76bc', 'measurementId': 'G-C95H67C4ZD'} |
class InstagramQueryId:
USER_MEDIAS = '17880160963012870'
USER_STORIES = '17890626976041463'
STORIES = '17873473675158481'
| class Instagramqueryid:
user_medias = '17880160963012870'
user_stories = '17890626976041463'
stories = '17873473675158481' |
Subsets and Splits