content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# HEAD # Destructing or Multiple Assignment Operators # DESCRIPTION # Describe incorrect usage of # multiple assignation which throws error # RESOURCES # # The number of items in the destructuring # have to be the same as variables used for assignation cat = ['fat', 'orange', 'loud'] # Will give an error since size is different size, color, disposition, name = cat # ERROR DETAILS - # Traceback (most recent call last): # File "<pyshell#84>", line 1, in <module> # size, color, disposition, name = cat # ValueError: need more than 3 values to unpack
cat = ['fat', 'orange', 'loud'] (size, color, disposition, name) = cat
pkg_dnf = { 'bind-utils': {}, 'bzip2': {}, 'coreutils': {}, 'curl': {}, 'diffutils': {}, 'file': {}, 'gcc': {}, 'gcc-c++': {}, 'git': {}, 'grep': {}, 'gzip': {}, 'hexedit': {}, 'hostname': {}, 'iotop': {}, 'iputils': {}, 'less': {}, 'lsof': {}, 'lynx': {}, 'man-db': {}, 'mlocate': {}, 'ncdu': {}, 'net-tools': {}, 'nmap': {}, 'nmap-ncat': {}, 'openssl': {}, 'p7zip': {}, 'p7zip-plugins': {}, 'patch': {}, 'pciutils': {}, 'psmisc': {}, 'redhat-rpm-config': {}, 'rsync': {}, 'screen': {}, 'sysstat': {}, 'tar': {}, 'tcpdump': {}, 'telnet': {}, 'traceroute': {}, 'tree': {}, 'unzip': {}, 'usbutils': {}, 'util-linux': {}, 'util-linux-user': {}, 'wget': {}, 'whois': {}, 'xz': {}, }
pkg_dnf = {'bind-utils': {}, 'bzip2': {}, 'coreutils': {}, 'curl': {}, 'diffutils': {}, 'file': {}, 'gcc': {}, 'gcc-c++': {}, 'git': {}, 'grep': {}, 'gzip': {}, 'hexedit': {}, 'hostname': {}, 'iotop': {}, 'iputils': {}, 'less': {}, 'lsof': {}, 'lynx': {}, 'man-db': {}, 'mlocate': {}, 'ncdu': {}, 'net-tools': {}, 'nmap': {}, 'nmap-ncat': {}, 'openssl': {}, 'p7zip': {}, 'p7zip-plugins': {}, 'patch': {}, 'pciutils': {}, 'psmisc': {}, 'redhat-rpm-config': {}, 'rsync': {}, 'screen': {}, 'sysstat': {}, 'tar': {}, 'tcpdump': {}, 'telnet': {}, 'traceroute': {}, 'tree': {}, 'unzip': {}, 'usbutils': {}, 'util-linux': {}, 'util-linux-user': {}, 'wget': {}, 'whois': {}, 'xz': {}}
"""NVX Impedance data.""" class Impedance: """Impedance holds impedance data from all EEG channels, as well as GND.""" _INVALID = 2147483647 # INT_MAX (assuming int is 4 bytes) """Invalid (not connected) impedance value.""" def __init__(self, raw_data, count_eeg): self.raw_data = raw_data self.count_eeg = count_eeg def channel(self, index): """Get impedance from a channel. Parameters ---------- index : int Raises ------ ValueError If index is not in range [0, count_eeg). Returns ------- int or None Impedance data, or None if the electrode is not connected. """ if index >= self.count_eeg: raise ValueError( "no channel with index " + str(index) + " (only " + str(self.count_eeg) + " channels present)") result = self.raw_data[index] if result == Impedance._INVALID: return None return result def ground(self): """Get impedance from GND. Returns ------- int or None Impedance data, or None if the electrode is not connected. """ result = self.raw_data[self.count_eeg] if result == Impedance._INVALID: return None return result
"""NVX Impedance data.""" class Impedance: """Impedance holds impedance data from all EEG channels, as well as GND.""" _invalid = 2147483647 'Invalid (not connected) impedance value.' def __init__(self, raw_data, count_eeg): self.raw_data = raw_data self.count_eeg = count_eeg def channel(self, index): """Get impedance from a channel. Parameters ---------- index : int Raises ------ ValueError If index is not in range [0, count_eeg). Returns ------- int or None Impedance data, or None if the electrode is not connected. """ if index >= self.count_eeg: raise value_error('no channel with index ' + str(index) + ' (only ' + str(self.count_eeg) + ' channels present)') result = self.raw_data[index] if result == Impedance._INVALID: return None return result def ground(self): """Get impedance from GND. Returns ------- int or None Impedance data, or None if the electrode is not connected. """ result = self.raw_data[self.count_eeg] if result == Impedance._INVALID: return None return result
# A - Set Lot Charge, Piece Price, Added Lead Time variables lot_charge = var('Lot Charge', 0, 'Lot charge for outside_service service', currency) piece_price = var('Piece Price', 0, 'Price per unit for the outside_service service', currency) added_lead_time = var('Added Lead Time', 0, 'Days of added lead time for outside_service service', number) # B - Define Extended Price extended_price = part.qty * piece_price # C - Compile costs if extended_price < lot_charge: # If the part quantity * piece price is less than the lot charge, then use the lot charge. PRICE = lot_charge else: # Otherwise, use the quantity * piece price. PRICE = extended_price # D - Define how many days this operation will contribute to the project lead time. DAYS = added_lead_time
lot_charge = var('Lot Charge', 0, 'Lot charge for outside_service service', currency) piece_price = var('Piece Price', 0, 'Price per unit for the outside_service service', currency) added_lead_time = var('Added Lead Time', 0, 'Days of added lead time for outside_service service', number) extended_price = part.qty * piece_price if extended_price < lot_charge: price = lot_charge else: price = extended_price days = added_lead_time
# # PySNMP MIB module ZHONE-GEN-VOICESTAT (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-GEN-VOICESTAT # Produced by pysmi-0.3.4 at Wed May 1 15:47:39 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) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") ObjectIdentity, Bits, Integer32, Counter64, IpAddress, mib_2, NotificationType, Counter32, ModuleIdentity, TimeTicks, Gauge32, Unsigned32, MibIdentifier, iso, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "Bits", "Integer32", "Counter64", "IpAddress", "mib-2", "NotificationType", "Counter32", "ModuleIdentity", "TimeTicks", "Gauge32", "Unsigned32", "MibIdentifier", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") zhoneSlotIndex, zhoneShelfIndex, zhoneGeneric = mibBuilder.importSymbols("Zhone", "zhoneSlotIndex", "zhoneShelfIndex", "zhoneGeneric") ZhoneRowStatus, = mibBuilder.importSymbols("Zhone-TC", "ZhoneRowStatus") zhoneVoiceStatsRecords = ModuleIdentity((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1)) zhoneVoiceStatsRecords.setRevisions(('2005-09-06 15:30', '2003-06-27 12:18',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: zhoneVoiceStatsRecords.setRevisionsDescriptions(('Add zhoneVoiceRingTable', 'V01.00.00 - Initial version',)) if mibBuilder.loadTexts: zhoneVoiceStatsRecords.setLastUpdated('200306271737Z') if mibBuilder.loadTexts: zhoneVoiceStatsRecords.setOrganization('Zhone Technologies, Inc.') if mibBuilder.loadTexts: zhoneVoiceStatsRecords.setContactInfo('Postal: Zhone Technologies, Inc. @ Zhone Way 7001 Oakport Street Oakland, CA 94621 USA Toll-Free: +1 877-ZHONE20 (+1 877-946-6320) Tel: +1-510-777-7000 Fax: +1-510-777-7001 E-mail: support@zhone.com') if mibBuilder.loadTexts: zhoneVoiceStatsRecords.setDescription('The MIB module to describe objects for voice call statistics. This MIB record contains tables that define voice calls statistics at the system, card, and subscriber end-point level for incoming, outgoing, and active calls. ') zhoneVoiceStats = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 3, 11)) if mibBuilder.loadTexts: zhoneVoiceStats.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceStats.setDescription('Voice Call Statistics. This Object contains all instances associated with voice calls statistics. In revision 0, Completed, Blocked, and Active calls Statistics are implemented for System, card, and subscriber end-points. ') zhoneSystemStats = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1)) if mibBuilder.loadTexts: zhoneSystemStats.setStatus('current') if mibBuilder.loadTexts: zhoneSystemStats.setDescription('The System voice statistics object is used to collect voice statistics at a system-wide level. These include statistics for incoming, outgoing, and active calls. The entry in this object is referenced using a static index of zero. ') systemIncomingCallsCompleted = MibScalar((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: systemIncomingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: systemIncomingCallsCompleted.setDescription('The number of completed incoming calls in the system.') systemIncomingCallsBlocked = MibScalar((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: systemIncomingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: systemIncomingCallsBlocked.setDescription('The number of blocked incoming calls in the system.') systemOutgoingCallsCompleted = MibScalar((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: systemOutgoingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: systemOutgoingCallsCompleted.setDescription('The number of completed outgoing calls in the system.') systemOutgoingCallsBlocked = MibScalar((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: systemOutgoingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: systemOutgoingCallsBlocked.setDescription('The number of blocked outgoing calls in the system.') systemActiveCalls = MibScalar((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: systemActiveCalls.setStatus('current') if mibBuilder.loadTexts: systemActiveCalls.setDescription('The number of currently active calls in the system.') zhoneCardStatsTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2), ) if mibBuilder.loadTexts: zhoneCardStatsTable.setStatus('current') if mibBuilder.loadTexts: zhoneCardStatsTable.setDescription('The card voice statistics table is used to collect voice calls statistics on any card configured to carry voice traffic. Statistics are currently supported for cards with AAL2, GR303, V52 and POTS subscribers. This table collects statistics for incoming calls, outgoing calls, and active calls. The entry in this table is referenced using shelf/slot indices. ') zhoneCardStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1), ).setIndexNames((0, "Zhone", "zhoneShelfIndex"), (0, "Zhone", "zhoneSlotIndex")) if mibBuilder.loadTexts: zhoneCardStatsEntry.setStatus('current') if mibBuilder.loadTexts: zhoneCardStatsEntry.setDescription('An entry in the zhoneCardStatsTable') cardIncomingCallsCompleted = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardIncomingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: cardIncomingCallsCompleted.setDescription('The number of completed incoming calls on the card.') cardIncomingCallsBlocked = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardIncomingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: cardIncomingCallsBlocked.setDescription('The number of blocked incoming calls on the card.') cardOutgoingCallsCompleted = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardOutgoingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: cardOutgoingCallsCompleted.setDescription('The number of completed outgoing calls on the card.') cardOutgoingCallsBlocked = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardOutgoingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: cardOutgoingCallsBlocked.setDescription('The number of blocked outgoing calls on the card.') cardActiveCalls = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardActiveCalls.setStatus('current') if mibBuilder.loadTexts: cardActiveCalls.setDescription('The number of currently active calls on the card.') zhoneSubscriberEPStatsTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3), ) if mibBuilder.loadTexts: zhoneSubscriberEPStatsTable.setStatus('current') if mibBuilder.loadTexts: zhoneSubscriberEPStatsTable.setDescription('The subscriber voice end-point statistics table is used to collect incoming, outgoing, and active voice calls statistics for any subscriber end point.The entry in this table is referenced using end-point index. ') zhoneSubscriberEPStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1), ).setIndexNames((0, "ZHONE-GEN-VOICESTAT", "subVoiceEndPointIndex")) if mibBuilder.loadTexts: zhoneSubscriberEPStatsEntry.setStatus('current') if mibBuilder.loadTexts: zhoneSubscriberEPStatsEntry.setDescription('An entry in the zhoneSubscriberEPStatsTable') subVoiceEndPointIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: subVoiceEndPointIndex.setStatus('current') if mibBuilder.loadTexts: subVoiceEndPointIndex.setDescription('This index is equal to the end-point indices defined for the subscriber voice end-point tables in the zhoneSubscriberRecords. These end-points include AAL2, GR303, V52, POTS, etc. For all the end point types, the end-point index is unique to the sytem. ') subEPIncomingCallsCompleted = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: subEPIncomingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: subEPIncomingCallsCompleted.setDescription('The number of completed incoming calls at the subscriber voice end point.') subEPIncomingCallsBlocked = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: subEPIncomingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: subEPIncomingCallsBlocked.setDescription('The number of blocked incoming calls at the subscriber voice end point.') subEPOutgoingCallsCompleted = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: subEPOutgoingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: subEPOutgoingCallsCompleted.setDescription('The number of completed outgoing calls at the subscriber voice end point.') subEPOutgoingCallsBlocked = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: subEPOutgoingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: subEPOutgoingCallsBlocked.setDescription('The number of blocked outgoing calls at the subscriber voice end point.') subEPActiveCalls = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: subEPActiveCalls.setStatus('current') if mibBuilder.loadTexts: subEPActiveCalls.setDescription('The number of currently active calls at the subscriber voice end point.') zhoneVoiceStatsObjectsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 7)).setObjects(("ZHONE-GEN-VOICESTAT", "systemIncomingCallsCompleted"), ("ZHONE-GEN-VOICESTAT", "systemIncomingCallsBlocked"), ("ZHONE-GEN-VOICESTAT", "systemOutgoingCallsCompleted"), ("ZHONE-GEN-VOICESTAT", "systemOutgoingCallsBlocked"), ("ZHONE-GEN-VOICESTAT", "systemActiveCalls"), ("ZHONE-GEN-VOICESTAT", "cardIncomingCallsCompleted"), ("ZHONE-GEN-VOICESTAT", "cardIncomingCallsBlocked"), ("ZHONE-GEN-VOICESTAT", "cardOutgoingCallsCompleted"), ("ZHONE-GEN-VOICESTAT", "cardOutgoingCallsBlocked"), ("ZHONE-GEN-VOICESTAT", "cardActiveCalls"), ("ZHONE-GEN-VOICESTAT", "subEPIncomingCallsCompleted"), ("ZHONE-GEN-VOICESTAT", "subEPIncomingCallsBlocked"), ("ZHONE-GEN-VOICESTAT", "subEPOutgoingCallsCompleted"), ("ZHONE-GEN-VOICESTAT", "subEPOutgoingCallsBlocked"), ("ZHONE-GEN-VOICESTAT", "subEPActiveCalls")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): zhoneVoiceStatsObjectsGroup = zhoneVoiceStatsObjectsGroup.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceStatsObjectsGroup.setDescription('This group contains objects associated with voice statistics.') zhoneVoiceRingTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8), ) if mibBuilder.loadTexts: zhoneVoiceRingTable.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingTable.setDescription('Table used to generate ring on a port.') zhoneVoiceRingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8, 1), ).setIndexNames((0, "ZHONE-GEN-VOICESTAT", "zhoneVoiceRingIfIndex")) if mibBuilder.loadTexts: zhoneVoiceRingEntry.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingEntry.setDescription('Row in the zhoneVoiceRing table - corresponds to a port on which ring can be generated. ') zhoneVoiceRingIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: zhoneVoiceRingIfIndex.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingIfIndex.setDescription('physical interface') zhoneVoiceRingRingingCadence = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("ringCadenceR0", 1), ("ringCadenceR1", 2), ("ringCadenceR2", 3), ("ringCadenceR3", 4), ("ringCadenceR4", 5), ("ringCadenceR5", 6), ("ringCadenceR6", 7), ("ringCadenceR7", 8), ("ringCadenceCommon", 9), ("ringCadenceSplash", 10)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoiceRingRingingCadence.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingRingingCadence.setDescription('Ringing cadence to use in test.') zhoneVoiceRingTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 999))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoiceRingTimer.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingTimer.setDescription('Time in seconds to continue ringing.') zhoneVoiceRingRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8, 1, 4), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoiceRingRowStatus.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingRowStatus.setDescription('Row status.') mibBuilder.exportSymbols("ZHONE-GEN-VOICESTAT", subEPOutgoingCallsCompleted=subEPOutgoingCallsCompleted, cardIncomingCallsCompleted=cardIncomingCallsCompleted, subEPIncomingCallsCompleted=subEPIncomingCallsCompleted, zhoneSubscriberEPStatsEntry=zhoneSubscriberEPStatsEntry, zhoneVoiceRingIfIndex=zhoneVoiceRingIfIndex, zhoneVoiceStats=zhoneVoiceStats, zhoneCardStatsEntry=zhoneCardStatsEntry, zhoneSystemStats=zhoneSystemStats, zhoneSubscriberEPStatsTable=zhoneSubscriberEPStatsTable, zhoneVoiceRingTimer=zhoneVoiceRingTimer, cardIncomingCallsBlocked=cardIncomingCallsBlocked, cardActiveCalls=cardActiveCalls, subVoiceEndPointIndex=subVoiceEndPointIndex, cardOutgoingCallsBlocked=cardOutgoingCallsBlocked, PYSNMP_MODULE_ID=zhoneVoiceStatsRecords, subEPOutgoingCallsBlocked=subEPOutgoingCallsBlocked, zhoneVoiceStatsRecords=zhoneVoiceStatsRecords, zhoneVoiceRingTable=zhoneVoiceRingTable, subEPActiveCalls=subEPActiveCalls, zhoneVoiceRingEntry=zhoneVoiceRingEntry, zhoneVoiceRingRingingCadence=zhoneVoiceRingRingingCadence, systemOutgoingCallsBlocked=systemOutgoingCallsBlocked, cardOutgoingCallsCompleted=cardOutgoingCallsCompleted, systemOutgoingCallsCompleted=systemOutgoingCallsCompleted, systemIncomingCallsCompleted=systemIncomingCallsCompleted, systemIncomingCallsBlocked=systemIncomingCallsBlocked, zhoneVoiceStatsObjectsGroup=zhoneVoiceStatsObjectsGroup, subEPIncomingCallsBlocked=subEPIncomingCallsBlocked, systemActiveCalls=systemActiveCalls, zhoneCardStatsTable=zhoneCardStatsTable, zhoneVoiceRingRowStatus=zhoneVoiceRingRowStatus)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection') (interface_index,) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex') (notification_group, object_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ObjectGroup', 'ModuleCompliance') (object_identity, bits, integer32, counter64, ip_address, mib_2, notification_type, counter32, module_identity, time_ticks, gauge32, unsigned32, mib_identifier, iso, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'Bits', 'Integer32', 'Counter64', 'IpAddress', 'mib-2', 'NotificationType', 'Counter32', 'ModuleIdentity', 'TimeTicks', 'Gauge32', 'Unsigned32', 'MibIdentifier', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') (zhone_slot_index, zhone_shelf_index, zhone_generic) = mibBuilder.importSymbols('Zhone', 'zhoneSlotIndex', 'zhoneShelfIndex', 'zhoneGeneric') (zhone_row_status,) = mibBuilder.importSymbols('Zhone-TC', 'ZhoneRowStatus') zhone_voice_stats_records = module_identity((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1)) zhoneVoiceStatsRecords.setRevisions(('2005-09-06 15:30', '2003-06-27 12:18')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: zhoneVoiceStatsRecords.setRevisionsDescriptions(('Add zhoneVoiceRingTable', 'V01.00.00 - Initial version')) if mibBuilder.loadTexts: zhoneVoiceStatsRecords.setLastUpdated('200306271737Z') if mibBuilder.loadTexts: zhoneVoiceStatsRecords.setOrganization('Zhone Technologies, Inc.') if mibBuilder.loadTexts: zhoneVoiceStatsRecords.setContactInfo('Postal: Zhone Technologies, Inc. @ Zhone Way 7001 Oakport Street Oakland, CA 94621 USA Toll-Free: +1 877-ZHONE20 (+1 877-946-6320) Tel: +1-510-777-7000 Fax: +1-510-777-7001 E-mail: support@zhone.com') if mibBuilder.loadTexts: zhoneVoiceStatsRecords.setDescription('The MIB module to describe objects for voice call statistics. This MIB record contains tables that define voice calls statistics at the system, card, and subscriber end-point level for incoming, outgoing, and active calls. ') zhone_voice_stats = object_identity((1, 3, 6, 1, 4, 1, 5504, 3, 11)) if mibBuilder.loadTexts: zhoneVoiceStats.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceStats.setDescription('Voice Call Statistics. This Object contains all instances associated with voice calls statistics. In revision 0, Completed, Blocked, and Active calls Statistics are implemented for System, card, and subscriber end-points. ') zhone_system_stats = object_identity((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1)) if mibBuilder.loadTexts: zhoneSystemStats.setStatus('current') if mibBuilder.loadTexts: zhoneSystemStats.setDescription('The System voice statistics object is used to collect voice statistics at a system-wide level. These include statistics for incoming, outgoing, and active calls. The entry in this object is referenced using a static index of zero. ') system_incoming_calls_completed = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: systemIncomingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: systemIncomingCallsCompleted.setDescription('The number of completed incoming calls in the system.') system_incoming_calls_blocked = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: systemIncomingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: systemIncomingCallsBlocked.setDescription('The number of blocked incoming calls in the system.') system_outgoing_calls_completed = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: systemOutgoingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: systemOutgoingCallsCompleted.setDescription('The number of completed outgoing calls in the system.') system_outgoing_calls_blocked = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: systemOutgoingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: systemOutgoingCallsBlocked.setDescription('The number of blocked outgoing calls in the system.') system_active_calls = mib_scalar((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 1, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: systemActiveCalls.setStatus('current') if mibBuilder.loadTexts: systemActiveCalls.setDescription('The number of currently active calls in the system.') zhone_card_stats_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2)) if mibBuilder.loadTexts: zhoneCardStatsTable.setStatus('current') if mibBuilder.loadTexts: zhoneCardStatsTable.setDescription('The card voice statistics table is used to collect voice calls statistics on any card configured to carry voice traffic. Statistics are currently supported for cards with AAL2, GR303, V52 and POTS subscribers. This table collects statistics for incoming calls, outgoing calls, and active calls. The entry in this table is referenced using shelf/slot indices. ') zhone_card_stats_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1)).setIndexNames((0, 'Zhone', 'zhoneShelfIndex'), (0, 'Zhone', 'zhoneSlotIndex')) if mibBuilder.loadTexts: zhoneCardStatsEntry.setStatus('current') if mibBuilder.loadTexts: zhoneCardStatsEntry.setDescription('An entry in the zhoneCardStatsTable') card_incoming_calls_completed = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cardIncomingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: cardIncomingCallsCompleted.setDescription('The number of completed incoming calls on the card.') card_incoming_calls_blocked = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cardIncomingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: cardIncomingCallsBlocked.setDescription('The number of blocked incoming calls on the card.') card_outgoing_calls_completed = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cardOutgoingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: cardOutgoingCallsCompleted.setDescription('The number of completed outgoing calls on the card.') card_outgoing_calls_blocked = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cardOutgoingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: cardOutgoingCallsBlocked.setDescription('The number of blocked outgoing calls on the card.') card_active_calls = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 2, 1, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cardActiveCalls.setStatus('current') if mibBuilder.loadTexts: cardActiveCalls.setDescription('The number of currently active calls on the card.') zhone_subscriber_ep_stats_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3)) if mibBuilder.loadTexts: zhoneSubscriberEPStatsTable.setStatus('current') if mibBuilder.loadTexts: zhoneSubscriberEPStatsTable.setDescription('The subscriber voice end-point statistics table is used to collect incoming, outgoing, and active voice calls statistics for any subscriber end point.The entry in this table is referenced using end-point index. ') zhone_subscriber_ep_stats_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1)).setIndexNames((0, 'ZHONE-GEN-VOICESTAT', 'subVoiceEndPointIndex')) if mibBuilder.loadTexts: zhoneSubscriberEPStatsEntry.setStatus('current') if mibBuilder.loadTexts: zhoneSubscriberEPStatsEntry.setDescription('An entry in the zhoneSubscriberEPStatsTable') sub_voice_end_point_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))) if mibBuilder.loadTexts: subVoiceEndPointIndex.setStatus('current') if mibBuilder.loadTexts: subVoiceEndPointIndex.setDescription('This index is equal to the end-point indices defined for the subscriber voice end-point tables in the zhoneSubscriberRecords. These end-points include AAL2, GR303, V52, POTS, etc. For all the end point types, the end-point index is unique to the sytem. ') sub_ep_incoming_calls_completed = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: subEPIncomingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: subEPIncomingCallsCompleted.setDescription('The number of completed incoming calls at the subscriber voice end point.') sub_ep_incoming_calls_blocked = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: subEPIncomingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: subEPIncomingCallsBlocked.setDescription('The number of blocked incoming calls at the subscriber voice end point.') sub_ep_outgoing_calls_completed = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: subEPOutgoingCallsCompleted.setStatus('current') if mibBuilder.loadTexts: subEPOutgoingCallsCompleted.setDescription('The number of completed outgoing calls at the subscriber voice end point.') sub_ep_outgoing_calls_blocked = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: subEPOutgoingCallsBlocked.setStatus('current') if mibBuilder.loadTexts: subEPOutgoingCallsBlocked.setDescription('The number of blocked outgoing calls at the subscriber voice end point.') sub_ep_active_calls = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 3, 1, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: subEPActiveCalls.setStatus('current') if mibBuilder.loadTexts: subEPActiveCalls.setDescription('The number of currently active calls at the subscriber voice end point.') zhone_voice_stats_objects_group = object_group((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 7)).setObjects(('ZHONE-GEN-VOICESTAT', 'systemIncomingCallsCompleted'), ('ZHONE-GEN-VOICESTAT', 'systemIncomingCallsBlocked'), ('ZHONE-GEN-VOICESTAT', 'systemOutgoingCallsCompleted'), ('ZHONE-GEN-VOICESTAT', 'systemOutgoingCallsBlocked'), ('ZHONE-GEN-VOICESTAT', 'systemActiveCalls'), ('ZHONE-GEN-VOICESTAT', 'cardIncomingCallsCompleted'), ('ZHONE-GEN-VOICESTAT', 'cardIncomingCallsBlocked'), ('ZHONE-GEN-VOICESTAT', 'cardOutgoingCallsCompleted'), ('ZHONE-GEN-VOICESTAT', 'cardOutgoingCallsBlocked'), ('ZHONE-GEN-VOICESTAT', 'cardActiveCalls'), ('ZHONE-GEN-VOICESTAT', 'subEPIncomingCallsCompleted'), ('ZHONE-GEN-VOICESTAT', 'subEPIncomingCallsBlocked'), ('ZHONE-GEN-VOICESTAT', 'subEPOutgoingCallsCompleted'), ('ZHONE-GEN-VOICESTAT', 'subEPOutgoingCallsBlocked'), ('ZHONE-GEN-VOICESTAT', 'subEPActiveCalls')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): zhone_voice_stats_objects_group = zhoneVoiceStatsObjectsGroup.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceStatsObjectsGroup.setDescription('This group contains objects associated with voice statistics.') zhone_voice_ring_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8)) if mibBuilder.loadTexts: zhoneVoiceRingTable.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingTable.setDescription('Table used to generate ring on a port.') zhone_voice_ring_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8, 1)).setIndexNames((0, 'ZHONE-GEN-VOICESTAT', 'zhoneVoiceRingIfIndex')) if mibBuilder.loadTexts: zhoneVoiceRingEntry.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingEntry.setDescription('Row in the zhoneVoiceRing table - corresponds to a port on which ring can be generated. ') zhone_voice_ring_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8, 1, 1), interface_index()) if mibBuilder.loadTexts: zhoneVoiceRingIfIndex.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingIfIndex.setDescription('physical interface') zhone_voice_ring_ringing_cadence = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=named_values(('ringCadenceR0', 1), ('ringCadenceR1', 2), ('ringCadenceR2', 3), ('ringCadenceR3', 4), ('ringCadenceR4', 5), ('ringCadenceR5', 6), ('ringCadenceR6', 7), ('ringCadenceR7', 8), ('ringCadenceCommon', 9), ('ringCadenceSplash', 10)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: zhoneVoiceRingRingingCadence.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingRingingCadence.setDescription('Ringing cadence to use in test.') zhone_voice_ring_timer = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 999))).setMaxAccess('readcreate') if mibBuilder.loadTexts: zhoneVoiceRingTimer.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingTimer.setDescription('Time in seconds to continue ringing.') zhone_voice_ring_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 3, 11, 1, 8, 1, 4), zhone_row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: zhoneVoiceRingRowStatus.setStatus('current') if mibBuilder.loadTexts: zhoneVoiceRingRowStatus.setDescription('Row status.') mibBuilder.exportSymbols('ZHONE-GEN-VOICESTAT', subEPOutgoingCallsCompleted=subEPOutgoingCallsCompleted, cardIncomingCallsCompleted=cardIncomingCallsCompleted, subEPIncomingCallsCompleted=subEPIncomingCallsCompleted, zhoneSubscriberEPStatsEntry=zhoneSubscriberEPStatsEntry, zhoneVoiceRingIfIndex=zhoneVoiceRingIfIndex, zhoneVoiceStats=zhoneVoiceStats, zhoneCardStatsEntry=zhoneCardStatsEntry, zhoneSystemStats=zhoneSystemStats, zhoneSubscriberEPStatsTable=zhoneSubscriberEPStatsTable, zhoneVoiceRingTimer=zhoneVoiceRingTimer, cardIncomingCallsBlocked=cardIncomingCallsBlocked, cardActiveCalls=cardActiveCalls, subVoiceEndPointIndex=subVoiceEndPointIndex, cardOutgoingCallsBlocked=cardOutgoingCallsBlocked, PYSNMP_MODULE_ID=zhoneVoiceStatsRecords, subEPOutgoingCallsBlocked=subEPOutgoingCallsBlocked, zhoneVoiceStatsRecords=zhoneVoiceStatsRecords, zhoneVoiceRingTable=zhoneVoiceRingTable, subEPActiveCalls=subEPActiveCalls, zhoneVoiceRingEntry=zhoneVoiceRingEntry, zhoneVoiceRingRingingCadence=zhoneVoiceRingRingingCadence, systemOutgoingCallsBlocked=systemOutgoingCallsBlocked, cardOutgoingCallsCompleted=cardOutgoingCallsCompleted, systemOutgoingCallsCompleted=systemOutgoingCallsCompleted, systemIncomingCallsCompleted=systemIncomingCallsCompleted, systemIncomingCallsBlocked=systemIncomingCallsBlocked, zhoneVoiceStatsObjectsGroup=zhoneVoiceStatsObjectsGroup, subEPIncomingCallsBlocked=subEPIncomingCallsBlocked, systemActiveCalls=systemActiveCalls, zhoneCardStatsTable=zhoneCardStatsTable, zhoneVoiceRingRowStatus=zhoneVoiceRingRowStatus)
'''https://practice.geeksforgeeks.org/problems/common-elements1132/1 Common elements Easy Accuracy: 38.69% Submissions: 81306 Points: 2 Given three arrays sorted in increasing order. Find the elements that are common in all three arrays. Note: can you take care of the duplicates without using any additional Data Structure? Example 1: Input: n1 = 6; A = {1, 5, 10, 20, 40, 80} n2 = 5; B = {6, 7, 20, 80, 100} n3 = 8; C = {3, 4, 15, 20, 30, 70, 80, 120} Output: 20 80 Explanation: 20 and 80 are the only common elements in A, B and C. Your Task: You don't need to read input or print anything. Your task is to complete the function commonElements() which take the 3 arrays A[], B[], C[] and their respective sizes n1, n2 and n3 as inputs and returns an array containing the common element present in all the 3 arrays in sorted order. If there are no such elements return an empty array. In this case the output will be printed as -1. Expected Time Complexity: O(n1 + n2 + n3) Expected Auxiliary Space: O(n1 + n2 + n3) Constraints: 1 <= n1, n2, n3 <= 10^5 The array elements can be both positive or negative integers.''' # User function Template for python3 class Solution: def commonElements(self, A, B, C, n1, n2, n3): # your code here return sorted(list(set(A) & set(B) & set(C))) # { # Driver Code Starts # Initial Template for Python 3 t = int(input()) for tc in range(t): n1, n2, n3 = list(map(int, input().split())) A = list(map(int, input().split())) B = list(map(int, input().split())) C = list(map(int, input().split())) ob = Solution() res = ob.commonElements(A, B, C, n1, n2, n3) if len(res) == 0: print(-1) else: for i in range(len(res)): print(res[i], end=" ") print() # } Driver Code Ends
"""https://practice.geeksforgeeks.org/problems/common-elements1132/1 Common elements Easy Accuracy: 38.69% Submissions: 81306 Points: 2 Given three arrays sorted in increasing order. Find the elements that are common in all three arrays. Note: can you take care of the duplicates without using any additional Data Structure? Example 1: Input: n1 = 6; A = {1, 5, 10, 20, 40, 80} n2 = 5; B = {6, 7, 20, 80, 100} n3 = 8; C = {3, 4, 15, 20, 30, 70, 80, 120} Output: 20 80 Explanation: 20 and 80 are the only common elements in A, B and C. Your Task: You don't need to read input or print anything. Your task is to complete the function commonElements() which take the 3 arrays A[], B[], C[] and their respective sizes n1, n2 and n3 as inputs and returns an array containing the common element present in all the 3 arrays in sorted order. If there are no such elements return an empty array. In this case the output will be printed as -1. Expected Time Complexity: O(n1 + n2 + n3) Expected Auxiliary Space: O(n1 + n2 + n3) Constraints: 1 <= n1, n2, n3 <= 10^5 The array elements can be both positive or negative integers.""" class Solution: def common_elements(self, A, B, C, n1, n2, n3): return sorted(list(set(A) & set(B) & set(C))) t = int(input()) for tc in range(t): (n1, n2, n3) = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) c = list(map(int, input().split())) ob = solution() res = ob.commonElements(A, B, C, n1, n2, n3) if len(res) == 0: print(-1) else: for i in range(len(res)): print(res[i], end=' ') print()
# the follow code is for key handover KEY_ACCEPTED = 1 KEY_NOT_ACCEPTED = 0 KEY_DESTINATION = 0 KEY_ESTATE = 1 KEY_ILOCK = 2 KEY_OTHER = 3 # the follow code is for note NOTE_USED = 1 NOTE_DISCARDED = 0 NOTE_TYPE_HOME = 0 NOTE_TYPE_OFFER = 1 NOTE_TYPE_USER = 2 # the follow code is for Utility UTILITY_USED = 1 UTILITY_DISCARDED = 0 # 0 =>discard, 1=>used IS_ACTIVE_USED = 1 IS_ACTIVE_DISCARDED = 0 # sms message type OFFER_READY_MESSAGE = 0 OFFER_FINISHED_MESSAGE = 1 INSPECTION_START = 2 INSPECTION_NEED_FIXATION = 3 INSPECTION_FINISHED = 4 PAYMENT_CONFIRMATION = 5 OFFER_PRIING_MESSAGE = 6 OFFER_FINISHED_MESSAGE_LINK = 'http://www.wehome.io/key-handling?home_id={}' INSPECTION_FINISHED_LINK = 'http://www.wehome.io/payment?home_id={}' OFFER_READY_MESSAGE_LINK = 'http://www.wehome.io/myhouse' # pm progress status PM_PROGRESS_INIT = 0 PM_PROGRESS_FIRST = 10 PM_PROGRESS_SECOND = 20 PM_PROGRESS_THIRD = 30 # property status PROPERTY_PENDINNG_STATUS = 0 #default PROPERTY_INSPECTING_STATUS = 1 #start inspection PROPERTY_MAINTANENCE_STATUS = 2 #3.4 PROPERTY_APPROVED_STATUS = 3 #3.3 PROPERTY_LEASING_STATUS = 4 # yes PROPERTY_REJECTED_STATUS = 5 # no PROPERTY_LEASED_STATUS = 6 #3.5 # wehome status # 1** => home info status # 2** => princing status # 3** => inspection status DEAL_NOT_PAY_FOR_PM = '310' DEAL_PAY_FOR_PM = '311' # 4** => deal status # 410 => deal agreed DEAL_AGREED = '410' # 42* => deal utility info status DEAL_UTILITY_INFO_WITHOUT_HOA = '420' DEAL_UTILITY_INFO_WITH_HOA = '421' # 430 => deal payment info status DEAL_PAYMENT_INFO = '430' # 440 => deal closed DEAL_CLOSED = '440' # 5** => rented status
key_accepted = 1 key_not_accepted = 0 key_destination = 0 key_estate = 1 key_ilock = 2 key_other = 3 note_used = 1 note_discarded = 0 note_type_home = 0 note_type_offer = 1 note_type_user = 2 utility_used = 1 utility_discarded = 0 is_active_used = 1 is_active_discarded = 0 offer_ready_message = 0 offer_finished_message = 1 inspection_start = 2 inspection_need_fixation = 3 inspection_finished = 4 payment_confirmation = 5 offer_priing_message = 6 offer_finished_message_link = 'http://www.wehome.io/key-handling?home_id={}' inspection_finished_link = 'http://www.wehome.io/payment?home_id={}' offer_ready_message_link = 'http://www.wehome.io/myhouse' pm_progress_init = 0 pm_progress_first = 10 pm_progress_second = 20 pm_progress_third = 30 property_pendinng_status = 0 property_inspecting_status = 1 property_maintanence_status = 2 property_approved_status = 3 property_leasing_status = 4 property_rejected_status = 5 property_leased_status = 6 deal_not_pay_for_pm = '310' deal_pay_for_pm = '311' deal_agreed = '410' deal_utility_info_without_hoa = '420' deal_utility_info_with_hoa = '421' deal_payment_info = '430' deal_closed = '440'
class Tile: """ map tile properties like opacity and movement block """ def __init__(self,blocked, block_sight=None): self.blocked = blocked #default movement blocking causes sight blocking if block_sight is None: block_sight = blocked self.block_sight = block_sight
class Tile: """ map tile properties like opacity and movement block """ def __init__(self, blocked, block_sight=None): self.blocked = blocked if block_sight is None: block_sight = blocked self.block_sight = block_sight
def mergeSort(lst): pass print(mergeSort([2,3,4,5,15,19,26,27,36,38,44,46,47,48,50] ))
def merge_sort(lst): pass print(merge_sort([2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]))
def attach_label_operation(label_id: 'Long' = None, campaign_id: 'Long' = None, ad_id: 'Long' = None, ad_group_id: 'Long' = None, criterion_id: 'Long' = None, customer_id: 'Long' = None, operator: 'String' = 'ADD', **kwargs): operation = { 'operator': operator.upper(), 'operand': { 'labelId': label_id, } } if customer_id: operation['operand']['customerId'] = customer_id if campaign_id: operation['operand']['campaignId'] = campaign_id operation['xsi_type'] = 'CampaignLabelOperation' if ad_group_id: operation['operand']['adGroupId'] = ad_group_id operation['xsi_type'] = 'AdGroupLabelOperation' if ad_id: if campaign_id: operation['operand'].pop('campaignId', None) operation['operand']['adId'] = ad_id operation['xsi_type'] = 'AdGroupAdLabelOperation' if criterion_id: if campaign_id: operation['operand'].pop('campaignId', None) operation['operand']['criterionId'] = criterion_id operation['xsi_type'] = 'AdGroupCriterionLabelOperation' return operation
def attach_label_operation(label_id: 'Long'=None, campaign_id: 'Long'=None, ad_id: 'Long'=None, ad_group_id: 'Long'=None, criterion_id: 'Long'=None, customer_id: 'Long'=None, operator: 'String'='ADD', **kwargs): operation = {'operator': operator.upper(), 'operand': {'labelId': label_id}} if customer_id: operation['operand']['customerId'] = customer_id if campaign_id: operation['operand']['campaignId'] = campaign_id operation['xsi_type'] = 'CampaignLabelOperation' if ad_group_id: operation['operand']['adGroupId'] = ad_group_id operation['xsi_type'] = 'AdGroupLabelOperation' if ad_id: if campaign_id: operation['operand'].pop('campaignId', None) operation['operand']['adId'] = ad_id operation['xsi_type'] = 'AdGroupAdLabelOperation' if criterion_id: if campaign_id: operation['operand'].pop('campaignId', None) operation['operand']['criterionId'] = criterion_id operation['xsi_type'] = 'AdGroupCriterionLabelOperation' return operation
"""Regression Follow jupyter notebook workflow for better understanding of how to apply data_reader and Regression model to train your AI. https://kotsky.github.io/projects/ai_from_scratch/regression_workflow.html Jupiter notebook: https://github.com/kotsky/ai-dev/blob/main/regression_workflow.ipynb Package: https://github.com/kotsky/ai-dev/blob/main/regression/regression.py """ """Logistic Regression Follow jupyter notebook workflow for better understanding of how to apply data_reader and Logistic Regression model to train your AI. Link: https://kotsky.github.io/projects/ai_from_scratch/logistic_regression_workflow.html Jupiter notebook: https://github.com/kotsky/ai-dev/blob/main/logistic_regression_workflow.ipynb Package: https://github.com/kotsky/ai-dev/blob/main/classification/logistic_regression.py https://kotsky.github.io/projects/ai_from_scratch/kmean_workflow.html """ """K-Nearest Neighbors Follow jupyter notebook workflow for better understanding of how to apply data_reader and K-Nearest Neighbors model to train your AI. Link: https://kotsky.github.io/projects/ai_from_scratch/knn_workflow.html Jupiter notebook: https://github.com/kotsky/ai-dev/blob/main/knn_workflow.ipynb Package: https://github.com/kotsky/ai-dev/blob/main/classification/knn.py """ """K-Mean Follow jupyter notebook workflow for better understanding of how to apply data_reader and K-Mean model to train your AI. Link: https://kotsky.github.io/projects/ai_from_scratch/kmean_workflow.html Jupiter notebook: https://github.com/kotsky/ai-dev/blob/main/kmean_workflow.ipynb Package: https://github.com/kotsky/ai-dev/blob/main/clusterization/kmean.py """ if __name__ == '__main__': pass
"""Regression Follow jupyter notebook workflow for better understanding of how to apply data_reader and Regression model to train your AI. https://kotsky.github.io/projects/ai_from_scratch/regression_workflow.html Jupiter notebook: https://github.com/kotsky/ai-dev/blob/main/regression_workflow.ipynb Package: https://github.com/kotsky/ai-dev/blob/main/regression/regression.py """ 'Logistic Regression\n\nFollow jupyter notebook workflow for better \nunderstanding of how to apply data_reader and\nLogistic Regression model to train your AI.\n\nLink: https://kotsky.github.io/projects/ai_from_scratch/logistic_regression_workflow.html\nJupiter notebook: https://github.com/kotsky/ai-dev/blob/main/logistic_regression_workflow.ipynb\nPackage: https://github.com/kotsky/ai-dev/blob/main/classification/logistic_regression.py\n\nhttps://kotsky.github.io/projects/ai_from_scratch/kmean_workflow.html\n\n' 'K-Nearest Neighbors\n\nFollow jupyter notebook workflow for better \nunderstanding of how to apply data_reader and\nK-Nearest Neighbors model to train your AI.\n\nLink: https://kotsky.github.io/projects/ai_from_scratch/knn_workflow.html\nJupiter notebook: https://github.com/kotsky/ai-dev/blob/main/knn_workflow.ipynb\nPackage: https://github.com/kotsky/ai-dev/blob/main/classification/knn.py\n\n' 'K-Mean\n\nFollow jupyter notebook workflow for better \nunderstanding of how to apply data_reader and\nK-Mean model to train your AI.\n\nLink: https://kotsky.github.io/projects/ai_from_scratch/kmean_workflow.html\nJupiter notebook: https://github.com/kotsky/ai-dev/blob/main/kmean_workflow.ipynb\nPackage: https://github.com/kotsky/ai-dev/blob/main/clusterization/kmean.py\n\n' if __name__ == '__main__': pass
# Source : https://leetcode.com/problems/shortest-palindrome/ # Author : henrytine # Date : 2020-07-23 ##################################################################################################### # # Given a string s, you are allowed to convert it to a palindrome by adding characters in front of # it. Find and return the shortest palindrome you can find by performing this transformation. # # Example 1: # # Input: "aacecaaa" # Output: "aaacecaaa" # # Example 2: # # Input: "abcd" # Output: "dcbabcd" ##################################################################################################### class Solution: def shortestPalindrome(self, s: str) -> str: r = s[::-1] for i in range(len(s) + 1): if s.startswith(r[i:]): return r[:i] + s
class Solution: def shortest_palindrome(self, s: str) -> str: r = s[::-1] for i in range(len(s) + 1): if s.startswith(r[i:]): return r[:i] + s
# -*- coding: utf-8 -*- """ Created on Tue Feb 14 20:22:47 2017 @author: Zachary """ def f(i): return i + 2 def g(i): return i > 5 def applyF_filterG(L, f, g): listA = [] for i in L: if g(f(i)) == True: listA.append(i) L[:] = listA if len(L) == 0: return -1 else: return max(L) L = [0, -10, 5, 6, -4] print(applyF_filterG(L, f, g)) print(L)
""" Created on Tue Feb 14 20:22:47 2017 @author: Zachary """ def f(i): return i + 2 def g(i): return i > 5 def apply_f_filter_g(L, f, g): list_a = [] for i in L: if g(f(i)) == True: listA.append(i) L[:] = listA if len(L) == 0: return -1 else: return max(L) l = [0, -10, 5, 6, -4] print(apply_f_filter_g(L, f, g)) print(L)
def update_parameters(parameters, gradients, lr, batch_size, a): parameters["Wax"] = parameters["Wax"] - (lr/batch_size) * gradients["dWax"] parameters["Waa"] = parameters["Waa"] - (lr / batch_size) * gradients["dWaa"] parameters["ba"] = parameters["ba"] - (lr / batch_size) * gradients["dba"] if a == "d": parameters["Wya"] = parameters["Wya"] - (lr / batch_size) * gradients["dWya"] parameters["by"] = parameters["by"] - (lr / batch_size) * gradients["dby"] return parameters
def update_parameters(parameters, gradients, lr, batch_size, a): parameters['Wax'] = parameters['Wax'] - lr / batch_size * gradients['dWax'] parameters['Waa'] = parameters['Waa'] - lr / batch_size * gradients['dWaa'] parameters['ba'] = parameters['ba'] - lr / batch_size * gradients['dba'] if a == 'd': parameters['Wya'] = parameters['Wya'] - lr / batch_size * gradients['dWya'] parameters['by'] = parameters['by'] - lr / batch_size * gradients['dby'] return parameters
#!/usr/bin/python3 s='ODITSZAPC' p='ba9876420' for comb in range(0, 2**9): x = comb i = 0 c = '' v = 0 while x != 0: f = x % 2 if f == 1: c += s[i] v += 1<<int(p[i], 16) i += 1 x = int(x/2) if c == '': continue print('Z%s = 0x%x' % (c, v))
s = 'ODITSZAPC' p = 'ba9876420' for comb in range(0, 2 ** 9): x = comb i = 0 c = '' v = 0 while x != 0: f = x % 2 if f == 1: c += s[i] v += 1 << int(p[i], 16) i += 1 x = int(x / 2) if c == '': continue print('Z%s = 0x%x' % (c, v))
""" author : Ali Emre SAVAS Link : https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem """ S = input().strip() try: print(int(S)) except: print("Bad String")
""" author : Ali Emre SAVAS Link : https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem """ s = input().strip() try: print(int(S)) except: print('Bad String')
MAX_INT8 = 1 << 7 - 1 MIN_INT8 = -1 << 7 MAX_INT16 = 1 << 15 - 1 MIN_INT16 = -1 << 15 MAX_INT32 = 1 << 31 - 1 MIN_INT32 = -1 << 31 MAX_INT64 = 1 << 63 - 1 MIN_INT64 = -1 << 63 MAX_UINT8 = 1 << 8 - 1 MAX_UINT16 = 1 << 16 - 1 MAX_UINT32 = 1 << 32 - 1 MAX_UINT64 = 1 << 64 - 1
max_int8 = 1 << 7 - 1 min_int8 = -1 << 7 max_int16 = 1 << 15 - 1 min_int16 = -1 << 15 max_int32 = 1 << 31 - 1 min_int32 = -1 << 31 max_int64 = 1 << 63 - 1 min_int64 = -1 << 63 max_uint8 = 1 << 8 - 1 max_uint16 = 1 << 16 - 1 max_uint32 = 1 << 32 - 1 max_uint64 = 1 << 64 - 1
# board # display board # play game # handle turn # check win # check rows # check coumns # check diagonals # check tie # flip player #--------Global Variables------ #Game board board = ["-","-","-", "-","-","-", "-","-","-",] #if game is still going game_still_going = True #Who won? or tie? winner = None #Whos turn is it current_player = "X" def display_board(): print(board[0] + " | " + board[1] + " | " + board[2]) print(board[3] + " | " + board[4] + " | " + board[5]) print(board[6] + " | " + board[7] + " | " + board[8]) # play a game of tic tac toe def play_game(): # Display initial board display_board() # While the game is still going while game_still_going: # handel a single turn of an arbitrary player handle_turn(current_player) # Check if the game has ended check_if_game_over() # Flip to the other player flip_player() # The game has ended if winner == "X" or winner == "O": print(winner + " won.") elif winner == None: print("Tie.") # Handle a single turn of an arbitrary player def handle_turn(player): print(player + "'s turn.") position = input("Choose a position from 1-9: ") valid = False while not valid: while position not in["1","2","3","4","5","6","7","8","9"]: position = input("Invalid input. Choose a position from 1-9: ") position = int(position) - 1 if board[position] == "-": valid = True else: print("You cant go there. Go again.") board[position] = player display_board() def check_if_game_over(): check_for_winner() check_if_tie() def check_for_winner(): # Set up a global variables global winner # check rows row_winner = check_rows() # check cloumns column_winner = check_columns() # check diagonals diagonal_winner = check_diagonals() if row_winner: #there was a win winner = row_winner elif column_winner: #there was a win winner = column_winner elif diagonal_winner: #there was a win winner = diagonal_winner else: #there was no win winner = None return def check_rows(): # Set up global variables global game_still_going # check if any rows have the same value and is not empty row_1 = board[0]==board[1]==board[2] != "-" row_2 = board[3]==board[4]==board[5] != "-" row_3 = board[6]==board[7]==board[8] != "-" if row_1 or row_2 or row_3: game_still_going = False # Return the winner (X or O) if row_1: return board[0] if row_2: return board[3] if row_3: return board[6] return def check_columns(): # Set up global variables global game_still_going # check if any column have the same value and is not empty column_1 = board[0]==board[3]==board[6] != "-" column_2 = board[1]==board[4]==board[7] != "-" column_3 = board[2]==board[5]==board[8] != "-" if column_1 or column_2 or column_3: game_still_going = False # Return the winner (X or O) if column_1: return board[0] if column_2: return board[1] if column_3: return board[2] return def check_diagonals(): # Set up global variables global game_still_going # check if any diagonal have the same value and is not empty diagonal_1 = board[0]==board[4]==board[8] != "-" diagonal_2 = board[6]==board[4]==board[2] != "-" if diagonal_1 or diagonal_2: game_still_going = False # Return the winner (X or O) if diagonal_1: return board[0] if diagonal_2: return board[6] return def check_if_tie(): global game_still_going if "-" not in board: game_still_going = False return def flip_player(): # global variable global current_player # if the current player was x, then change it to O and vice-versa if current_player == "X": current_player = "O" elif current_player == "O": current_player = "X" return play_game()
board = ['-', '-', '-', '-', '-', '-', '-', '-', '-'] game_still_going = True winner = None current_player = 'X' def display_board(): print(board[0] + ' | ' + board[1] + ' | ' + board[2]) print(board[3] + ' | ' + board[4] + ' | ' + board[5]) print(board[6] + ' | ' + board[7] + ' | ' + board[8]) def play_game(): display_board() while game_still_going: handle_turn(current_player) check_if_game_over() flip_player() if winner == 'X' or winner == 'O': print(winner + ' won.') elif winner == None: print('Tie.') def handle_turn(player): print(player + "'s turn.") position = input('Choose a position from 1-9: ') valid = False while not valid: while position not in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: position = input('Invalid input. Choose a position from 1-9: ') position = int(position) - 1 if board[position] == '-': valid = True else: print('You cant go there. Go again.') board[position] = player display_board() def check_if_game_over(): check_for_winner() check_if_tie() def check_for_winner(): global winner row_winner = check_rows() column_winner = check_columns() diagonal_winner = check_diagonals() if row_winner: winner = row_winner elif column_winner: winner = column_winner elif diagonal_winner: winner = diagonal_winner else: winner = None return def check_rows(): global game_still_going row_1 = board[0] == board[1] == board[2] != '-' row_2 = board[3] == board[4] == board[5] != '-' row_3 = board[6] == board[7] == board[8] != '-' if row_1 or row_2 or row_3: game_still_going = False if row_1: return board[0] if row_2: return board[3] if row_3: return board[6] return def check_columns(): global game_still_going column_1 = board[0] == board[3] == board[6] != '-' column_2 = board[1] == board[4] == board[7] != '-' column_3 = board[2] == board[5] == board[8] != '-' if column_1 or column_2 or column_3: game_still_going = False if column_1: return board[0] if column_2: return board[1] if column_3: return board[2] return def check_diagonals(): global game_still_going diagonal_1 = board[0] == board[4] == board[8] != '-' diagonal_2 = board[6] == board[4] == board[2] != '-' if diagonal_1 or diagonal_2: game_still_going = False if diagonal_1: return board[0] if diagonal_2: return board[6] return def check_if_tie(): global game_still_going if '-' not in board: game_still_going = False return def flip_player(): global current_player if current_player == 'X': current_player = 'O' elif current_player == 'O': current_player = 'X' return play_game()
# -*- coding: utf-8 -*- """ Created on Fri Jun 30 18:29:52 2017 MIT 6.00.1x course on edX.org: Midterm P6 Task: Write a function that satisfies the docstring @author: Andrey Tymofeiuk Important: This code is placed at GitHub to track my progress in programming and to show my way of thinking. Also I will be happy if somebody will find my solution interesting. But I respect The Honor Code and I ask you to respect it also - please don't use this solution to pass the MIT 6.00.1x course. """ def largest_odd_times(L): """ Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None """ # Andrey Tymofeiuk: Sometimes double mistake leads to peculiar right result dict_collect = {} list_final = [] for element in L: if element in dict_collect: dict_collect[element] += 1 else: dict_collect[element] = 0 for key in dict_collect: if dict_collect[key] % 2 == 0: list_final.append(key) if list_final != []: return max(list_final) else: return None
""" Created on Fri Jun 30 18:29:52 2017 MIT 6.00.1x course on edX.org: Midterm P6 Task: Write a function that satisfies the docstring @author: Andrey Tymofeiuk Important: This code is placed at GitHub to track my progress in programming and to show my way of thinking. Also I will be happy if somebody will find my solution interesting. But I respect The Honor Code and I ask you to respect it also - please don't use this solution to pass the MIT 6.00.1x course. """ def largest_odd_times(L): """ Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None """ dict_collect = {} list_final = [] for element in L: if element in dict_collect: dict_collect[element] += 1 else: dict_collect[element] = 0 for key in dict_collect: if dict_collect[key] % 2 == 0: list_final.append(key) if list_final != []: return max(list_final) else: return None
def __somefunc__(): return 42 def not_dunder_func(arg1, arg2): """Docstring of function1""" return 42
def __somefunc__(): return 42 def not_dunder_func(arg1, arg2): """Docstring of function1""" return 42
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1, l2): p1=l1 p2=l2 count=0 while p1 and p2: count+=p1.val count+=p2.val p1.val=count%10 count=count//10 p2=p2.next if p1.next is None: p1.next=p2 p1=None else: p1=p1.next while p2 and count>0: count+=p2.val p2.val=count%10 count=count//10 if p2.next is None and count>0: p2.next=ListNode(count) break else: p2=p2.next while p1 and count: count += p1.val p1.val = count % 10 count = count // 10 if p1.next is None and count > 0: p1.next = ListNode(count) break else: p1 = p1.next return l1
class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def add_two_numbers(self, l1, l2): p1 = l1 p2 = l2 count = 0 while p1 and p2: count += p1.val count += p2.val p1.val = count % 10 count = count // 10 p2 = p2.next if p1.next is None: p1.next = p2 p1 = None else: p1 = p1.next while p2 and count > 0: count += p2.val p2.val = count % 10 count = count // 10 if p2.next is None and count > 0: p2.next = list_node(count) break else: p2 = p2.next while p1 and count: count += p1.val p1.val = count % 10 count = count // 10 if p1.next is None and count > 0: p1.next = list_node(count) break else: p1 = p1.next return l1
height = 6 num = 1 for i in range(height,-height-1,-1): for j in range(1,abs(i)+1): print(end=" ") if(i >= 0) : num = 1 else: num = abs(i) + 1; for j in range(height,abs(i)+1,-1): print(num,end=" ") num += 1 print() # Output :- # 1 # 1 2 # 1 2 3 # 1 2 3 4 # 1 2 3 4 5 # 2 3 4 5 # 3 4 5 # 4 5 # 5
height = 6 num = 1 for i in range(height, -height - 1, -1): for j in range(1, abs(i) + 1): print(end=' ') if i >= 0: num = 1 else: num = abs(i) + 1 for j in range(height, abs(i) + 1, -1): print(num, end=' ') num += 1 print()
f1 = 1 f2 = 2 not_a_flag = 3 print("step: 1") print("stat_1: 0.5") print("stat_2: 0.6") print("step: 2") print("stat_1: 0.7") print("stat_2: 0.8")
f1 = 1 f2 = 2 not_a_flag = 3 print('step: 1') print('stat_1: 0.5') print('stat_2: 0.6') print('step: 2') print('stat_1: 0.7') print('stat_2: 0.8')
# -*- coding: utf-8 -*- """ Created on Sun Oct 27 00:30:31 2019 dogName1 = "One" dogName2 = "Two" dogName3 = "Three" dogName4 = "Four" dogName5 = "Five" dogName6 = "Six" @author: Gunardi Saputra """ print("Enter the name of dog 1: ") dogName1 = input() print("Enter the name of dog 2: ") dogName2 = input() print("Enter the name of dog 3: ") dogName3 = input() print("Enter the name of dog 4: ") dogName4 = input() print("Enter the name of dog 5: ") dogName5 = input() print("Enter the name of dog 6: ") dogName6 = input() print("The dog names are: " + dogName1 + " " + dogName2 + " " + dogName3 + " " + dogName4 + " " + dogName5 + " " + dogName6 + " ")
""" Created on Sun Oct 27 00:30:31 2019 dogName1 = "One" dogName2 = "Two" dogName3 = "Three" dogName4 = "Four" dogName5 = "Five" dogName6 = "Six" @author: Gunardi Saputra """ print('Enter the name of dog 1: ') dog_name1 = input() print('Enter the name of dog 2: ') dog_name2 = input() print('Enter the name of dog 3: ') dog_name3 = input() print('Enter the name of dog 4: ') dog_name4 = input() print('Enter the name of dog 5: ') dog_name5 = input() print('Enter the name of dog 6: ') dog_name6 = input() print('The dog names are: ' + dogName1 + ' ' + dogName2 + ' ' + dogName3 + ' ' + dogName4 + ' ' + dogName5 + ' ' + dogName6 + ' ')
load("@obazl_rules_ocaml//ocaml:providers.bzl", "OpamConfig", "BuildConfig") opam_pkg = { "async": ["v0.12.0"], "bignum": ["v0.12.0"], # WARNING: depends on zarith which depends on libgmp-dev on local system "bin_prot": ["v0.12.0"], "core": ["v0.12.1"], "core_kernel": ["v0.12.3"], "digestif": ["0.9.0"], "fieldslib": ["v0.12.0"], "num": ["1.1"], "ppx_assert": ["v0.12.0", ["ppx_assert.runtime-lib"]], "ppx_bench": ["v0.12.0", ["ppx_bench.runtime-lib"]], "ppx_bin_prot": ["v0.12.1"], "ppx_compare": ["v0.12.0", ["ppx_compare.runtime-lib"]], "ppx_custom_printf": ["v0.12.0"], "ppx_deriving": ["4.4.1", [ "ppx_deriving.enum", "ppx_deriving.eq", "ppx_deriving.std", "ppx_deriving.runtime" ]], "ppx_deriving_yojson": ["3.5.2", ["ppx_deriving_yojson.runtime"]], "ppx_enumerate": ["v0.12.0", ["ppx_enumerate.runtime-lib"]], "ppx_expect": ["v0.12.0", ["ppx_expect.collector"]], "ppx_fields_conv": ["v0.12.0"], "ppx_hash": ["v0.12.0", ["ppx_hash.runtime-lib"]], "ppx_inline_test": ["v0.12.0", ["ppx_inline_test.runtime-lib"]], "ppx_jane": ["v0.12.0"], "ppx_let": ["v0.12.0"], "ppx_module_timer": ["v0.12.0", ["ppx_module_timer.runtime"]], "ppx_sexp_conv": ["v0.12.0", ["ppx_sexp_conv.runtime-lib"]], "ppx_tools": ["5.1+4.06.0"], "ppxlib": ["0.8.1", ["ppxlib.metaquot"]], "yojson": ["1.7.0"] } opam = OpamConfig( version = "2.0", builds = { "mina-0.1.0": BuildConfig( default = True, switch = "4.07.1", compiler = "4.07.1", packages = opam_pkg, verify = True ), "4.07.1": BuildConfig( compiler = "4.07.1", packages = opam_pkg ), } )
load('@obazl_rules_ocaml//ocaml:providers.bzl', 'OpamConfig', 'BuildConfig') opam_pkg = {'async': ['v0.12.0'], 'bignum': ['v0.12.0'], 'bin_prot': ['v0.12.0'], 'core': ['v0.12.1'], 'core_kernel': ['v0.12.3'], 'digestif': ['0.9.0'], 'fieldslib': ['v0.12.0'], 'num': ['1.1'], 'ppx_assert': ['v0.12.0', ['ppx_assert.runtime-lib']], 'ppx_bench': ['v0.12.0', ['ppx_bench.runtime-lib']], 'ppx_bin_prot': ['v0.12.1'], 'ppx_compare': ['v0.12.0', ['ppx_compare.runtime-lib']], 'ppx_custom_printf': ['v0.12.0'], 'ppx_deriving': ['4.4.1', ['ppx_deriving.enum', 'ppx_deriving.eq', 'ppx_deriving.std', 'ppx_deriving.runtime']], 'ppx_deriving_yojson': ['3.5.2', ['ppx_deriving_yojson.runtime']], 'ppx_enumerate': ['v0.12.0', ['ppx_enumerate.runtime-lib']], 'ppx_expect': ['v0.12.0', ['ppx_expect.collector']], 'ppx_fields_conv': ['v0.12.0'], 'ppx_hash': ['v0.12.0', ['ppx_hash.runtime-lib']], 'ppx_inline_test': ['v0.12.0', ['ppx_inline_test.runtime-lib']], 'ppx_jane': ['v0.12.0'], 'ppx_let': ['v0.12.0'], 'ppx_module_timer': ['v0.12.0', ['ppx_module_timer.runtime']], 'ppx_sexp_conv': ['v0.12.0', ['ppx_sexp_conv.runtime-lib']], 'ppx_tools': ['5.1+4.06.0'], 'ppxlib': ['0.8.1', ['ppxlib.metaquot']], 'yojson': ['1.7.0']} opam = opam_config(version='2.0', builds={'mina-0.1.0': build_config(default=True, switch='4.07.1', compiler='4.07.1', packages=opam_pkg, verify=True), '4.07.1': build_config(compiler='4.07.1', packages=opam_pkg)})
keyFinancialIncomeStatement = [ # Valuation Measures "Revenue", "Total Revenue", "Cost of Revenue", ]
key_financial_income_statement = ['Revenue', 'Total Revenue', 'Cost of Revenue']
def classic_levenshtein(string_1, string_2): """ Calculates the Levenshtein distance between two strings. This version is easier to read, but significantly slower than the version below (up to several orders of magnitude). Useful for learning, less so otherwise. Usage:: >>> classic_levenshtein('kitten', 'sitting') 3 >>> classic_levenshtein('kitten', 'kitten') 0 >>> classic_levenshtein('', '') 0 """ len_1 = len(string_1) len_2 = len(string_2) cost = 0 if len_1 and len_2 and string_1[0] != string_2[0]: cost = 1 if len_1 == 0: return len_2 elif len_2 == 0: return len_1 else: return min( classic_levenshtein(string_1[1:], string_2) + 1, classic_levenshtein(string_1, string_2[1:]) + 1, classic_levenshtein(string_1[1:], string_2[1:]) + cost, )
def classic_levenshtein(string_1, string_2): """ Calculates the Levenshtein distance between two strings. This version is easier to read, but significantly slower than the version below (up to several orders of magnitude). Useful for learning, less so otherwise. Usage:: >>> classic_levenshtein('kitten', 'sitting') 3 >>> classic_levenshtein('kitten', 'kitten') 0 >>> classic_levenshtein('', '') 0 """ len_1 = len(string_1) len_2 = len(string_2) cost = 0 if len_1 and len_2 and (string_1[0] != string_2[0]): cost = 1 if len_1 == 0: return len_2 elif len_2 == 0: return len_1 else: return min(classic_levenshtein(string_1[1:], string_2) + 1, classic_levenshtein(string_1, string_2[1:]) + 1, classic_levenshtein(string_1[1:], string_2[1:]) + cost)
""" 981 time based key-value store medium Create a timebased key-value store class TimeMap, that supports two operations. 1. set(string key, string value, int timestamp) Stores the key and value, along with the given timestamp. 2. get(string key, int timestamp) Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the one with the largest timestamp_prev. If there are no values, it returns the empty string (""). """ class TimeMap: def __init__(self): self.time_map = {} def set(self, key: str, value: str, timestamp: int) -> None: if key not in self.time_map: self.time_map[key] = [(timestamp, value)] else: self.time_map[key].append((timestamp, value)) def get(self, key: str, timestamp: int) -> str: if key not in self.time_map: return "" curr_array = self.time_map[key] if curr_array[0][0] > timestamp: return "" left, right = 0, len(curr_array) while left < right - 1: mid = (left + right) // 2 if curr_array[mid][0] <= timestamp: left = mid else: right = mid - 1 return curr_array[left][1] sol = TimeMap() sol.set("foo", "bar", 1) sol.set("foo", "good", 2) print(sol.get("foo", 1)) # Your TimeMap object will be instantiated and called as such: # obj = TimeMap() # obj.set(key,value,timestamp) # param_2 = obj.get(key,timestamp)
""" 981 time based key-value store medium Create a timebased key-value store class TimeMap, that supports two operations. 1. set(string key, string value, int timestamp) Stores the key and value, along with the given timestamp. 2. get(string key, int timestamp) Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the one with the largest timestamp_prev. If there are no values, it returns the empty string (""). """ class Timemap: def __init__(self): self.time_map = {} def set(self, key: str, value: str, timestamp: int) -> None: if key not in self.time_map: self.time_map[key] = [(timestamp, value)] else: self.time_map[key].append((timestamp, value)) def get(self, key: str, timestamp: int) -> str: if key not in self.time_map: return '' curr_array = self.time_map[key] if curr_array[0][0] > timestamp: return '' (left, right) = (0, len(curr_array)) while left < right - 1: mid = (left + right) // 2 if curr_array[mid][0] <= timestamp: left = mid else: right = mid - 1 return curr_array[left][1] sol = time_map() sol.set('foo', 'bar', 1) sol.set('foo', 'good', 2) print(sol.get('foo', 1))
""" Module: 'network' on pySBC 1.13.0 with FW1.5.12-264 """ # MCU: (sysname='pySBC', nodename='pySBC', release='1.13.0 with FW1.5.12', version='v1.13-264-gb0c6ec5bb-dirty on 2020-11-25', machine='simpleRTK-SBC with STM32F745') # Stubber: 1.3.4 class SMS: '' def callback(): pass def send(): pass def isbusy(): pass def iserror(): pass class GSM: '' AUTHTYPE_CHAP = 2 AUTHTYPE_EAP = 5 AUTHTYPE_MSCHAP = 3 AUTHTYPE_MSCHAP_V2 = 4 AUTHTYPE_NONE = 0 AUTHTYPE_PAP = 1 SMS = None def active(): pass def config(): pass def connect(): pass def disconnect(): pass def ifconfig(): pass def imei(): pass def imsi(): pass def isconnected(): pass def qos(): pass def status(): pass class LAN: '' def active(): pass def config(): pass def ifconfig(): pass def isconnected(): pass def status(): pass def route(): pass
""" Module: 'network' on pySBC 1.13.0 with FW1.5.12-264 """ class Sms: """""" def callback(): pass def send(): pass def isbusy(): pass def iserror(): pass class Gsm: """""" authtype_chap = 2 authtype_eap = 5 authtype_mschap = 3 authtype_mschap_v2 = 4 authtype_none = 0 authtype_pap = 1 sms = None def active(): pass def config(): pass def connect(): pass def disconnect(): pass def ifconfig(): pass def imei(): pass def imsi(): pass def isconnected(): pass def qos(): pass def status(): pass class Lan: """""" def active(): pass def config(): pass def ifconfig(): pass def isconnected(): pass def status(): pass def route(): pass
# Author: Ben Wichser # Date: 12/12/2019 # Description: Jupiter oon movement. see www.adventofcode.com/2019 (day 12) for more information class Moon: """ Moon class.""" def __init__(self, position_x, position_y, position_z): """Initialization. Creates moon at given position. Creates initial velocity of zero in all three dimensions as well.""" self.position_x = position_x self.position_y = position_y self.position_z = position_z self.velocity_x = 0 self.velocity_y = 0 self.velocity_z = 0 def velocity_update(self, moons): """Updates this moon's velocity based on the positions of all the moons. Returns True.""" for moon in moons: if self.position_x > moon.position_x: self.velocity_x -= 1 elif self.position_x < moon.position_x: self.velocity_x += 1 if self.position_y > moon.position_y: self.velocity_y -= 1 elif self.position_y < moon.position_y: self.velocity_y += 1 if self.position_z > moon.position_z: self.velocity_z -= 1 elif self.position_z < moon.position_z: self.velocity_z += 1 return True def position_update(self): """Updates this moon's position based on its velocity. Returns True.""" self.position_x += self.velocity_x self.position_y += self.velocity_y self.position_z += self.velocity_z return True def energy_calculation(self): """Calculates this moon's energy is the product of the sum of the absolute positions and product of the absolute velocities. Returns the energy amount.""" energy = (abs(self.position_x) + abs(self.position_y) + abs(self.position_z)) * \ (abs(self.velocity_x) + abs(self.velocity_y) + abs(self.velocity_z)) return energy # Initial Moon Locations (input from AdventOfCode) # <x=-1, y=-4, z=0> # <x=4, y=7, z=-1> # <x=-14, y=-10, z=9> # <x=1, y=2, z=17> io = Moon(-1, -4, 0) europa = Moon(4, 7, -1) ganymede = Moon(-14, -10, 9) callisto = Moon(1, 2, 17) time = 1 moons = [io, europa, ganymede, callisto] while time <= 1000: for moon in moons: moon.velocity_update(moons) for moon in moons: moon.position_update() time += 1 total_energy = 0 for moon in moons: total_energy += moon.energy_calculation() print(total_energy)
class Moon: """ Moon class.""" def __init__(self, position_x, position_y, position_z): """Initialization. Creates moon at given position. Creates initial velocity of zero in all three dimensions as well.""" self.position_x = position_x self.position_y = position_y self.position_z = position_z self.velocity_x = 0 self.velocity_y = 0 self.velocity_z = 0 def velocity_update(self, moons): """Updates this moon's velocity based on the positions of all the moons. Returns True.""" for moon in moons: if self.position_x > moon.position_x: self.velocity_x -= 1 elif self.position_x < moon.position_x: self.velocity_x += 1 if self.position_y > moon.position_y: self.velocity_y -= 1 elif self.position_y < moon.position_y: self.velocity_y += 1 if self.position_z > moon.position_z: self.velocity_z -= 1 elif self.position_z < moon.position_z: self.velocity_z += 1 return True def position_update(self): """Updates this moon's position based on its velocity. Returns True.""" self.position_x += self.velocity_x self.position_y += self.velocity_y self.position_z += self.velocity_z return True def energy_calculation(self): """Calculates this moon's energy is the product of the sum of the absolute positions and product of the absolute velocities. Returns the energy amount.""" energy = (abs(self.position_x) + abs(self.position_y) + abs(self.position_z)) * (abs(self.velocity_x) + abs(self.velocity_y) + abs(self.velocity_z)) return energy io = moon(-1, -4, 0) europa = moon(4, 7, -1) ganymede = moon(-14, -10, 9) callisto = moon(1, 2, 17) time = 1 moons = [io, europa, ganymede, callisto] while time <= 1000: for moon in moons: moon.velocity_update(moons) for moon in moons: moon.position_update() time += 1 total_energy = 0 for moon in moons: total_energy += moon.energy_calculation() print(total_energy)
# -*- coding: utf-8 -*- """ Created on Sun Feb 26 17:29:16 2017 @author: Thautwarm """ template=\ """ package _PACKAGE_; import _ENTITY_PACKAGE_; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import GraceJava.SQL; import GraceJava.ToStr; public class _ENTITY_CLASS_NAME_Dao extends SQL{ public _ENTITY_CLASS_NAME_Dao() { setTypeMap(_ENTITY_CLASS_NAME_.getTypeMap()); setTableName("_ENTITY_OBJ_NAME_"); } public ArrayList<_ENTITY_CLASS_NAME_> selectEntity(String columns,String MatchValues){ ArrayList<_ENTITY_CLASS_NAME_> _ENTITY_OBJ_NAME_List= new ArrayList<_ENTITY_CLASS_NAME_>(); ResultSet res =Select(_ENTITY_CLASS_NAME_.toSQLColumns(),columns,MatchValues); String[] columnsKeys=columns.split(","); try{ while(res.next()){ _ENTITY_CLASS_NAME_ _ENTITY_OBJ_NAME_=new _ENTITY_CLASS_NAME_(); for(String column:columnsKeys){ Object obj=null; String type=this.TypeMap.get(column); switch (type){ case "Integer": obj=res.getInt(column); break; case "String": obj=res.getString(column); break; case "Date": obj= ToStr.Timestamp2Date(res.getTimestamp(column)); break; case "Double": obj= res.getDouble(column); break; case "Long": obj= res.getLong(column); break; default: break; } if (obj==null) { continue; } _ENTITY_OBJ_NAME_.setByKey(column, obj); } _ENTITY_OBJ_NAME_List.add(_ENTITY_OBJ_NAME_); } } catch (SQLException e){ e.printStackTrace(); } return _ENTITY_OBJ_NAME_List; } public ArrayList<_ENTITY_CLASS_NAME_> selectEntity(String columns,Object ...MatchValues){ ArrayList<_ENTITY_CLASS_NAME_> _ENTITY_OBJ_NAME_List= new ArrayList<_ENTITY_CLASS_NAME_>(); ResultSet res =Select(_ENTITY_CLASS_NAME_.toSQLColumns(),columns,MatchValues); String[] columnsKeys=columns.split(","); try{ while(res.next()){ _ENTITY_CLASS_NAME_ _ENTITY_OBJ_NAME_=new _ENTITY_CLASS_NAME_(); for(String column:columnsKeys){ Object obj=null; String type=this.TypeMap.get(column); switch (type){ case "Integer": obj=res.getInt(column); break; case "String": obj=res.getString(column); break; case "Date": obj= ToStr.Timestamp2Date(res.getTimestamp(column)); break; case "Double": obj= res.getDouble(column); break; case "Long": obj= res.getLong(column); break; default: break; } if (obj==null) { continue; } _ENTITY_OBJ_NAME_.setByKey(column, obj); } _ENTITY_OBJ_NAME_List.add(_ENTITY_OBJ_NAME_); } } catch (SQLException e){ e.printStackTrace(); } return _ENTITY_OBJ_NAME_List; } public ArrayList<_ENTITY_CLASS_NAME_> selectEntity(_ENTITY_CLASS_NAME_ _ENTITY_OBJ_NAME_Select){ String MatchValues=_ENTITY_OBJ_NAME_Select.toSQLValues(); ArrayList<_ENTITY_CLASS_NAME_> _ENTITY_OBJ_NAME_List= new ArrayList<_ENTITY_CLASS_NAME_>(); String columns=_ENTITY_CLASS_NAME_.toSQLColumns(); ResultSet res =Select(_ENTITY_CLASS_NAME_.toSQLColumns(),columns,MatchValues); String[] columnsKeys=columns.split(","); try{ while(res.next()){ _ENTITY_CLASS_NAME_ _ENTITY_OBJ_NAME_=new _ENTITY_CLASS_NAME_(); for(String column:columnsKeys){ Object obj=null; String type=this.TypeMap.get(column); switch (type){ case "Integer": obj=res.getInt(column); break; case "String": obj=res.getString(column); break; case "Date": obj= ToStr.Timestamp2Date(res.getTimestamp(column)); break; case "Double": obj= res.getDouble(column); break; case "Long": obj= res.getLong(column); break; default: break; } if (obj==null) { continue; } _ENTITY_OBJ_NAME_.setByKey(column, obj); } _ENTITY_OBJ_NAME_List.add(_ENTITY_OBJ_NAME_); } } catch (SQLException e){ e.printStackTrace(); } return _ENTITY_OBJ_NAME_List; } public boolean add(_ENTITY_CLASS_NAME_ _ENTITY_OBJ_NAME_){ if (isDuplicatedByKey("id",_ENTITY_OBJ_NAME_.getId()).equals("No")){ return addEntity(_ENTITY_CLASS_NAME_.toSQLColumns(),_ENTITY_OBJ_NAME_.toSQLValues()); } System.out.println("add_ENTITY_CLASS_NAME_Error-DuplicatedAdded."); return false; } } """ def getDao(_ENTITY_CLASS_NAME_,_ENTITY_PACKAGE_=None,_PACKAGE_='dao'): _ENTITY_OBJ_NAME_=_ENTITY_CLASS_NAME_.lower() if not _ENTITY_PACKAGE_:_ENTITY_PACKAGE_='entity.%s'%_ENTITY_CLASS_NAME_; return template.replace("_ENTITY_CLASS_NAME_",_ENTITY_CLASS_NAME_).replace("_ENTITY_OBJ_NAME_",_ENTITY_OBJ_NAME_)\ .replace("_ENTITY_PACKAGE_",_ENTITY_PACKAGE_).replace("_PACKAGE_",_PACKAGE_)
""" Created on Sun Feb 26 17:29:16 2017 @author: Thautwarm """ template = '\npackage _PACKAGE_;\nimport _ENTITY_PACKAGE_;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport GraceJava.SQL;\nimport GraceJava.ToStr;\npublic class _ENTITY_CLASS_NAME_Dao extends SQL{\n\n\tpublic _ENTITY_CLASS_NAME_Dao() {\n\t\tsetTypeMap(_ENTITY_CLASS_NAME_.getTypeMap());\n\t\tsetTableName("_ENTITY_OBJ_NAME_");\n\t}\n\tpublic ArrayList<_ENTITY_CLASS_NAME_> selectEntity(String columns,String MatchValues){\n\t\tArrayList<_ENTITY_CLASS_NAME_> _ENTITY_OBJ_NAME_List= new ArrayList<_ENTITY_CLASS_NAME_>();\n\t\tResultSet res =Select(_ENTITY_CLASS_NAME_.toSQLColumns(),columns,MatchValues);\n\t\tString[] columnsKeys=columns.split(",");\n\t\ttry{\n\t\twhile(res.next()){\n\t\t\t_ENTITY_CLASS_NAME_ _ENTITY_OBJ_NAME_=new _ENTITY_CLASS_NAME_();\n\t\t\tfor(String column:columnsKeys){\n\t\t\t\t\n\t\t\t\tObject obj=null;\n\t\t\t\tString type=this.TypeMap.get(column);\n\t\t\t\tswitch (type){\n \n\t\t\t\tcase "Integer":\n\t\t\t\t\tobj=res.getInt(column);\n\t\t\t\t\tbreak;\n\t\t\t\tcase "String":\n\t\t\t\t\tobj=res.getString(column);\n\t\t\t\t\tbreak;\n\t\t\t\tcase "Date":\n\t\t\t\t\tobj= ToStr.Timestamp2Date(res.getTimestamp(column));\n\t\t\t\t\tbreak;\n\t\t\t\tcase "Double":\n\t\t\t\t\tobj= res.getDouble(column);\n\t\t\t\t\tbreak;\n\t\t\t\tcase "Long":\n\t\t\t\t\tobj= res.getLong(column);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif (obj==null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t_ENTITY_OBJ_NAME_.setByKey(column, obj);\n\t\t\t}\n\t\t\t_ENTITY_OBJ_NAME_List.add(_ENTITY_OBJ_NAME_);\n\t\t\t}\n\t\t}\n\t\tcatch (SQLException e){\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn _ENTITY_OBJ_NAME_List;\n\t}\n\tpublic ArrayList<_ENTITY_CLASS_NAME_> selectEntity(String columns,Object ...MatchValues){\n\t\tArrayList<_ENTITY_CLASS_NAME_> _ENTITY_OBJ_NAME_List= new ArrayList<_ENTITY_CLASS_NAME_>();\n\t\tResultSet res =Select(_ENTITY_CLASS_NAME_.toSQLColumns(),columns,MatchValues);\n\t\tString[] columnsKeys=columns.split(",");\n\t\ttry{\n\t\twhile(res.next()){\n\t\t\t_ENTITY_CLASS_NAME_ _ENTITY_OBJ_NAME_=new _ENTITY_CLASS_NAME_();\n\t\t\tfor(String column:columnsKeys){\n\t\t\t\t\n\t\t\t\tObject obj=null;\n\t\t\t\tString type=this.TypeMap.get(column);\n\t\t\t\tswitch (type){\n \n\t\t\t\tcase "Integer":\n\t\t\t\t\tobj=res.getInt(column);\n\t\t\t\t\tbreak;\n\t\t\t\tcase "String":\n\t\t\t\t\tobj=res.getString(column);\n\t\t\t\t\tbreak;\n\t\t\t\tcase "Date":\n\t\t\t\t\tobj= ToStr.Timestamp2Date(res.getTimestamp(column));\n\t\t\t\t\tbreak;\n\t\t\t\tcase "Double":\n\t\t\t\t\tobj= res.getDouble(column);\n\t\t\t\t\tbreak;\n\t\t\t\tcase "Long":\n\t\t\t\t\tobj= res.getLong(column);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif (obj==null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t_ENTITY_OBJ_NAME_.setByKey(column, obj);\n\t\t\t}\n\t\t\t_ENTITY_OBJ_NAME_List.add(_ENTITY_OBJ_NAME_);\n\t\t\t}\n\t\t}\n\t\tcatch (SQLException e){\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn _ENTITY_OBJ_NAME_List;\n\t}\n \tpublic ArrayList<_ENTITY_CLASS_NAME_> selectEntity(_ENTITY_CLASS_NAME_ _ENTITY_OBJ_NAME_Select){\n String MatchValues=_ENTITY_OBJ_NAME_Select.toSQLValues();\n\t\tArrayList<_ENTITY_CLASS_NAME_> _ENTITY_OBJ_NAME_List= new ArrayList<_ENTITY_CLASS_NAME_>();\n\t\tString columns=_ENTITY_CLASS_NAME_.toSQLColumns();\n\t\tResultSet res =Select(_ENTITY_CLASS_NAME_.toSQLColumns(),columns,MatchValues);\n\t\tString[] columnsKeys=columns.split(",");\n\t\ttry{\n\t\twhile(res.next()){\n\t\t\t_ENTITY_CLASS_NAME_ _ENTITY_OBJ_NAME_=new _ENTITY_CLASS_NAME_();\n\t\t\tfor(String column:columnsKeys){\n\t\t\t\t\n\t\t\t\t\tObject obj=null;\n\t\t\t\tString type=this.TypeMap.get(column);\n\t\t\t\tswitch (type){\n \n\t\t\t\tcase "Integer":\n\t\t\t\t\tobj=res.getInt(column);\n\t\t\t\t\tbreak;\n\t\t\t\tcase "String":\n\t\t\t\t\tobj=res.getString(column);\n\t\t\t\t\tbreak;\n\t\t\t\tcase "Date":\n\t\t\t\t\tobj= ToStr.Timestamp2Date(res.getTimestamp(column));\n\t\t\t\t\tbreak;\n\t\t\t\tcase "Double":\n\t\t\t\t\tobj= res.getDouble(column);\n\t\t\t\t\tbreak;\n\t\t\t\tcase "Long":\n\t\t\t\t\tobj= res.getLong(column);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif (obj==null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t_ENTITY_OBJ_NAME_.setByKey(column, obj);\n\t\t\t}\n\t\t\t_ENTITY_OBJ_NAME_List.add(_ENTITY_OBJ_NAME_);\n\t\t\t}\n\t\t}\n\t\tcatch (SQLException e){\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn _ENTITY_OBJ_NAME_List;\n\t}\n\tpublic boolean add(_ENTITY_CLASS_NAME_ _ENTITY_OBJ_NAME_){\n\t\tif (isDuplicatedByKey("id",_ENTITY_OBJ_NAME_.getId()).equals("No")){\n\t\t\treturn addEntity(_ENTITY_CLASS_NAME_.toSQLColumns(),_ENTITY_OBJ_NAME_.toSQLValues());\n\t\t}\n System.out.println("add_ENTITY_CLASS_NAME_Error-DuplicatedAdded.");\n\t\treturn false;\n\t}\n}\n' def get_dao(_ENTITY_CLASS_NAME_, _ENTITY_PACKAGE_=None, _PACKAGE_='dao'): _entity_obj_name_ = _ENTITY_CLASS_NAME_.lower() if not _ENTITY_PACKAGE_: _entity_package_ = 'entity.%s' % _ENTITY_CLASS_NAME_ return template.replace('_ENTITY_CLASS_NAME_', _ENTITY_CLASS_NAME_).replace('_ENTITY_OBJ_NAME_', _ENTITY_OBJ_NAME_).replace('_ENTITY_PACKAGE_', _ENTITY_PACKAGE_).replace('_PACKAGE_', _PACKAGE_)
def wordInTarget(word, target): ''' Can a 'word', be made using letters from 'target'. ''' targetlist = list(target) i = 0 while i < len(word): letter = word[i] if letter in targetlist: targetlist.remove(letter) i += 1 else: return False return True
def word_in_target(word, target): """ Can a 'word', be made using letters from 'target'. """ targetlist = list(target) i = 0 while i < len(word): letter = word[i] if letter in targetlist: targetlist.remove(letter) i += 1 else: return False return True
N = int(input()) first_word = input() W = [input() for _ in range(N - 1)] last = first_word[-1] word_set = set([first_word]) for w in W: if w[0] != last or w in word_set: print("No") break word_set.add(w) last = w[-1] else: print("Yes")
n = int(input()) first_word = input() w = [input() for _ in range(N - 1)] last = first_word[-1] word_set = set([first_word]) for w in W: if w[0] != last or w in word_set: print('No') break word_set.add(w) last = w[-1] else: print('Yes')
''' este grupo de numeros tiene un bucle, digamos que hacemos el algoritmo para "x" numero la sucesion comenzara con (2, 2x, 2, ... , 2, 2x, 2, ...) donde ... es un bucle entonces cuando 2x aparezca por segunda vez cortamos alli la sucesion y sacamos el maximo ''' def algoritmo(a): lista = [] i = 0 cont = 0 xam = 0 n = 0 while(True): r = ((a - 1) ** n + (a + 1) ** n ) % (a ** 2) lista.append(r) i += 1 n += 1 if r == 2 * a: cont += 1 if cont == 2: lista = lista[0: i - 2] xam = max(lista) break return(xam) total = 0 for a in range(3, 1000 + 1): total += algoritmo(a) print(total)
""" este grupo de numeros tiene un bucle, digamos que hacemos el algoritmo para "x" numero la sucesion comenzara con (2, 2x, 2, ... , 2, 2x, 2, ...) donde ... es un bucle entonces cuando 2x aparezca por segunda vez cortamos alli la sucesion y sacamos el maximo """ def algoritmo(a): lista = [] i = 0 cont = 0 xam = 0 n = 0 while True: r = ((a - 1) ** n + (a + 1) ** n) % a ** 2 lista.append(r) i += 1 n += 1 if r == 2 * a: cont += 1 if cont == 2: lista = lista[0:i - 2] xam = max(lista) break return xam total = 0 for a in range(3, 1000 + 1): total += algoritmo(a) print(total)
def getConfidenceInterval(df): """ Compute 95% confidence interval (frequentist approach) Args: dataframe: first column is name(string), second column is score(numeric) Return: dataframe(three columns:name,lower_bound,upper_bound) """ pass def getCredibleInterval(df): """ compute 95% credible interval (bayesian approach) Args: dataframe: first column is name(string), second column is score(numeric) Return: dataframe(three columns:name,lower_bound,upper_bound) """ pass
def get_confidence_interval(df): """ Compute 95% confidence interval (frequentist approach) Args: dataframe: first column is name(string), second column is score(numeric) Return: dataframe(three columns:name,lower_bound,upper_bound) """ pass def get_credible_interval(df): """ compute 95% credible interval (bayesian approach) Args: dataframe: first column is name(string), second column is score(numeric) Return: dataframe(three columns:name,lower_bound,upper_bound) """ pass
""" https://leetcode.com/problems/special-positions-in-a-binary-matrix/ Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return the number of special positions in mat. A position (i,j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed). Example 1: Input: mat = [[1,0,0], [0,0,1], [1,0,0]] Output: 1 Explanation: (1,2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0. Example 2: Input: mat = [[1,0,0], [0,1,0], [0,0,1]] Output: 3 Explanation: (0,0), (1,1) and (2,2) are special positions. Example 3: Input: mat = [[0,0,0,1], [1,0,0,0], [0,1,1,0], [0,0,0,0]] Output: 2 Example 4: Input: mat = [[0,0,0,0,0], [1,0,0,0,0], [0,1,0,0,0], [0,0,1,0,0], [0,0,0,1,1]] Output: 3 Constraints: rows == mat.length cols == mat[i].length 1 <= rows, cols <= 100 mat[i][j] is 0 or 1. """ # time complexity: O(row*column), space complexity: O(column) class Solution: def numSpecial(self, mat: List[List[int]]) -> int: columns = set() for i in range(len(mat)): if sum(mat[i]) == 1: column = mat[i].index(1) if column not in columns and column-200 not in columns: columns.add(column) elif column in columns: columns.remove(column) columns.add(column-200) result = 0 for column in columns: if column >= 0: found = 0 for row in range(len(mat)): if mat[row][column] == 1: found += 1 if found > 1: break if found == 1: result += 1 return result
""" https://leetcode.com/problems/special-positions-in-a-binary-matrix/ Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return the number of special positions in mat. A position (i,j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed). Example 1: Input: mat = [[1,0,0], [0,0,1], [1,0,0]] Output: 1 Explanation: (1,2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0. Example 2: Input: mat = [[1,0,0], [0,1,0], [0,0,1]] Output: 3 Explanation: (0,0), (1,1) and (2,2) are special positions. Example 3: Input: mat = [[0,0,0,1], [1,0,0,0], [0,1,1,0], [0,0,0,0]] Output: 2 Example 4: Input: mat = [[0,0,0,0,0], [1,0,0,0,0], [0,1,0,0,0], [0,0,1,0,0], [0,0,0,1,1]] Output: 3 Constraints: rows == mat.length cols == mat[i].length 1 <= rows, cols <= 100 mat[i][j] is 0 or 1. """ class Solution: def num_special(self, mat: List[List[int]]) -> int: columns = set() for i in range(len(mat)): if sum(mat[i]) == 1: column = mat[i].index(1) if column not in columns and column - 200 not in columns: columns.add(column) elif column in columns: columns.remove(column) columns.add(column - 200) result = 0 for column in columns: if column >= 0: found = 0 for row in range(len(mat)): if mat[row][column] == 1: found += 1 if found > 1: break if found == 1: result += 1 return result
class FpsCounter: def __init__(self, update_interval_seconds = 0.5): """ read self.fps for output """ self.fps = 0. self.interval = update_interval_seconds self._counter = 0. self._age = 0. self._last_output_age = 0. def tick(self, dt): self._age += dt self._counter += 1. if self._age > self.interval: self.fps = self._counter / self._age self._age = 0. self._counter = 0. #print "fps:", self.fps
class Fpscounter: def __init__(self, update_interval_seconds=0.5): """ read self.fps for output """ self.fps = 0.0 self.interval = update_interval_seconds self._counter = 0.0 self._age = 0.0 self._last_output_age = 0.0 def tick(self, dt): self._age += dt self._counter += 1.0 if self._age > self.interval: self.fps = self._counter / self._age self._age = 0.0 self._counter = 0.0
'''> Greater that - True if left operand is greater than the right x > y < Less that - True if left operand is less than the right x < y == Equal to - True if both operands are equal x == y != Not equal to - True if operands are not equal x != y >= Greater than or equal to - True if left operand is greater than or equal to the right x >= y <= Less than or equal to - True if left operand is less than or equal to the right x <= y''' x = 10 y = 12 # Output: x > y is False print('x > y is',x>y) # Output: x < y is True print('x < y is',x<y) # Output: x == y is False print('x == y is',x==y) # Output: x != y is True print('x != y is',x!=y) # Output: x >= y is False print('x >= y is',x>=y) # Output: x <= y is True print('x <= y is',x<=y)
"""> Greater that - True if left operand is greater than the right x > y < Less that - True if left operand is less than the right x < y == Equal to - True if both operands are equal x == y != Not equal to - True if operands are not equal x != y >= Greater than or equal to - True if left operand is greater than or equal to the right x >= y <= Less than or equal to - True if left operand is less than or equal to the right x <= y""" x = 10 y = 12 print('x > y is', x > y) print('x < y is', x < y) print('x == y is', x == y) print('x != y is', x != y) print('x >= y is', x >= y) print('x <= y is', x <= y)
expected_output = { "vrf": { "default": { "address_family": { "ipv4": { "instance": { "65109": { "areas": { "0.0.0.8": { "database": { "lsa_types": { 1: { "lsa_type": 1, "lsas": { "192.168.165.220": { "adv_router": "192.168.165.220", "lsa_id": "192.168.165.220", "ospfv2": { "header": { "adv_router": "192.168.165.220", "age": 113, "checksum": "0x007C93", "link_count": 2, "lsa_id": "192.168.165.220", "seq_num": "0x800006E3", } }, }, "192.168.255.0": { "adv_router": "192.168.255.0", "lsa_id": "192.168.255.0", "ospfv2": { "header": { "adv_router": "192.168.255.0", "age": 1407, "checksum": "0x00ADD6", "link_count": 501, "lsa_id": "192.168.255.0", "seq_num": "0x800007BC", } }, }, "10.22.102.64": { "adv_router": "10.22.102.64", "lsa_id": "10.22.102.64", "ospfv2": { "header": { "adv_router": "10.22.102.64", "age": 2220, "checksum": "0x008BD8", "link_count": 3, "lsa_id": "10.22.102.64", "seq_num": "0x800003EC", } }, }, "172.31.197.252": { "adv_router": "172.31.197.252", "lsa_id": "172.31.197.252", "ospfv2": { "header": { "adv_router": "172.31.197.252", "age": 1272, "checksum": "0x00B9E5", "link_count": 6, "lsa_id": "172.31.197.252", "seq_num": "0x80000DBD", } }, }, "172.31.197.253": { "adv_router": "172.31.197.253", "lsa_id": "172.31.197.253", "ospfv2": { "header": { "adv_router": "172.31.197.253", "age": 663, "checksum": "0x00FFD8", "link_count": 4, "lsa_id": "172.31.197.253", "seq_num": "0x8000009D", } }, }, "172.31.197.254": { "adv_router": "172.31.197.254", "lsa_id": "172.31.197.254", "ospfv2": { "header": { "adv_router": "172.31.197.254", "age": 1900, "checksum": "0x00D029", "link_count": 3, "lsa_id": "172.31.197.254", "seq_num": "0x800000D9", } }, }, }, }, 2: { "lsa_type": 2, "lsas": { "192.168.255.0": { "adv_router": "172.31.197.252", "lsa_id": "192.168.255.0", "ospfv2": { "header": { "adv_router": "172.31.197.252", "age": 26, "checksum": "0x009E8D", "lsa_id": "192.168.255.0", "seq_num": "0x800000D1", } }, }, "10.22.102.50": { "adv_router": "10.22.102.64", "lsa_id": "10.22.102.50", "ospfv2": { "header": { "adv_router": "10.22.102.64", "age": 220, "checksum": "0x003A0A", "lsa_id": "10.22.102.50", "seq_num": "0x800000AD", } }, }, "10.22.102.58": { "adv_router": "10.22.102.64", "lsa_id": "10.22.102.58", "ospfv2": { "header": { "adv_router": "10.22.102.64", "age": 1220, "checksum": "0x00E2CD", "lsa_id": "10.22.102.58", "seq_num": "0x80000038", } }, }, "172.31.197.102": { "adv_router": "192.168.165.220", "lsa_id": "172.31.197.102", "ospfv2": { "header": { "adv_router": "192.168.165.220", "age": 113, "checksum": "0x009ACA", "lsa_id": "172.31.197.102", "seq_num": "0x80000055", } }, }, "172.31.197.94": { "adv_router": "172.31.197.254", "lsa_id": "172.31.197.94", "ospfv2": { "header": { "adv_router": "172.31.197.254", "age": 911, "checksum": "0x007ACC", "lsa_id": "172.31.197.94", "seq_num": "0x80000052", } }, }, "172.31.197.97": { "adv_router": "172.31.197.253", "lsa_id": "172.31.197.97", "ospfv2": { "header": { "adv_router": "172.31.197.253", "age": 663, "checksum": "0x00AAB4", "lsa_id": "172.31.197.97", "seq_num": "0x80000037", } }, }, }, }, 3: { "lsa_type": 3, "lsas": { "192.168.165.119": { "adv_router": "172.31.197.252", "lsa_id": "192.168.165.119", "ospfv2": { "header": { "adv_router": "172.31.197.252", "age": 1030, "checksum": "0x007847", "lsa_id": "192.168.165.119", "seq_num": "0x800000D4", } }, }, "192.168.165.120": { "adv_router": "172.31.197.252", "lsa_id": "192.168.165.120", "ospfv2": { "header": { "adv_router": "172.31.197.252", "age": 26, "checksum": "0x005160", "lsa_id": "192.168.165.120", "seq_num": "0x800003DE", } }, }, "192.168.165.48": { "adv_router": "172.31.197.252", "lsa_id": "192.168.165.48", "ospfv2": { "header": { "adv_router": "172.31.197.252", "age": 26, "checksum": "0x0006F6", "lsa_id": "192.168.165.48", "seq_num": "0x800003DF", } }, }, "192.168.165.56": { "adv_router": "172.31.197.252", "lsa_id": "192.168.165.56", "ospfv2": { "header": { "adv_router": "172.31.197.252", "age": 1779, "checksum": "0x00D42E", "lsa_id": "192.168.165.56", "seq_num": "0x800000D4", } }, }, }, }, 4: { "lsa_type": 4, "lsas": { "192.168.165.119": { "adv_router": "172.31.197.252", "lsa_id": "192.168.165.119", "ospfv2": { "header": { "adv_router": "172.31.197.252", "age": 1030, "checksum": "0x00605F", "lsa_id": "192.168.165.119", "seq_num": "0x800000D4", } }, }, "192.168.165.120": { "adv_router": "172.31.197.252", "lsa_id": "192.168.165.120", "ospfv2": { "header": { "adv_router": "172.31.197.252", "age": 26, "checksum": "0x003978", "lsa_id": "192.168.165.120", "seq_num": "0x800003DE", } }, }, }, }, } } } } } } } } } } }
expected_output = {'vrf': {'default': {'address_family': {'ipv4': {'instance': {'65109': {'areas': {'0.0.0.8': {'database': {'lsa_types': {1: {'lsa_type': 1, 'lsas': {'192.168.165.220': {'adv_router': '192.168.165.220', 'lsa_id': '192.168.165.220', 'ospfv2': {'header': {'adv_router': '192.168.165.220', 'age': 113, 'checksum': '0x007C93', 'link_count': 2, 'lsa_id': '192.168.165.220', 'seq_num': '0x800006E3'}}}, '192.168.255.0': {'adv_router': '192.168.255.0', 'lsa_id': '192.168.255.0', 'ospfv2': {'header': {'adv_router': '192.168.255.0', 'age': 1407, 'checksum': '0x00ADD6', 'link_count': 501, 'lsa_id': '192.168.255.0', 'seq_num': '0x800007BC'}}}, '10.22.102.64': {'adv_router': '10.22.102.64', 'lsa_id': '10.22.102.64', 'ospfv2': {'header': {'adv_router': '10.22.102.64', 'age': 2220, 'checksum': '0x008BD8', 'link_count': 3, 'lsa_id': '10.22.102.64', 'seq_num': '0x800003EC'}}}, '172.31.197.252': {'adv_router': '172.31.197.252', 'lsa_id': '172.31.197.252', 'ospfv2': {'header': {'adv_router': '172.31.197.252', 'age': 1272, 'checksum': '0x00B9E5', 'link_count': 6, 'lsa_id': '172.31.197.252', 'seq_num': '0x80000DBD'}}}, '172.31.197.253': {'adv_router': '172.31.197.253', 'lsa_id': '172.31.197.253', 'ospfv2': {'header': {'adv_router': '172.31.197.253', 'age': 663, 'checksum': '0x00FFD8', 'link_count': 4, 'lsa_id': '172.31.197.253', 'seq_num': '0x8000009D'}}}, '172.31.197.254': {'adv_router': '172.31.197.254', 'lsa_id': '172.31.197.254', 'ospfv2': {'header': {'adv_router': '172.31.197.254', 'age': 1900, 'checksum': '0x00D029', 'link_count': 3, 'lsa_id': '172.31.197.254', 'seq_num': '0x800000D9'}}}}}, 2: {'lsa_type': 2, 'lsas': {'192.168.255.0': {'adv_router': '172.31.197.252', 'lsa_id': '192.168.255.0', 'ospfv2': {'header': {'adv_router': '172.31.197.252', 'age': 26, 'checksum': '0x009E8D', 'lsa_id': '192.168.255.0', 'seq_num': '0x800000D1'}}}, '10.22.102.50': {'adv_router': '10.22.102.64', 'lsa_id': '10.22.102.50', 'ospfv2': {'header': {'adv_router': '10.22.102.64', 'age': 220, 'checksum': '0x003A0A', 'lsa_id': '10.22.102.50', 'seq_num': '0x800000AD'}}}, '10.22.102.58': {'adv_router': '10.22.102.64', 'lsa_id': '10.22.102.58', 'ospfv2': {'header': {'adv_router': '10.22.102.64', 'age': 1220, 'checksum': '0x00E2CD', 'lsa_id': '10.22.102.58', 'seq_num': '0x80000038'}}}, '172.31.197.102': {'adv_router': '192.168.165.220', 'lsa_id': '172.31.197.102', 'ospfv2': {'header': {'adv_router': '192.168.165.220', 'age': 113, 'checksum': '0x009ACA', 'lsa_id': '172.31.197.102', 'seq_num': '0x80000055'}}}, '172.31.197.94': {'adv_router': '172.31.197.254', 'lsa_id': '172.31.197.94', 'ospfv2': {'header': {'adv_router': '172.31.197.254', 'age': 911, 'checksum': '0x007ACC', 'lsa_id': '172.31.197.94', 'seq_num': '0x80000052'}}}, '172.31.197.97': {'adv_router': '172.31.197.253', 'lsa_id': '172.31.197.97', 'ospfv2': {'header': {'adv_router': '172.31.197.253', 'age': 663, 'checksum': '0x00AAB4', 'lsa_id': '172.31.197.97', 'seq_num': '0x80000037'}}}}}, 3: {'lsa_type': 3, 'lsas': {'192.168.165.119': {'adv_router': '172.31.197.252', 'lsa_id': '192.168.165.119', 'ospfv2': {'header': {'adv_router': '172.31.197.252', 'age': 1030, 'checksum': '0x007847', 'lsa_id': '192.168.165.119', 'seq_num': '0x800000D4'}}}, '192.168.165.120': {'adv_router': '172.31.197.252', 'lsa_id': '192.168.165.120', 'ospfv2': {'header': {'adv_router': '172.31.197.252', 'age': 26, 'checksum': '0x005160', 'lsa_id': '192.168.165.120', 'seq_num': '0x800003DE'}}}, '192.168.165.48': {'adv_router': '172.31.197.252', 'lsa_id': '192.168.165.48', 'ospfv2': {'header': {'adv_router': '172.31.197.252', 'age': 26, 'checksum': '0x0006F6', 'lsa_id': '192.168.165.48', 'seq_num': '0x800003DF'}}}, '192.168.165.56': {'adv_router': '172.31.197.252', 'lsa_id': '192.168.165.56', 'ospfv2': {'header': {'adv_router': '172.31.197.252', 'age': 1779, 'checksum': '0x00D42E', 'lsa_id': '192.168.165.56', 'seq_num': '0x800000D4'}}}}}, 4: {'lsa_type': 4, 'lsas': {'192.168.165.119': {'adv_router': '172.31.197.252', 'lsa_id': '192.168.165.119', 'ospfv2': {'header': {'adv_router': '172.31.197.252', 'age': 1030, 'checksum': '0x00605F', 'lsa_id': '192.168.165.119', 'seq_num': '0x800000D4'}}}, '192.168.165.120': {'adv_router': '172.31.197.252', 'lsa_id': '192.168.165.120', 'ospfv2': {'header': {'adv_router': '172.31.197.252', 'age': 26, 'checksum': '0x003978', 'lsa_id': '192.168.165.120', 'seq_num': '0x800003DE'}}}}}}}}}}}}}}}}
"""Graphite-beacon -- simple alerting system for Graphite.""" __version__ = "0.27.5" __license__ = "MIT"
"""Graphite-beacon -- simple alerting system for Graphite.""" __version__ = '0.27.5' __license__ = 'MIT'
{ "variables": { "major_version": "<!(node -pe 'v=process.versions.node.split(\".\"); v[0];')", "minor_version": "<!(node -pe 'v=process.versions.node.split(\".\"); v[1];')", "micro_version": "<!(node -pe 'v=process.versions.node.split(\".\"); v[2];')" }, "targets": [ { "target_name": "poppler", "sources": [ "src/poppler.cc", "src/NodePopplerDocument.cc", "src/NodePopplerPage.cc", "src/iconv_string.cc", "src/MemoryStream.cc" ], "libraries": [ "<!@(pkg-config --libs poppler)" ], "cflags": [ "<!@(pkg-config --cflags poppler)" ], "defines": [ "NODE_VERSION_MAJOR=<(major_version)", "NODE_VERSION_MINOR=<(minor_version)", "NODE_VERSION_MICRO=<(micro_version)" ], "conditions": [ ['OS=="mac"', { 'xcode_settings': { 'OTHER_CFLAGS': [ "<!@(pkg-config --cflags poppler)", "<!@(dirname -- `pkg-config --cflags poppler`)", "-stdlib=libc++" ], "OTHER_LDFLAGS": [ "-liconv" ] }, }], ['OS!="win"', { 'cflags_cc+': [ '-std=c++14', ], }], ], "include_dirs": [ "<!(node -e \"require('nan')\")" ] } ] }
{'variables': {'major_version': '<!(node -pe \'v=process.versions.node.split("."); v[0];\')', 'minor_version': '<!(node -pe \'v=process.versions.node.split("."); v[1];\')', 'micro_version': '<!(node -pe \'v=process.versions.node.split("."); v[2];\')'}, 'targets': [{'target_name': 'poppler', 'sources': ['src/poppler.cc', 'src/NodePopplerDocument.cc', 'src/NodePopplerPage.cc', 'src/iconv_string.cc', 'src/MemoryStream.cc'], 'libraries': ['<!@(pkg-config --libs poppler)'], 'cflags': ['<!@(pkg-config --cflags poppler)'], 'defines': ['NODE_VERSION_MAJOR=<(major_version)', 'NODE_VERSION_MINOR=<(minor_version)', 'NODE_VERSION_MICRO=<(micro_version)'], 'conditions': [['OS=="mac"', {'xcode_settings': {'OTHER_CFLAGS': ['<!@(pkg-config --cflags poppler)', '<!@(dirname -- `pkg-config --cflags poppler`)', '-stdlib=libc++'], 'OTHER_LDFLAGS': ['-liconv']}}], ['OS!="win"', {'cflags_cc+': ['-std=c++14']}]], 'include_dirs': ['<!(node -e "require(\'nan\')")']}]}
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, root: TreeNode): if not root: return [] parents = [root] res = [] while parents: cur_values = [] next_nodes = [] for node in parents: cur_values.append(node.val) if node.left: next_nodes.append(node.left) if node.right: next_nodes.append(node.right) parents = next_nodes res.append(cur_values) return res l1 = TreeNode(5) l1.left = TreeNode(1) l1.left.left = TreeNode(4) l1.right = TreeNode(2) l1.right.right = TreeNode(3) slu = Solution() print(slu.levelOrder(l1))
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def level_order(self, root: TreeNode): if not root: return [] parents = [root] res = [] while parents: cur_values = [] next_nodes = [] for node in parents: cur_values.append(node.val) if node.left: next_nodes.append(node.left) if node.right: next_nodes.append(node.right) parents = next_nodes res.append(cur_values) return res l1 = tree_node(5) l1.left = tree_node(1) l1.left.left = tree_node(4) l1.right = tree_node(2) l1.right.right = tree_node(3) slu = solution() print(slu.levelOrder(l1))
def get_stats(data, country_list=None): country_list = list(country_list) country_list_slugs = [] country_list_codes = [] error_lst = [] cases = [] new_cases = [] deaths = [] new_deaths = [] recovered = [] new_recovered = [] names = [] codes = [] stats = [] if not country_list: cases.append(data["Global"]["TotalConfirmed"]) new_cases.append(data["Global"]["NewConfirmed"]) deaths.append(data["Global"]["TotalDeaths"]) new_deaths.append(data["Global"]["NewDeaths"]) recovered.append(data["Global"]["TotalRecovered"]) new_recovered.append(data["Global"]["NewRecovered"]) stats.append(cases) stats.append(deaths) stats.append(recovered) if new_cases != 0: cases = f'**{format(int(cases[0]), ",d")}**' + " (+" + format(int(new_cases[0]), ",d") + ")" if new_deaths != 0: deaths = f'**{format(int(deaths[0]), ",d")}**' + " (+" + format(int(new_deaths[0]), ",d") + ")" if new_recovered != 0: recovered = f'**{format(int(recovered[0]), ",d")}**' + " (+" + format(int(new_recovered[0]), ",d") + ")" else: for i in range(0, len(country_list)): if len(country_list[i]) > 2: country_list[i] = country_list[i].lower() else: country_list[i] = country_list[i].upper() country_list = ["GB" if x == "UK" else x for x in country_list] country_list = ["korea-south" if x == "south-korea" else x for x in country_list] country_list = ["korea-south" if x == "korea" else x for x in country_list] country_list = ["korea-north" if x == "north-korea" else x for x in country_list] country_list = ["US" if x == "usa" else x for x in country_list] country_list = ["US" if x == "united-states-of-america" else x for x in country_list] slug = list(filter(lambda change_name: change_name["Slug"] in country_list, data["Countries"])) for i in range(0, len(slug)): country_list_codes.append(slug[i]["CountryCode"]) country_list_slugs.append(slug[i]["Slug"]) code = list(filter(lambda change_name: change_name["CountryCode"] in country_list, data["Countries"])) for i in range(0, len(code)): country_list_codes.append(code[i]["CountryCode"]) country_list_slugs.append(code[i]["Slug"]) for i in range(0, len(country_list)): if str.upper(country_list[i]) not in country_list_codes and str.lower(country_list[i]) not in country_list_slugs: error_lst.append(country_list[i]) for i in range(0, len(error_lst)): country_list.remove(error_lst[i]) new_lst = slug + code lst = sorted(new_lst, key=lambda item_num: item_num["Country"]) for i in range(0, len(lst)): cases.append(lst[i]["TotalConfirmed"]) new_cases.append(lst[i]["NewConfirmed"]) deaths.append(lst[i]["TotalDeaths"]) new_deaths.append(lst[i]["NewDeaths"]) recovered.append(lst[i]["TotalRecovered"]) new_recovered.append(lst[i]["NewRecovered"]) names.append(lst[i]["Country"]) codes.append(lst[i]["CountryCode"]) stats.append(lst[i]["TotalConfirmed"]) stats.append(lst[i]["TotalDeaths"]) stats.append(lst[i]["TotalRecovered"]) if new_cases[i] != 0: cases[i] = f'**{format(int(cases[i]), ",d")}**' + " (+" + format(int(new_cases[i]), ",d") + ")" else: cases[i] = f'**{format(int(cases[i]), ",d")}**' if new_deaths[i] != 0: deaths[i] = f'**{format(int(deaths[i]), ",d")}**' + " (+" + format(int(new_deaths[i]), ",d") + ")" else: deaths[i] = f'**{format(int(deaths[i]), ",d")}**' if new_recovered[i] != 0: recovered[i] = f'**{format(int(recovered[i]), ",d")}**' + " (+" + format(int(new_recovered[i]), ",d") + ")" else: recovered[i] = f'**{format(int(recovered[i]), ",d")}**' return cases, deaths, recovered, names, codes, error_lst, stats
def get_stats(data, country_list=None): country_list = list(country_list) country_list_slugs = [] country_list_codes = [] error_lst = [] cases = [] new_cases = [] deaths = [] new_deaths = [] recovered = [] new_recovered = [] names = [] codes = [] stats = [] if not country_list: cases.append(data['Global']['TotalConfirmed']) new_cases.append(data['Global']['NewConfirmed']) deaths.append(data['Global']['TotalDeaths']) new_deaths.append(data['Global']['NewDeaths']) recovered.append(data['Global']['TotalRecovered']) new_recovered.append(data['Global']['NewRecovered']) stats.append(cases) stats.append(deaths) stats.append(recovered) if new_cases != 0: cases = f"**{format(int(cases[0]), ',d')}**" + ' (+' + format(int(new_cases[0]), ',d') + ')' if new_deaths != 0: deaths = f"**{format(int(deaths[0]), ',d')}**" + ' (+' + format(int(new_deaths[0]), ',d') + ')' if new_recovered != 0: recovered = f"**{format(int(recovered[0]), ',d')}**" + ' (+' + format(int(new_recovered[0]), ',d') + ')' else: for i in range(0, len(country_list)): if len(country_list[i]) > 2: country_list[i] = country_list[i].lower() else: country_list[i] = country_list[i].upper() country_list = ['GB' if x == 'UK' else x for x in country_list] country_list = ['korea-south' if x == 'south-korea' else x for x in country_list] country_list = ['korea-south' if x == 'korea' else x for x in country_list] country_list = ['korea-north' if x == 'north-korea' else x for x in country_list] country_list = ['US' if x == 'usa' else x for x in country_list] country_list = ['US' if x == 'united-states-of-america' else x for x in country_list] slug = list(filter(lambda change_name: change_name['Slug'] in country_list, data['Countries'])) for i in range(0, len(slug)): country_list_codes.append(slug[i]['CountryCode']) country_list_slugs.append(slug[i]['Slug']) code = list(filter(lambda change_name: change_name['CountryCode'] in country_list, data['Countries'])) for i in range(0, len(code)): country_list_codes.append(code[i]['CountryCode']) country_list_slugs.append(code[i]['Slug']) for i in range(0, len(country_list)): if str.upper(country_list[i]) not in country_list_codes and str.lower(country_list[i]) not in country_list_slugs: error_lst.append(country_list[i]) for i in range(0, len(error_lst)): country_list.remove(error_lst[i]) new_lst = slug + code lst = sorted(new_lst, key=lambda item_num: item_num['Country']) for i in range(0, len(lst)): cases.append(lst[i]['TotalConfirmed']) new_cases.append(lst[i]['NewConfirmed']) deaths.append(lst[i]['TotalDeaths']) new_deaths.append(lst[i]['NewDeaths']) recovered.append(lst[i]['TotalRecovered']) new_recovered.append(lst[i]['NewRecovered']) names.append(lst[i]['Country']) codes.append(lst[i]['CountryCode']) stats.append(lst[i]['TotalConfirmed']) stats.append(lst[i]['TotalDeaths']) stats.append(lst[i]['TotalRecovered']) if new_cases[i] != 0: cases[i] = f"**{format(int(cases[i]), ',d')}**" + ' (+' + format(int(new_cases[i]), ',d') + ')' else: cases[i] = f"**{format(int(cases[i]), ',d')}**" if new_deaths[i] != 0: deaths[i] = f"**{format(int(deaths[i]), ',d')}**" + ' (+' + format(int(new_deaths[i]), ',d') + ')' else: deaths[i] = f"**{format(int(deaths[i]), ',d')}**" if new_recovered[i] != 0: recovered[i] = f"**{format(int(recovered[i]), ',d')}**" + ' (+' + format(int(new_recovered[i]), ',d') + ')' else: recovered[i] = f"**{format(int(recovered[i]), ',d')}**" return (cases, deaths, recovered, names, codes, error_lst, stats)
def sum_up_diagonals(matrix): """Given a matrix [square list of lists], return sum of diagonals. Sum of TL-to-BR diagonal along with BL-to-TR diagonal: >>> m1 = [ ... [1, 2], ... [30, 40], ... ] >>> sum_up_diagonals(m1) 73 >>> m2 = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9], ... ] >>> sum_up_diagonals(m2) 30 """ # unq_set = set(matrix) lst = [] total = 0 for x in matrix: lst.append(list(x)) length_of_matrix = len(matrix) if length_of_matrix == 2: tl = lst[0][0] + lst[1][1] br = lst[0][1] + lst[1][0] total = tl + br if length_of_matrix == 3: tl = lst[0][0] + lst[1][1] + lst[2][2] br = lst[2][0] + lst[1][1] + lst[0][2] total = tl + br return total # FIGURE THIS ONE OUT LATER: # total = 0 # for i in range(len(matrix)): # total += matrix[i][i] # total += matrix[i][-1 - i] # return total
def sum_up_diagonals(matrix): """Given a matrix [square list of lists], return sum of diagonals. Sum of TL-to-BR diagonal along with BL-to-TR diagonal: >>> m1 = [ ... [1, 2], ... [30, 40], ... ] >>> sum_up_diagonals(m1) 73 >>> m2 = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9], ... ] >>> sum_up_diagonals(m2) 30 """ lst = [] total = 0 for x in matrix: lst.append(list(x)) length_of_matrix = len(matrix) if length_of_matrix == 2: tl = lst[0][0] + lst[1][1] br = lst[0][1] + lst[1][0] total = tl + br if length_of_matrix == 3: tl = lst[0][0] + lst[1][1] + lst[2][2] br = lst[2][0] + lst[1][1] + lst[0][2] total = tl + br return total
""" Randy Zhu 11-06-2020 """ number_of_inputs = int(input()) inputs: "list[str]" = [] for _ in range(number_of_inputs): inputs += input().split(" ") # new_inputs = [] # for row in enumerate(inputs): # new_inputs += inputs[row[0]].split(" ") print(inputs)
""" Randy Zhu 11-06-2020 """ number_of_inputs = int(input()) inputs: 'list[str]' = [] for _ in range(number_of_inputs): inputs += input().split(' ') print(inputs)
class Platform: def set_nonblocking(self, read_fd): raise NotImplementedError( "Non-blocking capture not impelemented on this platform" ) def apply_workarounds(self): pass
class Platform: def set_nonblocking(self, read_fd): raise not_implemented_error('Non-blocking capture not impelemented on this platform') def apply_workarounds(self): pass
#request class DmRequest(object): __slots__ = ['gatewayobj'] def __init__(self, gatewayobj): self.gatewayobj = gatewayobj def DMchannel(self, channel_id): self.gatewayobj.send({'op':self.gatewayobj.OPCODE.DM_UPDATE,'d':{'channel_id':channel_id}})
class Dmrequest(object): __slots__ = ['gatewayobj'] def __init__(self, gatewayobj): self.gatewayobj = gatewayobj def d_mchannel(self, channel_id): self.gatewayobj.send({'op': self.gatewayobj.OPCODE.DM_UPDATE, 'd': {'channel_id': channel_id}})
numbers = [] # Going up first (1st digit cannot be 0) for digit1 in range(1, 10): for digit2 in range(0, 10): for digit3 in range(0, 10): if digit2 > digit1 and digit3 < digit2: numbers.append(str(digit1) + str(digit2) + str(digit3)) # Going down first for digit1 in range(1, 10): for digit2 in range(0, 10): for digit3 in range(0, 10): if digit2 < digit1 and digit3 > digit2: numbers.append(str(digit1) + str(digit2) + str(digit3)) satisfyCount = 0 for n in numbers: if n[1] == "6": print(n) satisfyCount += 1 print(f"{satisfyCount} numbers satisfy criteria")
numbers = [] for digit1 in range(1, 10): for digit2 in range(0, 10): for digit3 in range(0, 10): if digit2 > digit1 and digit3 < digit2: numbers.append(str(digit1) + str(digit2) + str(digit3)) for digit1 in range(1, 10): for digit2 in range(0, 10): for digit3 in range(0, 10): if digit2 < digit1 and digit3 > digit2: numbers.append(str(digit1) + str(digit2) + str(digit3)) satisfy_count = 0 for n in numbers: if n[1] == '6': print(n) satisfy_count += 1 print(f'{satisfyCount} numbers satisfy criteria')
# -*- coding: utf-8 -*- """ Handler utility to parse slicing keys. """ def parse_slice(ds_slice): """ Parse dataset slice Parameters ---------- ds_slice : tuple | int | slice | list Slice to extract from dataset Returns ------- ds_slice : tuple slice for axis (0, 1) """ if not isinstance(ds_slice, tuple): ds_slice = (ds_slice,) return ds_slice def parse_keys(keys): """ Parse keys for complex __getitem__ and __setitem__ Parameters ---------- keys : string | tuple key or key and slice to extract Returns ------- key : string key to extract key_slice : slice | tuple Slice or tuple of slices of key to extract """ if isinstance(keys, tuple): key = keys[0] key_slice = keys[1:] else: key = keys key_slice = (slice(None),) return key, key_slice
""" Handler utility to parse slicing keys. """ def parse_slice(ds_slice): """ Parse dataset slice Parameters ---------- ds_slice : tuple | int | slice | list Slice to extract from dataset Returns ------- ds_slice : tuple slice for axis (0, 1) """ if not isinstance(ds_slice, tuple): ds_slice = (ds_slice,) return ds_slice def parse_keys(keys): """ Parse keys for complex __getitem__ and __setitem__ Parameters ---------- keys : string | tuple key or key and slice to extract Returns ------- key : string key to extract key_slice : slice | tuple Slice or tuple of slices of key to extract """ if isinstance(keys, tuple): key = keys[0] key_slice = keys[1:] else: key = keys key_slice = (slice(None),) return (key, key_slice)
def MeasureTime( v, t ): sT = time.process_time( ) leer_matriz(v, t) triangulo_superior(v, t) eT = time.process_time( ) return float( eT - sT ) def leer_matriz(v, t): for i in range (t): for j in range (t): print ("Escriba el elemento %u de la columna %u: ", j+1, i+1) v[i][j] = input() for i in range (t): for j in range (t): printf(v[i][j]) print("\n") def triangulo_superior(v, t): x = 0 for i in range (t): for j in range (t): if (j > i): x += v[i][j] print ( "La suma es:", x ) max = 5 print ("Cuantos elementos va a tener la matriz?: (maximo 5)"); t = input() meassureTime (v, t)
def measure_time(v, t): s_t = time.process_time() leer_matriz(v, t) triangulo_superior(v, t) e_t = time.process_time() return float(eT - sT) def leer_matriz(v, t): for i in range(t): for j in range(t): print('Escriba el elemento %u de la columna %u: ', j + 1, i + 1) v[i][j] = input() for i in range(t): for j in range(t): printf(v[i][j]) print('\n') def triangulo_superior(v, t): x = 0 for i in range(t): for j in range(t): if j > i: x += v[i][j] print('La suma es:', x) max = 5 print('Cuantos elementos va a tener la matriz?: (maximo 5)') t = input() meassure_time(v, t)
a = 'In this letter I make some remarks on a general principle relevant to enciphering in general and my machine.' b = 'If qualified opinions incline to believe in the exponential conjecture, then I think we cannot afford not to make use of it.' c = 'The most direct computation would be for the enemy to try all 2^r possible keys, one by one.' d = 'The significance of this general conjecture, assuming its truth, is easy to see. It means that it may be feasible to design ciphers that are effectively unbreakable.' a = 'To consider the resistance of an enciphering process to being broken we should assume that at same times the enemy knows everything but the key being used and to break it needs only discover the key from this information.' b = 'The most direct computation would be for the enemy to try all 2^r possible keys, one by one.' c = 'An enciphering-deciphering machine (in general outline) of my invention has been sent to your organization.' d = 'We see immediately that one needs little information to begin to break down the process.' for s in (a, b, c, d): n = len(s) b = ((n + 1) // 16 + 1) * 16 + 16 # print('%3d = %2d + %2d/16' % (n, n // 16, n % 16)) print('%3d => %3d %s' % (n, b, s[:20]))
a = 'In this letter I make some remarks on a general principle relevant to enciphering in general and my machine.' b = 'If qualified opinions incline to believe in the exponential conjecture, then I think we cannot afford not to make use of it.' c = 'The most direct computation would be for the enemy to try all 2^r possible keys, one by one.' d = 'The significance of this general conjecture, assuming its truth, is easy to see. It means that it may be feasible to design ciphers that are effectively unbreakable.' a = 'To consider the resistance of an enciphering process to being broken we should assume that at same times the enemy knows everything but the key being used and to break it needs only discover the key from this information.' b = 'The most direct computation would be for the enemy to try all 2^r possible keys, one by one.' c = 'An enciphering-deciphering machine (in general outline) of my invention has been sent to your organization.' d = 'We see immediately that one needs little information to begin to break down the process.' for s in (a, b, c, d): n = len(s) b = ((n + 1) // 16 + 1) * 16 + 16 print('%3d => %3d %s' % (n, b, s[:20]))
weight=1 def run(): r.absrot(90) r.absrot(0) r.absrot(-90) r.absrot(90)
weight = 1 def run(): r.absrot(90) r.absrot(0) r.absrot(-90) r.absrot(90)
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '8/14/2020 6:00 PM' class Solution: def __init__(self): self.data = ['1', '11', '21', '1211', '111221'] def read(self, string): pre = string[0] count = 1 res = [] for val in string[1:]: if val == pre: count += 1 else: res.append(str(count)) count = 1 res.append(pre) pre = val res.append(str(count)) res.append(pre) return "".join(res) def countAndSay(self, n: int) -> str: if n <= len(self.data): return self.data[n - 1] else: for index in range(5, n): self.data.append(self.read(self.data[index - 1])) return self.data[-1] if __name__ == '__main__': res = Solution().countAndSay(6) print(res)
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '8/14/2020 6:00 PM' class Solution: def __init__(self): self.data = ['1', '11', '21', '1211', '111221'] def read(self, string): pre = string[0] count = 1 res = [] for val in string[1:]: if val == pre: count += 1 else: res.append(str(count)) count = 1 res.append(pre) pre = val res.append(str(count)) res.append(pre) return ''.join(res) def count_and_say(self, n: int) -> str: if n <= len(self.data): return self.data[n - 1] else: for index in range(5, n): self.data.append(self.read(self.data[index - 1])) return self.data[-1] if __name__ == '__main__': res = solution().countAndSay(6) print(res)
class JobState(basestring): """ Jobs execute as self-contained state machines. They follow a series of careful steps from creation to destruction. These steps are dictated by the states that they find themselves in as well as the allowable list of states they may transition into. The state can be an indicator of whether a job is executing and if not, why that is the case. Possible values: <ul> <li> "initial" - Initializing, <li> "queued" - Queued, <li> "running" - Running, <li> "waiting" - Waiting For Another Job, <li> "pausing" - Entering Paused State, <li> "paused" - Paused, <li> "quitting" - Entering Quit State, <li> "success" - Succeeded, <li> "failure" - Failed, <li> "reschedule" - Forcing Reschedule, <li> "error" - Internal Error, <li> "quit" - Quit, <li> "dead" - Died, <li> "unknown" - Unknown, <li> "restart" - Forcing Restart, <li> "dormant" - Waiting For External Event </ul> """ @staticmethod def get_api_name(): return "job-state"
class Jobstate(basestring): """ Jobs execute as self-contained state machines. They follow a series of careful steps from creation to destruction. These steps are dictated by the states that they find themselves in as well as the allowable list of states they may transition into. The state can be an indicator of whether a job is executing and if not, why that is the case. Possible values: <ul> <li> "initial" - Initializing, <li> "queued" - Queued, <li> "running" - Running, <li> "waiting" - Waiting For Another Job, <li> "pausing" - Entering Paused State, <li> "paused" - Paused, <li> "quitting" - Entering Quit State, <li> "success" - Succeeded, <li> "failure" - Failed, <li> "reschedule" - Forcing Reschedule, <li> "error" - Internal Error, <li> "quit" - Quit, <li> "dead" - Died, <li> "unknown" - Unknown, <li> "restart" - Forcing Restart, <li> "dormant" - Waiting For External Event </ul> """ @staticmethod def get_api_name(): return 'job-state'
# Sorting ## Sorting with keys airports = [ ('MROC', 'San Jose, CR'), ('KLAS', 'Las Vegas, USA'), ('EDDM', 'Munich, DE'), ('LSZH', 'Zurich, CH'), ('VNLK', 'Lukla, NEP') ] sorted_airports = dict(sorted(airports, key=lambda x:x[0])) print(sorted_airports)
airports = [('MROC', 'San Jose, CR'), ('KLAS', 'Las Vegas, USA'), ('EDDM', 'Munich, DE'), ('LSZH', 'Zurich, CH'), ('VNLK', 'Lukla, NEP')] sorted_airports = dict(sorted(airports, key=lambda x: x[0])) print(sorted_airports)
# Create Trend Filter to remove linear, annual, and semi-annual trend fl_tf = skdiscovery.data_structure.table.filters.TrendFilter('TrendFilter', []) # Create stage container for the trend filter sc_tf = StageContainer(fl_tf)
fl_tf = skdiscovery.data_structure.table.filters.TrendFilter('TrendFilter', []) sc_tf = stage_container(fl_tf)
# encode categorical protocol name to number def encode_protocol(text): # put frequent cases to the front if 'tcp' in text: return 6 elif 'udp' in text: return 17 elif 'icmp' in text: return 1 elif 'hopopt' in text: return 0 elif 'igmp' in text: return 2 elif 'ggp' in text: return 3 elif 'ipv4' in text: return 4 elif 'stp' in text: return 118 elif 'st' in text: return 5 elif 'cbt' in text: return 7 elif 'egp' in text: return 8 elif 'igp' in text: return 9 elif 'bbn-rcc' in text: return 10 elif 'nvp' in text: return 11 elif 'pup' in text: return 12 elif 'argus' in text: return 13 elif 'emcon' in text: return 14 elif 'xnet' in text: return 15 elif 'chaos' in text: return 16 elif 'mux' in text: return 18 elif 'dcn' in text: return 19 elif 'hmp' in text: return 20 elif 'prm' in text: return 21 elif 'xns-idp' in text: return 22 elif 'trunk-1' in text: return 23 elif 'trunk-2' in text: return 24 elif 'leaf-1' in text: return 25 elif 'leaf-2' in text: return 26 elif 'rdp' in text: return 27 elif 'irtp' in text: return 28 elif 'iso-tp4' in text: return 29 elif 'netblt' in text: return 30 elif 'mfe-nsp' in text: return 31 elif 'merit-inp' in text: return 32 elif 'dccp' in text: return 33 elif '3pc' in text: return 34 elif 'idpr' in text: return 35 elif 'xtp' in text: return 36 elif 'ddp' in text: return 37 elif 'idpr-cmtp' in text: return 38 elif 'tp++' in text: return 39 elif 'il' in text: return 40 elif 'sdrp' in text: return 42 elif 'ipv6-route' in text: return 43 elif 'ipv6-frag' in text: return 44 elif 'idrp' in text: return 45 elif 'rsvp' in text: return 46 elif 'gre' in text: return 47 elif 'dsr' in text: return 48 elif 'bna' in text: return 49 elif 'esp' in text: return 50 elif 'ah' in text: return 51 elif 'i-nlsp' in text: return 52 elif 'swipe' in text: return 53 elif 'narp' in text: return 54 elif 'mobile' in text: return 55 elif 'tlsp' in text: return 56 elif 'skip' in text: return 57 elif 'ipv6-icmp' in text: return 58 elif 'ipv6-nonxt' in text: return 59 elif 'ipv6-opts' in text: return 60 elif 'ipv6' in text: return 41 elif 'internal' in text: return 61 elif 'cftp' in text: return 62 elif 'local' in text: return 63 elif 'sat-expak' in text: return 64 elif 'kryptolan' in text: return 65 elif 'rvd' in text: return 66 elif 'ippc' in text: return 67 elif 'distributed' in text: return 68 elif 'sat-mon' in text: return 69 elif 'visa' in text: return 70 elif 'ipcv' in text: return 71 elif 'cpnx' in text: return 72 elif 'cphb' in text: return 73 elif 'wsn' in text: return 74 elif 'pvp' in text: return 75 elif 'br-sat-mon' in text: return 76 elif 'sun-nd' in text: return 77 elif 'wb-mon' in text: return 78 elif 'wb-expak' in text: return 79 elif 'iso-ip' in text: return 80 elif 'secure-vmtp' in text: return 82 elif 'vmtp' in text: return 81 elif 'vines' in text: return 83 elif 'ttp' in text: return 84 elif 'iptm' in text: return 84 elif 'nsfnet-igp' in text: return 85 elif 'dgp' in text: return 86 elif 'tcf' in text: return 87 elif 'eigrp' in text: return 88 elif 'ospfigp' in text: return 89 elif 'sprite-rpc' in text: return 90 elif 'larp' in text: return 91 elif 'mtp' in text: return 92 elif 'ax.25' in text: return 93 elif 'ipip' in text: return 94 elif 'micp' in text: return 95 elif 'ssc-sp' in text: return 96 elif 'etherip' in text: return 97 elif 'encap' in text: return 98 elif 'private-encryp' in text: return 99 elif 'gmtp' in text: return 100 elif 'ifmp' in text: return 101 elif 'pnni' in text: return 102 elif 'pim' in text: return 103 elif 'aris' in text: return 104 elif 'scps' in text: return 105 elif 'qnx' in text: return 106 elif 'a/n' in text: return 107 elif 'ipcomp' in text: return 108 elif 'snp' in text: return 109 elif 'compaq' in text: return 110 elif 'ipx-in-ip' in text: return 111 elif 'vrrp' in text: return 112 elif 'pgm' in text: return 113 elif '0-hop' in text: return 114 elif 'l2tp' in text: return 115 elif 'ddx' in text: return 116 elif 'iatp' in text: return 117 elif 'stp' in text: return 118 elif 'srp' in text: return 119 elif 'uti' in text: return 120 elif 'smp' in text: return 121 elif 'sm' in text: return 122 elif 'ptp' in text: return 123 elif 'isis' in text: return 124 elif 'fire' in text: return 125 elif 'crtp' in text: return 126 elif 'crudp' in text: return 127 elif 'sscopmce' in text: return 128 elif 'iplt' in text: return 129 elif 'sps' in text: return 130 elif 'pipe' in text: return 131 elif 'sctp' in text: return 132 elif 'fc' in text: return 133 elif 'rsvp-e2e-ignore' in text: return 134 elif 'mobility' in text: return 135 elif 'udplite' in text: return 136 elif 'mpls-in-ip' in text: return 137 elif 'manet' in text: return 138 elif 'hip' in text: return 139 elif 'shim6' in text: return 140 elif 'wesp' in text: return 141 elif 'rohc' in text: return 142 elif 'experiment' in text: return 143 # 253 elif 'test' in text: return 144 # 254 else: return 145 # 255
def encode_protocol(text): if 'tcp' in text: return 6 elif 'udp' in text: return 17 elif 'icmp' in text: return 1 elif 'hopopt' in text: return 0 elif 'igmp' in text: return 2 elif 'ggp' in text: return 3 elif 'ipv4' in text: return 4 elif 'stp' in text: return 118 elif 'st' in text: return 5 elif 'cbt' in text: return 7 elif 'egp' in text: return 8 elif 'igp' in text: return 9 elif 'bbn-rcc' in text: return 10 elif 'nvp' in text: return 11 elif 'pup' in text: return 12 elif 'argus' in text: return 13 elif 'emcon' in text: return 14 elif 'xnet' in text: return 15 elif 'chaos' in text: return 16 elif 'mux' in text: return 18 elif 'dcn' in text: return 19 elif 'hmp' in text: return 20 elif 'prm' in text: return 21 elif 'xns-idp' in text: return 22 elif 'trunk-1' in text: return 23 elif 'trunk-2' in text: return 24 elif 'leaf-1' in text: return 25 elif 'leaf-2' in text: return 26 elif 'rdp' in text: return 27 elif 'irtp' in text: return 28 elif 'iso-tp4' in text: return 29 elif 'netblt' in text: return 30 elif 'mfe-nsp' in text: return 31 elif 'merit-inp' in text: return 32 elif 'dccp' in text: return 33 elif '3pc' in text: return 34 elif 'idpr' in text: return 35 elif 'xtp' in text: return 36 elif 'ddp' in text: return 37 elif 'idpr-cmtp' in text: return 38 elif 'tp++' in text: return 39 elif 'il' in text: return 40 elif 'sdrp' in text: return 42 elif 'ipv6-route' in text: return 43 elif 'ipv6-frag' in text: return 44 elif 'idrp' in text: return 45 elif 'rsvp' in text: return 46 elif 'gre' in text: return 47 elif 'dsr' in text: return 48 elif 'bna' in text: return 49 elif 'esp' in text: return 50 elif 'ah' in text: return 51 elif 'i-nlsp' in text: return 52 elif 'swipe' in text: return 53 elif 'narp' in text: return 54 elif 'mobile' in text: return 55 elif 'tlsp' in text: return 56 elif 'skip' in text: return 57 elif 'ipv6-icmp' in text: return 58 elif 'ipv6-nonxt' in text: return 59 elif 'ipv6-opts' in text: return 60 elif 'ipv6' in text: return 41 elif 'internal' in text: return 61 elif 'cftp' in text: return 62 elif 'local' in text: return 63 elif 'sat-expak' in text: return 64 elif 'kryptolan' in text: return 65 elif 'rvd' in text: return 66 elif 'ippc' in text: return 67 elif 'distributed' in text: return 68 elif 'sat-mon' in text: return 69 elif 'visa' in text: return 70 elif 'ipcv' in text: return 71 elif 'cpnx' in text: return 72 elif 'cphb' in text: return 73 elif 'wsn' in text: return 74 elif 'pvp' in text: return 75 elif 'br-sat-mon' in text: return 76 elif 'sun-nd' in text: return 77 elif 'wb-mon' in text: return 78 elif 'wb-expak' in text: return 79 elif 'iso-ip' in text: return 80 elif 'secure-vmtp' in text: return 82 elif 'vmtp' in text: return 81 elif 'vines' in text: return 83 elif 'ttp' in text: return 84 elif 'iptm' in text: return 84 elif 'nsfnet-igp' in text: return 85 elif 'dgp' in text: return 86 elif 'tcf' in text: return 87 elif 'eigrp' in text: return 88 elif 'ospfigp' in text: return 89 elif 'sprite-rpc' in text: return 90 elif 'larp' in text: return 91 elif 'mtp' in text: return 92 elif 'ax.25' in text: return 93 elif 'ipip' in text: return 94 elif 'micp' in text: return 95 elif 'ssc-sp' in text: return 96 elif 'etherip' in text: return 97 elif 'encap' in text: return 98 elif 'private-encryp' in text: return 99 elif 'gmtp' in text: return 100 elif 'ifmp' in text: return 101 elif 'pnni' in text: return 102 elif 'pim' in text: return 103 elif 'aris' in text: return 104 elif 'scps' in text: return 105 elif 'qnx' in text: return 106 elif 'a/n' in text: return 107 elif 'ipcomp' in text: return 108 elif 'snp' in text: return 109 elif 'compaq' in text: return 110 elif 'ipx-in-ip' in text: return 111 elif 'vrrp' in text: return 112 elif 'pgm' in text: return 113 elif '0-hop' in text: return 114 elif 'l2tp' in text: return 115 elif 'ddx' in text: return 116 elif 'iatp' in text: return 117 elif 'stp' in text: return 118 elif 'srp' in text: return 119 elif 'uti' in text: return 120 elif 'smp' in text: return 121 elif 'sm' in text: return 122 elif 'ptp' in text: return 123 elif 'isis' in text: return 124 elif 'fire' in text: return 125 elif 'crtp' in text: return 126 elif 'crudp' in text: return 127 elif 'sscopmce' in text: return 128 elif 'iplt' in text: return 129 elif 'sps' in text: return 130 elif 'pipe' in text: return 131 elif 'sctp' in text: return 132 elif 'fc' in text: return 133 elif 'rsvp-e2e-ignore' in text: return 134 elif 'mobility' in text: return 135 elif 'udplite' in text: return 136 elif 'mpls-in-ip' in text: return 137 elif 'manet' in text: return 138 elif 'hip' in text: return 139 elif 'shim6' in text: return 140 elif 'wesp' in text: return 141 elif 'rohc' in text: return 142 elif 'experiment' in text: return 143 elif 'test' in text: return 144 else: return 145
class WebServer: def __init__(): pass
class Webserver: def __init__(): pass
class super: name ="" age ="" def set_user(self,a,b): self.name = a self.age = b def show(self): print(str(self.name)) print(str(self.age)) class sub(super): def pp(self): print("Python") obj1 = sub() obj1.set_user("AungMoeKyaw","22") obj1.show() obj1.pp()
class Super: name = '' age = '' def set_user(self, a, b): self.name = a self.age = b def show(self): print(str(self.name)) print(str(self.age)) class Sub(super): def pp(self): print('Python') obj1 = sub() obj1.set_user('AungMoeKyaw', '22') obj1.show() obj1.pp()
# Python3 code to find the element that occur only once INT_SIZE = 32 def getSingle(arr, n) : result = 0 for i in range(0, INT_SIZE) : sm = 0 x = (1 << i) for j in range(0, n) : if (arr[j] & x) : sm = sm + 1 if ((sm % 3)!= 0) : result = result | x return result arr = [12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7] n = len(arr) print("The element with single occurrence is ", getSingle(arr, n))
int_size = 32 def get_single(arr, n): result = 0 for i in range(0, INT_SIZE): sm = 0 x = 1 << i for j in range(0, n): if arr[j] & x: sm = sm + 1 if sm % 3 != 0: result = result | x return result arr = [12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7] n = len(arr) print('The element with single occurrence is ', get_single(arr, n))
# -*- coding: utf-8 -*- __about__ = """ This project demonstrates the use of a waiting list and signup codes for sites in private beta. Otherwise it is the same as basic_project. """
__about__ = '\nThis project demonstrates the use of a waiting list and signup codes for\nsites in private beta. Otherwise it is the same as basic_project.\n'
""" Convert a non-negative integer num to its English words representation. Example 1: Input: num = 123 Output: "One Hundred Twenty Three" Example 2: Input: num = 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3: Input: num = 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" Example 4: Input: num = 1234567891 Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One" Constraints: 0 <= num <= 2^31 - 1 """ class Solution: def __init__(self): self.numberToString = { '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': 'nineteen', '20': 'twenty', '30': 'thirty', '40': 'forty', '50': 'fifty', '60': 'sixty', '70': 'seventy', '80': 'eighty', '90': 'ninty', '100': 'hundred', '1000': 'thousand', '1000000': 'million', '1000000000': 'billion' } def lessThanThousand(self, num): if num < 1000: strNum = str(num) if strNum in self.numberToString.keys(): return self.numberToString[strNum] first = '' second = '' third = '' if len(strNum) == 3 and strNum[0] and strNum[0] != '0': first = f'{self.numberToString[strNum[0]]} {self.numberToString["100"]}' second = f'{self.numberToString[str(int(strNum[1]) * 10)]}' third = f'{self.numberToString[str(strNum[2])]}' if len(strNum) == 2: if strNum in self.numberToString.keys(): second = f'{self.numberToString[str(int(strNum))]}' else: second = f'{self.numberToString[str(int(strNum[0]) * 10)]}' third = f'{self.numberToString[str(strNum[1])]}' if len(strNum) == 1 and strNum[2] and strNum[2] != '0': third = f'{self.numberToString[str(strNum[2])]}' print('first ', first) print('second ', second) print('third ', third) return f'{first} {second} {third}' def numberToWords(self, num: int) -> str: return self.lessThanThousand(num) if __name__ == "__main__": # for i in range(1, 1000): # print(f'{i} ===> {Solution().numberToWords(i)}') print(f'{100} ===> {Solution().numberToWords(60)}')
""" Convert a non-negative integer num to its English words representation. Example 1: Input: num = 123 Output: "One Hundred Twenty Three" Example 2: Input: num = 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3: Input: num = 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" Example 4: Input: num = 1234567891 Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One" Constraints: 0 <= num <= 2^31 - 1 """ class Solution: def __init__(self): self.numberToString = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': 'nineteen', '20': 'twenty', '30': 'thirty', '40': 'forty', '50': 'fifty', '60': 'sixty', '70': 'seventy', '80': 'eighty', '90': 'ninty', '100': 'hundred', '1000': 'thousand', '1000000': 'million', '1000000000': 'billion'} def less_than_thousand(self, num): if num < 1000: str_num = str(num) if strNum in self.numberToString.keys(): return self.numberToString[strNum] first = '' second = '' third = '' if len(strNum) == 3 and strNum[0] and (strNum[0] != '0'): first = f"{self.numberToString[strNum[0]]} {self.numberToString['100']}" second = f'{self.numberToString[str(int(strNum[1]) * 10)]}' third = f'{self.numberToString[str(strNum[2])]}' if len(strNum) == 2: if strNum in self.numberToString.keys(): second = f'{self.numberToString[str(int(strNum))]}' else: second = f'{self.numberToString[str(int(strNum[0]) * 10)]}' third = f'{self.numberToString[str(strNum[1])]}' if len(strNum) == 1 and strNum[2] and (strNum[2] != '0'): third = f'{self.numberToString[str(strNum[2])]}' print('first ', first) print('second ', second) print('third ', third) return f'{first} {second} {third}' def number_to_words(self, num: int) -> str: return self.lessThanThousand(num) if __name__ == '__main__': print(f'{100} ===> {solution().numberToWords(60)}')
#!/usr/bin/env python __version__ = "3.0.0" version = __version__
__version__ = '3.0.0' version = __version__
def closest_intersections(first_wire, second_wire): least_no_of_steps = None shortest_mh_distance = None steps_taken_first = 0 point_a_first = (0, 0) for instr_first in first_wire: point_b_first, steps_to_b_first = next_point(point_a_first, instr_first) steps_taken_second = 0 point_a_second = (0, 0) for instr_second in second_wire: point_b_second, steps_to_b_second = next_point(point_a_second, instr_second) if intersection_coords := intersection((point_a_first, point_b_first), (point_a_second, point_b_second)): x, y = intersection_coords mh_distance = abs(x) + abs(y) steps = steps_taken_first + steps_taken_second + steps_to_intersection(intersection_coords, point_a_first, point_a_second) if not shortest_mh_distance or mh_distance < shortest_mh_distance: shortest_mh_distance = mh_distance if not least_no_of_steps or steps < least_no_of_steps: least_no_of_steps = steps point_a_second = point_b_second steps_taken_second += steps_to_b_second point_a_first = point_b_first steps_taken_first += steps_to_b_first return shortest_mh_distance, least_no_of_steps def next_point(point, instruction): x, y = point direction = instruction[:1] distance = int(instruction[1:]) if direction == 'U': y += distance elif direction == 'R': x += distance elif direction == 'D': y -= distance elif direction == 'L': x -= distance return (x, y), distance def intersection(line1, line2): line1_horizontal = line1[0][1] == line1[1][1] line2_horizontal = line2[0][1] == line2[1][1] if line1_horizontal == line2_horizontal: return None horizontal_line = line1 if line1_horizontal else line2 vertical_line = line1 if line2_horizontal else line2 horizontal_p1, horizontal_p2 = horizontal_line vertical_p1, vertical_p2 = vertical_line horizontal_y = horizontal_p1[1] vertical_x = vertical_p1[0] if vertical_x == 0 and horizontal_y == 0: return None horizontal_min_x = min(horizontal_p1[0], horizontal_p2[0]) horizontal_max_x = max(horizontal_p1[0], horizontal_p2[0]) vertical_min_y = min(vertical_p1[1], vertical_p2[1]) vertical_max_y = max(vertical_p1[1], vertical_p2[1]) horizontal_align = vertical_min_y <= horizontal_y <= vertical_max_y vertical_align = horizontal_min_x <= vertical_x <= horizontal_max_x return (vertical_x, horizontal_y) if vertical_align and horizontal_align else None def steps_to_intersection(intersection_coords, previous_point_first, previous_point_second): int_x, int_y = intersection_coords first_x, first_y = previous_point_first second_x, second_y = previous_point_second if first_x == int_x: return abs(abs(int_y) - abs(first_y)) + abs(abs(int_x) - abs(second_x)) else: return abs(abs(int_x) - abs(first_x)) + abs(abs(int_y) - abs(second_y))
def closest_intersections(first_wire, second_wire): least_no_of_steps = None shortest_mh_distance = None steps_taken_first = 0 point_a_first = (0, 0) for instr_first in first_wire: (point_b_first, steps_to_b_first) = next_point(point_a_first, instr_first) steps_taken_second = 0 point_a_second = (0, 0) for instr_second in second_wire: (point_b_second, steps_to_b_second) = next_point(point_a_second, instr_second) if (intersection_coords := intersection((point_a_first, point_b_first), (point_a_second, point_b_second))): (x, y) = intersection_coords mh_distance = abs(x) + abs(y) steps = steps_taken_first + steps_taken_second + steps_to_intersection(intersection_coords, point_a_first, point_a_second) if not shortest_mh_distance or mh_distance < shortest_mh_distance: shortest_mh_distance = mh_distance if not least_no_of_steps or steps < least_no_of_steps: least_no_of_steps = steps point_a_second = point_b_second steps_taken_second += steps_to_b_second point_a_first = point_b_first steps_taken_first += steps_to_b_first return (shortest_mh_distance, least_no_of_steps) def next_point(point, instruction): (x, y) = point direction = instruction[:1] distance = int(instruction[1:]) if direction == 'U': y += distance elif direction == 'R': x += distance elif direction == 'D': y -= distance elif direction == 'L': x -= distance return ((x, y), distance) def intersection(line1, line2): line1_horizontal = line1[0][1] == line1[1][1] line2_horizontal = line2[0][1] == line2[1][1] if line1_horizontal == line2_horizontal: return None horizontal_line = line1 if line1_horizontal else line2 vertical_line = line1 if line2_horizontal else line2 (horizontal_p1, horizontal_p2) = horizontal_line (vertical_p1, vertical_p2) = vertical_line horizontal_y = horizontal_p1[1] vertical_x = vertical_p1[0] if vertical_x == 0 and horizontal_y == 0: return None horizontal_min_x = min(horizontal_p1[0], horizontal_p2[0]) horizontal_max_x = max(horizontal_p1[0], horizontal_p2[0]) vertical_min_y = min(vertical_p1[1], vertical_p2[1]) vertical_max_y = max(vertical_p1[1], vertical_p2[1]) horizontal_align = vertical_min_y <= horizontal_y <= vertical_max_y vertical_align = horizontal_min_x <= vertical_x <= horizontal_max_x return (vertical_x, horizontal_y) if vertical_align and horizontal_align else None def steps_to_intersection(intersection_coords, previous_point_first, previous_point_second): (int_x, int_y) = intersection_coords (first_x, first_y) = previous_point_first (second_x, second_y) = previous_point_second if first_x == int_x: return abs(abs(int_y) - abs(first_y)) + abs(abs(int_x) - abs(second_x)) else: return abs(abs(int_x) - abs(first_x)) + abs(abs(int_y) - abs(second_y))
_COURSIER_CLI_VERSION = "2.12" _COURSIER_VERSION = "1.1.0-M9" COURSIER_CLI_SHA256 = "8e7333506bb0db2a262d747873a434a476570dd09b30b61bcbac95aff18a8a9b" COURSIER_CLI_MAVEN_PATH = "io/get-coursier/coursier-cli_{COURSIER_CLI_VERSION}/{COURSIER_VERSION}/coursier-cli_{COURSIER_CLI_VERSION}-{COURSIER_VERSION}-standalone.jar".format( COURSIER_CLI_VERSION = _COURSIER_CLI_VERSION, COURSIER_VERSION = _COURSIER_VERSION, )
_coursier_cli_version = '2.12' _coursier_version = '1.1.0-M9' coursier_cli_sha256 = '8e7333506bb0db2a262d747873a434a476570dd09b30b61bcbac95aff18a8a9b' coursier_cli_maven_path = 'io/get-coursier/coursier-cli_{COURSIER_CLI_VERSION}/{COURSIER_VERSION}/coursier-cli_{COURSIER_CLI_VERSION}-{COURSIER_VERSION}-standalone.jar'.format(COURSIER_CLI_VERSION=_COURSIER_CLI_VERSION, COURSIER_VERSION=_COURSIER_VERSION)
userinput = "" print("Before User input ", userinput) userinput = input("EnterSomething :") print("After User input ", userinput)
userinput = '' print('Before User input ', userinput) userinput = input('EnterSomething :') print('After User input ', userinput)
''' WRITTEN BY Ramon Rossi PURPOSE The prime number is position one is 2. The prime number in position two is 3. The prime number is position three is 5. This function is_prime() finds the prime number at any position. It accepts an integer as an argument which is the position of the prime number to find. It returns the prime number at that position. EXAMPLE is_prime(100) will find the prime number at position 100 - it should return 541. ''' def is_prime(position_int): # 1 is not prime, so start with 2 x = 2 prime_num_list = [] count_prime_num_position = 0 while True: if x == 2: # add 2 to prime number list prime_num_list.append(x) count_prime_num_position += 1 else: # check if x is prime by dividing by y for y in range(2, x): if x % y == 0: #print('Not prime') break if (y+1) == x: #print('Prime') prime_num_list.append(x) count_prime_num_position += 1 #print('divisor = {}'.format(y)) # if found enough prime numbers, break the loop if count_prime_num_position == position_int: break x += 1 print('Prime numbers up to position {}...'.format(position_int)) print(prime_num_list) return prime_num_list[position_int-1] # run test 1 print('Test 1'.center(40,'-')) position_int = 3 result = is_prime(position_int) print('The prime number at position {} is {}'.format(position_int, result)) if result == 5: print('Test passed\n') else: print('Test failed\n') # run test 2 print('Test 2'.center(40,'-')) position_int = 100 result = is_prime(position_int) print('The prime number at position {} is {}'.format(position_int, result)) if result == 541: print('Test passed\n') else: print('Test failed\n')
""" WRITTEN BY Ramon Rossi PURPOSE The prime number is position one is 2. The prime number in position two is 3. The prime number is position three is 5. This function is_prime() finds the prime number at any position. It accepts an integer as an argument which is the position of the prime number to find. It returns the prime number at that position. EXAMPLE is_prime(100) will find the prime number at position 100 - it should return 541. """ def is_prime(position_int): x = 2 prime_num_list = [] count_prime_num_position = 0 while True: if x == 2: prime_num_list.append(x) count_prime_num_position += 1 else: for y in range(2, x): if x % y == 0: break if y + 1 == x: prime_num_list.append(x) count_prime_num_position += 1 if count_prime_num_position == position_int: break x += 1 print('Prime numbers up to position {}...'.format(position_int)) print(prime_num_list) return prime_num_list[position_int - 1] print('Test 1'.center(40, '-')) position_int = 3 result = is_prime(position_int) print('The prime number at position {} is {}'.format(position_int, result)) if result == 5: print('Test passed\n') else: print('Test failed\n') print('Test 2'.center(40, '-')) position_int = 100 result = is_prime(position_int) print('The prime number at position {} is {}'.format(position_int, result)) if result == 541: print('Test passed\n') else: print('Test failed\n')
# -*- coding: utf-8 -*- # @Author: Anderson # @Date: 2018-10-05 01:44:18 # @Last Modified by: Anderson # @Last Modified time: 2018-11-26 11:20:20 def anagrams(strs): word_dict = {} for word in strs: sorted_word = ''.join(sorted(word)) if sorted_word not in word_dict: word_dict[sorted_word] = [word] else: word_dict[sorted_word].append(word) count = 0 for item in word_dict: if len(word_dict[item]) >= 2: count += 1 return count s = input() word_list = s.split(' ') print(anagrams(word_list))
def anagrams(strs): word_dict = {} for word in strs: sorted_word = ''.join(sorted(word)) if sorted_word not in word_dict: word_dict[sorted_word] = [word] else: word_dict[sorted_word].append(word) count = 0 for item in word_dict: if len(word_dict[item]) >= 2: count += 1 return count s = input() word_list = s.split(' ') print(anagrams(word_list))
name = input("Enter your name: ") print("Your name is", name, ".") age = int(input("Enter your age: ")) if age > 18: print(name, "is", age, "years old.") height = float(input("Enter your Height(cm):")) if height > 0: print("That's a positive size!") weight = float(input("Enter your Weight(kg):")) if weight > 0: print("That's a positive weight!") eyes = input("Eye colour:") print ("and your eye color is:"+eyes) hair = input("Hair colour:") print ("and your hair color is:"+hair)
name = input('Enter your name: ') print('Your name is', name, '.') age = int(input('Enter your age: ')) if age > 18: print(name, 'is', age, 'years old.') height = float(input('Enter your Height(cm):')) if height > 0: print("That's a positive size!") weight = float(input('Enter your Weight(kg):')) if weight > 0: print("That's a positive weight!") eyes = input('Eye colour:') print('and your eye color is:' + eyes) hair = input('Hair colour:') print('and your hair color is:' + hair)
t=int(input()) for i in range(t): n=int(input()) dp=[0 for i in range(n+1)] dp[0]=1 dp[1]=1 for i in range(2,n+1): for j in range(0,i): dp[i]+=dp[j]*dp[i-j-1] print(dp[n])
t = int(input()) for i in range(t): n = int(input()) dp = [0 for i in range(n + 1)] dp[0] = 1 dp[1] = 1 for i in range(2, n + 1): for j in range(0, i): dp[i] += dp[j] * dp[i - j - 1] print(dp[n])
# You have a red lottery ticket showing ints a, b, and c, each of which is 0, 1, or 2. # If they are all the value 2, the result is 10. # Otherwise if they are all the same, the result is 5. # Otherwise so long as both b and c are different from a, the result is 1. # Otherwise the result is 0. # Write a function that given a, b, c, returns the value of the ticket # for more info on this quiz, go to this url: http://www.programmr.com/red-lottery-ticket-3 def find_ticket_value(a, b, c): try: if a == 2 and b == 2 and c == 2: return 10 elif a == b and b == c and a == c: return 5 elif b != a and c != a: return 1 else: return 0 except TypeError: return "wrong Data Type!" if __name__ == "__main__": print(find_ticket_value(0, 2, 2))
def find_ticket_value(a, b, c): try: if a == 2 and b == 2 and (c == 2): return 10 elif a == b and b == c and (a == c): return 5 elif b != a and c != a: return 1 else: return 0 except TypeError: return 'wrong Data Type!' if __name__ == '__main__': print(find_ticket_value(0, 2, 2))
#!/usr/bin/env python3 """player module.""" class Player: """Player for Checkers.""" def __init__(self, token): """Initialize object.""" self._token = token.lower() self._unpromoted = 12 self._promoted = 0 self._total = self._unpromoted + self._promoted def get_token(self): """Return the token of this player. The token is for an unpromoted piece.""" return self._token def get_promoted_token(self): """Return the token of this player. The token is for a promoted piece.""" return self._token.upper() def promote(self): """Promote a number of pieces.""" self._unpromoted -= 1 self._promoted += 1 def sacrifice(self, unpromoted_count=0, promoted_count=0): """Decrease token count by specified number.""" self._unpromoted -= unpromoted_count self._promoted -= promoted_count self._total = self._unpromoted + self._promoted def token_total(self): """Return the total number of pieces this player has left.""" return self._total def __repr__(self): """String representation of the object.""" return self.get_token()
"""player module.""" class Player: """Player for Checkers.""" def __init__(self, token): """Initialize object.""" self._token = token.lower() self._unpromoted = 12 self._promoted = 0 self._total = self._unpromoted + self._promoted def get_token(self): """Return the token of this player. The token is for an unpromoted piece.""" return self._token def get_promoted_token(self): """Return the token of this player. The token is for a promoted piece.""" return self._token.upper() def promote(self): """Promote a number of pieces.""" self._unpromoted -= 1 self._promoted += 1 def sacrifice(self, unpromoted_count=0, promoted_count=0): """Decrease token count by specified number.""" self._unpromoted -= unpromoted_count self._promoted -= promoted_count self._total = self._unpromoted + self._promoted def token_total(self): """Return the total number of pieces this player has left.""" return self._total def __repr__(self): """String representation of the object.""" return self.get_token()
# 1 Write a Python function, which gets 2 numbers, and return True if the second number is first number divider, otherwise False. def divider(a, b): if b % a == 0: return True else: return False # 2 Write a Python function, which gets a number, and return True if that number is palindrome, otherwise False def palindrome(s): s=str(s) if s == s[::-1]: return True else: return False # 3 Write a Python function, which gets a number, and return True if that number is prime, otherwise False. def prime(x): if x <= 1: return False for i in range(2, x): if x % i == 0: return False else: return True # 4Write a Python function, which checks if a number is perfect - that is equal to the sum of its proper positive divisors. def perfect(number): l = [] for x in range(1, number): if number % x == 0: l.append(x) if number == sum(l): return True else: return False # 5Write a function, which gets 2 numbers, and return their Great common divisor - https://en.wikipedia.org/wiki/Euclidean_algorithm def gcd(number1, number2): if number1 % number2 == 0: return number2 if number2 % number1 == 0: return number1 else: x = 0 for i in range(1, number1): if number1 % i == 0 and number2 % i == 0: x = i return x def main(): print(divider(10, 5)) print(divider(10, 5)) print(palindrome(161)) print(prime(15)) print(perfect(134)) print(gcd(15, 5)) main()
def divider(a, b): if b % a == 0: return True else: return False def palindrome(s): s = str(s) if s == s[::-1]: return True else: return False def prime(x): if x <= 1: return False for i in range(2, x): if x % i == 0: return False else: return True def perfect(number): l = [] for x in range(1, number): if number % x == 0: l.append(x) if number == sum(l): return True else: return False def gcd(number1, number2): if number1 % number2 == 0: return number2 if number2 % number1 == 0: return number1 else: x = 0 for i in range(1, number1): if number1 % i == 0 and number2 % i == 0: x = i return x def main(): print(divider(10, 5)) print(divider(10, 5)) print(palindrome(161)) print(prime(15)) print(perfect(134)) print(gcd(15, 5)) main()
def get_fibonacci_huge(n): if n <= 1: return n previous = 0 current =1 sum = 1 for __ in range(2,n+1): previous,current = current, previous+current sum = sum+(current*current) # print(sum, ' ', current*current) return sum%10 if __name__ == '__main__': n = int(input()) print(get_fibonacci_huge(n))
def get_fibonacci_huge(n): if n <= 1: return n previous = 0 current = 1 sum = 1 for __ in range(2, n + 1): (previous, current) = (current, previous + current) sum = sum + current * current return sum % 10 if __name__ == '__main__': n = int(input()) print(get_fibonacci_huge(n))
class Particle(object): def __init__(self, sprite): self.gravity = PVector(0, 0.1) self.lifespan = 255 self.velocity = PVector() partSize = random(10, 60) self.part = createShape() self.part.beginShape(QUAD) self.part.noStroke() self.part.texture(sprite) self.part.normal(0, 0, 1) self.part.vertex(-partSize / 2, -partSize / 2, 0, 0) self.part.vertex(+partSize / 2, -partSize / 2, sprite.width, 0) self.part.vertex(+partSize / 2, +partSize / 2, sprite.width, sprite.height) self.part.vertex(-partSize / 2, +partSize / 2, 0, sprite.height) self.part.endShape() self.rebirth(width / 2, height / 2) self.lifespan = random(255) def getShape(self): return self.part def rebirth(self, x, y): a = random(TWO_PI) speed = random(0.5, 4) self.velocity = PVector(cos(a), sin(a)) self.velocity.mult(speed) self.lifespan = 255 self.part.resetMatrix() self.part.translate(x, y) def isDead(self): return self.lifespan < 0 def update(self): self.lifespan -= 1 self.velocity.add(self.gravity) self.part.setTint(color(255, self.lifespan)) self.part.translate(self.velocity.x, self.velocity.y)
class Particle(object): def __init__(self, sprite): self.gravity = p_vector(0, 0.1) self.lifespan = 255 self.velocity = p_vector() part_size = random(10, 60) self.part = create_shape() self.part.beginShape(QUAD) self.part.noStroke() self.part.texture(sprite) self.part.normal(0, 0, 1) self.part.vertex(-partSize / 2, -partSize / 2, 0, 0) self.part.vertex(+partSize / 2, -partSize / 2, sprite.width, 0) self.part.vertex(+partSize / 2, +partSize / 2, sprite.width, sprite.height) self.part.vertex(-partSize / 2, +partSize / 2, 0, sprite.height) self.part.endShape() self.rebirth(width / 2, height / 2) self.lifespan = random(255) def get_shape(self): return self.part def rebirth(self, x, y): a = random(TWO_PI) speed = random(0.5, 4) self.velocity = p_vector(cos(a), sin(a)) self.velocity.mult(speed) self.lifespan = 255 self.part.resetMatrix() self.part.translate(x, y) def is_dead(self): return self.lifespan < 0 def update(self): self.lifespan -= 1 self.velocity.add(self.gravity) self.part.setTint(color(255, self.lifespan)) self.part.translate(self.velocity.x, self.velocity.y)
# # PySNMP MIB module ZYXEL-OAM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-OAM-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:51:06 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") ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, MibIdentifier, ObjectIdentity, IpAddress, Integer32, Gauge32, ModuleIdentity, TimeTicks, Counter64, Bits, Counter32, NotificationType, iso = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "MibIdentifier", "ObjectIdentity", "IpAddress", "Integer32", "Gauge32", "ModuleIdentity", "TimeTicks", "Counter64", "Bits", "Counter32", "NotificationType", "iso") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt") zyxelOam = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56)) if mibBuilder.loadTexts: zyxelOam.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelOam.setOrganization('Enterprise Solution ZyXEL') if mibBuilder.loadTexts: zyxelOam.setContactInfo('') if mibBuilder.loadTexts: zyxelOam.setDescription('The subtree for Operations, Administration, and Maintenance (OAM)') zyxelOamSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1)) zyOamState = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyOamState.setStatus('current') if mibBuilder.loadTexts: zyOamState.setDescription('Enable/Disable administrative status on the switch.') zyxelOamPortTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 2), ) if mibBuilder.loadTexts: zyxelOamPortTable.setStatus('current') if mibBuilder.loadTexts: zyxelOamPortTable.setDescription('The table contains OAM (Operations, Administration, and Maintenance) port configuration. ') zyxelOamPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: zyxelOamPortEntry.setStatus('current') if mibBuilder.loadTexts: zyxelOamPortEntry.setDescription('An entry contains OAM port configuration.') zyOamPortFunctionsSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 2, 1, 1), Bits().clone(namedValues=NamedValues(("unidirectionalSupport", 0), ("loopbackSupport", 1), ("eventSupport", 2), ("variableSupport", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyOamPortFunctionsSupported.setReference('[802.3ah], 30.3.6.1.6') if mibBuilder.loadTexts: zyOamPortFunctionsSupported.setStatus('current') if mibBuilder.loadTexts: zyOamPortFunctionsSupported.setDescription("The OAM functions supported on this Ethernet-like interface. OAM consists of separate functional sets beyond the basic discovery process that is always required. These functional groups can be supported independently by any implementation. These values are communicated to the peer via the local configuration field of Information OAMPDUs. Setting 'unidirectionalSupport(0)' indicates that the OA entity supports the transmission of OAMPDUs on links that are operating in unidirectional mode (traffic flowing in one direction only). Setting 'loopbackSupport(1)' indicates that the OAM entity can initiate and respond to loopback commands. Setting 'eventSupport(2)' indicates that the OAM entity can send and receive Event Notification OAMPDUs. Setting 'variableSupport(3)' indicates that the OAM entity can send and receive Variable Request and Response OAMPDUs. ") mibBuilder.exportSymbols("ZYXEL-OAM-MIB", zyxelOamSetup=zyxelOamSetup, zyxelOam=zyxelOam, zyOamPortFunctionsSupported=zyOamPortFunctionsSupported, zyxelOamPortTable=zyxelOamPortTable, zyxelOamPortEntry=zyxelOamPortEntry, zyOamState=zyOamState, PYSNMP_MODULE_ID=zyxelOam)
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint') (if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex') (enabled_status,) = mibBuilder.importSymbols('P-BRIDGE-MIB', 'EnabledStatus') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (mib_scalar, mib_table, mib_table_row, mib_table_column, unsigned32, mib_identifier, object_identity, ip_address, integer32, gauge32, module_identity, time_ticks, counter64, bits, counter32, notification_type, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32', 'MibIdentifier', 'ObjectIdentity', 'IpAddress', 'Integer32', 'Gauge32', 'ModuleIdentity', 'TimeTicks', 'Counter64', 'Bits', 'Counter32', 'NotificationType', 'iso') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') (es_mgmt,) = mibBuilder.importSymbols('ZYXEL-ES-SMI', 'esMgmt') zyxel_oam = module_identity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56)) if mibBuilder.loadTexts: zyxelOam.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelOam.setOrganization('Enterprise Solution ZyXEL') if mibBuilder.loadTexts: zyxelOam.setContactInfo('') if mibBuilder.loadTexts: zyxelOam.setDescription('The subtree for Operations, Administration, and Maintenance (OAM)') zyxel_oam_setup = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1)) zy_oam_state = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 1), enabled_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyOamState.setStatus('current') if mibBuilder.loadTexts: zyOamState.setDescription('Enable/Disable administrative status on the switch.') zyxel_oam_port_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 2)) if mibBuilder.loadTexts: zyxelOamPortTable.setStatus('current') if mibBuilder.loadTexts: zyxelOamPortTable.setDescription('The table contains OAM (Operations, Administration, and Maintenance) port configuration. ') zyxel_oam_port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 2, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex')) if mibBuilder.loadTexts: zyxelOamPortEntry.setStatus('current') if mibBuilder.loadTexts: zyxelOamPortEntry.setDescription('An entry contains OAM port configuration.') zy_oam_port_functions_supported = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 2, 1, 1), bits().clone(namedValues=named_values(('unidirectionalSupport', 0), ('loopbackSupport', 1), ('eventSupport', 2), ('variableSupport', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyOamPortFunctionsSupported.setReference('[802.3ah], 30.3.6.1.6') if mibBuilder.loadTexts: zyOamPortFunctionsSupported.setStatus('current') if mibBuilder.loadTexts: zyOamPortFunctionsSupported.setDescription("The OAM functions supported on this Ethernet-like interface. OAM consists of separate functional sets beyond the basic discovery process that is always required. These functional groups can be supported independently by any implementation. These values are communicated to the peer via the local configuration field of Information OAMPDUs. Setting 'unidirectionalSupport(0)' indicates that the OA entity supports the transmission of OAMPDUs on links that are operating in unidirectional mode (traffic flowing in one direction only). Setting 'loopbackSupport(1)' indicates that the OAM entity can initiate and respond to loopback commands. Setting 'eventSupport(2)' indicates that the OAM entity can send and receive Event Notification OAMPDUs. Setting 'variableSupport(3)' indicates that the OAM entity can send and receive Variable Request and Response OAMPDUs. ") mibBuilder.exportSymbols('ZYXEL-OAM-MIB', zyxelOamSetup=zyxelOamSetup, zyxelOam=zyxelOam, zyOamPortFunctionsSupported=zyOamPortFunctionsSupported, zyxelOamPortTable=zyxelOamPortTable, zyxelOamPortEntry=zyxelOamPortEntry, zyOamState=zyOamState, PYSNMP_MODULE_ID=zyxelOam)
def intro(task): title = f" ** {task} ** " print ("\n") print ("*" * len(title)) print (title) print ("*" * len(title)) print ("\n") intro("School") class Person: def __init__(self, firstname, lastname, age, phone, email=None): self.firstname = firstname self.lastname = lastname self.age = age self.phone = phone self.email = email if isinstance(firstname, str) == False: raise ValueError("Lirstname should be a sting") if isinstance(lastname, str) == False: raise ValueError("Lastname should be a sting") if isinstance(age, int) == False: raise ValueError("Age should be a integrer") if isinstance(phone, int) == False and phone[0-2] == 467 and len(phone) == 11: raise ValueError("Age should be a 11 figure integrer that starts with 467") if email == None: self.email = str.lower(firstname) + "." + str.lower(lastname) + "@school.se" def sinfo(self): print("Name: " + self.firstname + " " + self.lastname) print(f"Age: {self.age}") print(f"Phone: {self.phone}") print("Email: " + self.email + "\n") class Student(Person): def __init__(self, firstname, lastname, age, phone, email=None, year=1 , grade=3, status="In school"): super().__init__(firstname,lastname,age,phone,email) self.year = year self.grade = grade self.status = status def longinfo(self): print("Name: " + self.firstname + " " + self.lastname) print("Status: " + self.status) print(f"Age: {self.age}") print(f"Phone: {self.phone}") print("Email: " + self.email) print(f"Grade: {self.grade}") print(f"Year in school: {self.year}\n") class Teacher(Person): def __init__(self, firstname, lastname, age, phone, salary, hired, email=None): super().__init__(firstname,lastname,age,phone,email) self.salary = salary self.hired = hired def longinfo(self): print("Name: " + self.firstname + " " + self.lastname) print(f"Age: {self.age}") print(f"Phone: {self.phone}") print("Email: " + self.email) print(f"Salary: ${self.salary}") print(f"Hired: {self.hired}\n") kalle = Person("Carl", "Forsudd", 8, 46749658745) karin = Student("Karin", "Petersson", 7, 46778934562) kajsa = Teacher("Kajsa", "Berggren", 42, 4678945645656, 12800, 1989) kajsa.sinfo() karin.sinfo() kajsa.longinfo() karin.longinfo()
def intro(task): title = f' ** {task} ** ' print('\n') print('*' * len(title)) print(title) print('*' * len(title)) print('\n') intro('School') class Person: def __init__(self, firstname, lastname, age, phone, email=None): self.firstname = firstname self.lastname = lastname self.age = age self.phone = phone self.email = email if isinstance(firstname, str) == False: raise value_error('Lirstname should be a sting') if isinstance(lastname, str) == False: raise value_error('Lastname should be a sting') if isinstance(age, int) == False: raise value_error('Age should be a integrer') if isinstance(phone, int) == False and phone[0 - 2] == 467 and (len(phone) == 11): raise value_error('Age should be a 11 figure integrer that starts with 467') if email == None: self.email = str.lower(firstname) + '.' + str.lower(lastname) + '@school.se' def sinfo(self): print('Name: ' + self.firstname + ' ' + self.lastname) print(f'Age: {self.age}') print(f'Phone: {self.phone}') print('Email: ' + self.email + '\n') class Student(Person): def __init__(self, firstname, lastname, age, phone, email=None, year=1, grade=3, status='In school'): super().__init__(firstname, lastname, age, phone, email) self.year = year self.grade = grade self.status = status def longinfo(self): print('Name: ' + self.firstname + ' ' + self.lastname) print('Status: ' + self.status) print(f'Age: {self.age}') print(f'Phone: {self.phone}') print('Email: ' + self.email) print(f'Grade: {self.grade}') print(f'Year in school: {self.year}\n') class Teacher(Person): def __init__(self, firstname, lastname, age, phone, salary, hired, email=None): super().__init__(firstname, lastname, age, phone, email) self.salary = salary self.hired = hired def longinfo(self): print('Name: ' + self.firstname + ' ' + self.lastname) print(f'Age: {self.age}') print(f'Phone: {self.phone}') print('Email: ' + self.email) print(f'Salary: ${self.salary}') print(f'Hired: {self.hired}\n') kalle = person('Carl', 'Forsudd', 8, 46749658745) karin = student('Karin', 'Petersson', 7, 46778934562) kajsa = teacher('Kajsa', 'Berggren', 42, 4678945645656, 12800, 1989) kajsa.sinfo() karin.sinfo() kajsa.longinfo() karin.longinfo()
def foo(y): x=y return x bar = foo(7)
def foo(y): x = y return x bar = foo(7)
class Solution: def countPrimes(self, n: int) -> int: primes = [] for i in range(2, n): for prime in primes: if i % prime == 0: break else: primes.append(i) return len(primes)
class Solution: def count_primes(self, n: int) -> int: primes = [] for i in range(2, n): for prime in primes: if i % prime == 0: break else: primes.append(i) return len(primes)
""" N 1^2 + 2^2 + 3^2 + ... + N^2 """ N = int(input()) sum = 0 for i in range(1, N + 1): sum += i ** 2 print(sum)
""" N 1^2 + 2^2 + 3^2 + ... + N^2 """ n = int(input()) sum = 0 for i in range(1, N + 1): sum += i ** 2 print(sum)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Used to simulate an enum with unique values class Enumeration(set): def __getattr__(self, name): if name in self: return name raise AttributeError def __setattr__(self, name, value): raise RuntimeError("Cannot override values") def __delattr__(self, name): raise RuntimeError("Cannot delete values")
class Enumeration(set): def __getattr__(self, name): if name in self: return name raise AttributeError def __setattr__(self, name, value): raise runtime_error('Cannot override values') def __delattr__(self, name): raise runtime_error('Cannot delete values')
def fib(n, c={0:1, 1:1}): if n not in c: x = n // 2 c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x) return c[n] fib(10000000) # calculating it takes a few seconds, printing it takes eons
def fib(n, c={0: 1, 1: 1}): if n not in c: x = n // 2 c[n] = fib(x - 1) * fib(n - x - 1) + fib(x) * fib(n - x) return c[n] fib(10000000)
def build_and(left, right): return {'type':'and','left':left,'right':right} def build_or(left,right): return {'type':'or','left':left,'right':right} def build_atom(atom): return {'type':'atom','atom':atom} def equal(p0,p1): if p0['type'] == p1['type']: if p1['type'] == 'atom': return p0['atom'] == p1['atom'] else: return equal(p0['left'],p1['left']) and equal(p0['right'],p1['right']) else: return False def normalize1(p): if p['type'] == 'atom': return p else: a = normalize1(p['left']) b = normalize1(p['right']) if p['type'] == 'or': if b['type'] == 'and': return build_and(build_or(a,b['left']), build_or(a,b['right'])) else: if a['type'] == 'and': return build_and(build_or(a['left'],b), build_or(a['right'],b)) else: return build_or(a,b) else: return build_and(a,b) def normalize(p): p0 = normalize1(p) while equal(p0,p) == False: p = p0 p0 = normalize1(p) return p0 def big_and(t,f): if len(t) == 1: return f(t[0]) else: return build_and(big_and(t[0:1],f),big_and(t[1:],f)) def big_or(t,f): if len(t) == 1: return f(t[0]) else: return build_or(big_or(t[0:1],f),big_or(t[1:],f)) def to_clauses(t): if t['type'] == "atom": return [[t['atom']]] if t['type'] == 'and': return to_clauses(t['left'])+to_clauses(t['right']) if t['type'] == 'or': return [to_clauses(t['left'])[0]+to_clauses(t['right'])[0]] def check_tree(tree,b): if tree['type'] == "atom": return True if tree['type'] == 'and' and b == True: return False if tree['type'] == "or": return check_tree(tree['left'],True) and check_tree(tree['right'],True) if tree['type'] == "and": return check_tree(tree['left'],b) and check_tree(tree['right'],b) def print_tree(p,acc): if p['type'] == 'atom': print(acc+p['type']+":"+str(p['atom'])) else: print(acc+p['type']) print_tree(p['left'],acc+"\t") print_tree(p['right'],acc+"\t")
def build_and(left, right): return {'type': 'and', 'left': left, 'right': right} def build_or(left, right): return {'type': 'or', 'left': left, 'right': right} def build_atom(atom): return {'type': 'atom', 'atom': atom} def equal(p0, p1): if p0['type'] == p1['type']: if p1['type'] == 'atom': return p0['atom'] == p1['atom'] else: return equal(p0['left'], p1['left']) and equal(p0['right'], p1['right']) else: return False def normalize1(p): if p['type'] == 'atom': return p else: a = normalize1(p['left']) b = normalize1(p['right']) if p['type'] == 'or': if b['type'] == 'and': return build_and(build_or(a, b['left']), build_or(a, b['right'])) elif a['type'] == 'and': return build_and(build_or(a['left'], b), build_or(a['right'], b)) else: return build_or(a, b) else: return build_and(a, b) def normalize(p): p0 = normalize1(p) while equal(p0, p) == False: p = p0 p0 = normalize1(p) return p0 def big_and(t, f): if len(t) == 1: return f(t[0]) else: return build_and(big_and(t[0:1], f), big_and(t[1:], f)) def big_or(t, f): if len(t) == 1: return f(t[0]) else: return build_or(big_or(t[0:1], f), big_or(t[1:], f)) def to_clauses(t): if t['type'] == 'atom': return [[t['atom']]] if t['type'] == 'and': return to_clauses(t['left']) + to_clauses(t['right']) if t['type'] == 'or': return [to_clauses(t['left'])[0] + to_clauses(t['right'])[0]] def check_tree(tree, b): if tree['type'] == 'atom': return True if tree['type'] == 'and' and b == True: return False if tree['type'] == 'or': return check_tree(tree['left'], True) and check_tree(tree['right'], True) if tree['type'] == 'and': return check_tree(tree['left'], b) and check_tree(tree['right'], b) def print_tree(p, acc): if p['type'] == 'atom': print(acc + p['type'] + ':' + str(p['atom'])) else: print(acc + p['type']) print_tree(p['left'], acc + '\t') print_tree(p['right'], acc + '\t')
self.con_win_size = 9 self.halfwin = con_win_size // 2 def load_data(self): for i in range(self.n_file): self.log("n." + str(i+1)) inp = np.load(os.path.join(self.data_path, os.listdir(self.data_path)[i])) full_x = np.pad(inp["imgs"], [(self.halfwin,self.halfwin), (0,0)], mode='constant') for frame_idx in range(len(inp['imgs'])): # load a context window centered around the frame index sample_x = np.swapaxes(full_x[frame_idx : frame_idx+self.con_win_size],0,1) self.training_data.append((sample_x.astype('float64'), inp['labels'][frame_idx][::-1].astype('float64')))
self.con_win_size = 9 self.halfwin = con_win_size // 2 def load_data(self): for i in range(self.n_file): self.log('n.' + str(i + 1)) inp = np.load(os.path.join(self.data_path, os.listdir(self.data_path)[i])) full_x = np.pad(inp['imgs'], [(self.halfwin, self.halfwin), (0, 0)], mode='constant') for frame_idx in range(len(inp['imgs'])): sample_x = np.swapaxes(full_x[frame_idx:frame_idx + self.con_win_size], 0, 1) self.training_data.append((sample_x.astype('float64'), inp['labels'][frame_idx][::-1].astype('float64')))
"""Serves as an interface for the two different console parsers (characterize and JUnit)""" class DefaultConsoleParser: # noinspection PyUnusedLocal def __init__(self, pipeline_name, pipeline_counter, stage_index, stage_name, job_name): self.console_log = None self.response = None self.success = True def insert_info(self, stage_id): # pragma: no cover raise NotImplementedError def get_failure_stage(self): # TODO: Investigate this: Surely a POST problem might cause us not to get any # POSTed test results, and then this code will indicate "startup"? if self.success: if "No Tests Run" in self.response: return "STARTUP" elif "All Tests Passed" in self.response: return "POST" elif self._check_test_failures(): return "TEST" else: return "UNKNOWN" else: return "STARTUP" def _check_test_failures(self): # pragma: no cover raise NotImplementedError
"""Serves as an interface for the two different console parsers (characterize and JUnit)""" class Defaultconsoleparser: def __init__(self, pipeline_name, pipeline_counter, stage_index, stage_name, job_name): self.console_log = None self.response = None self.success = True def insert_info(self, stage_id): raise NotImplementedError def get_failure_stage(self): if self.success: if 'No Tests Run' in self.response: return 'STARTUP' elif 'All Tests Passed' in self.response: return 'POST' elif self._check_test_failures(): return 'TEST' else: return 'UNKNOWN' else: return 'STARTUP' def _check_test_failures(self): raise NotImplementedError
class TTRssException(Exception): pass class TTRssArgumentException(TTRssException): pass class TTRssConfigurationException(TTRssException): pass
class Ttrssexception(Exception): pass class Ttrssargumentexception(TTRssException): pass class Ttrssconfigurationexception(TTRssException): pass
# # Represents a vertex in a DAG # # Copyright (c) 2013 by Michael Luckeneder # class Vertex(object): """Represents a vertex in a DAG""" def __init__(self, name): """Initialize the vertex""" self.name = name def __str__(self): """Returns String representation of vertex""" return self.name
class Vertex(object): """Represents a vertex in a DAG""" def __init__(self, name): """Initialize the vertex""" self.name = name def __str__(self): """Returns String representation of vertex""" return self.name
lista = ('carro','moto','trator','caminhao','coracao','ovo', 'mao','paralelepipedo','borboleta','onibus','Brasil','papai') for i in lista: print(f'\nA palavra {i}, possui as vogais: ',end='') for j in i: if j.lower() in 'aeiou': print(j, end=' ')
lista = ('carro', 'moto', 'trator', 'caminhao', 'coracao', 'ovo', 'mao', 'paralelepipedo', 'borboleta', 'onibus', 'Brasil', 'papai') for i in lista: print(f'\nA palavra {i}, possui as vogais: ', end='') for j in i: if j.lower() in 'aeiou': print(j, end=' ')
def find(n,m,index,cursor): if index == m: print(" ".join(map(str,foundlist))) return else: for i in range(cursor,n+1): if findnum[i] == True: continue else: findnum[i] = True foundlist[index] = cursor = i find(n,m,index+1,cursor) findnum[i] = False n,m = map(int,input().split()) findnum = [False]*(n+1) foundlist = [0]*m find(n,m,0,1)
def find(n, m, index, cursor): if index == m: print(' '.join(map(str, foundlist))) return else: for i in range(cursor, n + 1): if findnum[i] == True: continue else: findnum[i] = True foundlist[index] = cursor = i find(n, m, index + 1, cursor) findnum[i] = False (n, m) = map(int, input().split()) findnum = [False] * (n + 1) foundlist = [0] * m find(n, m, 0, 1)
#!/usr/bin/python3 """Create""" def text_indentation(text): """text indentation """ if type(text) is not str: raise TypeError("text must be a string") i = 0 while i < len(text): if text[i] not in [".", "?", ":"]: print(text[i], end='') else: print('{}\n'.format(text[i])) while (i + 1) < len(text) and ord(text[i + 1]) == 32: i += 1 i += 1
"""Create""" def text_indentation(text): """text indentation """ if type(text) is not str: raise type_error('text must be a string') i = 0 while i < len(text): if text[i] not in ['.', '?', ':']: print(text[i], end='') else: print('{}\n'.format(text[i])) while i + 1 < len(text) and ord(text[i + 1]) == 32: i += 1 i += 1
ONES = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'} TEENS = {11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'} TENS = {0: '', 1: 'ten', 2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety'} HUNDREDS = {1: 'onehundred', 2: 'twohundred', 3: 'threehundred', 4: 'fourhundred', 5: 'fivehundred', 6: 'sixhundred', 7: 'sevenhundred', 8: 'eighthundred', 9: 'ninehundred'} def solve(): words = [] # for number_as_str in (str(i) for i in range(1, 1001)): # print(number_as_str, len(number_as_str)) # if len_i == 1: # print(ONES[i]) # words += ONES[i] # elif len_i == 2: # try: # print(TEENS[i]) # words += TEENS[i] # except KeyError: # print(TENS[int(str_i[0])] + ONES[int(str_i[1])]) # words += TENS[int(str_i[0])] + ONES[int(str_i[1])] # elif len_i == 3: # try: # print(HUNDREDS[int(str_i[0])] + 'and' + TEENS[int(str_i[1:])]) # words += HUNDREDS[int(str_i[0])] + 'and' + TEENS[int(str_i[1:])] # except KeyError: # if i % 100 != 0: # print(HUNDREDS[int(str_i[0])] + 'and' + TENS[int(str_i[1])] + ONES[int(str_i[2])]) # words += HUNDREDS[int(str_i[0])] + 'and' + TENS[int(str_i[1])] + ONES[int(str_i[2])] # elif i % 100 == 0: # print(HUNDREDS[int(str_i[0])]) # words += HUNDREDS[int(str_i[0])] # elif len_i == 4: # print('onethousand') # words += 'onethousand' return len(''.join(words)) if __name__ == '__main__': print(solve())
ones = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'} teens = {11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'} tens = {0: '', 1: 'ten', 2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety'} hundreds = {1: 'onehundred', 2: 'twohundred', 3: 'threehundred', 4: 'fourhundred', 5: 'fivehundred', 6: 'sixhundred', 7: 'sevenhundred', 8: 'eighthundred', 9: 'ninehundred'} def solve(): words = [] return len(''.join(words)) if __name__ == '__main__': print(solve())
class Solution: def numDupDigitsAtMostN(self, N: int) -> int: list_n = list(map(int, str(N + 1))) res = 0 len_n = len(list_n) for i in range(1, len_n): res += 9 * self.get_cnt(9, i - 1) s = set() for i, x in enumerate(list_n): for y in range(0 if i else 1, x): if y in s: continue res += self.get_cnt(9 - i, len_n - i - 1) if x in s: break s.add(x) return N - res def get_cnt(self, m: int, n: int) -> int: if 0 == n: return 1 return self.get_cnt(m, n - 1) * (m - n + 1) if __name__ == '__main__': sol = Solution() # print(sol.numDupDigitsAtMostN(20)) print(sol.numDupDigitsAtMostN(100)) print(sol.numDupDigitsAtMostN(6718458))
class Solution: def num_dup_digits_at_most_n(self, N: int) -> int: list_n = list(map(int, str(N + 1))) res = 0 len_n = len(list_n) for i in range(1, len_n): res += 9 * self.get_cnt(9, i - 1) s = set() for (i, x) in enumerate(list_n): for y in range(0 if i else 1, x): if y in s: continue res += self.get_cnt(9 - i, len_n - i - 1) if x in s: break s.add(x) return N - res def get_cnt(self, m: int, n: int) -> int: if 0 == n: return 1 return self.get_cnt(m, n - 1) * (m - n + 1) if __name__ == '__main__': sol = solution() print(sol.numDupDigitsAtMostN(100)) print(sol.numDupDigitsAtMostN(6718458))
# -*- coding: utf-8 -*- # @Time :2021/3/8 10:48 # @Author :Ma Liang # @Email :mal818@126.com # @File :gameuniterror.py.py class GameUnitError(Exception): """Custom exception class for the 'AbstractGameUnit' and its subclasses""" def __init__(self, message=''): super().__init__(message) self.padding = '~' * 50 + '\r\n' self.error_message = "Unspecified Error!" class HealthMeterException(GameUnitError): """Custom exception to report Health Meter related problems""" def __init__(self, message=''): super(HealthMeterException, self).__init__(message) self.error_message = (self.padding + "ERROR: Health Meter Problem" + '\r\n' + self.padding) class HutError(Exception): def __init__(self, code): self.error_message = '' self.error_dict = { 000: "E000: Unspecified Error code", 101: "E101: Out of range: Number > 5", 102: "E102: Out of range, Negative number", 103: "E103: Not a number!", 104: "E104: You have already acquired this hut. Try again." "<INFO: You can NOT get healed in already acquired hut.>", } try: self.error_message = self.error_dict[code] except KeyError: self.error_message = self.error_dict[000] print("Error message: ",self.error_message)
class Gameuniterror(Exception): """Custom exception class for the 'AbstractGameUnit' and its subclasses""" def __init__(self, message=''): super().__init__(message) self.padding = '~' * 50 + '\r\n' self.error_message = 'Unspecified Error!' class Healthmeterexception(GameUnitError): """Custom exception to report Health Meter related problems""" def __init__(self, message=''): super(HealthMeterException, self).__init__(message) self.error_message = self.padding + 'ERROR: Health Meter Problem' + '\r\n' + self.padding class Huterror(Exception): def __init__(self, code): self.error_message = '' self.error_dict = {0: 'E000: Unspecified Error code', 101: 'E101: Out of range: Number > 5', 102: 'E102: Out of range, Negative number', 103: 'E103: Not a number!', 104: 'E104: You have already acquired this hut. Try again.<INFO: You can NOT get healed in already acquired hut.>'} try: self.error_message = self.error_dict[code] except KeyError: self.error_message = self.error_dict[0] print('Error message: ', self.error_message)
# # PySNMP MIB module HPN-ICF-COMMON-SYSTEM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-COMMON-SYSTEM-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:37:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection") hpnicf, = mibBuilder.importSymbols("HPN-ICF-OID-MIB", "hpnicf") InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Bits, Unsigned32, TimeTicks, IpAddress, NotificationType, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, iso, Gauge32, ObjectIdentity, ModuleIdentity, Counter32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Unsigned32", "TimeTicks", "IpAddress", "NotificationType", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "iso", "Gauge32", "ObjectIdentity", "ModuleIdentity", "Counter32", "Integer32") DisplayString, TextualConvention, DateAndTime = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "DateAndTime") hpnicfSystem = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6)) hpnicfSystem.setRevisions(('2004-06-30 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hpnicfSystem.setRevisionsDescriptions(('Initial revision of this MIB module.',)) if mibBuilder.loadTexts: hpnicfSystem.setLastUpdated('201206060000Z') if mibBuilder.loadTexts: hpnicfSystem.setOrganization('') if mibBuilder.loadTexts: hpnicfSystem.setContactInfo('') if mibBuilder.loadTexts: hpnicfSystem.setDescription('This file describes common MIB objects implemented by both Routers and Switches.') hpnicfWriteConfig = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("save", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfWriteConfig.setStatus('current') if mibBuilder.loadTexts: hpnicfWriteConfig.setDescription('Write config to router.') hpnicfStartFtpServer = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfStartFtpServer.setStatus('current') if mibBuilder.loadTexts: hpnicfStartFtpServer.setDescription('Decide whether start ftp-server.enable(1) indicates to start ftp-server; disable(2) indicates to stop ftp-server.') hpnicfReboot = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("normal", 0), ("reboot", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfReboot.setStatus('current') if mibBuilder.loadTexts: hpnicfReboot.setDescription("normal:do nothing. reboot :reboot the router. 'normal' will be returned when getting.") hpnicfSystemNotification = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8)) hpnicfWriteSuccessTrap = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 1)) if mibBuilder.loadTexts: hpnicfWriteSuccessTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfWriteSuccessTrap.setDescription('Send a trap about write success.') hpnicfWriteFailureTrap = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 2)) if mibBuilder.loadTexts: hpnicfWriteFailureTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfWriteFailureTrap.setDescription('Send a trap about write failure.') hpnicfRebootSendTrap = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 3)) if mibBuilder.loadTexts: hpnicfRebootSendTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfRebootSendTrap.setDescription("If a user restarts the device with command 'reboot', this trap will be sent two seconds before the device reboots.") hpnicfSysColdStartTrap = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 4)).setObjects(("HPN-ICF-COMMON-SYSTEM-MIB", "hpnicfSysFirstTrapTime")) if mibBuilder.loadTexts: hpnicfSysColdStartTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfSysColdStartTrap.setDescription('System cold start trap.') hpnicfSysWarmStartTrap = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 5)).setObjects(("HPN-ICF-COMMON-SYSTEM-MIB", "hpnicfSysFirstTrapTime")) if mibBuilder.loadTexts: hpnicfSysWarmStartTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfSysWarmStartTrap.setDescription('System warm start trap.') hpnicfSysLoghostUnreachableTrap = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 6)).setObjects(("HPN-ICF-COMMON-SYSTEM-MIB", "hpnicfSysLoghostIndex"), ("HPN-ICF-COMMON-SYSTEM-MIB", "hpnicfSysLoghostIpaddressType"), ("HPN-ICF-COMMON-SYSTEM-MIB", "hpnicfSysLoghostIpaddress"), ("HPN-ICF-COMMON-SYSTEM-MIB", "hpnicfSysLoghostTrapVpnName")) if mibBuilder.loadTexts: hpnicfSysLoghostUnreachableTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLoghostUnreachableTrap.setDescription('This notification will be sent when a loghost becomes unreachable.') hpnicfSoftwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 9), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfSoftwareVersion.setStatus('current') if mibBuilder.loadTexts: hpnicfSoftwareVersion.setDescription('Software version.') hpnicfSysBootType = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("coldStart", 1), ("warmStart", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfSysBootType.setStatus('current') if mibBuilder.loadTexts: hpnicfSysBootType.setDescription('Boot type of the system, indicates whether the last device reboot was by CLI (warm start) or power off (cold start).') hpnicfSystemInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11)) hpnicfSysStatisticPeriod = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 900))).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfSysStatisticPeriod.setStatus('current') if mibBuilder.loadTexts: hpnicfSysStatisticPeriod.setDescription('Statistic period. The device collects statistics within the period.') hpnicfSysSamplePeriod = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 300))).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfSysSamplePeriod.setStatus('current') if mibBuilder.loadTexts: hpnicfSysSamplePeriod.setDescription('Sampling period. The device takes samples periodically for statistics collection.') hpnicfSysTrapResendPeriod = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3600))).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfSysTrapResendPeriod.setStatus('current') if mibBuilder.loadTexts: hpnicfSysTrapResendPeriod.setDescription('Trap resending period. If the value is zero, the trap will not be re-sent.') hpnicfSysTrapCollectionPeriod = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 60))).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfSysTrapCollectionPeriod.setStatus('current') if mibBuilder.loadTexts: hpnicfSysTrapCollectionPeriod.setDescription('Trap collecting period. If the value is zero, the trap will not be re-sent.') hpnicfSysSnmpPort = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfSysSnmpPort.setStatus('current') if mibBuilder.loadTexts: hpnicfSysSnmpPort.setDescription('UDP port for SNMP protocol entity to receive messages except Trap-PDU.') hpnicfSysSnmpTrapPort = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfSysSnmpTrapPort.setStatus('current') if mibBuilder.loadTexts: hpnicfSysSnmpTrapPort.setDescription('UDP port for Trap-PDU to receive messages.') hpnicfSysNetID = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfSysNetID.setStatus('current') if mibBuilder.loadTexts: hpnicfSysNetID.setDescription('System Net ID.') hpnicfSysLastSampleTime = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 8), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfSysLastSampleTime.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLastSampleTime.setDescription('Last sampling time of the system.') hpnicfSysTrapSendNum = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 24))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfSysTrapSendNum.setStatus('current') if mibBuilder.loadTexts: hpnicfSysTrapSendNum.setDescription('Maximum number of times for sending a trap. If the value is zero, a trap will be sent at an interval continually.') hpnicfSysFirstTrapTime = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 10), TimeTicks()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfSysFirstTrapTime.setStatus('current') if mibBuilder.loadTexts: hpnicfSysFirstTrapTime.setDescription('Time when the first trap is sent.') hpnicfSysBannerMOTD = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 11), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 2000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfSysBannerMOTD.setStatus('current') if mibBuilder.loadTexts: hpnicfSysBannerMOTD.setDescription('An administratively configured message that is displayed to the user when the user logs in to the device through the console port or Web interface.') hpnicfSystemNotificationInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 12)) hpnicfSysLoghostIndex = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 12, 1), Integer32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfSysLoghostIndex.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLoghostIndex.setDescription('Index of loghost.') hpnicfSysLoghostIpaddressType = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 12, 2), InetAddressType()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfSysLoghostIpaddressType.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLoghostIpaddressType.setDescription('IP address type of the loghost.') hpnicfSysLoghostIpaddress = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 12, 3), InetAddress()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfSysLoghostIpaddress.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLoghostIpaddress.setDescription('IP address of the loghost.') hpnicfSysLoghostTrapVpnName = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 12, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfSysLoghostTrapVpnName.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLoghostTrapVpnName.setDescription('VPN name of the loghost.') mibBuilder.exportSymbols("HPN-ICF-COMMON-SYSTEM-MIB", hpnicfSysSamplePeriod=hpnicfSysSamplePeriod, hpnicfSysLoghostTrapVpnName=hpnicfSysLoghostTrapVpnName, hpnicfSysBootType=hpnicfSysBootType, hpnicfReboot=hpnicfReboot, hpnicfSysLoghostUnreachableTrap=hpnicfSysLoghostUnreachableTrap, hpnicfSysTrapResendPeriod=hpnicfSysTrapResendPeriod, hpnicfStartFtpServer=hpnicfStartFtpServer, hpnicfWriteConfig=hpnicfWriteConfig, hpnicfSysLoghostIndex=hpnicfSysLoghostIndex, hpnicfSysStatisticPeriod=hpnicfSysStatisticPeriod, hpnicfRebootSendTrap=hpnicfRebootSendTrap, hpnicfSysSnmpPort=hpnicfSysSnmpPort, hpnicfSysLastSampleTime=hpnicfSysLastSampleTime, hpnicfSystemInfo=hpnicfSystemInfo, hpnicfWriteSuccessTrap=hpnicfWriteSuccessTrap, hpnicfSysLoghostIpaddress=hpnicfSysLoghostIpaddress, hpnicfSysTrapCollectionPeriod=hpnicfSysTrapCollectionPeriod, hpnicfSystem=hpnicfSystem, hpnicfSysFirstTrapTime=hpnicfSysFirstTrapTime, PYSNMP_MODULE_ID=hpnicfSystem, hpnicfSysTrapSendNum=hpnicfSysTrapSendNum, hpnicfSoftwareVersion=hpnicfSoftwareVersion, hpnicfSysBannerMOTD=hpnicfSysBannerMOTD, hpnicfSystemNotification=hpnicfSystemNotification, hpnicfSysNetID=hpnicfSysNetID, hpnicfSysWarmStartTrap=hpnicfSysWarmStartTrap, hpnicfSysLoghostIpaddressType=hpnicfSysLoghostIpaddressType, hpnicfSystemNotificationInfo=hpnicfSystemNotificationInfo, hpnicfSysColdStartTrap=hpnicfSysColdStartTrap, hpnicfSysSnmpTrapPort=hpnicfSysSnmpTrapPort, hpnicfWriteFailureTrap=hpnicfWriteFailureTrap)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ConstraintsIntersection') (hpnicf,) = mibBuilder.importSymbols('HPN-ICF-OID-MIB', 'hpnicf') (inet_address, inet_address_type) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddress', 'InetAddressType') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (bits, unsigned32, time_ticks, ip_address, notification_type, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, iso, gauge32, object_identity, module_identity, counter32, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'Unsigned32', 'TimeTicks', 'IpAddress', 'NotificationType', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'iso', 'Gauge32', 'ObjectIdentity', 'ModuleIdentity', 'Counter32', 'Integer32') (display_string, textual_convention, date_and_time) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention', 'DateAndTime') hpnicf_system = module_identity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6)) hpnicfSystem.setRevisions(('2004-06-30 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hpnicfSystem.setRevisionsDescriptions(('Initial revision of this MIB module.',)) if mibBuilder.loadTexts: hpnicfSystem.setLastUpdated('201206060000Z') if mibBuilder.loadTexts: hpnicfSystem.setOrganization('') if mibBuilder.loadTexts: hpnicfSystem.setContactInfo('') if mibBuilder.loadTexts: hpnicfSystem.setDescription('This file describes common MIB objects implemented by both Routers and Switches.') hpnicf_write_config = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1))).clone(namedValues=named_values(('save', 1)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfWriteConfig.setStatus('current') if mibBuilder.loadTexts: hpnicfWriteConfig.setDescription('Write config to router.') hpnicf_start_ftp_server = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfStartFtpServer.setStatus('current') if mibBuilder.loadTexts: hpnicfStartFtpServer.setDescription('Decide whether start ftp-server.enable(1) indicates to start ftp-server; disable(2) indicates to stop ftp-server.') hpnicf_reboot = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('normal', 0), ('reboot', 1)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfReboot.setStatus('current') if mibBuilder.loadTexts: hpnicfReboot.setDescription("normal:do nothing. reboot :reboot the router. 'normal' will be returned when getting.") hpnicf_system_notification = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8)) hpnicf_write_success_trap = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 1)) if mibBuilder.loadTexts: hpnicfWriteSuccessTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfWriteSuccessTrap.setDescription('Send a trap about write success.') hpnicf_write_failure_trap = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 2)) if mibBuilder.loadTexts: hpnicfWriteFailureTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfWriteFailureTrap.setDescription('Send a trap about write failure.') hpnicf_reboot_send_trap = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 3)) if mibBuilder.loadTexts: hpnicfRebootSendTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfRebootSendTrap.setDescription("If a user restarts the device with command 'reboot', this trap will be sent two seconds before the device reboots.") hpnicf_sys_cold_start_trap = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 4)).setObjects(('HPN-ICF-COMMON-SYSTEM-MIB', 'hpnicfSysFirstTrapTime')) if mibBuilder.loadTexts: hpnicfSysColdStartTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfSysColdStartTrap.setDescription('System cold start trap.') hpnicf_sys_warm_start_trap = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 5)).setObjects(('HPN-ICF-COMMON-SYSTEM-MIB', 'hpnicfSysFirstTrapTime')) if mibBuilder.loadTexts: hpnicfSysWarmStartTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfSysWarmStartTrap.setDescription('System warm start trap.') hpnicf_sys_loghost_unreachable_trap = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 8, 6)).setObjects(('HPN-ICF-COMMON-SYSTEM-MIB', 'hpnicfSysLoghostIndex'), ('HPN-ICF-COMMON-SYSTEM-MIB', 'hpnicfSysLoghostIpaddressType'), ('HPN-ICF-COMMON-SYSTEM-MIB', 'hpnicfSysLoghostIpaddress'), ('HPN-ICF-COMMON-SYSTEM-MIB', 'hpnicfSysLoghostTrapVpnName')) if mibBuilder.loadTexts: hpnicfSysLoghostUnreachableTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLoghostUnreachableTrap.setDescription('This notification will be sent when a loghost becomes unreachable.') hpnicf_software_version = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 9), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfSoftwareVersion.setStatus('current') if mibBuilder.loadTexts: hpnicfSoftwareVersion.setDescription('Software version.') hpnicf_sys_boot_type = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('coldStart', 1), ('warmStart', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfSysBootType.setStatus('current') if mibBuilder.loadTexts: hpnicfSysBootType.setDescription('Boot type of the system, indicates whether the last device reboot was by CLI (warm start) or power off (cold start).') hpnicf_system_info = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11)) hpnicf_sys_statistic_period = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 900))).setUnits('seconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfSysStatisticPeriod.setStatus('current') if mibBuilder.loadTexts: hpnicfSysStatisticPeriod.setDescription('Statistic period. The device collects statistics within the period.') hpnicf_sys_sample_period = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 300))).setUnits('seconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfSysSamplePeriod.setStatus('current') if mibBuilder.loadTexts: hpnicfSysSamplePeriod.setDescription('Sampling period. The device takes samples periodically for statistics collection.') hpnicf_sys_trap_resend_period = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 3600))).setUnits('seconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfSysTrapResendPeriod.setStatus('current') if mibBuilder.loadTexts: hpnicfSysTrapResendPeriod.setDescription('Trap resending period. If the value is zero, the trap will not be re-sent.') hpnicf_sys_trap_collection_period = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 60))).setUnits('seconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfSysTrapCollectionPeriod.setStatus('current') if mibBuilder.loadTexts: hpnicfSysTrapCollectionPeriod.setDescription('Trap collecting period. If the value is zero, the trap will not be re-sent.') hpnicf_sys_snmp_port = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfSysSnmpPort.setStatus('current') if mibBuilder.loadTexts: hpnicfSysSnmpPort.setDescription('UDP port for SNMP protocol entity to receive messages except Trap-PDU.') hpnicf_sys_snmp_trap_port = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfSysSnmpTrapPort.setStatus('current') if mibBuilder.loadTexts: hpnicfSysSnmpTrapPort.setDescription('UDP port for Trap-PDU to receive messages.') hpnicf_sys_net_id = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 7), octet_string().subtype(subtypeSpec=value_size_constraint(0, 127))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfSysNetID.setStatus('current') if mibBuilder.loadTexts: hpnicfSysNetID.setDescription('System Net ID.') hpnicf_sys_last_sample_time = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 8), date_and_time()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfSysLastSampleTime.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLastSampleTime.setDescription('Last sampling time of the system.') hpnicf_sys_trap_send_num = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 9), integer32().subtype(subtypeSpec=value_range_constraint(0, 24))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfSysTrapSendNum.setStatus('current') if mibBuilder.loadTexts: hpnicfSysTrapSendNum.setDescription('Maximum number of times for sending a trap. If the value is zero, a trap will be sent at an interval continually.') hpnicf_sys_first_trap_time = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 10), time_ticks()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: hpnicfSysFirstTrapTime.setStatus('current') if mibBuilder.loadTexts: hpnicfSysFirstTrapTime.setDescription('Time when the first trap is sent.') hpnicf_sys_banner_motd = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 11, 11), octet_string().subtype(subtypeSpec=value_size_constraint(0, 2000))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfSysBannerMOTD.setStatus('current') if mibBuilder.loadTexts: hpnicfSysBannerMOTD.setDescription('An administratively configured message that is displayed to the user when the user logs in to the device through the console port or Web interface.') hpnicf_system_notification_info = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 12)) hpnicf_sys_loghost_index = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 12, 1), integer32()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: hpnicfSysLoghostIndex.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLoghostIndex.setDescription('Index of loghost.') hpnicf_sys_loghost_ipaddress_type = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 12, 2), inet_address_type()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: hpnicfSysLoghostIpaddressType.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLoghostIpaddressType.setDescription('IP address type of the loghost.') hpnicf_sys_loghost_ipaddress = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 12, 3), inet_address()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: hpnicfSysLoghostIpaddress.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLoghostIpaddress.setDescription('IP address of the loghost.') hpnicf_sys_loghost_trap_vpn_name = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 6, 12, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 31))).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: hpnicfSysLoghostTrapVpnName.setStatus('current') if mibBuilder.loadTexts: hpnicfSysLoghostTrapVpnName.setDescription('VPN name of the loghost.') mibBuilder.exportSymbols('HPN-ICF-COMMON-SYSTEM-MIB', hpnicfSysSamplePeriod=hpnicfSysSamplePeriod, hpnicfSysLoghostTrapVpnName=hpnicfSysLoghostTrapVpnName, hpnicfSysBootType=hpnicfSysBootType, hpnicfReboot=hpnicfReboot, hpnicfSysLoghostUnreachableTrap=hpnicfSysLoghostUnreachableTrap, hpnicfSysTrapResendPeriod=hpnicfSysTrapResendPeriod, hpnicfStartFtpServer=hpnicfStartFtpServer, hpnicfWriteConfig=hpnicfWriteConfig, hpnicfSysLoghostIndex=hpnicfSysLoghostIndex, hpnicfSysStatisticPeriod=hpnicfSysStatisticPeriod, hpnicfRebootSendTrap=hpnicfRebootSendTrap, hpnicfSysSnmpPort=hpnicfSysSnmpPort, hpnicfSysLastSampleTime=hpnicfSysLastSampleTime, hpnicfSystemInfo=hpnicfSystemInfo, hpnicfWriteSuccessTrap=hpnicfWriteSuccessTrap, hpnicfSysLoghostIpaddress=hpnicfSysLoghostIpaddress, hpnicfSysTrapCollectionPeriod=hpnicfSysTrapCollectionPeriod, hpnicfSystem=hpnicfSystem, hpnicfSysFirstTrapTime=hpnicfSysFirstTrapTime, PYSNMP_MODULE_ID=hpnicfSystem, hpnicfSysTrapSendNum=hpnicfSysTrapSendNum, hpnicfSoftwareVersion=hpnicfSoftwareVersion, hpnicfSysBannerMOTD=hpnicfSysBannerMOTD, hpnicfSystemNotification=hpnicfSystemNotification, hpnicfSysNetID=hpnicfSysNetID, hpnicfSysWarmStartTrap=hpnicfSysWarmStartTrap, hpnicfSysLoghostIpaddressType=hpnicfSysLoghostIpaddressType, hpnicfSystemNotificationInfo=hpnicfSystemNotificationInfo, hpnicfSysColdStartTrap=hpnicfSysColdStartTrap, hpnicfSysSnmpTrapPort=hpnicfSysSnmpTrapPort, hpnicfWriteFailureTrap=hpnicfWriteFailureTrap)
## Recursion with memoization # Time: O(n^3) class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: @lru_cache def recur( s, word_dict, start ): if start == len(s): return True for end in range( start+1, len(s)+1 ): if s[start:end] in word_dict and recur( s, word_dict, end ): return True return False return recur( s, frozenset(wordDict), 0 ) class SolutionII: def wordBreak(self, s: str, wordDict: List[str]) -> bool: memo = [-1]*len(s) def recur( s, word_dict, start ): if start == len(s): return True if memo[start] != -1: return memo[start] for end in range( start+1, len(s)+1 ): if s[start:end] in word_dict and recur( s, word_dict, end ): memo[start] = True return True memo[start] = False return False return recur( s, set(wordDict), 0 ) ## Brute Force # Time: O(2^n) class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: def recur( s, word_dict, start ): if start == len(s): return True for end in range( start+1, len(s)+1 ): if s[start:end] in word_dict and recur( s, word_dict, end ): return True return False return recur( s, set(wordDict), 0 )
class Solution: def word_break(self, s: str, wordDict: List[str]) -> bool: @lru_cache def recur(s, word_dict, start): if start == len(s): return True for end in range(start + 1, len(s) + 1): if s[start:end] in word_dict and recur(s, word_dict, end): return True return False return recur(s, frozenset(wordDict), 0) class Solutionii: def word_break(self, s: str, wordDict: List[str]) -> bool: memo = [-1] * len(s) def recur(s, word_dict, start): if start == len(s): return True if memo[start] != -1: return memo[start] for end in range(start + 1, len(s) + 1): if s[start:end] in word_dict and recur(s, word_dict, end): memo[start] = True return True memo[start] = False return False return recur(s, set(wordDict), 0) class Solution: def word_break(self, s: str, wordDict: List[str]) -> bool: def recur(s, word_dict, start): if start == len(s): return True for end in range(start + 1, len(s) + 1): if s[start:end] in word_dict and recur(s, word_dict, end): return True return False return recur(s, set(wordDict), 0)
expected_output = { "active_translations": {"dynamic": 0, "extended": 0, "static": 0, "total": 0}, "cef_punted_pkts": 0, "cef_translated_pkts": 0, "dynamic_mappings": { "inside_source": { "id": { 1: { "access_list": "test-robot", "match": "access-list test-robot pool test-robot", "pool": { "test-robot": { "allocated": 0, "allocated_percentage": 0, "end": "10.1.1.1", "misses": 0, "netmask": "255.255.255.252", "start": "10.1.1.1", "total_addresses": 1, "type": "generic", } }, "refcount": 0, } } } }, "expired_translations": 11013, "hits": 3358708, "interfaces": { "inside": ["TenGigabitEthernet0/1/0"], "outside": ["TenGigabitEthernet0/2/0"], }, "ip_alias_add_fail": 0, "limit_entry_add_fail": 0, "mapping_stats_drop": 0, "misses": 11050, "pool_stats_drop": 0, "port_block_alloc_fail": 0, }
expected_output = {'active_translations': {'dynamic': 0, 'extended': 0, 'static': 0, 'total': 0}, 'cef_punted_pkts': 0, 'cef_translated_pkts': 0, 'dynamic_mappings': {'inside_source': {'id': {1: {'access_list': 'test-robot', 'match': 'access-list test-robot pool test-robot', 'pool': {'test-robot': {'allocated': 0, 'allocated_percentage': 0, 'end': '10.1.1.1', 'misses': 0, 'netmask': '255.255.255.252', 'start': '10.1.1.1', 'total_addresses': 1, 'type': 'generic'}}, 'refcount': 0}}}}, 'expired_translations': 11013, 'hits': 3358708, 'interfaces': {'inside': ['TenGigabitEthernet0/1/0'], 'outside': ['TenGigabitEthernet0/2/0']}, 'ip_alias_add_fail': 0, 'limit_entry_add_fail': 0, 'mapping_stats_drop': 0, 'misses': 11050, 'pool_stats_drop': 0, 'port_block_alloc_fail': 0}
# Copyright (C) 2021 Clinton Garwood # MIT Open Source Initiative Approved License # while_true_clinton.py # CIS-135 Python # Assignment #9 # # # Lab 9 # Get while_yes and enter Loop # Initial Value received from input is a string value # print("While Looping Exercises") #while_yes = input("Yes or No? Input y for yes, or n for no") # # While Yes Loop # while_yes = 'y' # while while_yes == 'y' or while_yes == "Y": # print("'While-Yes Loop' runs as long as 'y' is entered, any other character exits the loop") # while_yes = input("Type y to continue, or any other character to exit.") # print("Exited Loop Successfully") # # While True Loop # while_true = True # This is a boolean value (True or False) # while(while_true == True): # print("While True loop will run until False (#2) is entered") # t_f = int(input("Enter 1 for True, or 2 for False ")) # if t_f == 1: # pass # elif t_f == 2: # while_true = False # print("While True Loop Successfully") # While False Loop while_false = False # This is a boolean value (True or False) while(while_false != True): print("While False loop will exit if True (#1) is entered") t_f = int(input("Enter 1 for True, or 2 for False ")) if t_f == 1: while_false = True else: print("") print("Exited While False Loop Successfully")
while_false = False while while_false != True: print('While False loop will exit if True (#1) is entered') t_f = int(input('Enter 1 for True, or 2 for False ')) if t_f == 1: while_false = True else: print('') print('Exited While False Loop Successfully')
class Glass: capacity = 250 def __init__(self): self.content = 0 def get_space_left(self): return self.capacity - self.content def fill(self, ml): """ Fills water in the glass If no space for ml, nothing is filled in the glass """ if self.get_space_left() < ml: return f'Cannot add {ml} ml' self.content += ml return f'Glass filled with {ml} ml' # Don't do this, prefer defensive programming # def fill(self, ml): # if ml <= self.get_space_left(): # self.content += ml # return f'Glass filled with {ml} ml' # # return f'Cannot add {ml} ml' def empty(self): self.content = 0 return 'Glass is now empty' def info(self): return f'{self.get_space_left()} ml left' glass = Glass() print(glass.fill(100)) print(glass.fill.__doc__) print(glass.fill(200)) print(glass.empty()) print(glass.fill(200)) print(glass.info()) print(' --- glass.__dict__ ---') for key, value in glass.__dict__.items(): print(key, value) def print_name(func): def internal_func(*args, **kwargs): print(f'****Called {func.__name__} ****') return func(*args, **kwargs) return internal_func print(' --- Glass.__dict__ ---') for key, value in Glass.__dict__.items(): if callable(value): setattr(Glass, key, print_name(value)) g = Glass() print(g.fill(100)) print(g.fill.__doc__) print(g.fill(200)) print(g.empty()) print(g.fill(200)) print(g.info())
class Glass: capacity = 250 def __init__(self): self.content = 0 def get_space_left(self): return self.capacity - self.content def fill(self, ml): """ Fills water in the glass If no space for ml, nothing is filled in the glass """ if self.get_space_left() < ml: return f'Cannot add {ml} ml' self.content += ml return f'Glass filled with {ml} ml' def empty(self): self.content = 0 return 'Glass is now empty' def info(self): return f'{self.get_space_left()} ml left' glass = glass() print(glass.fill(100)) print(glass.fill.__doc__) print(glass.fill(200)) print(glass.empty()) print(glass.fill(200)) print(glass.info()) print(' --- glass.__dict__ ---') for (key, value) in glass.__dict__.items(): print(key, value) def print_name(func): def internal_func(*args, **kwargs): print(f'****Called {func.__name__} ****') return func(*args, **kwargs) return internal_func print(' --- Glass.__dict__ ---') for (key, value) in Glass.__dict__.items(): if callable(value): setattr(Glass, key, print_name(value)) g = glass() print(g.fill(100)) print(g.fill.__doc__) print(g.fill(200)) print(g.empty()) print(g.fill(200)) print(g.info())
engine.run_script('init-touchcursor') # https://github.com/autokey/autokey/issues/127 # Can't simulate multimedia keys #127 # xmodmap -pk | grep XF86AudioRaiseVolume # 123 0x1008ff13 (XF86AudioRaiseVolume) 0x0000 (NoSymbol) 0x1008ff13 (XF86AudioRaiseVolume) # keyboard.send_keys("<code123>") # https://unix.stackexchange.com/questions/342554/how-to-enable-my-keyboards-volume-keys-in-xfce/342555 # xfce4-pulseaudio-plugin # pactl -- set-sink-volume 0 +5% # raise volume by each 10% (more than 100% possible, might distort the sound) # pactl -- set-sink-volume 0 -5% # reduce volume by each 10% # pactl -- set-sink-mute 0 toggle # mute/unmutes audio system.exec_command("pactl -- set-sink-volume 0 +5%", getOutput=False)
engine.run_script('init-touchcursor') system.exec_command('pactl -- set-sink-volume 0 +5%', getOutput=False)
class Solution: def twoSum(self, nums: list[int], target: int) -> list[int]: l = len(nums) data = {} for i in range(l): xa = nums[i] if xa in data: return [data[xa], i] xb = target - xa data[xb] = i return [] def alternate(self, nums: list[int], target: int) -> list[int]: l = len(nums) for i in range(l - 1): for j in range(i + 1, l): if nums[i] + nums[j] == target: return [i, j] return []
class Solution: def two_sum(self, nums: list[int], target: int) -> list[int]: l = len(nums) data = {} for i in range(l): xa = nums[i] if xa in data: return [data[xa], i] xb = target - xa data[xb] = i return [] def alternate(self, nums: list[int], target: int) -> list[int]: l = len(nums) for i in range(l - 1): for j in range(i + 1, l): if nums[i] + nums[j] == target: return [i, j] return []