content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Non-OOP # Bank Version 1 # Single account accountName = 'Joe' accountBalance = 100 accountPassword = 'soup' while True: print() print('Press b to get the balance') print('Press d to make a deposit') print('Press w to make a withdrawal') print('Press s to show the account') print('Press q to quit') print() action = input('What do you want to do? ') action = action.lower() # force lowercase action = action[0] # just use first letter print() if action == 'b': print('Get Balance:') userPassword = input('Please enter the password: ') if userPassword != accountPassword: print('Incorrect password') else: print('Your balance is:', accountBalance) elif action == 'd': print('Deposit:') userDepositAmount = input('Please enter amount to deposit: ') userDepositAmount = int(userDepositAmount) userPassword = input('Please enter the password: ') if userDepositAmount < 0: print('You cannot deposit a negative amount!') elif userPassword != accountPassword: print('Incorrect password') else: #OK accountBalance = accountBalance + userDepositAmount print('Your new balance is:', accountBalance) elif action == 's': # show print('Show:') print(' Name', accountName) print(' Balance:', accountBalance) print(' Password:', accountPassword) print() elif action == 'q': break elif action == 'w': print('Withdraw:') userWithdrawAmount = input('Please enter the amount to withdraw: ') userWithdrawAmount = int(userWithdrawAmount) userPassword = input('Please enter the password: ') if userWithdrawAmount < 0: print('You cannot withdraw a negative amount') elif userPassword != accountPassword: print('Incorrect password for this account') elif userWithdrawAmount > accountBalance: print('You cannot withdraw more than you have in your account') else: #OK accountBalance = accountBalance - userWithdrawAmount print('Your new balance is:', accountBalance) print('Done')
account_name = 'Joe' account_balance = 100 account_password = 'soup' while True: print() print('Press b to get the balance') print('Press d to make a deposit') print('Press w to make a withdrawal') print('Press s to show the account') print('Press q to quit') print() action = input('What do you want to do? ') action = action.lower() action = action[0] print() if action == 'b': print('Get Balance:') user_password = input('Please enter the password: ') if userPassword != accountPassword: print('Incorrect password') else: print('Your balance is:', accountBalance) elif action == 'd': print('Deposit:') user_deposit_amount = input('Please enter amount to deposit: ') user_deposit_amount = int(userDepositAmount) user_password = input('Please enter the password: ') if userDepositAmount < 0: print('You cannot deposit a negative amount!') elif userPassword != accountPassword: print('Incorrect password') else: account_balance = accountBalance + userDepositAmount print('Your new balance is:', accountBalance) elif action == 's': print('Show:') print(' Name', accountName) print(' Balance:', accountBalance) print(' Password:', accountPassword) print() elif action == 'q': break elif action == 'w': print('Withdraw:') user_withdraw_amount = input('Please enter the amount to withdraw: ') user_withdraw_amount = int(userWithdrawAmount) user_password = input('Please enter the password: ') if userWithdrawAmount < 0: print('You cannot withdraw a negative amount') elif userPassword != accountPassword: print('Incorrect password for this account') elif userWithdrawAmount > accountBalance: print('You cannot withdraw more than you have in your account') else: account_balance = accountBalance - userWithdrawAmount print('Your new balance is:', accountBalance) print('Done')
def getball(): rest() i01.setHandSpeed("right", 0.85, 0.75, 0.75, 0.75, 0.85, 0.75) i01.setArmSpeed("right", 1.0, 1.0, 1.0, 0.85) i01.setHeadSpeed(0.9, 0.9) i01.setTorsoSpeed(0.75, 0.55, 1.0) i01.moveHead(45,65) i01.moveArm("left",5,90,16,15) i01.moveArm("right",6,85,110,22) i01.moveHand("left",50,50,40,20,20,90) i01.moveHand("right",0,0,0,3,0,11) i01.moveTorso(101,100,90) sleep(2.5) i01.moveHand("right",180,140,140,3,0,11)
def getball(): rest() i01.setHandSpeed('right', 0.85, 0.75, 0.75, 0.75, 0.85, 0.75) i01.setArmSpeed('right', 1.0, 1.0, 1.0, 0.85) i01.setHeadSpeed(0.9, 0.9) i01.setTorsoSpeed(0.75, 0.55, 1.0) i01.moveHead(45, 65) i01.moveArm('left', 5, 90, 16, 15) i01.moveArm('right', 6, 85, 110, 22) i01.moveHand('left', 50, 50, 40, 20, 20, 90) i01.moveHand('right', 0, 0, 0, 3, 0, 11) i01.moveTorso(101, 100, 90) sleep(2.5) i01.moveHand('right', 180, 140, 140, 3, 0, 11)
# config.py cfg = { 'name': 'Retinaface', 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True }
cfg = {'name': 'Retinaface', 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True}
class Publisher: def __init__(self): self.observers = [] def add(self, observer): if observer not in self.observers: self.observers.append(observer) else: print(f'Failed to add: {observer}') def remove(self, observer): try: self.observers.remove(observer) except ValueError: print(f'Failed to remove: {observer}') def notify(self): [o.notify(self) for o in self.observers] class DefaultFormatter(Publisher): def __init__(self, name): Publisher.__init__(self) self.name = name self._data = 0 def __str__(self): return f"{type(self).__name__}: '{self.name}' has data = {self._data}" @property def data(self): return self._data @data.setter def data(self, new_value): try: self._data = int(new_value) except ValueError as e: print(f'Error: {e}') else: self.notify() class HexFormatterObs: def notify(self, publisher): value = hex(publisher.data) print(f"{type(self).__name__}: '{publisher.name}' has now hex data = {value}") class BinaryFormatterObs: def notify(self, publisher): value = bin(publisher.data) print(f"{type(self).__name__}: '{publisher.name}' has now bin data = {value}") def main(): df = DefaultFormatter('test1') print(df) print() hf = HexFormatterObs() df.add(hf) df.data = 3 print(df) print() bf = BinaryFormatterObs() df.add(bf) df.data = 21 print(df) print() df.remove(hf) df.data = 40 print(df) print() df.remove(hf) df.add(bf) df.data = 'hello' print(df) print() df.data = 15.8 print(df) if __name__ == '__main__': main()
class Publisher: def __init__(self): self.observers = [] def add(self, observer): if observer not in self.observers: self.observers.append(observer) else: print(f'Failed to add: {observer}') def remove(self, observer): try: self.observers.remove(observer) except ValueError: print(f'Failed to remove: {observer}') def notify(self): [o.notify(self) for o in self.observers] class Defaultformatter(Publisher): def __init__(self, name): Publisher.__init__(self) self.name = name self._data = 0 def __str__(self): return f"{type(self).__name__}: '{self.name}' has data = {self._data}" @property def data(self): return self._data @data.setter def data(self, new_value): try: self._data = int(new_value) except ValueError as e: print(f'Error: {e}') else: self.notify() class Hexformatterobs: def notify(self, publisher): value = hex(publisher.data) print(f"{type(self).__name__}: '{publisher.name}' has now hex data = {value}") class Binaryformatterobs: def notify(self, publisher): value = bin(publisher.data) print(f"{type(self).__name__}: '{publisher.name}' has now bin data = {value}") def main(): df = default_formatter('test1') print(df) print() hf = hex_formatter_obs() df.add(hf) df.data = 3 print(df) print() bf = binary_formatter_obs() df.add(bf) df.data = 21 print(df) print() df.remove(hf) df.data = 40 print(df) print() df.remove(hf) df.add(bf) df.data = 'hello' print(df) print() df.data = 15.8 print(df) if __name__ == '__main__': main()
# https://www.acmicpc.net/problem/1110 class PlusCycle(object): def get_new_number(self, num): sum_of_each = int(num[0]) + int(num[1]) return str(num[1]) + str(sum_of_each%10) def get_cycle(self, n): n = '{:02d}'.format(int(n)) target = n count = 1 new_number = self.get_new_number(n) while new_number != target: n = new_number new_number = self.get_new_number(n) count+=1 return count if __name__ == "__main__": pc = PlusCycle() print(pc.get_cycle(input()))
class Pluscycle(object): def get_new_number(self, num): sum_of_each = int(num[0]) + int(num[1]) return str(num[1]) + str(sum_of_each % 10) def get_cycle(self, n): n = '{:02d}'.format(int(n)) target = n count = 1 new_number = self.get_new_number(n) while new_number != target: n = new_number new_number = self.get_new_number(n) count += 1 return count if __name__ == '__main__': pc = plus_cycle() print(pc.get_cycle(input()))
# # PySNMP MIB module NASUNI-FILER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://text/NASUNI-FILER-MIB # Produced by pysmi-0.3.4 at Mon Sep 20 10:57:46 2021 # On host C02YJ1DPJHD2 platform Darwin version 20.4.0 by user mpipaliya # Using Python version 3.7.4 (default, Oct 12 2019, 18:55:28) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") ObjectIdentity, MibIdentifier, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Gauge32, Integer32, Counter32, Unsigned32, Counter64, enterprises, NotificationType, IpAddress, iso, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "MibIdentifier", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Gauge32", "Integer32", "Counter32", "Unsigned32", "Counter64", "enterprises", "NotificationType", "IpAddress", "iso", "TimeTicks") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") nasuni = ModuleIdentity((1, 3, 6, 1, 4, 1, 42040)) nasuni.setRevisions(('2013-07-13 00:00',)) if mibBuilder.loadTexts: nasuni.setLastUpdated('201307130000Z') if mibBuilder.loadTexts: nasuni.setOrganization('Nasuni Corporation') filer = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1)) filerIdentifier = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 1), DisplayString().clone('Nasuni Filer')).setMaxAccess("readonly") if mibBuilder.loadTexts: filerIdentifier.setStatus('current') filerVersion = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerVersion.setStatus('current') filerSerialNumber = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerSerialNumber.setStatus('current') filerUptime = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 4), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerUptime.setStatus('current') filerUpdateAvailable = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerUpdateAvailable.setStatus('current') filerTotalUnprotectedData = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 6), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalUnprotectedData.setStatus('current') filerPushesCompleted = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 7), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerPushesCompleted.setStatus('current') filerTotalPushed = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 8), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalPushed.setStatus('current') filerTotalRead = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 9), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalRead.setStatus('current') filerOpensForRead = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 10), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerOpensForRead.setStatus('current') filerOpensForWrite = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 11), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerOpensForWrite.setStatus('current') filerMergeConflicts = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 12), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerMergeConflicts.setStatus('current') filerReadHits = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 13), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerReadHits.setStatus('current') filerReadMisses = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 14), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerReadMisses.setStatus('current') filerNextFsckAfter = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 15), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerNextFsckAfter.setStatus('current') filerCache = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1, 100)) filerCacheTotal = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 1), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: filerCacheTotal.setStatus('current') filerCacheUsed = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 2), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: filerCacheUsed.setStatus('current') filerCacheFree = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 3), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: filerCacheFree.setStatus('current') filerPlatform = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1, 101)) filerPlatformName = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerPlatformName.setStatus('current') filerPlatformType = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerPlatformType.setStatus('current') filerPackageFormat = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerPackageFormat.setStatus('current') filerBiosVersion = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerBiosVersion.setStatus('current') filerCpuModel = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerCpuModel.setStatus('current') filerPhysCpuCount = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerPhysCpuCount.setStatus('current') filerCoreCount = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerCoreCount.setStatus('current') filerCpuArch = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerCpuArch.setStatus('current') filerCpuFreq = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 9), Counter64()).setUnits('hertz').setMaxAccess("readonly") if mibBuilder.loadTexts: filerCpuFreq.setStatus('current') filerDiskCount = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerDiskCount.setStatus('current') filerTotalMemory = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 11), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalMemory.setStatus('current') filerDeviceCache = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 12), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerDeviceCache.setStatus('current') filerDeviceVar = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 13), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerDeviceVar.setStatus('current') filerDeviceRoot = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 14), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerDeviceRoot.setStatus('current') filerDeviceNasuni = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 15), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerDeviceNasuni.setStatus('current') filerHealth = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1, 102)) filerAmbientTemp = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 1), Integer32()).setUnits('degrees celsius').setMaxAccess("readonly") if mibBuilder.loadTexts: filerAmbientTemp.setStatus('current') filerInletTemp = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 2), Integer32()).setUnits('degrees celsius').setMaxAccess("readonly") if mibBuilder.loadTexts: filerInletTemp.setStatus('current') filerExhaustTemp = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 3), Integer32()).setUnits('degrees celsius').setMaxAccess("readonly") if mibBuilder.loadTexts: filerExhaustTemp.setStatus('current') filerNumPowerSupplies = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerNumPowerSupplies.setStatus('current') filerPowerSupplyErrors = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerPowerSupplyErrors.setStatus('current') filerNumRaidArrays = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerNumRaidArrays.setStatus('current') filerRaidArrayErrors = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerRaidArrayErrors.setStatus('current') filerNumRaidDisks = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerNumRaidDisks.setStatus('current') filerRaidDiskErrors = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerRaidDiskErrors.setStatus('current') filerCifs = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1, 103)) filerNfs = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1, 104)) filerFtp = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1, 109)) filerIscsi = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1, 105)) filerTotalShares = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 103, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalShares.setStatus('current') filerTotalShareLocks = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 103, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalShareLocks.setStatus('current') filerTotalShareClients = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 103, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalShareClients.setStatus('current') filerTotalExports = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 104, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalExports.setStatus('current') filerTotalFtpdirs = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 109, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalFtpdirs.setStatus('current') filerTotalIscsiTargets = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 105, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalIscsiTargets.setStatus('current') filerTotalIscsiClients = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 105, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalIscsiClients.setStatus('current') filerMobile = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1, 106)) filerTotalMobileLicenses = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 106, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTotalMobileLicenses.setStatus('current') filerNumIOSLicenses = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 106, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerNumIOSLicenses.setStatus('current') filerNumAndroidLicenses = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 106, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerNumAndroidLicenses.setStatus('current') filerServices = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1, 107)) filerSupportServiceEnabled = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 107, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerSupportServiceEnabled.setStatus('current') filerSupportServiceConnected = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 107, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerSupportServiceConnected.setStatus('current') filerSupportServiceRunning = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 107, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerSupportServiceRunning.setStatus('current') filerSupportServiceTimeout = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 107, 4), Integer32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: filerSupportServiceTimeout.setStatus('current') filerNetwork = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 1, 108)) filerCloudOut = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 1), Counter64()).setUnits('bits/second').setMaxAccess("readonly") if mibBuilder.loadTexts: filerCloudOut.setStatus('current') filerCloudIn = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 2), Counter64()).setUnits('bits/second').setMaxAccess("readonly") if mibBuilder.loadTexts: filerCloudIn.setStatus('current') filerMobileOut = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 3), Counter64()).setUnits('bits/second').setMaxAccess("readonly") if mibBuilder.loadTexts: filerMobileOut.setStatus('current') filerMobileIn = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 4), Counter64()).setUnits('bits/second').setMaxAccess("readonly") if mibBuilder.loadTexts: filerMobileIn.setStatus('current') filerUIOut = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 5), Counter64()).setUnits('bits/second').setMaxAccess("readonly") if mibBuilder.loadTexts: filerUIOut.setStatus('current') filerUIIn = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 6), Counter64()).setUnits('bits/second').setMaxAccess("readonly") if mibBuilder.loadTexts: filerUIIn.setStatus('current') filerClientsOut = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 7), Counter64()).setUnits('bits/second').setMaxAccess("readonly") if mibBuilder.loadTexts: filerClientsOut.setStatus('current') filerClientsIn = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 8), Counter64()).setUnits('bits/second').setMaxAccess("readonly") if mibBuilder.loadTexts: filerClientsIn.setStatus('current') filerMigrationOut = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 9), Counter64()).setUnits('bits/second').setMaxAccess("readonly") if mibBuilder.loadTexts: filerMigrationOut.setStatus('current') filerMigrationIn = MibScalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 10), Counter64()).setUnits('bits/second').setMaxAccess("readonly") if mibBuilder.loadTexts: filerMigrationIn.setStatus('current') volumes = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 2)) volumeCount = MibScalar((1, 3, 6, 1, 4, 1, 42040, 2, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeCount.setStatus('current') volumeTable = MibTable((1, 3, 6, 1, 4, 1, 42040, 2, 2), ) if mibBuilder.loadTexts: volumeTable.setStatus('current') volumeTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1), ).setIndexNames((0, "NASUNI-FILER-MIB", "volumeTableIndex")) if mibBuilder.loadTexts: volumeTableEntry.setStatus('current') volumeTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 999))) if mibBuilder.loadTexts: volumeTableIndex.setStatus('current') volumeTableDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableDescription.setStatus('current') volumeTableProvider = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableProvider.setStatus('current') volumeTableProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableProtocol.setStatus('current') volumeTableStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableStatus.setStatus('current') volumeTableAccessibleData = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 6), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableAccessibleData.setStatus('current') volumeTableUnprotectedData = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 7), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableUnprotectedData.setStatus('current') volumeTableLastSnapshotStart = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableLastSnapshotStart.setStatus('current') volumeTableLastSnapshotEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 9), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableLastSnapshotEnd.setStatus('current') volumeTableLastSnapshotDuration = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 10), Integer32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableLastSnapshotDuration.setStatus('current') volumeTableLastSnapshotVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 11), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableLastSnapshotVersion.setStatus('current') volumeTableIsActive = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableIsActive.setStatus('current') volumeTableIsShared = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableIsShared.setStatus('current') volumeTableIsReadOnly = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 14), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableIsReadOnly.setStatus('current') volumeTableIsPinned = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 15), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableIsPinned.setStatus('current') volumeTableIsRemote = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 16), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableIsRemote.setStatus('current') volumeTableAvEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 17), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableAvEnabled.setStatus('current') volumeTableRemoteAccessEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 18), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableRemoteAccessEnabled.setStatus('current') volumeTableQuota = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 19), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableQuota.setStatus('current') volumeTableNumAVViolations = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 20), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableNumAVViolations.setStatus('current') volumeTableNumFileAlerts = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 21), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableNumFileAlerts.setStatus('current') volumeTableNumExports = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 22), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableNumExports.setStatus('current') volumeTableNumShares = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 23), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableNumShares.setStatus('current') volumeTableNumFtpdirs = MibTableColumn((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 24), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: volumeTableNumFtpdirs.setStatus('current') account = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 3)) accountLicensedCapacity = MibScalar((1, 3, 6, 1, 4, 1, 42040, 3, 1), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: accountLicensedCapacity.setStatus('current') accountUsedCapacity = MibScalar((1, 3, 6, 1, 4, 1, 42040, 3, 2), Counter64()).setUnits('bytes').setMaxAccess("readonly") if mibBuilder.loadTexts: accountUsedCapacity.setStatus('current') accountPercentUsedCapacity = MibScalar((1, 3, 6, 1, 4, 1, 42040, 3, 3), Integer32()).setUnits('percent').setMaxAccess("readonly") if mibBuilder.loadTexts: accountPercentUsedCapacity.setStatus('current') filerTrapsWrap = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 100)) filerTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 42040, 100, 0)) filerTrapType = MibScalar((1, 3, 6, 1, 4, 1, 42040, 100, 0, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTrapType.setStatus('current') filerTrapLevel = MibScalar((1, 3, 6, 1, 4, 1, 42040, 100, 0, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTrapLevel.setStatus('current') filerTrapMessage = MibScalar((1, 3, 6, 1, 4, 1, 42040, 100, 0, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: filerTrapMessage.setStatus('current') filerTrap = NotificationType((1, 3, 6, 1, 4, 1, 42040, 100, 0, 4)).setObjects(("NASUNI-FILER-MIB", "filerTrapType"), ("NASUNI-FILER-MIB", "filerTrapLevel"), ("NASUNI-FILER-MIB", "filerTrapMessage")) if mibBuilder.loadTexts: filerTrap.setStatus('current') mibBuilder.exportSymbols("NASUNI-FILER-MIB", filerRaidDiskErrors=filerRaidDiskErrors, filerTotalExports=filerTotalExports, filerTraps=filerTraps, filerVersion=filerVersion, volumeTableLastSnapshotDuration=volumeTableLastSnapshotDuration, volumeTableIndex=volumeTableIndex, volumeTableIsRemote=volumeTableIsRemote, volumeTableIsShared=volumeTableIsShared, filerCacheTotal=filerCacheTotal, filerIscsi=filerIscsi, filerTrapsWrap=filerTrapsWrap, filerNetwork=filerNetwork, filerTotalMobileLicenses=filerTotalMobileLicenses, volumeTableNumFileAlerts=volumeTableNumFileAlerts, filerCacheUsed=filerCacheUsed, filerNumPowerSupplies=filerNumPowerSupplies, volumeTableLastSnapshotStart=volumeTableLastSnapshotStart, volumeTableIsReadOnly=volumeTableIsReadOnly, filerMigrationOut=filerMigrationOut, filerInletTemp=filerInletTemp, filerPlatform=filerPlatform, filerServices=filerServices, filerTotalUnprotectedData=filerTotalUnprotectedData, filerDeviceVar=filerDeviceVar, filerCpuFreq=filerCpuFreq, filerHealth=filerHealth, filerOpensForWrite=filerOpensForWrite, filerNumRaidArrays=filerNumRaidArrays, filerExhaustTemp=filerExhaustTemp, filerSupportServiceEnabled=filerSupportServiceEnabled, volumeTableLastSnapshotEnd=volumeTableLastSnapshotEnd, filerNumRaidDisks=filerNumRaidDisks, filerPackageFormat=filerPackageFormat, filerTrapLevel=filerTrapLevel, filerCoreCount=filerCoreCount, filerMigrationIn=filerMigrationIn, filerNextFsckAfter=filerNextFsckAfter, filerAmbientTemp=filerAmbientTemp, filerPlatformName=filerPlatformName, filerDeviceRoot=filerDeviceRoot, filerPowerSupplyErrors=filerPowerSupplyErrors, filerPushesCompleted=filerPushesCompleted, filerTotalPushed=filerTotalPushed, volumeTableAccessibleData=volumeTableAccessibleData, filerTrap=filerTrap, filerMobile=filerMobile, filerTrapMessage=filerTrapMessage, filerOpensForRead=filerOpensForRead, filerUIOut=filerUIOut, filer=filer, filerNumIOSLicenses=filerNumIOSLicenses, filerTotalShareClients=filerTotalShareClients, filerSupportServiceConnected=filerSupportServiceConnected, filerTotalIscsiTargets=filerTotalIscsiTargets, volumeTableIsActive=volumeTableIsActive, filerUptime=filerUptime, volumeTableNumShares=volumeTableNumShares, filerDeviceCache=filerDeviceCache, volumeTableNumExports=volumeTableNumExports, volumes=volumes, filerPhysCpuCount=filerPhysCpuCount, filerUIIn=filerUIIn, volumeTableLastSnapshotVersion=volumeTableLastSnapshotVersion, filerSupportServiceRunning=filerSupportServiceRunning, volumeTableProtocol=volumeTableProtocol, filerBiosVersion=filerBiosVersion, accountUsedCapacity=accountUsedCapacity, filerSerialNumber=filerSerialNumber, filerCpuArch=filerCpuArch, account=account, filerIdentifier=filerIdentifier, filerCache=filerCache, PYSNMP_MODULE_ID=nasuni, filerReadMisses=filerReadMisses, filerTotalShareLocks=filerTotalShareLocks, filerTotalFtpdirs=filerTotalFtpdirs, accountPercentUsedCapacity=accountPercentUsedCapacity, filerCloudIn=filerCloudIn, filerNumAndroidLicenses=filerNumAndroidLicenses, filerCifs=filerCifs, filerTotalIscsiClients=filerTotalIscsiClients, filerMergeConflicts=filerMergeConflicts, filerRaidArrayErrors=filerRaidArrayErrors, filerClientsOut=filerClientsOut, volumeCount=volumeCount, volumeTableDescription=volumeTableDescription, volumeTableIsPinned=volumeTableIsPinned, volumeTable=volumeTable, filerUpdateAvailable=filerUpdateAvailable, volumeTableNumFtpdirs=volumeTableNumFtpdirs, filerClientsIn=filerClientsIn, filerCacheFree=filerCacheFree, volumeTableProvider=volumeTableProvider, filerNfs=filerNfs, filerMobileIn=filerMobileIn, filerTotalRead=filerTotalRead, filerPlatformType=filerPlatformType, filerDiskCount=filerDiskCount, volumeTableAvEnabled=volumeTableAvEnabled, volumeTableStatus=volumeTableStatus, volumeTableQuota=volumeTableQuota, volumeTableEntry=volumeTableEntry, filerTrapType=filerTrapType, filerCpuModel=filerCpuModel, filerReadHits=filerReadHits, accountLicensedCapacity=accountLicensedCapacity, nasuni=nasuni, volumeTableNumAVViolations=volumeTableNumAVViolations, filerTotalMemory=filerTotalMemory, volumeTableUnprotectedData=volumeTableUnprotectedData, filerCloudOut=filerCloudOut, filerDeviceNasuni=filerDeviceNasuni, volumeTableRemoteAccessEnabled=volumeTableRemoteAccessEnabled, filerTotalShares=filerTotalShares, filerSupportServiceTimeout=filerSupportServiceTimeout, filerMobileOut=filerMobileOut, filerFtp=filerFtp)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'SingleValueConstraint') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (object_identity, mib_identifier, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, bits, gauge32, integer32, counter32, unsigned32, counter64, enterprises, notification_type, ip_address, iso, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'MibIdentifier', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'Gauge32', 'Integer32', 'Counter32', 'Unsigned32', 'Counter64', 'enterprises', 'NotificationType', 'IpAddress', 'iso', 'TimeTicks') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') nasuni = module_identity((1, 3, 6, 1, 4, 1, 42040)) nasuni.setRevisions(('2013-07-13 00:00',)) if mibBuilder.loadTexts: nasuni.setLastUpdated('201307130000Z') if mibBuilder.loadTexts: nasuni.setOrganization('Nasuni Corporation') filer = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1)) filer_identifier = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 1), display_string().clone('Nasuni Filer')).setMaxAccess('readonly') if mibBuilder.loadTexts: filerIdentifier.setStatus('current') filer_version = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 2), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerVersion.setStatus('current') filer_serial_number = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerSerialNumber.setStatus('current') filer_uptime = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 4), time_ticks()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerUptime.setStatus('current') filer_update_available = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 5), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerUpdateAvailable.setStatus('current') filer_total_unprotected_data = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 6), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalUnprotectedData.setStatus('current') filer_pushes_completed = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 7), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerPushesCompleted.setStatus('current') filer_total_pushed = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 8), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalPushed.setStatus('current') filer_total_read = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 9), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalRead.setStatus('current') filer_opens_for_read = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 10), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerOpensForRead.setStatus('current') filer_opens_for_write = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 11), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerOpensForWrite.setStatus('current') filer_merge_conflicts = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 12), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerMergeConflicts.setStatus('current') filer_read_hits = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 13), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerReadHits.setStatus('current') filer_read_misses = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 14), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerReadMisses.setStatus('current') filer_next_fsck_after = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 15), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerNextFsckAfter.setStatus('current') filer_cache = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1, 100)) filer_cache_total = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 1), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: filerCacheTotal.setStatus('current') filer_cache_used = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 2), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: filerCacheUsed.setStatus('current') filer_cache_free = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 3), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: filerCacheFree.setStatus('current') filer_platform = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1, 101)) filer_platform_name = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 1), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerPlatformName.setStatus('current') filer_platform_type = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 2), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerPlatformType.setStatus('current') filer_package_format = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerPackageFormat.setStatus('current') filer_bios_version = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 4), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerBiosVersion.setStatus('current') filer_cpu_model = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 5), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerCpuModel.setStatus('current') filer_phys_cpu_count = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerPhysCpuCount.setStatus('current') filer_core_count = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerCoreCount.setStatus('current') filer_cpu_arch = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 8), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerCpuArch.setStatus('current') filer_cpu_freq = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 9), counter64()).setUnits('hertz').setMaxAccess('readonly') if mibBuilder.loadTexts: filerCpuFreq.setStatus('current') filer_disk_count = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 10), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerDiskCount.setStatus('current') filer_total_memory = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 101, 11), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalMemory.setStatus('current') filer_device_cache = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 12), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerDeviceCache.setStatus('current') filer_device_var = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 13), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerDeviceVar.setStatus('current') filer_device_root = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 14), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerDeviceRoot.setStatus('current') filer_device_nasuni = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 100, 15), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerDeviceNasuni.setStatus('current') filer_health = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1, 102)) filer_ambient_temp = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 1), integer32()).setUnits('degrees celsius').setMaxAccess('readonly') if mibBuilder.loadTexts: filerAmbientTemp.setStatus('current') filer_inlet_temp = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 2), integer32()).setUnits('degrees celsius').setMaxAccess('readonly') if mibBuilder.loadTexts: filerInletTemp.setStatus('current') filer_exhaust_temp = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 3), integer32()).setUnits('degrees celsius').setMaxAccess('readonly') if mibBuilder.loadTexts: filerExhaustTemp.setStatus('current') filer_num_power_supplies = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerNumPowerSupplies.setStatus('current') filer_power_supply_errors = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerPowerSupplyErrors.setStatus('current') filer_num_raid_arrays = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerNumRaidArrays.setStatus('current') filer_raid_array_errors = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerRaidArrayErrors.setStatus('current') filer_num_raid_disks = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 8), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerNumRaidDisks.setStatus('current') filer_raid_disk_errors = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 102, 9), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerRaidDiskErrors.setStatus('current') filer_cifs = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1, 103)) filer_nfs = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1, 104)) filer_ftp = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1, 109)) filer_iscsi = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1, 105)) filer_total_shares = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 103, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalShares.setStatus('current') filer_total_share_locks = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 103, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalShareLocks.setStatus('current') filer_total_share_clients = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 103, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalShareClients.setStatus('current') filer_total_exports = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 104, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalExports.setStatus('current') filer_total_ftpdirs = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 109, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalFtpdirs.setStatus('current') filer_total_iscsi_targets = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 105, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalIscsiTargets.setStatus('current') filer_total_iscsi_clients = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 105, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalIscsiClients.setStatus('current') filer_mobile = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1, 106)) filer_total_mobile_licenses = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 106, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTotalMobileLicenses.setStatus('current') filer_num_ios_licenses = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 106, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerNumIOSLicenses.setStatus('current') filer_num_android_licenses = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 106, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerNumAndroidLicenses.setStatus('current') filer_services = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1, 107)) filer_support_service_enabled = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 107, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerSupportServiceEnabled.setStatus('current') filer_support_service_connected = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 107, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerSupportServiceConnected.setStatus('current') filer_support_service_running = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 107, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerSupportServiceRunning.setStatus('current') filer_support_service_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 107, 4), integer32()).setUnits('seconds').setMaxAccess('readonly') if mibBuilder.loadTexts: filerSupportServiceTimeout.setStatus('current') filer_network = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 1, 108)) filer_cloud_out = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 1), counter64()).setUnits('bits/second').setMaxAccess('readonly') if mibBuilder.loadTexts: filerCloudOut.setStatus('current') filer_cloud_in = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 2), counter64()).setUnits('bits/second').setMaxAccess('readonly') if mibBuilder.loadTexts: filerCloudIn.setStatus('current') filer_mobile_out = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 3), counter64()).setUnits('bits/second').setMaxAccess('readonly') if mibBuilder.loadTexts: filerMobileOut.setStatus('current') filer_mobile_in = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 4), counter64()).setUnits('bits/second').setMaxAccess('readonly') if mibBuilder.loadTexts: filerMobileIn.setStatus('current') filer_ui_out = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 5), counter64()).setUnits('bits/second').setMaxAccess('readonly') if mibBuilder.loadTexts: filerUIOut.setStatus('current') filer_ui_in = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 6), counter64()).setUnits('bits/second').setMaxAccess('readonly') if mibBuilder.loadTexts: filerUIIn.setStatus('current') filer_clients_out = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 7), counter64()).setUnits('bits/second').setMaxAccess('readonly') if mibBuilder.loadTexts: filerClientsOut.setStatus('current') filer_clients_in = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 8), counter64()).setUnits('bits/second').setMaxAccess('readonly') if mibBuilder.loadTexts: filerClientsIn.setStatus('current') filer_migration_out = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 9), counter64()).setUnits('bits/second').setMaxAccess('readonly') if mibBuilder.loadTexts: filerMigrationOut.setStatus('current') filer_migration_in = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 1, 108, 10), counter64()).setUnits('bits/second').setMaxAccess('readonly') if mibBuilder.loadTexts: filerMigrationIn.setStatus('current') volumes = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 2)) volume_count = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 2, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeCount.setStatus('current') volume_table = mib_table((1, 3, 6, 1, 4, 1, 42040, 2, 2)) if mibBuilder.loadTexts: volumeTable.setStatus('current') volume_table_entry = mib_table_row((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1)).setIndexNames((0, 'NASUNI-FILER-MIB', 'volumeTableIndex')) if mibBuilder.loadTexts: volumeTableEntry.setStatus('current') volume_table_index = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 999))) if mibBuilder.loadTexts: volumeTableIndex.setStatus('current') volume_table_description = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 2), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableDescription.setStatus('current') volume_table_provider = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableProvider.setStatus('current') volume_table_protocol = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 4), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableProtocol.setStatus('current') volume_table_status = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 5), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableStatus.setStatus('current') volume_table_accessible_data = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 6), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableAccessibleData.setStatus('current') volume_table_unprotected_data = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 7), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableUnprotectedData.setStatus('current') volume_table_last_snapshot_start = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 8), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableLastSnapshotStart.setStatus('current') volume_table_last_snapshot_end = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 9), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableLastSnapshotEnd.setStatus('current') volume_table_last_snapshot_duration = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 10), integer32()).setUnits('seconds').setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableLastSnapshotDuration.setStatus('current') volume_table_last_snapshot_version = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 11), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableLastSnapshotVersion.setStatus('current') volume_table_is_active = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 12), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableIsActive.setStatus('current') volume_table_is_shared = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 13), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableIsShared.setStatus('current') volume_table_is_read_only = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 14), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableIsReadOnly.setStatus('current') volume_table_is_pinned = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 15), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableIsPinned.setStatus('current') volume_table_is_remote = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 16), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableIsRemote.setStatus('current') volume_table_av_enabled = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 17), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableAvEnabled.setStatus('current') volume_table_remote_access_enabled = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 18), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableRemoteAccessEnabled.setStatus('current') volume_table_quota = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 19), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableQuota.setStatus('current') volume_table_num_av_violations = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 20), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableNumAVViolations.setStatus('current') volume_table_num_file_alerts = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 21), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableNumFileAlerts.setStatus('current') volume_table_num_exports = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 22), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableNumExports.setStatus('current') volume_table_num_shares = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 23), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableNumShares.setStatus('current') volume_table_num_ftpdirs = mib_table_column((1, 3, 6, 1, 4, 1, 42040, 2, 2, 1, 24), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: volumeTableNumFtpdirs.setStatus('current') account = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 3)) account_licensed_capacity = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 3, 1), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: accountLicensedCapacity.setStatus('current') account_used_capacity = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 3, 2), counter64()).setUnits('bytes').setMaxAccess('readonly') if mibBuilder.loadTexts: accountUsedCapacity.setStatus('current') account_percent_used_capacity = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 3, 3), integer32()).setUnits('percent').setMaxAccess('readonly') if mibBuilder.loadTexts: accountPercentUsedCapacity.setStatus('current') filer_traps_wrap = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 100)) filer_traps = mib_identifier((1, 3, 6, 1, 4, 1, 42040, 100, 0)) filer_trap_type = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 100, 0, 1), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTrapType.setStatus('current') filer_trap_level = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 100, 0, 2), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTrapLevel.setStatus('current') filer_trap_message = mib_scalar((1, 3, 6, 1, 4, 1, 42040, 100, 0, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: filerTrapMessage.setStatus('current') filer_trap = notification_type((1, 3, 6, 1, 4, 1, 42040, 100, 0, 4)).setObjects(('NASUNI-FILER-MIB', 'filerTrapType'), ('NASUNI-FILER-MIB', 'filerTrapLevel'), ('NASUNI-FILER-MIB', 'filerTrapMessage')) if mibBuilder.loadTexts: filerTrap.setStatus('current') mibBuilder.exportSymbols('NASUNI-FILER-MIB', filerRaidDiskErrors=filerRaidDiskErrors, filerTotalExports=filerTotalExports, filerTraps=filerTraps, filerVersion=filerVersion, volumeTableLastSnapshotDuration=volumeTableLastSnapshotDuration, volumeTableIndex=volumeTableIndex, volumeTableIsRemote=volumeTableIsRemote, volumeTableIsShared=volumeTableIsShared, filerCacheTotal=filerCacheTotal, filerIscsi=filerIscsi, filerTrapsWrap=filerTrapsWrap, filerNetwork=filerNetwork, filerTotalMobileLicenses=filerTotalMobileLicenses, volumeTableNumFileAlerts=volumeTableNumFileAlerts, filerCacheUsed=filerCacheUsed, filerNumPowerSupplies=filerNumPowerSupplies, volumeTableLastSnapshotStart=volumeTableLastSnapshotStart, volumeTableIsReadOnly=volumeTableIsReadOnly, filerMigrationOut=filerMigrationOut, filerInletTemp=filerInletTemp, filerPlatform=filerPlatform, filerServices=filerServices, filerTotalUnprotectedData=filerTotalUnprotectedData, filerDeviceVar=filerDeviceVar, filerCpuFreq=filerCpuFreq, filerHealth=filerHealth, filerOpensForWrite=filerOpensForWrite, filerNumRaidArrays=filerNumRaidArrays, filerExhaustTemp=filerExhaustTemp, filerSupportServiceEnabled=filerSupportServiceEnabled, volumeTableLastSnapshotEnd=volumeTableLastSnapshotEnd, filerNumRaidDisks=filerNumRaidDisks, filerPackageFormat=filerPackageFormat, filerTrapLevel=filerTrapLevel, filerCoreCount=filerCoreCount, filerMigrationIn=filerMigrationIn, filerNextFsckAfter=filerNextFsckAfter, filerAmbientTemp=filerAmbientTemp, filerPlatformName=filerPlatformName, filerDeviceRoot=filerDeviceRoot, filerPowerSupplyErrors=filerPowerSupplyErrors, filerPushesCompleted=filerPushesCompleted, filerTotalPushed=filerTotalPushed, volumeTableAccessibleData=volumeTableAccessibleData, filerTrap=filerTrap, filerMobile=filerMobile, filerTrapMessage=filerTrapMessage, filerOpensForRead=filerOpensForRead, filerUIOut=filerUIOut, filer=filer, filerNumIOSLicenses=filerNumIOSLicenses, filerTotalShareClients=filerTotalShareClients, filerSupportServiceConnected=filerSupportServiceConnected, filerTotalIscsiTargets=filerTotalIscsiTargets, volumeTableIsActive=volumeTableIsActive, filerUptime=filerUptime, volumeTableNumShares=volumeTableNumShares, filerDeviceCache=filerDeviceCache, volumeTableNumExports=volumeTableNumExports, volumes=volumes, filerPhysCpuCount=filerPhysCpuCount, filerUIIn=filerUIIn, volumeTableLastSnapshotVersion=volumeTableLastSnapshotVersion, filerSupportServiceRunning=filerSupportServiceRunning, volumeTableProtocol=volumeTableProtocol, filerBiosVersion=filerBiosVersion, accountUsedCapacity=accountUsedCapacity, filerSerialNumber=filerSerialNumber, filerCpuArch=filerCpuArch, account=account, filerIdentifier=filerIdentifier, filerCache=filerCache, PYSNMP_MODULE_ID=nasuni, filerReadMisses=filerReadMisses, filerTotalShareLocks=filerTotalShareLocks, filerTotalFtpdirs=filerTotalFtpdirs, accountPercentUsedCapacity=accountPercentUsedCapacity, filerCloudIn=filerCloudIn, filerNumAndroidLicenses=filerNumAndroidLicenses, filerCifs=filerCifs, filerTotalIscsiClients=filerTotalIscsiClients, filerMergeConflicts=filerMergeConflicts, filerRaidArrayErrors=filerRaidArrayErrors, filerClientsOut=filerClientsOut, volumeCount=volumeCount, volumeTableDescription=volumeTableDescription, volumeTableIsPinned=volumeTableIsPinned, volumeTable=volumeTable, filerUpdateAvailable=filerUpdateAvailable, volumeTableNumFtpdirs=volumeTableNumFtpdirs, filerClientsIn=filerClientsIn, filerCacheFree=filerCacheFree, volumeTableProvider=volumeTableProvider, filerNfs=filerNfs, filerMobileIn=filerMobileIn, filerTotalRead=filerTotalRead, filerPlatformType=filerPlatformType, filerDiskCount=filerDiskCount, volumeTableAvEnabled=volumeTableAvEnabled, volumeTableStatus=volumeTableStatus, volumeTableQuota=volumeTableQuota, volumeTableEntry=volumeTableEntry, filerTrapType=filerTrapType, filerCpuModel=filerCpuModel, filerReadHits=filerReadHits, accountLicensedCapacity=accountLicensedCapacity, nasuni=nasuni, volumeTableNumAVViolations=volumeTableNumAVViolations, filerTotalMemory=filerTotalMemory, volumeTableUnprotectedData=volumeTableUnprotectedData, filerCloudOut=filerCloudOut, filerDeviceNasuni=filerDeviceNasuni, volumeTableRemoteAccessEnabled=volumeTableRemoteAccessEnabled, filerTotalShares=filerTotalShares, filerSupportServiceTimeout=filerSupportServiceTimeout, filerMobileOut=filerMobileOut, filerFtp=filerFtp)
class VersionMixin(object): def _get_versioned_class(self, attribute): attribute = getattr(self, attribute) version = self.request.version # Return default if version is not specified if not version: return attribute["default"] try: # Return version return attribute[version] except KeyError: # Return default if version not found return attribute["default"] def get_filterset_class(self): try: # Return appropriate filterset for version return self._get_versioned_class("filterset_classes") except AttributeError: # If filterset_classes is not set, don't do anything return super().get_filterset_class() def get_serializer_class(self): try: # Return appropriate serializer for version return self._get_versioned_class("serializer_classes") except AttributeError: # If serializer_classes is not set, don't do anything return super().get_serializer_class()
class Versionmixin(object): def _get_versioned_class(self, attribute): attribute = getattr(self, attribute) version = self.request.version if not version: return attribute['default'] try: return attribute[version] except KeyError: return attribute['default'] def get_filterset_class(self): try: return self._get_versioned_class('filterset_classes') except AttributeError: return super().get_filterset_class() def get_serializer_class(self): try: return self._get_versioned_class('serializer_classes') except AttributeError: return super().get_serializer_class()
def area(): return larg * comp larg = float(input('informe a largura ')) comp = float(input('informe o comprimento ')) print(area())
def area(): return larg * comp larg = float(input('informe a largura ')) comp = float(input('informe o comprimento ')) print(area())
def csvReader(file): ''' Reads a csv file creates a dictionary with the first three comma seperated values of each line key and the fourth as value. ''' fileObject = open(file) data = fileObject.readlines() dic = {} for i in range(0,len(data)): try: dic[data[i].strip('\n')[:len(data[i].strip('\n'))-2]] += int(data[i].strip('\n')[-1]) except: dic[data[i].strip('\n')[:len(data[i].strip('\n'))-2]] = int(data[i].strip('\n')[-1]) fileObject.close() return dic if __name__ == "__main__": print(csvReader('helloworld.csv'))
def csv_reader(file): """ Reads a csv file creates a dictionary with the first three comma seperated values of each line key and the fourth as value. """ file_object = open(file) data = fileObject.readlines() dic = {} for i in range(0, len(data)): try: dic[data[i].strip('\n')[:len(data[i].strip('\n')) - 2]] += int(data[i].strip('\n')[-1]) except: dic[data[i].strip('\n')[:len(data[i].strip('\n')) - 2]] = int(data[i].strip('\n')[-1]) fileObject.close() return dic if __name__ == '__main__': print(csv_reader('helloworld.csv'))
# solution 1 a = [1,2,1,3,4,5,5] a = list(set(a)) print(a) # solution 2 a = [1,2,1,3,4,5,5] res = [] for i in a: if i not in res: res.append(i) print(res)
a = [1, 2, 1, 3, 4, 5, 5] a = list(set(a)) print(a) a = [1, 2, 1, 3, 4, 5, 5] res = [] for i in a: if i not in res: res.append(i) print(res)
#Creacion de la clase class Persona: def __init__(self, nombre, edad): self.__nombre = nombre self.__edad = edad def __str__(self): return "Nombre: "+self.__nombre+" y edad : "+str(self.__edad)
class Persona: def __init__(self, nombre, edad): self.__nombre = nombre self.__edad = edad def __str__(self): return 'Nombre: ' + self.__nombre + ' y edad : ' + str(self.__edad)
class Allergies: def __init__(self, score): self.score = score def allergic_to(self, item): return item in self.lst @property def lst(self): allergieList = ['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats'] allergicTo = list() pos = 0 aux = self.score while 2 ** pos < self.score: pos += 1 while pos >= 0 and aux > 0: if 2 ** pos <= aux: aux -= 2 ** pos if pos < len(allergieList): allergicTo.append(allergieList[pos]) pos -= 1 return allergicTo
class Allergies: def __init__(self, score): self.score = score def allergic_to(self, item): return item in self.lst @property def lst(self): allergie_list = ['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats'] allergic_to = list() pos = 0 aux = self.score while 2 ** pos < self.score: pos += 1 while pos >= 0 and aux > 0: if 2 ** pos <= aux: aux -= 2 ** pos if pos < len(allergieList): allergicTo.append(allergieList[pos]) pos -= 1 return allergicTo
'''API END_POINT''' CENTER_CODE = 'PUT YOUR CENTER CODE HERE!!!!' API_ENDPOINT = "PUT YOUR URL HERE!!!!" URL_TIMEOUT = 3 '''QR Scanners config''' IN_SCANNER = '/dev/ttyUSB0' OUT_SCANNER = '/dev/ttyUSB1' WAIT_SECONDS_BLOCK_DOOR = 2.5 NUM_SCANNERS = 2 '''I2C Bus Options''' DEVICE_BUS = 1 PHY_DOORS_NUMBERS = 1 DEVICE_ADDR_DOOR_1_OPEN = 0x10 DEVICE_ADDR_DOOR_1_CLOSE = 0x10 CODE_DOOR_1_OPEN = 0x01 CODE_DOOR_1_CLOSE = 0x02 ENABLE_DOOR = 0xFF DISABLE_DOOR = 0x00 NO_DEVICE_ADDR = 0x00 '''Door Logic''' CONFIG_SYSTEM = { "scanner1" : { "port" : IN_SCANNER, "dev_addr_op" : DEVICE_ADDR_DOOR_1_OPEN, "dev_addr_cl" : DEVICE_ADDR_DOOR_1_CLOSE, "open_code" : CODE_DOOR_1_OPEN, "close_code" : CODE_DOOR_1_OPEN, "way" : True #'''True: WayIN''' }, "scanner2" : { "port" : OUT_SCANNER, "dev_addr_op" : DEVICE_ADDR_DOOR_1_OPEN, "dev_addr_cl" : DEVICE_ADDR_DOOR_1_CLOSE, "open_code" : CODE_DOOR_1_OPEN, "close_code" : CODE_DOOR_1_OPEN, "way" : False #'''False: WayOut''' } } #print(CONFIG_SYSTEM)
"""API END_POINT""" center_code = 'PUT YOUR CENTER CODE HERE!!!!' api_endpoint = 'PUT YOUR URL HERE!!!!' url_timeout = 3 'QR Scanners config' in_scanner = '/dev/ttyUSB0' out_scanner = '/dev/ttyUSB1' wait_seconds_block_door = 2.5 num_scanners = 2 'I2C Bus Options' device_bus = 1 phy_doors_numbers = 1 device_addr_door_1_open = 16 device_addr_door_1_close = 16 code_door_1_open = 1 code_door_1_close = 2 enable_door = 255 disable_door = 0 no_device_addr = 0 'Door Logic' config_system = {'scanner1': {'port': IN_SCANNER, 'dev_addr_op': DEVICE_ADDR_DOOR_1_OPEN, 'dev_addr_cl': DEVICE_ADDR_DOOR_1_CLOSE, 'open_code': CODE_DOOR_1_OPEN, 'close_code': CODE_DOOR_1_OPEN, 'way': True}, 'scanner2': {'port': OUT_SCANNER, 'dev_addr_op': DEVICE_ADDR_DOOR_1_OPEN, 'dev_addr_cl': DEVICE_ADDR_DOOR_1_CLOSE, 'open_code': CODE_DOOR_1_OPEN, 'close_code': CODE_DOOR_1_OPEN, 'way': False}}
def bubble_sort(nums): for i in range(len(nums) - 1): for j in range(len(nums) - i - 1): if nums[j] > nums[j + 1]: nums[j + 1], nums[j] = nums[j], nums[j + 1] return nums def quick_sort(nums): if len(nums) < 1: return nums p = nums[0] l = [] r = [] for i in nums: if i < p: l.append(i) elif i > p: r.append(i) return quick_sort(l) + [p] + quick_sort(r) def selection_sort(nums): for i in range(len(nums) - 1): mik = i for j in range(i + 1, len(nums)): if nums[j] < nums[mik]: mik = j nums[i], nums[mik] = nums[mik], nums[i] return nums def BubbleSort(lst): n = len(lst) if n <= 1: return lst for i in range(0, n): for j in range(0, n - i - 1): if lst[j] > lst[j + 1]: (lst[j], lst[j + 1]) = (lst[j + 1], lst[j]) if __name__ == '__main__': ll = [4, 8, 1, 3, 2, 9, 7] # print(bubble_sort(ll)) print(quick_sort(ll))
def bubble_sort(nums): for i in range(len(nums) - 1): for j in range(len(nums) - i - 1): if nums[j] > nums[j + 1]: (nums[j + 1], nums[j]) = (nums[j], nums[j + 1]) return nums def quick_sort(nums): if len(nums) < 1: return nums p = nums[0] l = [] r = [] for i in nums: if i < p: l.append(i) elif i > p: r.append(i) return quick_sort(l) + [p] + quick_sort(r) def selection_sort(nums): for i in range(len(nums) - 1): mik = i for j in range(i + 1, len(nums)): if nums[j] < nums[mik]: mik = j (nums[i], nums[mik]) = (nums[mik], nums[i]) return nums def bubble_sort(lst): n = len(lst) if n <= 1: return lst for i in range(0, n): for j in range(0, n - i - 1): if lst[j] > lst[j + 1]: (lst[j], lst[j + 1]) = (lst[j + 1], lst[j]) if __name__ == '__main__': ll = [4, 8, 1, 3, 2, 9, 7] print(quick_sort(ll))
XK_ISO_Lock = 0xFE01 XK_ISO_Level2_Latch = 0xFE02 XK_ISO_Level3_Shift = 0xFE03 XK_ISO_Level3_Latch = 0xFE04 XK_ISO_Level3_Lock = 0xFE05 XK_ISO_Group_Shift = 0xFF7E XK_ISO_Group_Latch = 0xFE06 XK_ISO_Group_Lock = 0xFE07 XK_ISO_Next_Group = 0xFE08 XK_ISO_Next_Group_Lock = 0xFE09 XK_ISO_Prev_Group = 0xFE0A XK_ISO_Prev_Group_Lock = 0xFE0B XK_ISO_First_Group = 0xFE0C XK_ISO_First_Group_Lock = 0xFE0D XK_ISO_Last_Group = 0xFE0E XK_ISO_Last_Group_Lock = 0xFE0F XK_ISO_Left_Tab = 0xFE20 XK_ISO_Move_Line_Up = 0xFE21 XK_ISO_Move_Line_Down = 0xFE22 XK_ISO_Partial_Line_Up = 0xFE23 XK_ISO_Partial_Line_Down = 0xFE24 XK_ISO_Partial_Space_Left = 0xFE25 XK_ISO_Partial_Space_Right = 0xFE26 XK_ISO_Set_Margin_Left = 0xFE27 XK_ISO_Set_Margin_Right = 0xFE28 XK_ISO_Release_Margin_Left = 0xFE29 XK_ISO_Release_Margin_Right = 0xFE2A XK_ISO_Release_Both_Margins = 0xFE2B XK_ISO_Fast_Cursor_Left = 0xFE2C XK_ISO_Fast_Cursor_Right = 0xFE2D XK_ISO_Fast_Cursor_Up = 0xFE2E XK_ISO_Fast_Cursor_Down = 0xFE2F XK_ISO_Continuous_Underline = 0xFE30 XK_ISO_Discontinuous_Underline = 0xFE31 XK_ISO_Emphasize = 0xFE32 XK_ISO_Center_Object = 0xFE33 XK_ISO_Enter = 0xFE34 XK_dead_grave = 0xFE50 XK_dead_acute = 0xFE51 XK_dead_circumflex = 0xFE52 XK_dead_tilde = 0xFE53 XK_dead_macron = 0xFE54 XK_dead_breve = 0xFE55 XK_dead_abovedot = 0xFE56 XK_dead_diaeresis = 0xFE57 XK_dead_abovering = 0xFE58 XK_dead_doubleacute = 0xFE59 XK_dead_caron = 0xFE5A XK_dead_cedilla = 0xFE5B XK_dead_ogonek = 0xFE5C XK_dead_iota = 0xFE5D XK_dead_voiced_sound = 0xFE5E XK_dead_semivoiced_sound = 0xFE5F XK_dead_belowdot = 0xFE60 XK_First_Virtual_Screen = 0xFED0 XK_Prev_Virtual_Screen = 0xFED1 XK_Next_Virtual_Screen = 0xFED2 XK_Last_Virtual_Screen = 0xFED4 XK_Terminate_Server = 0xFED5 XK_AccessX_Enable = 0xFE70 XK_AccessX_Feedback_Enable = 0xFE71 XK_RepeatKeys_Enable = 0xFE72 XK_SlowKeys_Enable = 0xFE73 XK_BounceKeys_Enable = 0xFE74 XK_StickyKeys_Enable = 0xFE75 XK_MouseKeys_Enable = 0xFE76 XK_MouseKeys_Accel_Enable = 0xFE77 XK_Overlay1_Enable = 0xFE78 XK_Overlay2_Enable = 0xFE79 XK_AudibleBell_Enable = 0xFE7A XK_Pointer_Left = 0xFEE0 XK_Pointer_Right = 0xFEE1 XK_Pointer_Up = 0xFEE2 XK_Pointer_Down = 0xFEE3 XK_Pointer_UpLeft = 0xFEE4 XK_Pointer_UpRight = 0xFEE5 XK_Pointer_DownLeft = 0xFEE6 XK_Pointer_DownRight = 0xFEE7 XK_Pointer_Button_Dflt = 0xFEE8 XK_Pointer_Button1 = 0xFEE9 XK_Pointer_Button2 = 0xFEEA XK_Pointer_Button3 = 0xFEEB XK_Pointer_Button4 = 0xFEEC XK_Pointer_Button5 = 0xFEED XK_Pointer_DblClick_Dflt = 0xFEEE XK_Pointer_DblClick1 = 0xFEEF XK_Pointer_DblClick2 = 0xFEF0 XK_Pointer_DblClick3 = 0xFEF1 XK_Pointer_DblClick4 = 0xFEF2 XK_Pointer_DblClick5 = 0xFEF3 XK_Pointer_Drag_Dflt = 0xFEF4 XK_Pointer_Drag1 = 0xFEF5 XK_Pointer_Drag2 = 0xFEF6 XK_Pointer_Drag3 = 0xFEF7 XK_Pointer_Drag4 = 0xFEF8 XK_Pointer_Drag5 = 0xFEFD XK_Pointer_EnableKeys = 0xFEF9 XK_Pointer_Accelerate = 0xFEFA XK_Pointer_DfltBtnNext = 0xFEFB XK_Pointer_DfltBtnPrev = 0xFEFC
xk_iso__lock = 65025 xk_iso__level2__latch = 65026 xk_iso__level3__shift = 65027 xk_iso__level3__latch = 65028 xk_iso__level3__lock = 65029 xk_iso__group__shift = 65406 xk_iso__group__latch = 65030 xk_iso__group__lock = 65031 xk_iso__next__group = 65032 xk_iso__next__group__lock = 65033 xk_iso__prev__group = 65034 xk_iso__prev__group__lock = 65035 xk_iso__first__group = 65036 xk_iso__first__group__lock = 65037 xk_iso__last__group = 65038 xk_iso__last__group__lock = 65039 xk_iso__left__tab = 65056 xk_iso__move__line__up = 65057 xk_iso__move__line__down = 65058 xk_iso__partial__line__up = 65059 xk_iso__partial__line__down = 65060 xk_iso__partial__space__left = 65061 xk_iso__partial__space__right = 65062 xk_iso__set__margin__left = 65063 xk_iso__set__margin__right = 65064 xk_iso__release__margin__left = 65065 xk_iso__release__margin__right = 65066 xk_iso__release__both__margins = 65067 xk_iso__fast__cursor__left = 65068 xk_iso__fast__cursor__right = 65069 xk_iso__fast__cursor__up = 65070 xk_iso__fast__cursor__down = 65071 xk_iso__continuous__underline = 65072 xk_iso__discontinuous__underline = 65073 xk_iso__emphasize = 65074 xk_iso__center__object = 65075 xk_iso__enter = 65076 xk_dead_grave = 65104 xk_dead_acute = 65105 xk_dead_circumflex = 65106 xk_dead_tilde = 65107 xk_dead_macron = 65108 xk_dead_breve = 65109 xk_dead_abovedot = 65110 xk_dead_diaeresis = 65111 xk_dead_abovering = 65112 xk_dead_doubleacute = 65113 xk_dead_caron = 65114 xk_dead_cedilla = 65115 xk_dead_ogonek = 65116 xk_dead_iota = 65117 xk_dead_voiced_sound = 65118 xk_dead_semivoiced_sound = 65119 xk_dead_belowdot = 65120 xk__first__virtual__screen = 65232 xk__prev__virtual__screen = 65233 xk__next__virtual__screen = 65234 xk__last__virtual__screen = 65236 xk__terminate__server = 65237 xk__access_x__enable = 65136 xk__access_x__feedback__enable = 65137 xk__repeat_keys__enable = 65138 xk__slow_keys__enable = 65139 xk__bounce_keys__enable = 65140 xk__sticky_keys__enable = 65141 xk__mouse_keys__enable = 65142 xk__mouse_keys__accel__enable = 65143 xk__overlay1__enable = 65144 xk__overlay2__enable = 65145 xk__audible_bell__enable = 65146 xk__pointer__left = 65248 xk__pointer__right = 65249 xk__pointer__up = 65250 xk__pointer__down = 65251 xk__pointer__up_left = 65252 xk__pointer__up_right = 65253 xk__pointer__down_left = 65254 xk__pointer__down_right = 65255 xk__pointer__button__dflt = 65256 xk__pointer__button1 = 65257 xk__pointer__button2 = 65258 xk__pointer__button3 = 65259 xk__pointer__button4 = 65260 xk__pointer__button5 = 65261 xk__pointer__dbl_click__dflt = 65262 xk__pointer__dbl_click1 = 65263 xk__pointer__dbl_click2 = 65264 xk__pointer__dbl_click3 = 65265 xk__pointer__dbl_click4 = 65266 xk__pointer__dbl_click5 = 65267 xk__pointer__drag__dflt = 65268 xk__pointer__drag1 = 65269 xk__pointer__drag2 = 65270 xk__pointer__drag3 = 65271 xk__pointer__drag4 = 65272 xk__pointer__drag5 = 65277 xk__pointer__enable_keys = 65273 xk__pointer__accelerate = 65274 xk__pointer__dflt_btn_next = 65275 xk__pointer__dflt_btn_prev = 65276
names = {'anonymous','tazri','focasa','troy','farha'}; # can use for loop for access names sets for name in names : print("Hello, "+name.title()+"!"); # can check value is exist in sets ? print("\n'tazri' in names : ",'tazri' in names); print("'solus' not in names : ",'solus' not in names); print("'xenon' in names : ",'xenon' in names);
names = {'anonymous', 'tazri', 'focasa', 'troy', 'farha'} for name in names: print('Hello, ' + name.title() + '!') print("\n'tazri' in names : ", 'tazri' in names) print("'solus' not in names : ", 'solus' not in names) print("'xenon' in names : ", 'xenon' in names)
def GenerateConfig(context): resources = [] project = context.env["project"] zone = context.properties["zone"] instance_name = "gcp-vm-" + context.env["project"] machine_type = context.properties["machineType"] resources.append({ "name": instance_name, "type": "compute.v1.instances", "properties": { "zone": zone, "machineType": "zones/{}/machineTypes/{}".format(zone, machine_type), "disks": [{ "boot": True, "autoDelete": True, "initializeParams": { "diskName": "boot-disk-" + instance_name, "sourceImage": "projects/debian-cloud/global/images/debian-10-buster-v20200910", "diskType": "projects/{}/zones/{}/diskTypes/pd-standard".format(project, zone), "diskSizeGb": "10", } }], "networkInterfaces": [{ "subnetwork": context.properties["nic1-subnet"], "accessConfigs": [{ "name": "External NAT", "type": "ONE_TO_ONE_NAT", "networkTier": "STANDARD" }] }] } }) return {"resources": resources}
def generate_config(context): resources = [] project = context.env['project'] zone = context.properties['zone'] instance_name = 'gcp-vm-' + context.env['project'] machine_type = context.properties['machineType'] resources.append({'name': instance_name, 'type': 'compute.v1.instances', 'properties': {'zone': zone, 'machineType': 'zones/{}/machineTypes/{}'.format(zone, machine_type), 'disks': [{'boot': True, 'autoDelete': True, 'initializeParams': {'diskName': 'boot-disk-' + instance_name, 'sourceImage': 'projects/debian-cloud/global/images/debian-10-buster-v20200910', 'diskType': 'projects/{}/zones/{}/diskTypes/pd-standard'.format(project, zone), 'diskSizeGb': '10'}}], 'networkInterfaces': [{'subnetwork': context.properties['nic1-subnet'], 'accessConfigs': [{'name': 'External NAT', 'type': 'ONE_TO_ONE_NAT', 'networkTier': 'STANDARD'}]}]}}) return {'resources': resources}
my_vals = [623, '43', 324.523, '23', '23.23', 234, '342'] def add(values): '''take a list of values and adds them up We assume that the contents of the list is either int, float or str where strings are numbers that can be converted to an int/float Parameters ---------- values : list (any) a list that represents values to add (can be int, float, or str) Returns ------- float the sum of all the values''' list_of_numbers = [] for val in values: number = float(val) list_of_numbers.append(number) sum_of_vals = sum(list_of_numbers) return sum_of_vals sum_of_vals = add(my_vals) print(sum_of_vals) # Celsius to F # celsius x 9 / 5 + 32 cur_temp = 14 def cel_to_f(temp_c): temp_f = temp_c * 9/5 + 32 return temp_f temp_f = cel_to_f(cur_temp) print(temp_f) # F to C # (F - 32) * 5 / 9 def f_to_cel(temp_f): temp_c = (temp_f - 32) * 5 / 9 return temp_c temp_c = f_to_cel(temp_f) print(temp_c) pokedex = { 25: { 'name': 'Pikachu', 'type': 'electric' }, 1: { 'name': 'Bulbasaur', 'type': 'grass' }, 4: { 'name': 'Charmander', 'type': 'fire' } } def pokemon_info(index_number): '''prints out the pokemon info Pokemon at <index> is called <name> with a type of <type> '''
my_vals = [623, '43', 324.523, '23', '23.23', 234, '342'] def add(values): """take a list of values and adds them up We assume that the contents of the list is either int, float or str where strings are numbers that can be converted to an int/float Parameters ---------- values : list (any) a list that represents values to add (can be int, float, or str) Returns ------- float the sum of all the values""" list_of_numbers = [] for val in values: number = float(val) list_of_numbers.append(number) sum_of_vals = sum(list_of_numbers) return sum_of_vals sum_of_vals = add(my_vals) print(sum_of_vals) cur_temp = 14 def cel_to_f(temp_c): temp_f = temp_c * 9 / 5 + 32 return temp_f temp_f = cel_to_f(cur_temp) print(temp_f) def f_to_cel(temp_f): temp_c = (temp_f - 32) * 5 / 9 return temp_c temp_c = f_to_cel(temp_f) print(temp_c) pokedex = {25: {'name': 'Pikachu', 'type': 'electric'}, 1: {'name': 'Bulbasaur', 'type': 'grass'}, 4: {'name': 'Charmander', 'type': 'fire'}} def pokemon_info(index_number): """prints out the pokemon info Pokemon at <index> is called <name> with a type of <type> """
PPTIK_GRAVITY = 9.77876 class StationKind: V1 = 'L' STATIONARY = 'S' MOBILE = 'M' class StationState: ALERT = 'A' READY = 'R' ECO = 'E' HIGH_RATE = 'H' NORMAL_RATE = 'N' LOST = 'L'
pptik_gravity = 9.77876 class Stationkind: v1 = 'L' stationary = 'S' mobile = 'M' class Stationstate: alert = 'A' ready = 'R' eco = 'E' high_rate = 'H' normal_rate = 'N' lost = 'L'
# 1st solution class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: if not firstList or not secondList: return [] first, second = 0, 0 result = [] while first < len(firstList) and second < len(secondList): listOne = firstList[first] listTwo = secondList[second] if listOne[0] <= listTwo[0] <= listOne[1]: if listTwo[1] <= listOne[1]: segment = [listTwo[0], listTwo[1]] second += 1 else: segment = [listTwo[0], listOne[1]] first += 1 result.append(segment) elif listTwo[0] <= listOne[0] <= listTwo[1]: if listOne[1] <= listTwo[1]: segment = [listOne[0], listOne[1]] first += 1 else: segment = [listOne[0], listTwo[1]] second += 1 result.append(segment) elif listOne[0] >= listTwo[1]: second += 1 elif listTwo[0] >= listOne[1]: first += 1 return result # 2nd solution # O(m + n) time | O(m + n) space class Solution: def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]: ans = [] i = j = 0 while i < len(A) and j < len(B): # Let's check if A[i] intersects B[j]. # lo - the startpoint of the intersection # hi - the endpoint of the intersection lo = max(A[i][0], B[j][0]) hi = min(A[i][1], B[j][1]) if lo <= hi: ans.append([lo, hi]) # Remove the interval with the smallest endpoint if A[i][1] < B[j][1]: i += 1 else: j += 1 return ans
class Solution: def interval_intersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: if not firstList or not secondList: return [] (first, second) = (0, 0) result = [] while first < len(firstList) and second < len(secondList): list_one = firstList[first] list_two = secondList[second] if listOne[0] <= listTwo[0] <= listOne[1]: if listTwo[1] <= listOne[1]: segment = [listTwo[0], listTwo[1]] second += 1 else: segment = [listTwo[0], listOne[1]] first += 1 result.append(segment) elif listTwo[0] <= listOne[0] <= listTwo[1]: if listOne[1] <= listTwo[1]: segment = [listOne[0], listOne[1]] first += 1 else: segment = [listOne[0], listTwo[1]] second += 1 result.append(segment) elif listOne[0] >= listTwo[1]: second += 1 elif listTwo[0] >= listOne[1]: first += 1 return result class Solution: def interval_intersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]: ans = [] i = j = 0 while i < len(A) and j < len(B): lo = max(A[i][0], B[j][0]) hi = min(A[i][1], B[j][1]) if lo <= hi: ans.append([lo, hi]) if A[i][1] < B[j][1]: i += 1 else: j += 1 return ans
# # PySNMP MIB module WWP-VOIP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-VOIP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:32:08 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") NotificationType, Integer32, Bits, Counter32, Counter64, IpAddress, TimeTicks, iso, MibIdentifier, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Gauge32, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Integer32", "Bits", "Counter32", "Counter64", "IpAddress", "TimeTicks", "iso", "MibIdentifier", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Gauge32", "ObjectIdentity") DisplayString, MacAddress, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "MacAddress", "TextualConvention") wwpModules, = mibBuilder.importSymbols("WWP-SMI", "wwpModules") wwpVoipMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 6141, 2, 15)) wwpVoipMIB.setRevisions(('2001-04-03 17:00',)) if mibBuilder.loadTexts: wwpVoipMIB.setLastUpdated('200104031700Z') if mibBuilder.loadTexts: wwpVoipMIB.setOrganization('World Wide Packets, Inc') wwpVoipMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1)) wwpVoip = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1)) wwpVoipMIBNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 2)) wwpVoipMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 2, 0)) wwpVoipMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 3)) wwpVoipMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 3, 1)) wwpVoipMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 3, 2)) wwpVoipTable = MibTable((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1), ) if mibBuilder.loadTexts: wwpVoipTable.setStatus('current') wwpVoipEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1), ).setIndexNames((0, "WWP-VOIP-MIB", "wwpVoipIndex")) if mibBuilder.loadTexts: wwpVoipEntry.setStatus('current') wwpVoipIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpVoipIndex.setStatus('current') wwpVoipDownLoaderVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpVoipDownLoaderVersion.setStatus('current') wwpVoipApplicationVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpVoipApplicationVersion.setStatus('current') wwpVoipPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpVoipPortNum.setStatus('current') wwpVoipIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 5), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpVoipIpAddr.setStatus('current') wwpVoipNumResets = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpVoipNumResets.setStatus('current') wwpVoipCallAgentAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 7), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpVoipCallAgentAddr.setStatus('current') wwpVoipResetOp = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("none", 0), ("reset", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpVoipResetOp.setStatus('current') wwpVoipDiagFailNotification = NotificationType((1, 3, 6, 1, 4, 1, 6141, 2, 15, 2, 0, 1)) if mibBuilder.loadTexts: wwpVoipDiagFailNotification.setStatus('current') mibBuilder.exportSymbols("WWP-VOIP-MIB", wwpVoipMIBNotificationPrefix=wwpVoipMIBNotificationPrefix, wwpVoipMIBNotifications=wwpVoipMIBNotifications, PYSNMP_MODULE_ID=wwpVoipMIB, wwpVoipMIBConformance=wwpVoipMIBConformance, wwpVoipDownLoaderVersion=wwpVoipDownLoaderVersion, wwpVoipMIBObjects=wwpVoipMIBObjects, wwpVoipMIBGroups=wwpVoipMIBGroups, wwpVoipMIBCompliances=wwpVoipMIBCompliances, wwpVoipNumResets=wwpVoipNumResets, wwpVoip=wwpVoip, wwpVoipDiagFailNotification=wwpVoipDiagFailNotification, wwpVoipTable=wwpVoipTable, wwpVoipEntry=wwpVoipEntry, wwpVoipApplicationVersion=wwpVoipApplicationVersion, wwpVoipPortNum=wwpVoipPortNum, wwpVoipIpAddr=wwpVoipIpAddr, wwpVoipResetOp=wwpVoipResetOp, wwpVoipCallAgentAddr=wwpVoipCallAgentAddr, wwpVoipIndex=wwpVoipIndex, wwpVoipMIB=wwpVoipMIB)
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_union, value_size_constraint, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (notification_type, integer32, bits, counter32, counter64, ip_address, time_ticks, iso, mib_identifier, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, gauge32, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'Integer32', 'Bits', 'Counter32', 'Counter64', 'IpAddress', 'TimeTicks', 'iso', 'MibIdentifier', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Gauge32', 'ObjectIdentity') (display_string, mac_address, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'MacAddress', 'TextualConvention') (wwp_modules,) = mibBuilder.importSymbols('WWP-SMI', 'wwpModules') wwp_voip_mib = module_identity((1, 3, 6, 1, 4, 1, 6141, 2, 15)) wwpVoipMIB.setRevisions(('2001-04-03 17:00',)) if mibBuilder.loadTexts: wwpVoipMIB.setLastUpdated('200104031700Z') if mibBuilder.loadTexts: wwpVoipMIB.setOrganization('World Wide Packets, Inc') wwp_voip_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1)) wwp_voip = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1)) wwp_voip_mib_notification_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 2)) wwp_voip_mib_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 2, 0)) wwp_voip_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 3)) wwp_voip_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 3, 1)) wwp_voip_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 15, 3, 2)) wwp_voip_table = mib_table((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1)) if mibBuilder.loadTexts: wwpVoipTable.setStatus('current') wwp_voip_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1)).setIndexNames((0, 'WWP-VOIP-MIB', 'wwpVoipIndex')) if mibBuilder.loadTexts: wwpVoipEntry.setStatus('current') wwp_voip_index = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpVoipIndex.setStatus('current') wwp_voip_down_loader_version = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 2), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpVoipDownLoaderVersion.setStatus('current') wwp_voip_application_version = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpVoipApplicationVersion.setStatus('current') wwp_voip_port_num = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpVoipPortNum.setStatus('current') wwp_voip_ip_addr = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 5), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpVoipIpAddr.setStatus('current') wwp_voip_num_resets = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpVoipNumResets.setStatus('current') wwp_voip_call_agent_addr = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 7), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpVoipCallAgentAddr.setStatus('current') wwp_voip_reset_op = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 15, 1, 1, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('none', 0), ('reset', 1)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpVoipResetOp.setStatus('current') wwp_voip_diag_fail_notification = notification_type((1, 3, 6, 1, 4, 1, 6141, 2, 15, 2, 0, 1)) if mibBuilder.loadTexts: wwpVoipDiagFailNotification.setStatus('current') mibBuilder.exportSymbols('WWP-VOIP-MIB', wwpVoipMIBNotificationPrefix=wwpVoipMIBNotificationPrefix, wwpVoipMIBNotifications=wwpVoipMIBNotifications, PYSNMP_MODULE_ID=wwpVoipMIB, wwpVoipMIBConformance=wwpVoipMIBConformance, wwpVoipDownLoaderVersion=wwpVoipDownLoaderVersion, wwpVoipMIBObjects=wwpVoipMIBObjects, wwpVoipMIBGroups=wwpVoipMIBGroups, wwpVoipMIBCompliances=wwpVoipMIBCompliances, wwpVoipNumResets=wwpVoipNumResets, wwpVoip=wwpVoip, wwpVoipDiagFailNotification=wwpVoipDiagFailNotification, wwpVoipTable=wwpVoipTable, wwpVoipEntry=wwpVoipEntry, wwpVoipApplicationVersion=wwpVoipApplicationVersion, wwpVoipPortNum=wwpVoipPortNum, wwpVoipIpAddr=wwpVoipIpAddr, wwpVoipResetOp=wwpVoipResetOp, wwpVoipCallAgentAddr=wwpVoipCallAgentAddr, wwpVoipIndex=wwpVoipIndex, wwpVoipMIB=wwpVoipMIB)
graph = { '5' : ['3','7'], '3' : ['2', '4'], '7' : ['8'], '2' : [], '4' : ['8'], '8' : [] } # List for visited nodes. visited = [] #Initialize a queue queue = [] # distance initialization (dict) dist = {} #function for BFS def bfs_shortest_path(visited, graph, start_node, end_node): global dist dist[start_node] = 0 visited.append(start_node) queue.append(start_node) if (start_node == end_node): return dist[end_node] # Creating loop to visit each node while(len(queue) != 0): m = queue.pop(0) print (m, end = " ") for neighbour in graph[m]: if(neighbour not in visited): dist[neighbour] = dist[m] + 1 visited.append(neighbour) queue.append(neighbour) return dist[end_node] my_dist = bfs_shortest_path(visited, graph, '5', '8') print("\n" + str(my_dist))
graph = {'5': ['3', '7'], '3': ['2', '4'], '7': ['8'], '2': [], '4': ['8'], '8': []} visited = [] queue = [] dist = {} def bfs_shortest_path(visited, graph, start_node, end_node): global dist dist[start_node] = 0 visited.append(start_node) queue.append(start_node) if start_node == end_node: return dist[end_node] while len(queue) != 0: m = queue.pop(0) print(m, end=' ') for neighbour in graph[m]: if neighbour not in visited: dist[neighbour] = dist[m] + 1 visited.append(neighbour) queue.append(neighbour) return dist[end_node] my_dist = bfs_shortest_path(visited, graph, '5', '8') print('\n' + str(my_dist))
def star(): print("How Much Rows You Want") n = int(input()) print("Enter 1 or Non Zero for True and 0 For False") n2 = int(input()) n1 = bool((n2)) if n1 is True: for i in range(n): i = i+1 print(i*"*") elif n1 is False: for i in range(n): i = n-i print(i*"*") star()
def star(): print('How Much Rows You Want') n = int(input()) print('Enter 1 or Non Zero for True and 0 For False') n2 = int(input()) n1 = bool(n2) if n1 is True: for i in range(n): i = i + 1 print(i * '*') elif n1 is False: for i in range(n): i = n - i print(i * '*') star()
#!/usr/bin/env python3 with open("input.txt", "r") as f: num = [] for elem in f.read().split(","): num.append(int(elem)) positions = set(num) steps = -1 for position in positions: current = 0 for elem in num: current += abs(elem - position) if steps < 0 or current < steps: steps = current print(steps)
with open('input.txt', 'r') as f: num = [] for elem in f.read().split(','): num.append(int(elem)) positions = set(num) steps = -1 for position in positions: current = 0 for elem in num: current += abs(elem - position) if steps < 0 or current < steps: steps = current print(steps)
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: s, res = {}, [] for i in range(len(numbers)): if numbers[i] in s.keys(): res.append(s[numbers[i]] + 1) res.append(i + 1) return res s[target - numbers[i]] = i return res
class Solution: def two_sum(self, numbers: List[int], target: int) -> List[int]: (s, res) = ({}, []) for i in range(len(numbers)): if numbers[i] in s.keys(): res.append(s[numbers[i]] + 1) res.append(i + 1) return res s[target - numbers[i]] = i return res
# historgram def histogram(s): d = dict() for c in s: a = d.get(c, 0) d[c] = 1+a return sorted(d) h = histogram("brantosaurus") print(h)
def histogram(s): d = dict() for c in s: a = d.get(c, 0) d[c] = 1 + a return sorted(d) h = histogram('brantosaurus') print(h)
class FirmwareGPIO: def __init__(self, scfg): crtl_inputs = scfg.analog_ctrl_inputs + scfg.digital_ctrl_inputs ctrl_outputs = scfg.analog_ctrl_outputs + scfg.digital_ctrl_outputs self.getter_dict = {} for probe in ctrl_outputs: if probe.o_addr is not None: self.getter_dict[probe.o_addr] = probe.name self.setter_dict = {} for param in crtl_inputs: if param.i_addr is not None: self.setter_dict[param.i_addr] = param.name self.hdr_text = self.gen_hdr_text() self.src_text = self.gen_src_text() def gen_hdr_text(self): retval = ''' #include "xgpio.h" int init_GPIO(); ''' # add setter declarations for k, v in self.setter_dict.items(): retval += f''' void set_{v}(u32 val); ''' # add getter declarations for k, v in self.getter_dict.items(): retval += f''' u32 get_{v}(); ''' # return the code return retval def gen_src_text(self): retval = ''' #include "xparameters.h" #include "xgpio.h" #include "sleep.h" XGpio Gpio0; // chan 1: o_ctrl, chan 2: o_data XGpio Gpio1; // chan 1: i_ctrl, chan 2: i_data int init_GPIO(){ int status0, status1; status0 = XGpio_Initialize(&Gpio0, XPAR_GPIO_0_DEVICE_ID); status1 = XGpio_Initialize(&Gpio1, XPAR_GPIO_1_DEVICE_ID); if ((status0 == XST_SUCCESS) && (status1 == XST_SUCCESS)) { return 0; } else { return 1; } } u32 get_value(u32 addr){ XGpio_DiscreteWrite(&Gpio0, 1, addr); usleep(1); return XGpio_DiscreteRead(&Gpio0, 2); } void set_value(u32 addr, u32 val){ // set address and data XGpio_DiscreteWrite(&Gpio1, 1, addr); XGpio_DiscreteWrite(&Gpio1, 2, val); usleep(1); // assert "valid" XGpio_DiscreteWrite(&Gpio1, 1, addr | (1UL << 30)); usleep(1); // de-assert "valid" XGpio_DiscreteWrite(&Gpio1, 1, addr); usleep(1); } ''' # add setter definitions for k, v in self.setter_dict.items(): retval += f''' void set_{v}(u32 val){{ set_value({k}, val); }} ''' # add setter definitions for k, v in self.getter_dict.items(): retval += f''' u32 get_{v}(){{ return get_value({k}); }} ''' # return the code return retval
class Firmwaregpio: def __init__(self, scfg): crtl_inputs = scfg.analog_ctrl_inputs + scfg.digital_ctrl_inputs ctrl_outputs = scfg.analog_ctrl_outputs + scfg.digital_ctrl_outputs self.getter_dict = {} for probe in ctrl_outputs: if probe.o_addr is not None: self.getter_dict[probe.o_addr] = probe.name self.setter_dict = {} for param in crtl_inputs: if param.i_addr is not None: self.setter_dict[param.i_addr] = param.name self.hdr_text = self.gen_hdr_text() self.src_text = self.gen_src_text() def gen_hdr_text(self): retval = '\n#include "xgpio.h"\n\nint init_GPIO();\n' for (k, v) in self.setter_dict.items(): retval += f'\nvoid set_{v}(u32 val);\n' for (k, v) in self.getter_dict.items(): retval += f'\nu32 get_{v}();\n' return retval def gen_src_text(self): retval = '\n#include "xparameters.h"\n#include "xgpio.h"\n#include "sleep.h"\n\nXGpio Gpio0; // chan 1: o_ctrl, chan 2: o_data\nXGpio Gpio1; // chan 1: i_ctrl, chan 2: i_data\n\nint init_GPIO(){\n int status0, status1;\n status0 = XGpio_Initialize(&Gpio0, XPAR_GPIO_0_DEVICE_ID);\n status1 = XGpio_Initialize(&Gpio1, XPAR_GPIO_1_DEVICE_ID);\n if ((status0 == XST_SUCCESS) && (status1 == XST_SUCCESS)) {\n return 0;\n } else {\n return 1;\n }\n}\n\nu32 get_value(u32 addr){\n XGpio_DiscreteWrite(&Gpio0, 1, addr);\n usleep(1);\n return XGpio_DiscreteRead(&Gpio0, 2);\n}\n\nvoid set_value(u32 addr, u32 val){\n // set address and data\n XGpio_DiscreteWrite(&Gpio1, 1, addr);\n XGpio_DiscreteWrite(&Gpio1, 2, val);\n usleep(1);\n\n // assert "valid"\n XGpio_DiscreteWrite(&Gpio1, 1, addr | (1UL << 30));\n usleep(1);\n\n // de-assert "valid"\n XGpio_DiscreteWrite(&Gpio1, 1, addr);\n usleep(1);\n}\n' for (k, v) in self.setter_dict.items(): retval += f'\nvoid set_{v}(u32 val){{\n set_value({k}, val);\n}}\n' for (k, v) in self.getter_dict.items(): retval += f'\nu32 get_{v}(){{\n return get_value({k});\n}}\n' return retval
def Articles(): articles = [ { 'id' : 1, 'title' : 'Article one', 'body' : 'Now ParseHub will call this handler every time the status of a run changes. It doesnt matter how long the run takes, or if it queued up on our servers for a while. Itll just work', 'auther': 'Refuge', 'create_date' : '04-24-2018' }, { 'id' : 2, 'title' : 'Article Two', 'body' : 'My Kickstarter project was a big success! Im now releasing a chapter of the new and improved Flask Mega-Tutorial every Tuesday here on this blog!', 'auther': 'Wise', 'create_date' : '04-26-2018' }, { 'id' : 3, 'title' : 'Article Three', 'body' : 'I have also created ebook and video versions of the complete tutorial, which Im offering for sale. Click on the book cover below for more information!', 'auther': 'Homie', 'create_date' : '04-30-2018' } ] return articles
def articles(): articles = [{'id': 1, 'title': 'Article one', 'body': 'Now ParseHub will call this handler every time the status of a run changes. It doesnt matter how long the run takes, or if it queued up on our servers for a while. Itll just work', 'auther': 'Refuge', 'create_date': '04-24-2018'}, {'id': 2, 'title': 'Article Two', 'body': 'My Kickstarter project was a big success! Im now releasing a chapter of the new and improved Flask Mega-Tutorial every Tuesday here on this blog!', 'auther': 'Wise', 'create_date': '04-26-2018'}, {'id': 3, 'title': 'Article Three', 'body': 'I have also created ebook and video versions of the complete tutorial, which Im offering for sale. Click on the book cover below for more information!', 'auther': 'Homie', 'create_date': '04-30-2018'}] return articles
DOMAIN = "ble_mesh" PLATFORM_LIGHT = "light" HANDLE_ID = 14 CMD_FUNCTION = 0xFB CMD_GPIO_CONTROL = 0xE7 CMD_OUT_1 = 0xF1 CMD_ON = 0x01 CMD_OFF = 0x00
domain = 'ble_mesh' platform_light = 'light' handle_id = 14 cmd_function = 251 cmd_gpio_control = 231 cmd_out_1 = 241 cmd_on = 1 cmd_off = 0
for _ in range(int(input())): a, b = [int(i) for i in input().split()] if a > b: print(">") elif a < b: print("<") else: print("=")
for _ in range(int(input())): (a, b) = [int(i) for i in input().split()] if a > b: print('>') elif a < b: print('<') else: print('=')
a = list(input()) cnt = 0 x = 0 for i in range(len(a)-1): if a[i] == a[i+1]: cnt += 1 if x <= cnt: x = cnt elif a[i] != a[i+1]: cnt = 0 print(x+1)
a = list(input()) cnt = 0 x = 0 for i in range(len(a) - 1): if a[i] == a[i + 1]: cnt += 1 if x <= cnt: x = cnt elif a[i] != a[i + 1]: cnt = 0 print(x + 1)
# Test proper handling of exceptions within generator across yield def gen(): try: yield 1 raise ValueError print("FAIL") raise SystemExit except ValueError: pass yield 2 for i in gen(): print(i) # Test throwing exceptions out of generator def gen2(): yield 1 raise ValueError yield 2 yield 3 g = gen2() print(next(g)) try: print(next(g)) print("FAIL") raise SystemExit except ValueError: pass try: print(next(g)) print("FAIL") raise SystemExit except StopIteration: pass # Test throwing exception into generator def gen3(): yield 1 try: yield 2 print("FAIL") raise SystemExit except ValueError: yield 3 yield 4 yield 5 g = gen3() print(next(g)) print(next(g)) print("out of throw:", g.throw(ValueError)) print(next(g)) try: print("out of throw2:", g.throw(ValueError)) print("FAIL") raise SystemExit except ValueError: print("PASS")
def gen(): try: yield 1 raise ValueError print('FAIL') raise SystemExit except ValueError: pass yield 2 for i in gen(): print(i) def gen2(): yield 1 raise ValueError yield 2 yield 3 g = gen2() print(next(g)) try: print(next(g)) print('FAIL') raise SystemExit except ValueError: pass try: print(next(g)) print('FAIL') raise SystemExit except StopIteration: pass def gen3(): yield 1 try: yield 2 print('FAIL') raise SystemExit except ValueError: yield 3 yield 4 yield 5 g = gen3() print(next(g)) print(next(g)) print('out of throw:', g.throw(ValueError)) print(next(g)) try: print('out of throw2:', g.throw(ValueError)) print('FAIL') raise SystemExit except ValueError: print('PASS')
with open("testfile.txt", "wb") as f1: for i in range(0, 65536): a = i//256 b = i%256 f1.write(bytes([a, b]))
with open('testfile.txt', 'wb') as f1: for i in range(0, 65536): a = i // 256 b = i % 256 f1.write(bytes([a, b]))
# Array (mutable, resizable) class Array: # Declare the necessary values used for the Array _capacity = None _size = None _array = None # Initialize these values with the capacity chosen def __init__(self, capacity): self._capacity = capacity self._size = 0 self._array = [None] * capacity # Return the current size of the Array (how many items are in it) def get_size(self): return self._size # Return the current capacity of the Array (how many items it can hold) def get_capacity(self): return self._capacity # Return whether the Array is empty (True) or not (False) def is_empty(self): return True if self._size == 0 else False # Return the item at a given index, if the index is within bounds def at(self, index): if index < 0 or index >= self._size: # Check if index is out of bounds raise IndexError('Must enter a valid index') return self._array[index] # Return the index of the item we're searching for within our array, return -1 if not found def find(self, item): for i in range(self._size): if self._array[i] is item: # Check if current value of array is strictly equal to the given item return i # Found the item, return its index return -1 # Didn't find the item, return -1 # Push an item to the end of the array def push(self, item): if self._size == self._capacity: # Check if array size is at max capacity, adjust accordingly self._resize(self._capacity * 2) self._array[self._size] = item self._size += 1 # Insert an item in the desired index of the array def insert(self, index, item): if index < 0 or index > self._size: # Check if index is out of bounds raise IndexError('Must enter a valid index (for contiguous memory)') if self._size == self._capacity: # Check if array size is at max capacity, adjust accordingly self._resize(self._capacity * 2) if not index == self._size: # Check if the index I chose is the tail of my current array self._shift_indexes(index, True) # If it is not the tail, shift the indexes accordingly else: self._size += 1 # Update size manually, because ._shift_indexes wasn't called self._array[index] = item # Prepend an item at the head of the array def prepend(self, item): if self._size == self._capacity: # Check if array size is at max capacity, adjust accordingly self._resize(self._capacity * 2) if not self.is_empty(): # Check if array is empty, aka size is 0 self._shift_indexes(0, True) # If it is not empty, shift the indexes accordingly else: self._size += 1 # Update size manually, because ._shift_indexes wasn't called self._array[0] = item # Pop the tail of the array and return it def pop(self): _temp_tail = self._array[self._size - 1] # Store the tail of the array in a variable so we can return it later self._array[self._size - 1] = None # Remove the tail of the array self._size -= 1 if self._size <= self._capacity / 4: # Check if array size is 1/4 of max capacity, adjust accordingly self._resize(int(self._capacity / 2)) return _temp_tail # Delete the item at the given index of the array and return it def delete(self, index): if index < 0 or index >= self._size: # Check if index is out of bounds raise IndexError('Must enter a valid index') _temp_deleted = self._array[index] # Store the deleted item of the array in a variable to return later self._array[index] = None # Delete the item at the given index if not index == self._size - 1: # If the index is not the tail, will have to shift indexes self._shift_indexes(index, False) else: self._size -= 1 # Update size manually, because ._shift_indexes wasn't called if self._size <= self._capacity / 4: # Check if array size is 1/4 of max capacity, adjust accordingly self._resize(int(self._capacity / 2)) return _temp_deleted # Remove the item with the value passed in, and return its index def remove(self, item): _found_index = self.find(item) # Store the index returned from .find() in a variable if _found_index is -1: # Check if the returned index is -1, if so, raise a ValueError raise ValueError('Item not found, please enter a valid value') self._array[_found_index] = None # Remove the item from the array if not _found_index == self._size - 1: # If the index found is not the tail, will have to shift indexes self._shift_indexes(_found_index, False) else: self._size -= 1 # Update size manually, because ._shift_indexes wasn't called if self._size <= self._capacity / 4: # Check if array size is 1/4 of max capacity, adjust accordingly self._resize(int(self._capacity / 2)) return _found_index # (Private) Resize the array with the given (new) capacity def _resize(self, new_capacity): _temp_array = [None] * new_capacity # Allocate desired memory to a temporary array for i in range(self._size): _temp_array[i] = self._array[i] # Copy each value from the original array to the temporary array self._array = _temp_array # Update the original array to its resized version _temp_array = None # Deallocate memory from temporary array self._capacity = new_capacity # Update the capacity so it matches the resized array # (Private) Shift indexes to the right, or to the left, and update the array's size def _shift_indexes(self, start_index, shift_right): if shift_right is True: # Shift indexes to the right for i in range(self._size, start_index, -1): # Start from the tail of the array self._array[i] = self._array[i-1] self._size += 1 if shift_right is False: # Shift indexes to the left for i in range(start_index, self._size - 1): # Start from the index passed in self._array[i] = self._array[i+1] self._size -= 1
class Array: _capacity = None _size = None _array = None def __init__(self, capacity): self._capacity = capacity self._size = 0 self._array = [None] * capacity def get_size(self): return self._size def get_capacity(self): return self._capacity def is_empty(self): return True if self._size == 0 else False def at(self, index): if index < 0 or index >= self._size: raise index_error('Must enter a valid index') return self._array[index] def find(self, item): for i in range(self._size): if self._array[i] is item: return i return -1 def push(self, item): if self._size == self._capacity: self._resize(self._capacity * 2) self._array[self._size] = item self._size += 1 def insert(self, index, item): if index < 0 or index > self._size: raise index_error('Must enter a valid index (for contiguous memory)') if self._size == self._capacity: self._resize(self._capacity * 2) if not index == self._size: self._shift_indexes(index, True) else: self._size += 1 self._array[index] = item def prepend(self, item): if self._size == self._capacity: self._resize(self._capacity * 2) if not self.is_empty(): self._shift_indexes(0, True) else: self._size += 1 self._array[0] = item def pop(self): _temp_tail = self._array[self._size - 1] self._array[self._size - 1] = None self._size -= 1 if self._size <= self._capacity / 4: self._resize(int(self._capacity / 2)) return _temp_tail def delete(self, index): if index < 0 or index >= self._size: raise index_error('Must enter a valid index') _temp_deleted = self._array[index] self._array[index] = None if not index == self._size - 1: self._shift_indexes(index, False) else: self._size -= 1 if self._size <= self._capacity / 4: self._resize(int(self._capacity / 2)) return _temp_deleted def remove(self, item): _found_index = self.find(item) if _found_index is -1: raise value_error('Item not found, please enter a valid value') self._array[_found_index] = None if not _found_index == self._size - 1: self._shift_indexes(_found_index, False) else: self._size -= 1 if self._size <= self._capacity / 4: self._resize(int(self._capacity / 2)) return _found_index def _resize(self, new_capacity): _temp_array = [None] * new_capacity for i in range(self._size): _temp_array[i] = self._array[i] self._array = _temp_array _temp_array = None self._capacity = new_capacity def _shift_indexes(self, start_index, shift_right): if shift_right is True: for i in range(self._size, start_index, -1): self._array[i] = self._array[i - 1] self._size += 1 if shift_right is False: for i in range(start_index, self._size - 1): self._array[i] = self._array[i + 1] self._size -= 1
class Solution: def nextGreaterElements(self, nums: list) -> list: if not nums: return [] monotonic_stack = [(nums[0], 0)] nums = nums + nums next_greater = {} for i, num in enumerate(nums[1:], 1): while monotonic_stack: if num > monotonic_stack[-1][0]: val, idx = monotonic_stack.pop() next_greater[(val, idx)] = num else: break if i < len(nums) // 2: monotonic_stack.append((num, i)) res = [-1] * (len(nums) // 2) for i, n in enumerate(nums[:len(nums) // 2]): if (n, i) in next_greater: res[i] = next_greater[(n, i)] return res
class Solution: def next_greater_elements(self, nums: list) -> list: if not nums: return [] monotonic_stack = [(nums[0], 0)] nums = nums + nums next_greater = {} for (i, num) in enumerate(nums[1:], 1): while monotonic_stack: if num > monotonic_stack[-1][0]: (val, idx) = monotonic_stack.pop() next_greater[val, idx] = num else: break if i < len(nums) // 2: monotonic_stack.append((num, i)) res = [-1] * (len(nums) // 2) for (i, n) in enumerate(nums[:len(nums) // 2]): if (n, i) in next_greater: res[i] = next_greater[n, i] return res
# List of rooms, characters, and weapons room_list = ['Study','Hall','Lounge','Library','Billiard','Dining','Conservatory','Ballroom','Kitchen'] hall_list = ['Hall A','Hall B','Hall C','Hall D','Hall E','Hall F','Hall G','Hall H','Hall I','Hall J','Hall K','Hall L'] character_list = ['Miss Scarlet','Mrs. Peacock','Professor Plum','Mr. Boddy','Mrs. White','Colonel Mustard'] weapon_list = ['Wrench','Candle Stick','Rope','Lead Pipe','Dagger','Revolver']
room_list = ['Study', 'Hall', 'Lounge', 'Library', 'Billiard', 'Dining', 'Conservatory', 'Ballroom', 'Kitchen'] hall_list = ['Hall A', 'Hall B', 'Hall C', 'Hall D', 'Hall E', 'Hall F', 'Hall G', 'Hall H', 'Hall I', 'Hall J', 'Hall K', 'Hall L'] character_list = ['Miss Scarlet', 'Mrs. Peacock', 'Professor Plum', 'Mr. Boddy', 'Mrs. White', 'Colonel Mustard'] weapon_list = ['Wrench', 'Candle Stick', 'Rope', 'Lead Pipe', 'Dagger', 'Revolver']
class MetadataNotFound(Exception): pass class MetadataCorruption(Exception): pass class NotYetImplemented(Exception): pass class SPConfigurationMissing(Exception): pass
class Metadatanotfound(Exception): pass class Metadatacorruption(Exception): pass class Notyetimplemented(Exception): pass class Spconfigurationmissing(Exception): pass
inp = input() arr = inp.split(' ') L = int(arr[0]) N = int(arr[1]) dic = [] for i in range(0,L): st = input() stri = st.split(' ') dic.append(stri) for i in range(0,N): inp = input() tr = False for j in range(0,L): temp = dic[j] if(inp == temp[0]): print(temp[1]) tr = True break if(tr): continue if(inp[len(inp)-1] == 'y' and len(inp)>1): if(inp[len(inp)-2] != 'a' and inp[len(inp)-2] != 'e' and inp[len(inp)-2] != 'i' and inp[len(inp)-2] != 'o' and inp[len(inp)-2] != 'u'): print(inp[0:len(inp)-1] + 'ies') continue if(inp[len(inp)-1] == 'o' or inp[len(inp)-1] == 's' or inp[len(inp)-1] == 'x' or (inp[len(inp)-2] == 'c' and inp[len(inp)-1] == 'h') or (inp[len(inp)-2] == 's' and inp[len(inp)-1] == 'h')): print(inp + 'es') continue print(inp + 's')
inp = input() arr = inp.split(' ') l = int(arr[0]) n = int(arr[1]) dic = [] for i in range(0, L): st = input() stri = st.split(' ') dic.append(stri) for i in range(0, N): inp = input() tr = False for j in range(0, L): temp = dic[j] if inp == temp[0]: print(temp[1]) tr = True break if tr: continue if inp[len(inp) - 1] == 'y' and len(inp) > 1: if inp[len(inp) - 2] != 'a' and inp[len(inp) - 2] != 'e' and (inp[len(inp) - 2] != 'i') and (inp[len(inp) - 2] != 'o') and (inp[len(inp) - 2] != 'u'): print(inp[0:len(inp) - 1] + 'ies') continue if inp[len(inp) - 1] == 'o' or inp[len(inp) - 1] == 's' or inp[len(inp) - 1] == 'x' or (inp[len(inp) - 2] == 'c' and inp[len(inp) - 1] == 'h') or (inp[len(inp) - 2] == 's' and inp[len(inp) - 1] == 'h'): print(inp + 'es') continue print(inp + 's')
__all__ = ( 'decode_int', 'decode_str', 'decode_lst' ) def decode_int(data, pos): end = data[pos:].index(b'e') if data[pos+1] == ord('-'): return (int(data[pos + 2:pos + end]) * -1, end) else: return (int(data[pos + 1:pos + end]), end + pos) # return data as raw bytes not decoded to ASCII def decode_str(data, pos): index = data[pos:].find(b':') length = int(data[pos: pos+ index]) return (data[pos + index + 1: pos + index + length+1], length + pos + index + 1) def decode_lst(data): lst = [] i = 1 while data[i] != ord(b'e'): elem, newpos = decode_dic[bytes([data[i]])](data, i) i = newpos lst.append(elem) return lst decode_dic = {} decode_dic[b'0'] = decode_str decode_dic[b'1'] = decode_str decode_dic[b'2'] = decode_str decode_dic[b'3'] = decode_str decode_dic[b'4'] = decode_str decode_dic[b'5'] = decode_str decode_dic[b'6'] = decode_str decode_dic[b'7'] = decode_str decode_dic[b'8'] = decode_str decode_dic[b'9'] = decode_str decode_dic[b'i'] = decode_int
__all__ = ('decode_int', 'decode_str', 'decode_lst') def decode_int(data, pos): end = data[pos:].index(b'e') if data[pos + 1] == ord('-'): return (int(data[pos + 2:pos + end]) * -1, end) else: return (int(data[pos + 1:pos + end]), end + pos) def decode_str(data, pos): index = data[pos:].find(b':') length = int(data[pos:pos + index]) return (data[pos + index + 1:pos + index + length + 1], length + pos + index + 1) def decode_lst(data): lst = [] i = 1 while data[i] != ord(b'e'): (elem, newpos) = decode_dic[bytes([data[i]])](data, i) i = newpos lst.append(elem) return lst decode_dic = {} decode_dic[b'0'] = decode_str decode_dic[b'1'] = decode_str decode_dic[b'2'] = decode_str decode_dic[b'3'] = decode_str decode_dic[b'4'] = decode_str decode_dic[b'5'] = decode_str decode_dic[b'6'] = decode_str decode_dic[b'7'] = decode_str decode_dic[b'8'] = decode_str decode_dic[b'9'] = decode_str decode_dic[b'i'] = decode_int
def seat_decode(seat): row = int(seat[:7].replace("F", "0").replace("B", "1"), 2) column = int(seat[7:].replace("L", "0").replace("R", "1"), 2) return row * 8 + column if __name__ == "__main__": with open("input.txt", "r") as f: ids = {seat_decode(line.strip()) for line in f.readlines()} result1 = max(ids) print(f"Result 1: {result1}") for seat in range(min(ids), max(ids)): if seat - 1 in ids and seat + 1 in ids and seat not in ids: result2 = seat break print(f"Result 2: {result2}")
def seat_decode(seat): row = int(seat[:7].replace('F', '0').replace('B', '1'), 2) column = int(seat[7:].replace('L', '0').replace('R', '1'), 2) return row * 8 + column if __name__ == '__main__': with open('input.txt', 'r') as f: ids = {seat_decode(line.strip()) for line in f.readlines()} result1 = max(ids) print(f'Result 1: {result1}') for seat in range(min(ids), max(ids)): if seat - 1 in ids and seat + 1 in ids and (seat not in ids): result2 = seat break print(f'Result 2: {result2}')
dicio = {"Nome": str(input('Nome do jogador: '))} partidas = int(input(f'Quantas partidas {dicio["Nome"]} jogou? ')) lista = [] for c in range(partidas): dicio["Gols"] = int((input(f'Quantos gols na partida {c+1}: '))) lista.append(dicio["Gols"]) dicio["Gols"] = lista total = int() for c in lista: total += c dicio["Total"] = total print('-='*30) print(dicio) print('-='*30) for c, v in dicio.items(): print(f'O campo {c} tem o valor {v}') print('-='*30) print(f'O jogador {dicio["Nome"]} jogou {partidas} partidas.') for c, v in enumerate(lista): print(f' => Na partida {c+1}, fez {v} gols.') print(f'Foi um total de {total} gols.')
dicio = {'Nome': str(input('Nome do jogador: '))} partidas = int(input(f"Quantas partidas {dicio['Nome']} jogou? ")) lista = [] for c in range(partidas): dicio['Gols'] = int(input(f'Quantos gols na partida {c + 1}: ')) lista.append(dicio['Gols']) dicio['Gols'] = lista total = int() for c in lista: total += c dicio['Total'] = total print('-=' * 30) print(dicio) print('-=' * 30) for (c, v) in dicio.items(): print(f'O campo {c} tem o valor {v}') print('-=' * 30) print(f"O jogador {dicio['Nome']} jogou {partidas} partidas.") for (c, v) in enumerate(lista): print(f' => Na partida {c + 1}, fez {v} gols.') print(f'Foi um total de {total} gols.')
def data(): return { "test": { "min/layer2/weights": { "displayName": "min/layer2/weights", "description": "" } }, "train": { "min/layer2/weights": { "displayName": "min/layer2/weights", "description": "" } } }
def data(): return {'test': {'min/layer2/weights': {'displayName': 'min/layer2/weights', 'description': ''}}, 'train': {'min/layer2/weights': {'displayName': 'min/layer2/weights', 'description': ''}}}
#!/usr/bin/env/ python # encoding: utf-8 __author__ = 'aldur'
__author__ = 'aldur'
# Python 3.6.1 with open("input.txt", "r") as f: puzzle_input = [] for line in f: puzzle_input.append(line.strip().split(" ")) total = 0 for phrase in puzzle_input: bad = False for word in phrase: if phrase.count(word) > 1: bad = True break if not bad: total += 1 print(total)
with open('input.txt', 'r') as f: puzzle_input = [] for line in f: puzzle_input.append(line.strip().split(' ')) total = 0 for phrase in puzzle_input: bad = False for word in phrase: if phrase.count(word) > 1: bad = True break if not bad: total += 1 print(total)
def Select_sort1(): A = [-9, -8, 640, 25, 12, 22, 33, 23, 45, 11, -2, -5, 99, 0] for i in range(len(A)): minimum = i for j in range(i+1, len(A)): if A[minimum] > A[j]: minimum = j A[i], A[minimum] = A[minimum], A[i] print("After sort:") print(A) def Select_sort2(): A = [-9, -8, 640, 25, 12, 22, 33, 23, 45, 11, -2, -5, 99, 0] counter = 0 array = [] for i in A: counter += 1 for j in A[counter:]: if i > j: i = j A.remove(i) A.insert(counter-1, i) array.append(i) print("After sort:") print(A) Select_sort1() Select_sort2()
def select_sort1(): a = [-9, -8, 640, 25, 12, 22, 33, 23, 45, 11, -2, -5, 99, 0] for i in range(len(A)): minimum = i for j in range(i + 1, len(A)): if A[minimum] > A[j]: minimum = j (A[i], A[minimum]) = (A[minimum], A[i]) print('After sort:') print(A) def select_sort2(): a = [-9, -8, 640, 25, 12, 22, 33, 23, 45, 11, -2, -5, 99, 0] counter = 0 array = [] for i in A: counter += 1 for j in A[counter:]: if i > j: i = j A.remove(i) A.insert(counter - 1, i) array.append(i) print('After sort:') print(A) select_sort1() select_sort2()
emails = sorted(set([line.strip() for line in open("email_domains.txt")])) for email in emails: print("'{email}',".format(email=email))
emails = sorted(set([line.strip() for line in open('email_domains.txt')])) for email in emails: print("'{email}',".format(email=email))
for _ in range(int(input())): string = input() new_str= "" new_str += string[0] for i in range(1, len(string)): if string[i] == "L": on = string[i-1] elif string[i] == "R": on = string[i+1] else: on = string[i] new_str += on print(new_str)
for _ in range(int(input())): string = input() new_str = '' new_str += string[0] for i in range(1, len(string)): if string[i] == 'L': on = string[i - 1] elif string[i] == 'R': on = string[i + 1] else: on = string[i] new_str += on print(new_str)
# https://www.hackerrank.com/challenges/any-or-all/problem def is_palindrome(number): return number == number[::-1] N = int(input()) array = list(input().split()) print( all(int(element) >= 0 for element in array) and any(is_palindrome(element) for element in array) )
def is_palindrome(number): return number == number[::-1] n = int(input()) array = list(input().split()) print(all((int(element) >= 0 for element in array)) and any((is_palindrome(element) for element in array)))
def flownet_v1_s(input): pass
def flownet_v1_s(input): pass
prime = [2,3] i = 4 while len(prime)<10001: s = True for j in prime: if i%j == 0: s = False break if s: prime.append(i) i = i + 1 print(prime[-1])
prime = [2, 3] i = 4 while len(prime) < 10001: s = True for j in prime: if i % j == 0: s = False break if s: prime.append(i) i = i + 1 print(prime[-1])
def rotation_string(str): l = [] #str = "" for i in str: l.append(i) #print(l) for j in range(len(l) // 2): a = l[j] b = l[-(j+1)] l[j] = b l[-(j+1)] = a return l
def rotation_string(str): l = [] for i in str: l.append(i) for j in range(len(l) // 2): a = l[j] b = l[-(j + 1)] l[j] = b l[-(j + 1)] = a return l
def descending(x,n): t=0 # by selection sorting for i in range(0,n-1,1): for j in range(i+1,n,1): if x[i]<x[j]: t=x[i] x[i]=x[j] x[j]=t return (x) # To sort a list in descending order print("This programme sorts a list in descending order : ") n=int(input("Enter the number of elements in the list : ")) x=[(i*0) for i in range(0,n,1)] for i in range(0,n,1): x[i]=int(input()) x=descending(x,n) print("The list in descending order is : ") for i in range(0,n,1): print(x[i],end=" ")
def descending(x, n): t = 0 for i in range(0, n - 1, 1): for j in range(i + 1, n, 1): if x[i] < x[j]: t = x[i] x[i] = x[j] x[j] = t return x print('This programme sorts a list in descending order : ') n = int(input('Enter the number of elements in the list : ')) x = [i * 0 for i in range(0, n, 1)] for i in range(0, n, 1): x[i] = int(input()) x = descending(x, n) print('The list in descending order is : ') for i in range(0, n, 1): print(x[i], end=' ')
config = {'MAX_BOUND':512.0, 'MIN_BOUND':-1024.0, 'PIXEL_MEAN':0.25, 'NORM_CROP':True }
config = {'MAX_BOUND': 512.0, 'MIN_BOUND': -1024.0, 'PIXEL_MEAN': 0.25, 'NORM_CROP': True}
# # PySNMP MIB module ELTEX-ULD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-ULD-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:48:10 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, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint") eltexLtd, = mibBuilder.importSymbols("ELTEX-SMI-ACTUAL", "eltexLtd") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") NotificationType, Unsigned32, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, ModuleIdentity, Integer32, Counter64, TimeTicks, MibIdentifier, Bits, iso, Counter32, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Unsigned32", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "ModuleIdentity", "Integer32", "Counter64", "TimeTicks", "MibIdentifier", "Bits", "iso", "Counter32", "Gauge32") DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TruthValue", "TextualConvention") eltexULDMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 35265, 34)) if mibBuilder.loadTexts: eltexULDMIB.setLastUpdated('201301280000Z') if mibBuilder.loadTexts: eltexULDMIB.setOrganization('Eltex Ltd.') eltexULDNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 35265, 34, 0)) eltexULDMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 35265, 34, 1)) eltexULDTable = MibTable((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1), ) if mibBuilder.loadTexts: eltexULDTable.setStatus('current') eltexULDEntry = MibTableRow((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: eltexULDEntry.setStatus('current') eltexULDAdminState = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: eltexULDAdminState.setStatus('current') eltexULDOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: eltexULDOperStatus.setStatus('current') eltexULDMode = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("log", 1), ("err-disable", 2))).clone('log')).setMaxAccess("readwrite") if mibBuilder.loadTexts: eltexULDMode.setStatus('current') eltexULDDiscoveryTime = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 300)).clone(5)).setMaxAccess("readwrite") if mibBuilder.loadTexts: eltexULDDiscoveryTime.setStatus('current') eltexULDIsAggressive = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 5), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: eltexULDIsAggressive.setStatus('current') eltexULDLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("unknown", 1), ("unidirectional", 2), ("bidirectional", 3), ("tx-rx-loop", 4), ("neighbor-mismatch", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: eltexULDLinkStatus.setStatus('current') eltexULDLinkStatusChanged = NotificationType((1, 3, 6, 1, 4, 1, 35265, 34, 0, 1)).setObjects(("IF-MIB", "ifIndex"), ("ELTEX-ULD-MIB", "eltexULDLinkStatus")) if mibBuilder.loadTexts: eltexULDLinkStatusChanged.setStatus('current') mibBuilder.exportSymbols("ELTEX-ULD-MIB", eltexULDNotifications=eltexULDNotifications, eltexULDLinkStatus=eltexULDLinkStatus, eltexULDOperStatus=eltexULDOperStatus, eltexULDAdminState=eltexULDAdminState, eltexULDMgmt=eltexULDMgmt, eltexULDIsAggressive=eltexULDIsAggressive, PYSNMP_MODULE_ID=eltexULDMIB, eltexULDDiscoveryTime=eltexULDDiscoveryTime, eltexULDMIB=eltexULDMIB, eltexULDEntry=eltexULDEntry, eltexULDMode=eltexULDMode, eltexULDLinkStatusChanged=eltexULDLinkStatusChanged, eltexULDTable=eltexULDTable)
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_range_constraint, constraints_intersection, constraints_union, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint') (eltex_ltd,) = mibBuilder.importSymbols('ELTEX-SMI-ACTUAL', 'eltexLtd') (if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (notification_type, unsigned32, ip_address, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, module_identity, integer32, counter64, time_ticks, mib_identifier, bits, iso, counter32, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'Unsigned32', 'IpAddress', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'ModuleIdentity', 'Integer32', 'Counter64', 'TimeTicks', 'MibIdentifier', 'Bits', 'iso', 'Counter32', 'Gauge32') (display_string, truth_value, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TruthValue', 'TextualConvention') eltex_uldmib = module_identity((1, 3, 6, 1, 4, 1, 35265, 34)) if mibBuilder.loadTexts: eltexULDMIB.setLastUpdated('201301280000Z') if mibBuilder.loadTexts: eltexULDMIB.setOrganization('Eltex Ltd.') eltex_uld_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 35265, 34, 0)) eltex_uld_mgmt = mib_identifier((1, 3, 6, 1, 4, 1, 35265, 34, 1)) eltex_uld_table = mib_table((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1)) if mibBuilder.loadTexts: eltexULDTable.setStatus('current') eltex_uld_entry = mib_table_row((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex')) if mibBuilder.loadTexts: eltexULDEntry.setStatus('current') eltex_uld_admin_state = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('disabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: eltexULDAdminState.setStatus('current') eltex_uld_oper_status = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: eltexULDOperStatus.setStatus('current') eltex_uld_mode = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('log', 1), ('err-disable', 2))).clone('log')).setMaxAccess('readwrite') if mibBuilder.loadTexts: eltexULDMode.setStatus('current') eltex_uld_discovery_time = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(5, 300)).clone(5)).setMaxAccess('readwrite') if mibBuilder.loadTexts: eltexULDDiscoveryTime.setStatus('current') eltex_uld_is_aggressive = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 5), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: eltexULDIsAggressive.setStatus('current') eltex_uld_link_status = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 34, 1, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('unknown', 1), ('unidirectional', 2), ('bidirectional', 3), ('tx-rx-loop', 4), ('neighbor-mismatch', 5)))).setMaxAccess('readonly') if mibBuilder.loadTexts: eltexULDLinkStatus.setStatus('current') eltex_uld_link_status_changed = notification_type((1, 3, 6, 1, 4, 1, 35265, 34, 0, 1)).setObjects(('IF-MIB', 'ifIndex'), ('ELTEX-ULD-MIB', 'eltexULDLinkStatus')) if mibBuilder.loadTexts: eltexULDLinkStatusChanged.setStatus('current') mibBuilder.exportSymbols('ELTEX-ULD-MIB', eltexULDNotifications=eltexULDNotifications, eltexULDLinkStatus=eltexULDLinkStatus, eltexULDOperStatus=eltexULDOperStatus, eltexULDAdminState=eltexULDAdminState, eltexULDMgmt=eltexULDMgmt, eltexULDIsAggressive=eltexULDIsAggressive, PYSNMP_MODULE_ID=eltexULDMIB, eltexULDDiscoveryTime=eltexULDDiscoveryTime, eltexULDMIB=eltexULDMIB, eltexULDEntry=eltexULDEntry, eltexULDMode=eltexULDMode, eltexULDLinkStatusChanged=eltexULDLinkStatusChanged, eltexULDTable=eltexULDTable)
n = int(input('Enter a Value for N:\n')) count = 1 while count <= n: v1 = count v2 = count + 1 if count +2 < n: v3 = count + 2 else: v3 = ' ' print(f'{v1} {v2} {v3}') count += 3
n = int(input('Enter a Value for N:\n')) count = 1 while count <= n: v1 = count v2 = count + 1 if count + 2 < n: v3 = count + 2 else: v3 = ' ' print(f'{v1} {v2} {v3}') count += 3
# https://www.codewars.com/kata/578553c3a1b8d5c40300037c/python # Given an array of ones and zeroes, convert the equivalent binary value to an integer. # Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1. # Examples: # Testing: [0, 0, 0, 1] ==> 1 # Testing: [0, 0, 1, 0] ==> 2 # Testing: [0, 1, 0, 1] ==> 5 # Testing: [1, 0, 0, 1] ==> 9 # Testing: [0, 0, 1, 0] ==> 2 # Testing: [0, 1, 1, 0] ==> 6 # Testing: [1, 1, 1, 1] ==> 15 # Testing: [1, 0, 1, 1] ==> 11 def binary_array_to_number(arr): binary = ''.join(map(str,arr)) return int(binary, 2) print(binary_array_to_number([1, 0, 0, 0, 1]))
def binary_array_to_number(arr): binary = ''.join(map(str, arr)) return int(binary, 2) print(binary_array_to_number([1, 0, 0, 0, 1]))
def gap_sort(x): gap = len(x) swap= True while gap > 1 or swap: gap = max(1, int(gap / 1.3)) swap= False for i in range(len(x) - gap): j = i+gap if x[i] > x[j]: x[i], x[j] = x[j], x[i] swap= True lst = [3,6,4,8,9,0,6,5,2,10,1] print("Unsorted: ", lst) gap_sort(lst) print("Sorted: ", lst)
def gap_sort(x): gap = len(x) swap = True while gap > 1 or swap: gap = max(1, int(gap / 1.3)) swap = False for i in range(len(x) - gap): j = i + gap if x[i] > x[j]: (x[i], x[j]) = (x[j], x[i]) swap = True lst = [3, 6, 4, 8, 9, 0, 6, 5, 2, 10, 1] print('Unsorted: ', lst) gap_sort(lst) print('Sorted: ', lst)
#!/usr/bin/env python # -*- coding: utf-8 -*- modelChemistry = "CBS-QB3" useHinderedRotors = True useBondCorrections = False species('CH2CHOOH', 'CH2CHOOH.py') statmech('CH2CHOOH') thermo('CH2CHOOH', 'Wilhoit')
model_chemistry = 'CBS-QB3' use_hindered_rotors = True use_bond_corrections = False species('CH2CHOOH', 'CH2CHOOH.py') statmech('CH2CHOOH') thermo('CH2CHOOH', 'Wilhoit')
#: Module purely exists to test patching things. thing = True it = lambda: False def get_thing(): global thing return thing def get_it(): global it return it
thing = True it = lambda : False def get_thing(): global thing return thing def get_it(): global it return it
li=[] n=int(input("Enter Number of Elements in List")) print("Enter Numbers") for i in range(n): ele=int(input()) li.append(ele) l1=[] for i in li: l1.insert(len(l1)-1,i) print(l1)
li = [] n = int(input('Enter Number of Elements in List')) print('Enter Numbers') for i in range(n): ele = int(input()) li.append(ele) l1 = [] for i in li: l1.insert(len(l1) - 1, i) print(l1)
phone_book = dict() enough = False while True: if enough: break command = input() if command == 'stop': break elif command == 'search': while True: person = input() if person == 'stop': enough = True break if person not in phone_book: print(f'Contact {person} does not exist.') else: print(f'{person} -> {phone_book[person]}') else: name, number = command.split('-') if name not in phone_book: phone_book[name] = '' phone_book[name] = number
phone_book = dict() enough = False while True: if enough: break command = input() if command == 'stop': break elif command == 'search': while True: person = input() if person == 'stop': enough = True break if person not in phone_book: print(f'Contact {person} does not exist.') else: print(f'{person} -> {phone_book[person]}') else: (name, number) = command.split('-') if name not in phone_book: phone_book[name] = '' phone_book[name] = number
#In this program we will enter a number and get its factors as the output in a list format. num = int(input("Enter number: ")) def factors(n): flist = [] for i in range(1,n+1): if n%i == 0: flist.append(i) return flist print(factors(num))
num = int(input('Enter number: ')) def factors(n): flist = [] for i in range(1, n + 1): if n % i == 0: flist.append(i) return flist print(factors(num))
class initial(): def solution(self, nums): prefix = [1] * len(nums) suffix = [1] * len(nums) for i in range(1, len(nums)): prefix[i] = prefix[i-1] * nums[i-1] for j in range(len(nums)-2, -1, -1): suffix[j] = suffix[j+1] * nums[j+1] return [prefix[i] * suffix[i] for i in range(len(nums))] # https://leetcode.com/problems/product-of-array-except-self/ # Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. # The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. # You must write an algorithm that runs in O(n) time and without using the division operation. # Score Card # Did I need hints # Did you finish within 30 min # Finished in 20 min # Was the solution optimal # The solution is optimal for time but not space # Were there any bugs # I forgot to correctly multiply the first nums by i-1 so that result wasn't quite right and wasted 4 min # test case 1 nums = [1, 2, 3, 4] # output = [24,12,8,6] sol = initial() print(sol.solution(nums)) # This could be improved to o(1) space if we convert either suffix or prefix to be the nums array and then dynamically solving the other on the fly # 4 5 3 3 = 3.75
class Initial: def solution(self, nums): prefix = [1] * len(nums) suffix = [1] * len(nums) for i in range(1, len(nums)): prefix[i] = prefix[i - 1] * nums[i - 1] for j in range(len(nums) - 2, -1, -1): suffix[j] = suffix[j + 1] * nums[j + 1] return [prefix[i] * suffix[i] for i in range(len(nums))] nums = [1, 2, 3, 4] sol = initial() print(sol.solution(nums))
def parse(filename: str) -> list[int]: with open(filename) as file: line = file.read() return list(map(int, line.split(','))) def solve(fishes: list[int], days: int) -> int: for _ in range(days): for i in range(len(fishes)): fishes[i] -= 1 if fishes[i] < 0: fishes[i] = 6 fishes.append(8) return len(fishes) def main(): input = parse('data/day6.txt') result = solve(input, 80) print(result) if __name__ == '__main__': main()
def parse(filename: str) -> list[int]: with open(filename) as file: line = file.read() return list(map(int, line.split(','))) def solve(fishes: list[int], days: int) -> int: for _ in range(days): for i in range(len(fishes)): fishes[i] -= 1 if fishes[i] < 0: fishes[i] = 6 fishes.append(8) return len(fishes) def main(): input = parse('data/day6.txt') result = solve(input, 80) print(result) if __name__ == '__main__': main()
#leia o tamanho do lado de um quadrado e #imprima como resultado a area. lado=float(input("Informe o lado do quadrado: ")) area=lado*lado print(f"A area do quadrado eh {area}")
lado = float(input('Informe o lado do quadrado: ')) area = lado * lado print(f'A area do quadrado eh {area}')
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: maxi = 0 def dfs( node ): nonlocal maxi if node is None: return -1 left = dfs( node.left ) + 1 right = dfs( node.right ) + 1 cur_sum = left + right maxi = max( cur_sum, maxi ) return max( left, right ) dfs( root ) return maxi
class Solution: def diameter_of_binary_tree(self, root: Optional[TreeNode]) -> int: maxi = 0 def dfs(node): nonlocal maxi if node is None: return -1 left = dfs(node.left) + 1 right = dfs(node.right) + 1 cur_sum = left + right maxi = max(cur_sum, maxi) return max(left, right) dfs(root) return maxi
class dotHierarchicList_t(object): # no doc aObjects = None ModelFatherObject = None nObjects = None ObjectsLeftToGet = None OperationType = None
class Dothierarchiclist_T(object): a_objects = None model_father_object = None n_objects = None objects_left_to_get = None operation_type = None
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head: return None if not head.next: return head temp = head.next head.next = self.swapPairs(temp.next) temp.next = head return temp
class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def swap_pairs(self, head: ListNode) -> ListNode: if not head: return None if not head.next: return head temp = head.next head.next = self.swapPairs(temp.next) temp.next = head return temp
''' Factorial (hacker challenge). Write a function factorial() that returns the factorial of the given number. For example, factorial(5) should return 120. Do this using recursion; remember that factorial(n) = n * factorial(n-1). ''' def factorial(n): if n == 1 or n == 0: return 1 if n == 2: return 2 return n*factorial(n-1) print(factorial(5)) def factorial_iter(n): res = 1 for i in range(1, n+1): print('before ', res, i) res *= i print('after ', res, i) return res print(factorial_iter(5))
""" Factorial (hacker challenge). Write a function factorial() that returns the factorial of the given number. For example, factorial(5) should return 120. Do this using recursion; remember that factorial(n) = n * factorial(n-1). """ def factorial(n): if n == 1 or n == 0: return 1 if n == 2: return 2 return n * factorial(n - 1) print(factorial(5)) def factorial_iter(n): res = 1 for i in range(1, n + 1): print('before ', res, i) res *= i print('after ', res, i) return res print(factorial_iter(5))
def infini(y : int) -> int: x : int = y while x >= 0: x = x + 1 return x def f(x : int) -> int: return x + 1
def infini(y: int) -> int: x: int = y while x >= 0: x = x + 1 return x def f(x: int) -> int: return x + 1
def changeConf(xmin=2., xmax=16., resolution=2, Nxx=1000, Ntt=20000, \ every_scalar_t=10, every_aaray_t=100, \ amplitud=0.1, sigma=1, x0=9., Boundaries=0, Metric=1): conf = open('input.par','w') conf.write('&parameters') conf.write('xmin = ' + str(xmin) + '\n') conf.write('xmax = ' + str(xmax) + '\n') conf.write('resolution = ' + str(resolution) + '\n') conf.write('Nxx = ' + str(Nxx) + '\n') conf.write('Ntt = ' + str(Ntt) + '\n') conf.write('courant = 0.25' + '\n') conf.write('every_scalar_t = ' + str(every_scalar_t) + '\n') conf.write('every_array_t = ' + str(every_aaray_t) + '\n') conf.write('amplitud = ' + str(amplitud) + '\n') conf.write('sigma = ' + str(sigma) + '\n') conf.write('x0 = ' + str(x0) + '\n') conf.write('Boundaries = ' + str(Boundaries) + '\n') conf.write('Metric = ' + str(Metric) + '\n') conf.write('\\') conf.close() print('-------------------------')
def change_conf(xmin=2.0, xmax=16.0, resolution=2, Nxx=1000, Ntt=20000, every_scalar_t=10, every_aaray_t=100, amplitud=0.1, sigma=1, x0=9.0, Boundaries=0, Metric=1): conf = open('input.par', 'w') conf.write('&parameters') conf.write('xmin = ' + str(xmin) + '\n') conf.write('xmax = ' + str(xmax) + '\n') conf.write('resolution = ' + str(resolution) + '\n') conf.write('Nxx = ' + str(Nxx) + '\n') conf.write('Ntt = ' + str(Ntt) + '\n') conf.write('courant = 0.25' + '\n') conf.write('every_scalar_t = ' + str(every_scalar_t) + '\n') conf.write('every_array_t = ' + str(every_aaray_t) + '\n') conf.write('amplitud = ' + str(amplitud) + '\n') conf.write('sigma = ' + str(sigma) + '\n') conf.write('x0 = ' + str(x0) + '\n') conf.write('Boundaries = ' + str(Boundaries) + '\n') conf.write('Metric = ' + str(Metric) + '\n') conf.write('\\') conf.close() print('-------------------------')
class Day3: def part1(self): with open(r'C:\Coding\AdventOfCode\AOC2019\Data\Data3.txt') as f: lines = f.read().splitlines() firstPath = lines[0].split(',') secondPath = lines[1].split(',') firstPathCoordinates = self.wiresPositionsDictionary(firstPath) secondPathCoordinates = self.wiresPositionsDictionary(secondPath) manhattanDistance = 9999999999999 for coordinate in firstPathCoordinates: if coordinate in secondPathCoordinates: distance = abs(coordinate.X) + abs(coordinate.Y) if 0 < distance < manhattanDistance: manhattanDistance = distance print("Day 3, part 1: " + str(manhattanDistance)) def wiresPositionsDictionary(self, commands) -> dict: position = Position(0, 0) dictionary = {position: 0} for command in commands: firstLetter = command[0] number = int(command[1:]) i = 0 while i < number: i += 1 if firstLetter == 'U': position = Position(position.X, position.Y + 1) if position.X != 0 and position.Y != 0: dictionary[position] = 1 if firstLetter == 'D': position = Position(position.X, position.Y - 1) if position.X != 0 and position.Y != 0: dictionary[position] = 1 if firstLetter == 'L': position = Position(position.X - 1, position.Y) if position.X != 0 and position.Y != 0: dictionary[position] = 1 if firstLetter == 'R': position = Position(position.X + 1, position.Y) if position.X != 0 or position.Y != 0: dictionary[position] = 1 return dictionary def part2(self): with open(r'C:\Coding\AdventOfCode\AOC2019\Data\Data3.txt') as f: lines = f.read().splitlines() firstPath = lines[0].split(',') secondPath = lines[1].split(',') firstPathCoordinates = self.wiresPositionsDictionaryWithTime(firstPath) secondPathCoordinates = self.wiresPositionsDictionaryWithTime(secondPath) minimumTime = 9999999999999 for coordinate in firstPathCoordinates: if coordinate in secondPathCoordinates: time = firstPathCoordinates[coordinate] + secondPathCoordinates[coordinate] if 0 < time < minimumTime: minimumTime = time print("Day 3, part 2: " + str(minimumTime)) def wiresPositionsDictionaryWithTime(self, commands) -> dict: position = Position(0, 0) dictionary = {position: 0} time = 1 for command in commands: firstLetter = command[0] number = int(command[1:]) i = 0 while i < number: i += 1 if firstLetter == 'U': position = Position(position.X, position.Y + 1) self.addToDictionary(dictionary, position, time) if firstLetter == 'D': position = Position(position.X, position.Y - 1) self.addToDictionary(dictionary, position, time) if firstLetter == 'L': position = Position(position.X - 1, position.Y) self.addToDictionary(dictionary, position, time) if firstLetter == 'R': position = Position(position.X + 1, position.Y) self.addToDictionary(dictionary, position, time) time += 1 return dictionary def addToDictionary(self, dictionary, position, time): if (position.X != 0 or position.Y != 0) and position not in dictionary: dictionary[position] = time class Position: X = 0 Y = 0 def __init__(self, x, y): self.X = x self.Y = y def __eq__(self, other): return self.X == other.X and self.Y == other.Y def __hash__(self): return hash((self.X, self.Y))
class Day3: def part1(self): with open('C:\\Coding\\AdventOfCode\\AOC2019\\Data\\Data3.txt') as f: lines = f.read().splitlines() first_path = lines[0].split(',') second_path = lines[1].split(',') first_path_coordinates = self.wiresPositionsDictionary(firstPath) second_path_coordinates = self.wiresPositionsDictionary(secondPath) manhattan_distance = 9999999999999 for coordinate in firstPathCoordinates: if coordinate in secondPathCoordinates: distance = abs(coordinate.X) + abs(coordinate.Y) if 0 < distance < manhattanDistance: manhattan_distance = distance print('Day 3, part 1: ' + str(manhattanDistance)) def wires_positions_dictionary(self, commands) -> dict: position = position(0, 0) dictionary = {position: 0} for command in commands: first_letter = command[0] number = int(command[1:]) i = 0 while i < number: i += 1 if firstLetter == 'U': position = position(position.X, position.Y + 1) if position.X != 0 and position.Y != 0: dictionary[position] = 1 if firstLetter == 'D': position = position(position.X, position.Y - 1) if position.X != 0 and position.Y != 0: dictionary[position] = 1 if firstLetter == 'L': position = position(position.X - 1, position.Y) if position.X != 0 and position.Y != 0: dictionary[position] = 1 if firstLetter == 'R': position = position(position.X + 1, position.Y) if position.X != 0 or position.Y != 0: dictionary[position] = 1 return dictionary def part2(self): with open('C:\\Coding\\AdventOfCode\\AOC2019\\Data\\Data3.txt') as f: lines = f.read().splitlines() first_path = lines[0].split(',') second_path = lines[1].split(',') first_path_coordinates = self.wiresPositionsDictionaryWithTime(firstPath) second_path_coordinates = self.wiresPositionsDictionaryWithTime(secondPath) minimum_time = 9999999999999 for coordinate in firstPathCoordinates: if coordinate in secondPathCoordinates: time = firstPathCoordinates[coordinate] + secondPathCoordinates[coordinate] if 0 < time < minimumTime: minimum_time = time print('Day 3, part 2: ' + str(minimumTime)) def wires_positions_dictionary_with_time(self, commands) -> dict: position = position(0, 0) dictionary = {position: 0} time = 1 for command in commands: first_letter = command[0] number = int(command[1:]) i = 0 while i < number: i += 1 if firstLetter == 'U': position = position(position.X, position.Y + 1) self.addToDictionary(dictionary, position, time) if firstLetter == 'D': position = position(position.X, position.Y - 1) self.addToDictionary(dictionary, position, time) if firstLetter == 'L': position = position(position.X - 1, position.Y) self.addToDictionary(dictionary, position, time) if firstLetter == 'R': position = position(position.X + 1, position.Y) self.addToDictionary(dictionary, position, time) time += 1 return dictionary def add_to_dictionary(self, dictionary, position, time): if (position.X != 0 or position.Y != 0) and position not in dictionary: dictionary[position] = time class Position: x = 0 y = 0 def __init__(self, x, y): self.X = x self.Y = y def __eq__(self, other): return self.X == other.X and self.Y == other.Y def __hash__(self): return hash((self.X, self.Y))
# -------------------------------------- #! /usr/bin/python # File: 283. Move Zeros.py # Author: Kimberly Gao class Solution: def _init_(self,name): self.name = name # My 1st solution: (Run time: 68ms(29.57%)) (2 pointer) # Memory Usage: 15.4 MB (61.79%) def moveZeros1(self, nums): slow = 0 for fast in range(len(nums)): if nums[fast] != 0: nums[slow] = nums[fast] slow += 1 for fast in range (slow, len(nums)): nums[fast] = 0 return nums # My 2nt solution: (Run time: 72ms(28.1%)) (2 pointer) # Memory Usage: 15.5 MB (19.46%) def moveZeros2(self, nums): slow = 0 for fast in range(len(nums)): i = nums[slow] nums[slow] = nums[fast] nums[fast] = i slow += 1 return nums '''For python, can use if num == o: nums.remove(num) nums.append(num) Also consider using: for slow in xrange(len(nums)) ''' if __name__ == '__main__': nums = [0,1,0,3,12] # nums = 0 should be taken into consideration my_solution = Solution().moveZeros1(nums) print(my_solution) better_solution = Solution().moveZeros2(nums) print(better_solution)
class Solution: def _init_(self, name): self.name = name def move_zeros1(self, nums): slow = 0 for fast in range(len(nums)): if nums[fast] != 0: nums[slow] = nums[fast] slow += 1 for fast in range(slow, len(nums)): nums[fast] = 0 return nums def move_zeros2(self, nums): slow = 0 for fast in range(len(nums)): i = nums[slow] nums[slow] = nums[fast] nums[fast] = i slow += 1 return nums 'For python, can use\n if num == o:\n nums.remove(num)\n nums.append(num)\n \n Also consider using:\n for slow in xrange(len(nums))\n ' if __name__ == '__main__': nums = [0, 1, 0, 3, 12] my_solution = solution().moveZeros1(nums) print(my_solution) better_solution = solution().moveZeros2(nums) print(better_solution)
''' Created on Nov 3, 2018 @author: nilson.nieto ''' list_numeros =input("Ingrese varios numeros separados por espacio : ").split(" , ") for i in list_numeros: print(i)
""" Created on Nov 3, 2018 @author: nilson.nieto """ list_numeros = input('Ingrese varios numeros separados por espacio : ').split(' , ') for i in list_numeros: print(i)
def get_fuel(mass): return int(mass / 3) - 2 def get_fuel_including_fuel(mass): total = 0 while True: fuel = get_fuel(mass) if fuel <= 0: break total += fuel mass = fuel return total # Part one with open('input') as f: print(sum( get_fuel( int(line)) # mass for line in f)) # Part two with open('input') as f: print(sum( get_fuel_including_fuel( int(line)) # mass for line in f))
def get_fuel(mass): return int(mass / 3) - 2 def get_fuel_including_fuel(mass): total = 0 while True: fuel = get_fuel(mass) if fuel <= 0: break total += fuel mass = fuel return total with open('input') as f: print(sum((get_fuel(int(line)) for line in f))) with open('input') as f: print(sum((get_fuel_including_fuel(int(line)) for line in f)))
class Manager: def __init__(self): self.worker = None def set_worker(self, worker): assert "Worker" in [el.__name__ for el in worker.__class__.__mro__], "'worker' must be of type Worker" self.worker = worker def manage(self): if self.worker is not None: self.worker.work() class Worker: def work(self): print("I'm working!!") class SuperWorker(Worker): def work(self): print("I work very hard!!!") class LazyWorker(Worker): def work(self): print("I do not work very hard...") class Animal: def feed(self): return "I am eating!" worker = Worker() manager = Manager() manager.set_worker(worker) manager.manage() super_worker = SuperWorker() lazy_worker = LazyWorker() animal = Animal() try: manager.set_worker(super_worker) manager.manage() except AssertionError: print("manager fails to support super_worker....")
class Manager: def __init__(self): self.worker = None def set_worker(self, worker): assert 'Worker' in [el.__name__ for el in worker.__class__.__mro__], "'worker' must be of type Worker" self.worker = worker def manage(self): if self.worker is not None: self.worker.work() class Worker: def work(self): print("I'm working!!") class Superworker(Worker): def work(self): print('I work very hard!!!') class Lazyworker(Worker): def work(self): print('I do not work very hard...') class Animal: def feed(self): return 'I am eating!' worker = worker() manager = manager() manager.set_worker(worker) manager.manage() super_worker = super_worker() lazy_worker = lazy_worker() animal = animal() try: manager.set_worker(super_worker) manager.manage() except AssertionError: print('manager fails to support super_worker....')
N, K = map(int, input().split()) A = [0] total = 0 a = list(map(int, input().split())) ans = 0 m = {0: 1} for x in a: total += x count = m.get(total - K, 0) ans += count m[total] = m.get(total, 0) + 1 A.append(total) print(ans)
(n, k) = map(int, input().split()) a = [0] total = 0 a = list(map(int, input().split())) ans = 0 m = {0: 1} for x in a: total += x count = m.get(total - K, 0) ans += count m[total] = m.get(total, 0) + 1 A.append(total) print(ans)
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: # sliding window, O(N) time, O(1) space globMax = tempMax = sum(nums[:k]) for i in range(k, len(nums)): tempMax += (nums[i] - nums[i-k]) globMax = max(tempMax, globMax) return globMax / k
class Solution: def find_max_average(self, nums: List[int], k: int) -> float: glob_max = temp_max = sum(nums[:k]) for i in range(k, len(nums)): temp_max += nums[i] - nums[i - k] glob_max = max(tempMax, globMax) return globMax / k
#Task 4: Login functionality # In its parameter list, define three parameters: database, username, and password. def login(database, username, password): if username in dict.keys(database) and database[username] == password: print("Welcome back: ", username) elif username in dict.keys(database) or password in dict.values(database): print("Check your credentials again!") else: print("Something went wrong") def register(database, username): if username in dict.values(database): print("Username already registered") else: print("Username successfully registered: ", username) def donate(username): donation_amount = float(input("Enter an amount to donate: ")) donation = f'{username} donated ${donation_amount}' return donation def show_donations(donations): print("\n--- All Donations ---") if not donations: print("There are currently no donations") else: for d in donations: print(d)
def login(database, username, password): if username in dict.keys(database) and database[username] == password: print('Welcome back: ', username) elif username in dict.keys(database) or password in dict.values(database): print('Check your credentials again!') else: print('Something went wrong') def register(database, username): if username in dict.values(database): print('Username already registered') else: print('Username successfully registered: ', username) def donate(username): donation_amount = float(input('Enter an amount to donate: ')) donation = f'{username} donated ${donation_amount}' return donation def show_donations(donations): print('\n--- All Donations ---') if not donations: print('There are currently no donations') else: for d in donations: print(d)
H, W = map(int, input().split()) N = 0 a_map = [] for i in range(H): a = list(map(int, input().split())) a_map.append(a) result = [] for i in range(H): for j in range(W): if a_map[i][j]%2==1: if j < W - 1: N += 1 result.append([i + 1, j + 1, i + 1, j + 2]) a_map[i][j + 1] += 1; a_map[i][j] -= 1; elif i < H - 1: N += 1; result.append([i + 1, j + 1, i + 2, j + 1]) a_map[i][j] -= 1; a_map[i + 1][j] += 1; print(N) for a in result: print(a[0], a[1], a[2], a[3])
(h, w) = map(int, input().split()) n = 0 a_map = [] for i in range(H): a = list(map(int, input().split())) a_map.append(a) result = [] for i in range(H): for j in range(W): if a_map[i][j] % 2 == 1: if j < W - 1: n += 1 result.append([i + 1, j + 1, i + 1, j + 2]) a_map[i][j + 1] += 1 a_map[i][j] -= 1 elif i < H - 1: n += 1 result.append([i + 1, j + 1, i + 2, j + 1]) a_map[i][j] -= 1 a_map[i + 1][j] += 1 print(N) for a in result: print(a[0], a[1], a[2], a[3])
class Stairs: def designs(self, maxHeight, minWidth, totalHeight, totalWidth): c = 0 for r in xrange(1, maxHeight + 1): if totalHeight % r == 0: n = totalHeight / r if ( n > 1 and totalWidth % (n - 1) == 0 and totalWidth / (n - 1) >= minWidth ): c += 1 return c
class Stairs: def designs(self, maxHeight, minWidth, totalHeight, totalWidth): c = 0 for r in xrange(1, maxHeight + 1): if totalHeight % r == 0: n = totalHeight / r if n > 1 and totalWidth % (n - 1) == 0 and (totalWidth / (n - 1) >= minWidth): c += 1 return c
length = int(raw_input()) s = raw_input() n = length / 4 A = T = G = C = 0 for i in s: if i == 'A': A += 1 elif i == 'T': T += 1 elif i == 'G': G += 1 else: C += 1 res = 0 if A != n or C != n or G != n or T != n: res = length l = 0 for r in xrange(length): if s[r] == 'A': A -= 1 if s[r] == 'T': T -= 1 if s[r] == 'G': G -= 1 if s[r] == 'C': C -= 1 while A <= n and C <= n and G <= n and T <= n and l <= r: res = min(res, r - l + 1) if s[l] == 'A': A += 1 if s[l] == 'T': T += 1 if s[l] == 'G': G += 1 if s[l] == 'C': C += 1 l += 1 print(res)
length = int(raw_input()) s = raw_input() n = length / 4 a = t = g = c = 0 for i in s: if i == 'A': a += 1 elif i == 'T': t += 1 elif i == 'G': g += 1 else: c += 1 res = 0 if A != n or C != n or G != n or (T != n): res = length l = 0 for r in xrange(length): if s[r] == 'A': a -= 1 if s[r] == 'T': t -= 1 if s[r] == 'G': g -= 1 if s[r] == 'C': c -= 1 while A <= n and C <= n and (G <= n) and (T <= n) and (l <= r): res = min(res, r - l + 1) if s[l] == 'A': a += 1 if s[l] == 'T': t += 1 if s[l] == 'G': g += 1 if s[l] == 'C': c += 1 l += 1 print(res)
class JellyBean: def __init__( self, mass = 0 ): self.mass = mass def __add__( self, other ): other_mass = other.mass other.mass = 0 return JellyBean( self.mass + other_mass ) def __sub__( self, other ): self_mass = self.mass self.mass -= other.mass def __str__( self ): return f"Mass: { self.mass }" def __repr__( self ): return f"{ self.__dict__ }" jelly = JellyBean( 3 ) bean = JellyBean( 2 ) jelly += bean print( jelly ) print( bean )
class Jellybean: def __init__(self, mass=0): self.mass = mass def __add__(self, other): other_mass = other.mass other.mass = 0 return jelly_bean(self.mass + other_mass) def __sub__(self, other): self_mass = self.mass self.mass -= other.mass def __str__(self): return f'Mass: {self.mass}' def __repr__(self): return f'{self.__dict__}' jelly = jelly_bean(3) bean = jelly_bean(2) jelly += bean print(jelly) print(bean)
class PlayerAlreadyHasItemError(Exception): pass class PlayerNotInitializedError(Exception): pass
class Playeralreadyhasitemerror(Exception): pass class Playernotinitializederror(Exception): pass
# Preferences defaults PREFERENCES_PATH = "./config/preferences.json" PREFERENCES_DEFAULTS = { 'on_time': 1200, 'off_time': 300 } # Bot configureation DISCORD_TOKEN = "from https://discord.com/developers" ADMIN_ID = 420 USER_ID = 999 DEV_MODE = True PREFIX = '!!' PREFIXES = ('johnsmith ', 'john smith ') COGS_LIST = ['cogs.misc', 'cogs.testing', 'cogs.admin']
preferences_path = './config/preferences.json' preferences_defaults = {'on_time': 1200, 'off_time': 300} discord_token = 'from https://discord.com/developers' admin_id = 420 user_id = 999 dev_mode = True prefix = '!!' prefixes = ('johnsmith ', 'john smith ') cogs_list = ['cogs.misc', 'cogs.testing', 'cogs.admin']
# has_good_credit = True # has_criminal_record = True # # if has_good_credit and not has_criminal_record: # print("Eligible for loan") # temperature = 35 # # if temperature > 30: # print("It's a hot day") # else: # print("It's not a hot day") name = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" if len(name) < 3: print("Name must be at least 3 characters long") elif len(name) > 50: print("Name cannot be more than 50 characters long") else: print("Name looks good!")
name = 'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd' if len(name) < 3: print('Name must be at least 3 characters long') elif len(name) > 50: print('Name cannot be more than 50 characters long') else: print('Name looks good!')
x = '' while True: x = input() print(x) if x == 'end': break print('end')
x = '' while True: x = input() print(x) if x == 'end': break print('end')
# -*- coding: utf-8 -*- def main(): s = sorted([input() for _ in range(15)]) print(s[6]) if __name__ == '__main__': main()
def main(): s = sorted([input() for _ in range(15)]) print(s[6]) if __name__ == '__main__': main()
# Perulangan pada set dan dictionary print('\n==========Perulangan Pada Set==========') set_integer = {10, 20, 30, 40, 50} # Cara pertama for item in set_integer: print(item, end=' ') print('') # Cara kedua for i in range(len(set_integer)): print(list(set_integer)[i], end=' ') print('') # Cara ketiga i = 0 while i < len(set_integer): print(list(set_integer)[i], end=' ') i = i + 1 print('\n\n==========Perulangan Pada Dictionary==========') # Menambah item dictionary_kosong = {} list_string = ['aku', 'sedang', 'belajar', 'python'] for i in range(len(list_string)): dictionary_kosong[i] = list_string[i] # dictionary_kosong.update({i:list_string[i]}) print(dictionary_kosong) # Menampilkan item dictionary_hari = {1:'Senin', 2:'Selasa', 3:'Rabu', 4:'Kamis', 5:'Jumat', 6:'Sabtu', 7:'Minggu'} # Cara pertama for key in dictionary_hari.keys(): print(key, end=' ' ) print('') for value in dictionary_hari.values(): print(value, end=' ') print('') # Cara kedua for key, value in dictionary_hari.items(): print(key, value, end=' ') print('') # Cara ketiga i = 0 while i < len(dictionary_hari): key = list(dictionary_hari.keys()) print(key[i], dictionary_hari[key[i]], end=' ') i = i + 1
print('\n==========Perulangan Pada Set==========') set_integer = {10, 20, 30, 40, 50} for item in set_integer: print(item, end=' ') print('') for i in range(len(set_integer)): print(list(set_integer)[i], end=' ') print('') i = 0 while i < len(set_integer): print(list(set_integer)[i], end=' ') i = i + 1 print('\n\n==========Perulangan Pada Dictionary==========') dictionary_kosong = {} list_string = ['aku', 'sedang', 'belajar', 'python'] for i in range(len(list_string)): dictionary_kosong[i] = list_string[i] print(dictionary_kosong) dictionary_hari = {1: 'Senin', 2: 'Selasa', 3: 'Rabu', 4: 'Kamis', 5: 'Jumat', 6: 'Sabtu', 7: 'Minggu'} for key in dictionary_hari.keys(): print(key, end=' ') print('') for value in dictionary_hari.values(): print(value, end=' ') print('') for (key, value) in dictionary_hari.items(): print(key, value, end=' ') print('') i = 0 while i < len(dictionary_hari): key = list(dictionary_hari.keys()) print(key[i], dictionary_hari[key[i]], end=' ') i = i + 1
def word_time(word, elapsed_time): return [word, elapsed_time] p0 = [word_time('START', 0), word_time('What', 0.2), word_time('great', 0.4), word_time('luck', 0.8)] p1 = [word_time('START', 0), word_time('What', 0.6), word_time('great', 0.8), word_time('luck', 1.19)] p0 p1
def word_time(word, elapsed_time): return [word, elapsed_time] p0 = [word_time('START', 0), word_time('What', 0.2), word_time('great', 0.4), word_time('luck', 0.8)] p1 = [word_time('START', 0), word_time('What', 0.6), word_time('great', 0.8), word_time('luck', 1.19)] p0 p1
# Definition for singly-linked list. # class LinkedListNode: # def __init__(self, value = 0, next = None): # self.value = value # self.next = next class Solution: def containsCycle(self, head): if not head or not head.next: return False current = head s = set() while current: if id(current) in s: return True s.add(id(current)) current = current.next return False
class Solution: def contains_cycle(self, head): if not head or not head.next: return False current = head s = set() while current: if id(current) in s: return True s.add(id(current)) current = current.next return False
def inf(): while True: yield for _ in inf(): input('>')
def inf(): while True: yield for _ in inf(): input('>')
def grep(pattern): print("Searching for", pattern) while True: line = (yield) if pattern in line: print(line) search = grep('coroutine') next(search) search.send("I love you") search.send("Don't you love me") search.send("I love coroutines")
def grep(pattern): print('Searching for', pattern) while True: line = (yield) if pattern in line: print(line) search = grep('coroutine') next(search) search.send('I love you') search.send("Don't you love me") search.send('I love coroutines')
def conf(): return { "id":"discord", "description":"this is the discord c360 component", "enabled":False, }
def conf(): return {'id': 'discord', 'description': 'this is the discord c360 component', 'enabled': False}
S = input() l = len(S) nhug = 0 for i in range(l//2): if S[i] != S[l-1-i]: nhug += 1 print(nhug)
s = input() l = len(S) nhug = 0 for i in range(l // 2): if S[i] != S[l - 1 - i]: nhug += 1 print(nhug)
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print("Hi there! I'm {}, {} years old!".format(self.name, self.age)) maria = Person("Maria Popova", 25) pesho = Person("Pesho", 27) print(maria) # name = Maria Popova # age = 25
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print("Hi there! I'm {}, {} years old!".format(self.name, self.age)) maria = person('Maria Popova', 25) pesho = person('Pesho', 27) print(maria)
class Solution: def maxNumber(self, nums1, nums2, k): def merge(arr1, arr2): res, i, j = [], 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i:] >= arr2[j:]: res.append(arr1[i]) i += 1 else: res.append(arr2[j]) j += 1 if i < len(arr1): res += arr1[i:] elif j < len(arr2): res += arr2[j:] return res def makeArr(arr, l): i, res = 0, [] for r in range(l - 1, -1, -1): num, i = max(arr[i:-r] or arr[i:]) i = -i + 1 res.append(num) return res nums1, nums2, choices = [(num, -i) for i, num in enumerate(nums1)], [(num, -i) for i, num in enumerate(nums2)], [] for m in range(k + 1): if m > len(nums1) or k - m > len(nums2): continue arr1, arr2 = makeArr(nums1, m), makeArr(nums2, k - m) choices.append(merge(arr1, arr2)) return max(choices)
class Solution: def max_number(self, nums1, nums2, k): def merge(arr1, arr2): (res, i, j) = ([], 0, 0) while i < len(arr1) and j < len(arr2): if arr1[i:] >= arr2[j:]: res.append(arr1[i]) i += 1 else: res.append(arr2[j]) j += 1 if i < len(arr1): res += arr1[i:] elif j < len(arr2): res += arr2[j:] return res def make_arr(arr, l): (i, res) = (0, []) for r in range(l - 1, -1, -1): (num, i) = max(arr[i:-r] or arr[i:]) i = -i + 1 res.append(num) return res (nums1, nums2, choices) = ([(num, -i) for (i, num) in enumerate(nums1)], [(num, -i) for (i, num) in enumerate(nums2)], []) for m in range(k + 1): if m > len(nums1) or k - m > len(nums2): continue (arr1, arr2) = (make_arr(nums1, m), make_arr(nums2, k - m)) choices.append(merge(arr1, arr2)) return max(choices)
def sudoku2(grid): seen = set() # Iterate through grid for i in range(len(grid)): for j in range(len(grid[i])): current_value = grid[i][j] if current_value != ".": if ( (current_value + " found in row " + str(i)) in seen or (current_value + " found in column " + str(j)) in seen or ( current_value + " found in subgrid " + str(i // 3) + "-" + str(j // 3) ) in seen ): return False seen.add(current_value + " found in row " + str(i)) seen.add(current_value + " found in column " + str(j)) seen.add( current_value + " found in subgrid " + str(i // 3) + "-" + str(j // 3) ) return True
def sudoku2(grid): seen = set() for i in range(len(grid)): for j in range(len(grid[i])): current_value = grid[i][j] if current_value != '.': if current_value + ' found in row ' + str(i) in seen or current_value + ' found in column ' + str(j) in seen or current_value + ' found in subgrid ' + str(i // 3) + '-' + str(j // 3) in seen: return False seen.add(current_value + ' found in row ' + str(i)) seen.add(current_value + ' found in column ' + str(j)) seen.add(current_value + ' found in subgrid ' + str(i // 3) + '-' + str(j // 3)) return True
FEATURES = 'FEATURES' AUTH_GITHUB = 'AUTH_GITHUB' AUTH_GITLAB = 'AUTH_GITLAB' AUTH_BITBUCKET = 'AUTH_BITBUCKET' AUTH_AZURE = 'AUTH_AZURE' AFFINITIES = 'AFFINITIES' ARCHIVES_ROOT = 'ARCHIVES_ROOT' DOWNLOADS_ROOT = 'DOWNLOADS_ROOT' ADMIN = 'ADMIN' NODE_SELECTORS = 'NODE_SELECTORS' TOLERATIONS = 'TOLERATIONS' ANNOTATIONS = 'ANNOTATIONS' K8S_SECRETS = 'K8S_SECRETS' K8S_CONFIG_MAPS = 'K8S_CONFIG_MAPS' K8S_RESOURCES = 'K8S_RESOURCES' ENV_VARS = 'ENV_VARS' NOTEBOOKS = 'NOTEBOOKS' TENSORBOARDS = 'TENSORBOARDS' GROUPS = 'GROUPS' BUILD_JOBS = 'BUILD_JOBS' KANIKO = 'KANIKO' SCHEDULER = 'SCHEDULER' STATS = 'STATS' EMAIL = 'EMAIL' CONTAINER_NAME = 'CONTAINER_NAME' MAX_RESTARTS = 'MAX_RESTARTS' INTEGRATIONS_WEBHOOKS = 'INTEGRATIONS_WEBHOOKS' TTL = 'TTL' REPOS = 'REPOS' SIDECARS = 'SIDECARS' INIT = 'INIT' K8S = 'K8S' CLEANING_INTERVALS = 'CLEANING_INTERVALS' POLYFLOW = 'POLYFLOW' SERVICE_ACCOUNTS = 'SERVICE_ACCOUNTS' ACCESS = 'ACCESS'
features = 'FEATURES' auth_github = 'AUTH_GITHUB' auth_gitlab = 'AUTH_GITLAB' auth_bitbucket = 'AUTH_BITBUCKET' auth_azure = 'AUTH_AZURE' affinities = 'AFFINITIES' archives_root = 'ARCHIVES_ROOT' downloads_root = 'DOWNLOADS_ROOT' admin = 'ADMIN' node_selectors = 'NODE_SELECTORS' tolerations = 'TOLERATIONS' annotations = 'ANNOTATIONS' k8_s_secrets = 'K8S_SECRETS' k8_s_config_maps = 'K8S_CONFIG_MAPS' k8_s_resources = 'K8S_RESOURCES' env_vars = 'ENV_VARS' notebooks = 'NOTEBOOKS' tensorboards = 'TENSORBOARDS' groups = 'GROUPS' build_jobs = 'BUILD_JOBS' kaniko = 'KANIKO' scheduler = 'SCHEDULER' stats = 'STATS' email = 'EMAIL' container_name = 'CONTAINER_NAME' max_restarts = 'MAX_RESTARTS' integrations_webhooks = 'INTEGRATIONS_WEBHOOKS' ttl = 'TTL' repos = 'REPOS' sidecars = 'SIDECARS' init = 'INIT' k8_s = 'K8S' cleaning_intervals = 'CLEANING_INTERVALS' polyflow = 'POLYFLOW' service_accounts = 'SERVICE_ACCOUNTS' access = 'ACCESS'
# Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or . She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game. # For each game, Emma will get an array of clouds numbered if they are safe or if they must be avoided. For example, indexed from . The number on each cloud is its index in the list so she must avoid the clouds at indexes and . She could follow the following two paths: or . The first path takes jumps while the second takes . # Function Description # Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer. # jumpingOnClouds has the following parameter(s): # c: an array of binary integers # Input Format # The first line contains an integer , the total number of clouds. The second line contains space-separated binary integers describing clouds where . # Constraints # Output Format # Print the minimum number of jumps needed to win the game. # Sample Input 0 # 7 # 0 0 1 0 0 1 0 # Sample Output 0 # 4 # Explanation 0: # Emma must avoid and . She can win the game with a minimum of jumps: def jumpingOnClouds(c): if len(c) == 1: return 0 if len(c) == 2: return 0 if c[1] == 1 else 1 if c[2] == 1: return 1 + jumpingOnClouds(c[1:]) if c[2] == 0: return 1 + jumpingOnClouds(c[2:]) print(jumpingOnClouds([0, 0, 0, 0, 1, 0])) array = [0, 0, 0, 0, 1, 0] print(array[1:])
def jumping_on_clouds(c): if len(c) == 1: return 0 if len(c) == 2: return 0 if c[1] == 1 else 1 if c[2] == 1: return 1 + jumping_on_clouds(c[1:]) if c[2] == 0: return 1 + jumping_on_clouds(c[2:]) print(jumping_on_clouds([0, 0, 0, 0, 1, 0])) array = [0, 0, 0, 0, 1, 0] print(array[1:])