content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
#
# PySNMP MIB module CISCO-STACK-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-STACK-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 12:12:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint")
ciscoAgentCapability, = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability")
AgentCapabilities, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "NotificationGroup", "ModuleCompliance")
ObjectIdentity, Gauge32, Counter64, Counter32, Integer32, Bits, ModuleIdentity, iso, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, MibIdentifier, IpAddress, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "Gauge32", "Counter64", "Counter32", "Integer32", "Bits", "ModuleIdentity", "iso", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "MibIdentifier", "IpAddress", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ciscoStackCapability = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 7, 378))
ciscoStackCapability.setRevisions(('2008-03-19 00:00', '2006-03-15 00:00', '2005-01-19 00:00', '2003-12-17 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoStackCapability.setRevisionsDescriptions(('Added ciscoStackCapCatOSV08R0701PCat6k for Cisco CatOS 8.7(1).', 'Add VARIATIONs for notifications chassisAlarmOff, chassisAlarmOn, moduleDown and moduleUp, in ciscoStackCapCatOSV08R0101Cat6k.', 'Added ciscoStackCapV12R0112cE01PCat6k for Cisco IOS 12.1(12c)E1.', 'Initial version of this MIB module.',))
if mibBuilder.loadTexts: ciscoStackCapability.setLastUpdated('200803190000Z')
if mibBuilder.loadTexts: ciscoStackCapability.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts: ciscoStackCapability.setContactInfo(' Cisco Systems Customer Service Postal: 170 West Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-lan-switch-snmp@cisco.com, cs-snmp@cisco.com')
if mibBuilder.loadTexts: ciscoStackCapability.setDescription('The capabilities description of CISCO-STACK-MIB.')
ciscoStackCapCatOSV08R0101Cat6k = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapCatOSV08R0101Cat6k = ciscoStackCapCatOSV08R0101Cat6k.setProductRelease('Cisco CatOS 8.1(1) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapCatOSV08R0101Cat6k = ciscoStackCapCatOSV08R0101Cat6k.setStatus('current')
if mibBuilder.loadTexts: ciscoStackCapCatOSV08R0101Cat6k.setDescription('CISCO-STACK-MIB capabilities.')
ciscoStackCapV12R0111bEXCat6k = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapV12R0111bEXCat6k = ciscoStackCapV12R0111bEXCat6k.setProductRelease('Cisco IOS 12.1(11b)EX on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapV12R0111bEXCat6k = ciscoStackCapV12R0111bEXCat6k.setStatus('current')
if mibBuilder.loadTexts: ciscoStackCapV12R0111bEXCat6k.setDescription('CISCO-STACK-MIB capabilities.')
ciscoStackCapV12R0112cE01PCat6k = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapV12R0112cE01PCat6k = ciscoStackCapV12R0112cE01PCat6k.setProductRelease('Cisco IOS 12.1(12c)E1 on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapV12R0112cE01PCat6k = ciscoStackCapV12R0112cE01PCat6k.setStatus('current')
if mibBuilder.loadTexts: ciscoStackCapV12R0112cE01PCat6k.setDescription('CISCO-STACK-MIB capabilities.')
ciscoStackCapCatOSV08R0701PCat6k = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapCatOSV08R0701PCat6k = ciscoStackCapCatOSV08R0701PCat6k.setProductRelease('Cisco CatOS 8.7(1) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapCatOSV08R0701PCat6k = ciscoStackCapCatOSV08R0701PCat6k.setStatus('current')
if mibBuilder.loadTexts: ciscoStackCapCatOSV08R0701PCat6k.setDescription('CISCO-STACK-MIB capabilities.')
mibBuilder.exportSymbols("CISCO-STACK-CAPABILITY", ciscoStackCapCatOSV08R0101Cat6k=ciscoStackCapCatOSV08R0101Cat6k, ciscoStackCapability=ciscoStackCapability, PYSNMP_MODULE_ID=ciscoStackCapability, ciscoStackCapCatOSV08R0701PCat6k=ciscoStackCapCatOSV08R0701PCat6k, ciscoStackCapV12R0112cE01PCat6k=ciscoStackCapV12R0112cE01PCat6k, ciscoStackCapV12R0111bEXCat6k=ciscoStackCapV12R0111bEXCat6k)
|
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueRangeConstraint', 'SingleValueConstraint', 'ValueSizeConstraint')
(cisco_agent_capability,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoAgentCapability')
(agent_capabilities, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'AgentCapabilities', 'NotificationGroup', 'ModuleCompliance')
(object_identity, gauge32, counter64, counter32, integer32, bits, module_identity, iso, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, mib_identifier, ip_address, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'Gauge32', 'Counter64', 'Counter32', 'Integer32', 'Bits', 'ModuleIdentity', 'iso', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'MibIdentifier', 'IpAddress', 'NotificationType')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
cisco_stack_capability = module_identity((1, 3, 6, 1, 4, 1, 9, 7, 378))
ciscoStackCapability.setRevisions(('2008-03-19 00:00', '2006-03-15 00:00', '2005-01-19 00:00', '2003-12-17 00:00'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
ciscoStackCapability.setRevisionsDescriptions(('Added ciscoStackCapCatOSV08R0701PCat6k for Cisco CatOS 8.7(1).', 'Add VARIATIONs for notifications chassisAlarmOff, chassisAlarmOn, moduleDown and moduleUp, in ciscoStackCapCatOSV08R0101Cat6k.', 'Added ciscoStackCapV12R0112cE01PCat6k for Cisco IOS 12.1(12c)E1.', 'Initial version of this MIB module.'))
if mibBuilder.loadTexts:
ciscoStackCapability.setLastUpdated('200803190000Z')
if mibBuilder.loadTexts:
ciscoStackCapability.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts:
ciscoStackCapability.setContactInfo(' Cisco Systems Customer Service Postal: 170 West Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-lan-switch-snmp@cisco.com, cs-snmp@cisco.com')
if mibBuilder.loadTexts:
ciscoStackCapability.setDescription('The capabilities description of CISCO-STACK-MIB.')
cisco_stack_cap_cat_osv08_r0101_cat6k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_stack_cap_cat_osv08_r0101_cat6k = ciscoStackCapCatOSV08R0101Cat6k.setProductRelease('Cisco CatOS 8.1(1) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_stack_cap_cat_osv08_r0101_cat6k = ciscoStackCapCatOSV08R0101Cat6k.setStatus('current')
if mibBuilder.loadTexts:
ciscoStackCapCatOSV08R0101Cat6k.setDescription('CISCO-STACK-MIB capabilities.')
cisco_stack_cap_v12_r0111b_ex_cat6k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_stack_cap_v12_r0111b_ex_cat6k = ciscoStackCapV12R0111bEXCat6k.setProductRelease('Cisco IOS 12.1(11b)EX on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_stack_cap_v12_r0111b_ex_cat6k = ciscoStackCapV12R0111bEXCat6k.setStatus('current')
if mibBuilder.loadTexts:
ciscoStackCapV12R0111bEXCat6k.setDescription('CISCO-STACK-MIB capabilities.')
cisco_stack_cap_v12_r0112c_e01_p_cat6k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_stack_cap_v12_r0112c_e01_p_cat6k = ciscoStackCapV12R0112cE01PCat6k.setProductRelease('Cisco IOS 12.1(12c)E1 on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_stack_cap_v12_r0112c_e01_p_cat6k = ciscoStackCapV12R0112cE01PCat6k.setStatus('current')
if mibBuilder.loadTexts:
ciscoStackCapV12R0112cE01PCat6k.setDescription('CISCO-STACK-MIB capabilities.')
cisco_stack_cap_cat_osv08_r0701_p_cat6k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_stack_cap_cat_osv08_r0701_p_cat6k = ciscoStackCapCatOSV08R0701PCat6k.setProductRelease('Cisco CatOS 8.7(1) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_stack_cap_cat_osv08_r0701_p_cat6k = ciscoStackCapCatOSV08R0701PCat6k.setStatus('current')
if mibBuilder.loadTexts:
ciscoStackCapCatOSV08R0701PCat6k.setDescription('CISCO-STACK-MIB capabilities.')
mibBuilder.exportSymbols('CISCO-STACK-CAPABILITY', ciscoStackCapCatOSV08R0101Cat6k=ciscoStackCapCatOSV08R0101Cat6k, ciscoStackCapability=ciscoStackCapability, PYSNMP_MODULE_ID=ciscoStackCapability, ciscoStackCapCatOSV08R0701PCat6k=ciscoStackCapCatOSV08R0701PCat6k, ciscoStackCapV12R0112cE01PCat6k=ciscoStackCapV12R0112cE01PCat6k, ciscoStackCapV12R0111bEXCat6k=ciscoStackCapV12R0111bEXCat6k)
|
description = 'system setup'
group = 'lowlevel'
sysconfig = dict(
cache='localhost',
instrument='ESTIA',
experiment='Exp',
datasinks=['conssink', 'filesink', 'daemonsink'],
)
modules = ['nicos.commands.standard']
includes = ['temp']
devices = dict(
ESTIA=device('nicos.devices.instrument.Instrument',
description='instrument object',
instrument='estia',
responsible='Artur Glavic <artur.glavic@psi.ch>',
website='https://confluence.esss.lu.se/display/ESTIA',
operators=['ESS', 'PSI'],
facility='Paul Scherrer Institut (PSI)',
),
Sample=device('nicos.devices.sample.Sample',
description='The currently used sample',
),
Exp=device('nicos.devices.experiment.Experiment',
description='experiment object',
dataroot='/opt/nicos-data',
sendmail=True,
serviceexp='p0',
sample='Sample',
),
filesink=device('nicos.devices.datasinks.AsciiScanfileSink',
),
conssink=device('nicos.devices.datasinks.ConsoleScanSink',
),
daemonsink=device('nicos.devices.datasinks.DaemonSink',
),
Space=device('nicos.devices.generic.FreeSpace',
description='The amount of free space for storing data',
path='/opt/nicos-data',
minfree=5,
),
)
|
description = 'system setup'
group = 'lowlevel'
sysconfig = dict(cache='localhost', instrument='ESTIA', experiment='Exp', datasinks=['conssink', 'filesink', 'daemonsink'])
modules = ['nicos.commands.standard']
includes = ['temp']
devices = dict(ESTIA=device('nicos.devices.instrument.Instrument', description='instrument object', instrument='estia', responsible='Artur Glavic <artur.glavic@psi.ch>', website='https://confluence.esss.lu.se/display/ESTIA', operators=['ESS', 'PSI'], facility='Paul Scherrer Institut (PSI)'), Sample=device('nicos.devices.sample.Sample', description='The currently used sample'), Exp=device('nicos.devices.experiment.Experiment', description='experiment object', dataroot='/opt/nicos-data', sendmail=True, serviceexp='p0', sample='Sample'), filesink=device('nicos.devices.datasinks.AsciiScanfileSink'), conssink=device('nicos.devices.datasinks.ConsoleScanSink'), daemonsink=device('nicos.devices.datasinks.DaemonSink'), Space=device('nicos.devices.generic.FreeSpace', description='The amount of free space for storing data', path='/opt/nicos-data', minfree=5))
|
a = float(input())
b = float(input())
c = float(input())
media = (a * 2 + b * 3 + c * 5) / (2 + 3 + 5)
print("MEDIA = {:.1f}".format(media))
|
a = float(input())
b = float(input())
c = float(input())
media = (a * 2 + b * 3 + c * 5) / (2 + 3 + 5)
print('MEDIA = {:.1f}'.format(media))
|
#Aula 7
#Dicionarios
lista = []
# dicionario = {'Nome':'Matheus', 'Sobrenome': 'Schuetz' }
# print(dicionario)
# print(dicionario['Sobrenome'])
nome = 'Maria'
lista_notas = [10,20,50,70]
media = sum(lista_notas)/len(lista_notas)
situacao = 'Reprovado'
if media >=7:
situacao = 'Aprovado'
dicionario_alunos = {'Nome':nome, 'Lista_Notas':lista_notas, 'Media':media, 'Situacao':situacao}
print(f"{dicionario_alunos['Nome']} - {dicionario_alunos['Situacao']}")
|
lista = []
nome = 'Maria'
lista_notas = [10, 20, 50, 70]
media = sum(lista_notas) / len(lista_notas)
situacao = 'Reprovado'
if media >= 7:
situacao = 'Aprovado'
dicionario_alunos = {'Nome': nome, 'Lista_Notas': lista_notas, 'Media': media, 'Situacao': situacao}
print(f"{dicionario_alunos['Nome']} - {dicionario_alunos['Situacao']}")
|
TEACHER_AUTHORITIES = [
'VIEW_PROFILE',
'JUDGE_TASK',
'SHARE_TASK',
'VIEW_ABSENT',
'SUBMIT_LESSON',
'VIEW_LESSON',
'VIEW_ACTIVITY',
'EDIT_PROFILE',
'GIVE_TASK',
'VIEW_TASK',
'ADD_ABSENT'
]
STUDENT_AUTHORITIES = [
'VIEW_PROFILE',
'VIEW_LESSON',
'VIEW_ACTIVITY',
'VIEW_TASK_FRAGMENT',
'DOING_TASK',
'VIEW_ABSENT',
'EDIT_PROFILE',
]
OTHER_AUTHORITIES = [
'VIEW_LESSON',
'VIEW_MAP',
'VIEW_CHALLENGE'
'EDIT_SCHOOL',
'EDIT_PROFILE',
'DO_CHALLENGE',
'ADD_SCHOOL'
]
|
teacher_authorities = ['VIEW_PROFILE', 'JUDGE_TASK', 'SHARE_TASK', 'VIEW_ABSENT', 'SUBMIT_LESSON', 'VIEW_LESSON', 'VIEW_ACTIVITY', 'EDIT_PROFILE', 'GIVE_TASK', 'VIEW_TASK', 'ADD_ABSENT']
student_authorities = ['VIEW_PROFILE', 'VIEW_LESSON', 'VIEW_ACTIVITY', 'VIEW_TASK_FRAGMENT', 'DOING_TASK', 'VIEW_ABSENT', 'EDIT_PROFILE']
other_authorities = ['VIEW_LESSON', 'VIEW_MAP', 'VIEW_CHALLENGEEDIT_SCHOOL', 'EDIT_PROFILE', 'DO_CHALLENGE', 'ADD_SCHOOL']
|
def _init():
global _global_dict
_global_dict = {}
def set_value(key, value):
_global_dict[key] = value
def get_value(key):
return _global_dict.get(key)
_init()
|
def _init():
global _global_dict
_global_dict = {}
def set_value(key, value):
_global_dict[key] = value
def get_value(key):
return _global_dict.get(key)
_init()
|
#
# PySNMP MIB module CISCO-VLAN-GROUP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VLAN-GROUP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:29 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
Cisco2KVlanList, = mibBuilder.importSymbols("CISCO-TC", "Cisco2KVlanList")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
Unsigned32, IpAddress, ModuleIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Counter64, NotificationType, ObjectIdentity, Gauge32, Integer32, TimeTicks, Counter32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "IpAddress", "ModuleIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Counter64", "NotificationType", "ObjectIdentity", "Gauge32", "Integer32", "TimeTicks", "Counter32", "MibIdentifier")
RowStatus, TextualConvention, DisplayString, StorageType = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "DisplayString", "StorageType")
ciscoVlanGroupMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 709))
ciscoVlanGroupMIB.setRevisions(('2011-03-22 00:00', '2009-11-20 00:00',))
if mibBuilder.loadTexts: ciscoVlanGroupMIB.setLastUpdated('201103220000Z')
if mibBuilder.loadTexts: ciscoVlanGroupMIB.setOrganization('Cisco Systems, Inc.')
ciscoVlanGroupMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 0))
ciscoVlanGroupMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 1))
ciscoVlanGroupMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 2))
cvgConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1), )
if mibBuilder.loadTexts: cvgConfigTable.setStatus('current')
cvgConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1), ).setIndexNames((0, "CISCO-VLAN-GROUP-MIB", "cvgConfigGroupName"))
if mibBuilder.loadTexts: cvgConfigEntry.setStatus('current')
cvgConfigGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32)))
if mibBuilder.loadTexts: cvgConfigGroupName.setStatus('current')
cvgConfigVlansFirst2K = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 2), Cisco2KVlanList()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvgConfigVlansFirst2K.setStatus('current')
cvgConfigVlansSecond2K = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 3), Cisco2KVlanList()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvgConfigVlansSecond2K.setStatus('current')
cvgConfigStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 4), StorageType().clone('volatile')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvgConfigStorageType.setStatus('current')
cvgConfigRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvgConfigRowStatus.setStatus('current')
cvgConfigTableSize = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvgConfigTableSize.setStatus('current')
ciscoVlanGroupMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 1))
ciscoVlanGroupMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 2))
ciscoVlanGroupMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 1, 1)).setObjects(("CISCO-VLAN-GROUP-MIB", "ciscoVlanGroupConfigGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoVlanGroupMIBCompliance = ciscoVlanGroupMIBCompliance.setStatus('deprecated')
ciscoVlanGroupMIBCompliance2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 1, 2)).setObjects(("CISCO-VLAN-GROUP-MIB", "ciscoVlanGroupConfigGroup"), ("CISCO-VLAN-GROUP-MIB", "cvgConfigTableSizeGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoVlanGroupMIBCompliance2 = ciscoVlanGroupMIBCompliance2.setStatus('current')
ciscoVlanGroupConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 2, 1)).setObjects(("CISCO-VLAN-GROUP-MIB", "cvgConfigVlansFirst2K"), ("CISCO-VLAN-GROUP-MIB", "cvgConfigVlansSecond2K"), ("CISCO-VLAN-GROUP-MIB", "cvgConfigRowStatus"), ("CISCO-VLAN-GROUP-MIB", "cvgConfigStorageType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoVlanGroupConfigGroup = ciscoVlanGroupConfigGroup.setStatus('current')
cvgConfigTableSizeGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 2, 2)).setObjects(("CISCO-VLAN-GROUP-MIB", "cvgConfigTableSize"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cvgConfigTableSizeGroup = cvgConfigTableSizeGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-VLAN-GROUP-MIB", cvgConfigEntry=cvgConfigEntry, cvgConfigTableSizeGroup=cvgConfigTableSizeGroup, cvgConfigTable=cvgConfigTable, ciscoVlanGroupConfigGroup=ciscoVlanGroupConfigGroup, ciscoVlanGroupMIBNotifs=ciscoVlanGroupMIBNotifs, ciscoVlanGroupMIBGroups=ciscoVlanGroupMIBGroups, cvgConfigGroupName=cvgConfigGroupName, ciscoVlanGroupMIBConform=ciscoVlanGroupMIBConform, ciscoVlanGroupMIBCompliance2=ciscoVlanGroupMIBCompliance2, ciscoVlanGroupMIB=ciscoVlanGroupMIB, ciscoVlanGroupMIBCompliance=ciscoVlanGroupMIBCompliance, PYSNMP_MODULE_ID=ciscoVlanGroupMIB, cvgConfigRowStatus=cvgConfigRowStatus, cvgConfigVlansFirst2K=cvgConfigVlansFirst2K, ciscoVlanGroupMIBCompliances=ciscoVlanGroupMIBCompliances, cvgConfigVlansSecond2K=cvgConfigVlansSecond2K, ciscoVlanGroupMIBObjects=ciscoVlanGroupMIBObjects, cvgConfigTableSize=cvgConfigTableSize, cvgConfigStorageType=cvgConfigStorageType)
|
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection')
(cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt')
(cisco2_k_vlan_list,) = mibBuilder.importSymbols('CISCO-TC', 'Cisco2KVlanList')
(snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
(notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup')
(unsigned32, ip_address, module_identity, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, counter64, notification_type, object_identity, gauge32, integer32, time_ticks, counter32, mib_identifier) = mibBuilder.importSymbols('SNMPv2-SMI', 'Unsigned32', 'IpAddress', 'ModuleIdentity', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'Counter64', 'NotificationType', 'ObjectIdentity', 'Gauge32', 'Integer32', 'TimeTicks', 'Counter32', 'MibIdentifier')
(row_status, textual_convention, display_string, storage_type) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'TextualConvention', 'DisplayString', 'StorageType')
cisco_vlan_group_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 709))
ciscoVlanGroupMIB.setRevisions(('2011-03-22 00:00', '2009-11-20 00:00'))
if mibBuilder.loadTexts:
ciscoVlanGroupMIB.setLastUpdated('201103220000Z')
if mibBuilder.loadTexts:
ciscoVlanGroupMIB.setOrganization('Cisco Systems, Inc.')
cisco_vlan_group_mib_notifs = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 0))
cisco_vlan_group_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 1))
cisco_vlan_group_mib_conform = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 2))
cvg_config_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1))
if mibBuilder.loadTexts:
cvgConfigTable.setStatus('current')
cvg_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1)).setIndexNames((0, 'CISCO-VLAN-GROUP-MIB', 'cvgConfigGroupName'))
if mibBuilder.loadTexts:
cvgConfigEntry.setStatus('current')
cvg_config_group_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 1), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 32)))
if mibBuilder.loadTexts:
cvgConfigGroupName.setStatus('current')
cvg_config_vlans_first2_k = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 2), cisco2_k_vlan_list()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cvgConfigVlansFirst2K.setStatus('current')
cvg_config_vlans_second2_k = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 3), cisco2_k_vlan_list()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cvgConfigVlansSecond2K.setStatus('current')
cvg_config_storage_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 4), storage_type().clone('volatile')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cvgConfigStorageType.setStatus('current')
cvg_config_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 5), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cvgConfigRowStatus.setStatus('current')
cvg_config_table_size = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 2), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cvgConfigTableSize.setStatus('current')
cisco_vlan_group_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 1))
cisco_vlan_group_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 2))
cisco_vlan_group_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 1, 1)).setObjects(('CISCO-VLAN-GROUP-MIB', 'ciscoVlanGroupConfigGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_vlan_group_mib_compliance = ciscoVlanGroupMIBCompliance.setStatus('deprecated')
cisco_vlan_group_mib_compliance2 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 1, 2)).setObjects(('CISCO-VLAN-GROUP-MIB', 'ciscoVlanGroupConfigGroup'), ('CISCO-VLAN-GROUP-MIB', 'cvgConfigTableSizeGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_vlan_group_mib_compliance2 = ciscoVlanGroupMIBCompliance2.setStatus('current')
cisco_vlan_group_config_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 2, 1)).setObjects(('CISCO-VLAN-GROUP-MIB', 'cvgConfigVlansFirst2K'), ('CISCO-VLAN-GROUP-MIB', 'cvgConfigVlansSecond2K'), ('CISCO-VLAN-GROUP-MIB', 'cvgConfigRowStatus'), ('CISCO-VLAN-GROUP-MIB', 'cvgConfigStorageType'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_vlan_group_config_group = ciscoVlanGroupConfigGroup.setStatus('current')
cvg_config_table_size_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 2, 2)).setObjects(('CISCO-VLAN-GROUP-MIB', 'cvgConfigTableSize'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cvg_config_table_size_group = cvgConfigTableSizeGroup.setStatus('current')
mibBuilder.exportSymbols('CISCO-VLAN-GROUP-MIB', cvgConfigEntry=cvgConfigEntry, cvgConfigTableSizeGroup=cvgConfigTableSizeGroup, cvgConfigTable=cvgConfigTable, ciscoVlanGroupConfigGroup=ciscoVlanGroupConfigGroup, ciscoVlanGroupMIBNotifs=ciscoVlanGroupMIBNotifs, ciscoVlanGroupMIBGroups=ciscoVlanGroupMIBGroups, cvgConfigGroupName=cvgConfigGroupName, ciscoVlanGroupMIBConform=ciscoVlanGroupMIBConform, ciscoVlanGroupMIBCompliance2=ciscoVlanGroupMIBCompliance2, ciscoVlanGroupMIB=ciscoVlanGroupMIB, ciscoVlanGroupMIBCompliance=ciscoVlanGroupMIBCompliance, PYSNMP_MODULE_ID=ciscoVlanGroupMIB, cvgConfigRowStatus=cvgConfigRowStatus, cvgConfigVlansFirst2K=cvgConfigVlansFirst2K, ciscoVlanGroupMIBCompliances=ciscoVlanGroupMIBCompliances, cvgConfigVlansSecond2K=cvgConfigVlansSecond2K, ciscoVlanGroupMIBObjects=ciscoVlanGroupMIBObjects, cvgConfigTableSize=cvgConfigTableSize, cvgConfigStorageType=cvgConfigStorageType)
|
def hello_world():
print("hello world")
# [REQ-002]
def hello_world_2():
print("hello world")
# [/REQ-002]
|
def hello_world():
print('hello world')
def hello_world_2():
print('hello world')
|
class Solution:
def solve(self, s, pairs):
letters = set(ascii_lowercase)
leaders = {letter:letter for letter in letters}
followers = {letter:[letter] for letter in letters}
for a,b in pairs:
if leaders[a] == leaders[b]: continue
if len(followers[a]) < len(followers[b]): a,b = b,a
old_leader = leaders[b]
new_leader = leaders[a]
for follower in followers[old_leader]:
leaders[follower] = new_leader
followers[new_leader].append(follower)
followers[old_leader] = []
return all(leaders[s[i]]==leaders[s[~i]] for i in range(len(s)))
|
class Solution:
def solve(self, s, pairs):
letters = set(ascii_lowercase)
leaders = {letter: letter for letter in letters}
followers = {letter: [letter] for letter in letters}
for (a, b) in pairs:
if leaders[a] == leaders[b]:
continue
if len(followers[a]) < len(followers[b]):
(a, b) = (b, a)
old_leader = leaders[b]
new_leader = leaders[a]
for follower in followers[old_leader]:
leaders[follower] = new_leader
followers[new_leader].append(follower)
followers[old_leader] = []
return all((leaders[s[i]] == leaders[s[~i]] for i in range(len(s))))
|
prompt = "How old are you?"
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
age = int(message)
if age < 3:
print("Free")
elif age < 12:
print("The fare is 10 dollar")
else:
print("The fare is 15 dollar")
|
prompt = 'How old are you?'
message = ''
while message != 'quit':
message = input(prompt)
if message != 'quit':
age = int(message)
if age < 3:
print('Free')
elif age < 12:
print('The fare is 10 dollar')
else:
print('The fare is 15 dollar')
|
# Variables
first_name = "Ada"
# print function followed by variable name.
print("Hello,", first_name)
print(first_name, "is learning Python")
# print takes multiple arguments.
print("These", "will be", "joined together by spaces")
# input statement.
first_name = input("What is your first name? ")
print("Hello,", first_name)
|
first_name = 'Ada'
print('Hello,', first_name)
print(first_name, 'is learning Python')
print('These', 'will be', 'joined together by spaces')
first_name = input('What is your first name? ')
print('Hello,', first_name)
|
def extractThehlifestyleCom(item):
'''
Parser for 'thehlifestyle.com'
'''
tstr = str(item['tags']).lower()
if 'review' in tstr:
return None
if 'actors' in tstr:
return None
if 'game' in tstr:
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('The Beloved Imperial Consort translation', 'The Beloved Imperial Consort', 'translated'),
('Good Morning, Miss Undercover Translation', 'Good Morning, Miss Undercover', 'translated'),
('Hilarous Pampered Consort Translation', 'Hilarous Pampered Consort', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
def extract_thehlifestyle_com(item):
"""
Parser for 'thehlifestyle.com'
"""
tstr = str(item['tags']).lower()
if 'review' in tstr:
return None
if 'actors' in tstr:
return None
if 'game' in tstr:
return None
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [('The Beloved Imperial Consort translation', 'The Beloved Imperial Consort', 'translated'), ('Good Morning, Miss Undercover Translation', 'Good Morning, Miss Undercover', 'translated'), ('Hilarous Pampered Consort Translation', 'Hilarous Pampered Consort', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap:
if tagname in item['tags']:
return build_release_message_with_type(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
"""Volatility 3 Linux Constants.
Windows-specific values that aren't found in debug symbols
"""
KERNEL_MODULE_NAMES = ["ntkrnlmp", "ntkrnlpa", "ntkrpamp", "ntoskrnl"]
"""The list of names that kernel modules can have within the windows OS"""
|
"""Volatility 3 Linux Constants.
Windows-specific values that aren't found in debug symbols
"""
kernel_module_names = ['ntkrnlmp', 'ntkrnlpa', 'ntkrpamp', 'ntoskrnl']
'The list of names that kernel modules can have within the windows OS'
|
"""
This subpackage is intented for low-level extension developers and compiler
developers. Regular user SHOULD NOT use code in this module.
This contains compilable utility functions that can interact directly with
the compiler to implement low-level internal code.
"""
|
"""
This subpackage is intented for low-level extension developers and compiler
developers. Regular user SHOULD NOT use code in this module.
This contains compilable utility functions that can interact directly with
the compiler to implement low-level internal code.
"""
|
'''
Given the root of a binary tree,
check whether it is a mirror of itself (i.e., symmetric around its center).
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
"""
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.left = n2
n1.right = n3
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def dfs(root1, root2):
if root1 == root2 == None: return True
if not root1 or not root2: return False
if root1.val != root2.val: return False
return dfs(root1.left, root2.right) and dfs(root1.right, root2.left)
if not root: return True
return dfs(root.left, root.right)
def isSymmetric_iter_TLE(self, root: Optional[TreeNode]) -> bool:
que = []
ans = True
que.append(root)
if not root:
return ans
if not root.left and not root.right:
return ans
while que:
length = len(que)
val_list = []
for _ in range(length):
root = que.pop(0)
if not root:
val_list.append(None)
else:
val_list.append(root.val)
if root.left:
que.append(root.left)
else:
que.append(None)
if root.right:
que.append(root.right)
else:
que.append(None)
if length == 1:
ans = ans and True
else:
a, b = val_list[:int(length / 2)], val_list[int(length / 2):]
b.reverse()
if a == b:
ans = ans and True
else:
ans = ans and False
return ans
|
'''
Given the root of a binary tree,
check whether it is a mirror of itself (i.e., symmetric around its center).
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ 2 2
/ \\ / 3 4 4 3
But the following is not:
1
/ 2 2
\\ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
"""
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.left = n2
n1.right = n3
'''
class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def is_symmetric(self, root: TreeNode) -> bool:
def dfs(root1, root2):
if root1 == root2 == None:
return True
if not root1 or not root2:
return False
if root1.val != root2.val:
return False
return dfs(root1.left, root2.right) and dfs(root1.right, root2.left)
if not root:
return True
return dfs(root.left, root.right)
def is_symmetric_iter_tle(self, root: Optional[TreeNode]) -> bool:
que = []
ans = True
que.append(root)
if not root:
return ans
if not root.left and (not root.right):
return ans
while que:
length = len(que)
val_list = []
for _ in range(length):
root = que.pop(0)
if not root:
val_list.append(None)
else:
val_list.append(root.val)
if root.left:
que.append(root.left)
else:
que.append(None)
if root.right:
que.append(root.right)
else:
que.append(None)
if length == 1:
ans = ans and True
else:
(a, b) = (val_list[:int(length / 2)], val_list[int(length / 2):])
b.reverse()
if a == b:
ans = ans and True
else:
ans = ans and False
return ans
|
""" Definitions used to parse DTED files. """
# Definitions of DTED Record lengths.
UHL_SIZE = 80
DSI_SIZE = 648
ACC_SIZE = 2700
# Definitions of the value DTED uses for void data.
VOID_DATA_VALUE = (-1 << 15) + 1
_UTF8 = "utf-8"
|
""" Definitions used to parse DTED files. """
uhl_size = 80
dsi_size = 648
acc_size = 2700
void_data_value = (-1 << 15) + 1
_utf8 = 'utf-8'
|
ATTACK = '-'
SUPPORT = '+'
NEUTRAL = '0'
CRITICAL_SUPPORT = '+!'
CRITICAL_ATTACK = '-!'
WEAK_SUPPORT = '+*'
WEAK_ATTACK = '-*'
NON_SUPPORT = '+~'
NON_ATTACK = '-~'
TRIPOLAR_RELATIONS = [ATTACK, SUPPORT, NEUTRAL]
QUADPOLAR_RELATIONS = [ATTACK, SUPPORT, NEUTRAL, CRITICAL_SUPPORT]
def get_type(val):
if val > 0:
return SUPPORT
elif val < 0:
return ATTACK
else:
return NEUTRAL
def get_relations_set(G, rel=None):
return set([edge for edge in G.edges if rel is None or G.edges[edge]['type'] == rel])
|
attack = '-'
support = '+'
neutral = '0'
critical_support = '+!'
critical_attack = '-!'
weak_support = '+*'
weak_attack = '-*'
non_support = '+~'
non_attack = '-~'
tripolar_relations = [ATTACK, SUPPORT, NEUTRAL]
quadpolar_relations = [ATTACK, SUPPORT, NEUTRAL, CRITICAL_SUPPORT]
def get_type(val):
if val > 0:
return SUPPORT
elif val < 0:
return ATTACK
else:
return NEUTRAL
def get_relations_set(G, rel=None):
return set([edge for edge in G.edges if rel is None or G.edges[edge]['type'] == rel])
|
# repeating strings
s = "?"
for i in range(4):
print(s, end="")
print()
print(s * 4)
# looping strings
text = "This is an example."
count = 0
for char in text:
# isalpha() returns true if the character is a-z
if char.isalpha():
count += 1
|
s = '?'
for i in range(4):
print(s, end='')
print()
print(s * 4)
text = 'This is an example.'
count = 0
for char in text:
if char.isalpha():
count += 1
|
CREDENTIALS = {
'username': 'Replace with your WA username',
'password': 'Replace with your WA password (b64)'
}
DEFAULT_RECIPIENTS = ('single-user@s.whatsapp.net', 'group-chat@g.us',)
HOST_NOTIFICATION = '%(emoji)s %(type)s HOST ALERT %(emoji)s\n\n' + \
'Host %(host)s, %(address)s is %(state)s.\n\n' + \
'%(info)s\n\n' + \
'%(time)s'
SERVICE_NOTIFICATION = '%(emoji)s %(type)s SERVICE ALERT %(emoji)s\n\n' + \
'Service %(service)s @ %(host)s, %(address)s is %(state)s.\n\n' + \
'%(info)s\n\n' + \
'%(time)s'
|
credentials = {'username': 'Replace with your WA username', 'password': 'Replace with your WA password (b64)'}
default_recipients = ('single-user@s.whatsapp.net', 'group-chat@g.us')
host_notification = '%(emoji)s %(type)s HOST ALERT %(emoji)s\n\n' + 'Host %(host)s, %(address)s is %(state)s.\n\n' + '%(info)s\n\n' + '%(time)s'
service_notification = '%(emoji)s %(type)s SERVICE ALERT %(emoji)s\n\n' + 'Service %(service)s @ %(host)s, %(address)s is %(state)s.\n\n' + '%(info)s\n\n' + '%(time)s'
|
'''9. Write a Python program to get the difference between the two lists. '''
def difference_twoLists(lst1, lst2):
lst1 = set(lst1)
lst2 = set(lst2)
return list(lst1 - lst2)
print(difference_twoLists([1, 2, 3, 4], [4, 5, 6, 7]))
print(difference_twoLists([1, 2, 3, 4], [0, 5, 6, 7]))
print(difference_twoLists([1, 2, 3, 4], [3, 5, 6, 7]))
|
"""9. Write a Python program to get the difference between the two lists. """
def difference_two_lists(lst1, lst2):
lst1 = set(lst1)
lst2 = set(lst2)
return list(lst1 - lst2)
print(difference_two_lists([1, 2, 3, 4], [4, 5, 6, 7]))
print(difference_two_lists([1, 2, 3, 4], [0, 5, 6, 7]))
print(difference_two_lists([1, 2, 3, 4], [3, 5, 6, 7]))
|
'''
module for implementation of
cycle sort
'''
def cycle_sort(arr: list):
writes = 0
for cycleStart in range(0, len(arr) - 1):
item = arr[cycleStart]
pos = cycleStart
for i in range(cycleStart + 1, len(arr)):
if (arr[i] < item):
pos += 1
if (pos == cycleStart):
continue
while (item == arr[pos]):
pos += 1
arr[pos], item = item, arr[pos]
writes += 1
while (pos != cycleStart):
pos = cycleStart
for i in range(cycleStart + 1, len(arr)):
if (arr[i] < item):
pos += 1
while (item == arr[pos]):
pos += 1
arr[pos], item = item, arr[pos]
writes += 1
return arr
'''
PyAlgo
Devansh Singh
'''
|
"""
module for implementation of
cycle sort
"""
def cycle_sort(arr: list):
writes = 0
for cycle_start in range(0, len(arr) - 1):
item = arr[cycleStart]
pos = cycleStart
for i in range(cycleStart + 1, len(arr)):
if arr[i] < item:
pos += 1
if pos == cycleStart:
continue
while item == arr[pos]:
pos += 1
(arr[pos], item) = (item, arr[pos])
writes += 1
while pos != cycleStart:
pos = cycleStart
for i in range(cycleStart + 1, len(arr)):
if arr[i] < item:
pos += 1
while item == arr[pos]:
pos += 1
(arr[pos], item) = (item, arr[pos])
writes += 1
return arr
'\nPyAlgo\nDevansh Singh\n'
|
class Error(Exception):
"""Base class for BMI exceptions"""
pass
class VarNameError(Error):
"""Exception to indicate a bad input/output variable name"""
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class BMI(object):
def initialize(self, filename):
pass
def run(self, time):
pass
def finalize(self):
pass
def get_input_var_names(self):
pass
def get_output_var_names(self):
pass
def get_var_grid(self, var_name):
pass
def get_var_type(self, var_name):
pass
def get_var_units(self, var_name):
pass
def get_time_step(self):
pass
def get_start_time(self):
pass
def get_current_time(self):
pass
def get_end_time(self):
pass
def get_grid_rank(self, grid_id):
pass
def get_grid_spacing(self, grid_id):
pass
def get_grid_shape(self, grid_id):
pass
def get_grid_x(self, grid_id):
pass
def get_grid_y(self, grid_id):
pass
def get_grid_z(self, grid_id):
pass
def get_grid_connectivity(self, grid_id):
pass
def get_grid_offset(self, grid_id):
pass
|
class Error(Exception):
"""Base class for BMI exceptions"""
pass
class Varnameerror(Error):
"""Exception to indicate a bad input/output variable name"""
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class Bmi(object):
def initialize(self, filename):
pass
def run(self, time):
pass
def finalize(self):
pass
def get_input_var_names(self):
pass
def get_output_var_names(self):
pass
def get_var_grid(self, var_name):
pass
def get_var_type(self, var_name):
pass
def get_var_units(self, var_name):
pass
def get_time_step(self):
pass
def get_start_time(self):
pass
def get_current_time(self):
pass
def get_end_time(self):
pass
def get_grid_rank(self, grid_id):
pass
def get_grid_spacing(self, grid_id):
pass
def get_grid_shape(self, grid_id):
pass
def get_grid_x(self, grid_id):
pass
def get_grid_y(self, grid_id):
pass
def get_grid_z(self, grid_id):
pass
def get_grid_connectivity(self, grid_id):
pass
def get_grid_offset(self, grid_id):
pass
|
class Script:
@staticmethod
def main():
cities = ["Albuquerque", "Anaheim", "Anchorage", "Arlington", "Atlanta", "Aurora", "Austin", "Bakersfield", "Baltimore", "Boston", "Buffalo", "Charlotte-Mecklenburg", "Cincinnati", "Cleveland", "Colorado Springs", "Corpus Christi", "Dallas", "Denver", "Detroit", "El Paso", "Fort Wayne", "Fort Worth", "Fresno", "Greensboro", "Henderson", "Houston", "Indianapolis", "Jacksonville", "Jersey City", "Kansas City", "Las Vegas", "Lexington", "Lincoln", "Long Beach", "Los Angeles", "Louisville Metro", "Memphis", "Mesa", "Miami", "Milwaukee", "Minneapolis", "Mobile", "Nashville", "New Orleans", "New York", "Newark", "Oakland", "Oklahoma City", "Omaha", "Philadelphia", "Phoenix", "Pittsburgh", "Plano", "Portland", "Raleigh", "Riverside", "Sacramento", "San Antonio", "San Diego", "San Francisco", "San Jose", "Santa Ana", "Seattle", "St. Louis", "St. Paul", "Stockton", "Tampa", "Toledo", "Tucson", "Tulsa", "Virginia Beach", "Washington", "Wichita"]
first_alb = ((cities[0] if 0 < len(cities) else None) == "Albuquerque")
second_alb = ((cities[1] if 1 < len(cities) else None) == "Albuquerque")
first_last = ((cities[0] if 0 < len(cities) else None) == python_internal_ArrayImpl._get(cities, (len(cities) - 1)))
print(str(first_alb))
print(str(second_alb))
print(str(first_last))
class python_internal_ArrayImpl:
@staticmethod
def _get(x,idx):
if ((idx > -1) and ((idx < len(x)))):
return x[idx]
else:
return None
Script.main()
|
class Script:
@staticmethod
def main():
cities = ['Albuquerque', 'Anaheim', 'Anchorage', 'Arlington', 'Atlanta', 'Aurora', 'Austin', 'Bakersfield', 'Baltimore', 'Boston', 'Buffalo', 'Charlotte-Mecklenburg', 'Cincinnati', 'Cleveland', 'Colorado Springs', 'Corpus Christi', 'Dallas', 'Denver', 'Detroit', 'El Paso', 'Fort Wayne', 'Fort Worth', 'Fresno', 'Greensboro', 'Henderson', 'Houston', 'Indianapolis', 'Jacksonville', 'Jersey City', 'Kansas City', 'Las Vegas', 'Lexington', 'Lincoln', 'Long Beach', 'Los Angeles', 'Louisville Metro', 'Memphis', 'Mesa', 'Miami', 'Milwaukee', 'Minneapolis', 'Mobile', 'Nashville', 'New Orleans', 'New York', 'Newark', 'Oakland', 'Oklahoma City', 'Omaha', 'Philadelphia', 'Phoenix', 'Pittsburgh', 'Plano', 'Portland', 'Raleigh', 'Riverside', 'Sacramento', 'San Antonio', 'San Diego', 'San Francisco', 'San Jose', 'Santa Ana', 'Seattle', 'St. Louis', 'St. Paul', 'Stockton', 'Tampa', 'Toledo', 'Tucson', 'Tulsa', 'Virginia Beach', 'Washington', 'Wichita']
first_alb = (cities[0] if 0 < len(cities) else None) == 'Albuquerque'
second_alb = (cities[1] if 1 < len(cities) else None) == 'Albuquerque'
first_last = (cities[0] if 0 < len(cities) else None) == python_internal_ArrayImpl._get(cities, len(cities) - 1)
print(str(first_alb))
print(str(second_alb))
print(str(first_last))
class Python_Internal_Arrayimpl:
@staticmethod
def _get(x, idx):
if idx > -1 and idx < len(x):
return x[idx]
else:
return None
Script.main()
|
"""
Some of the options of the protocol specification
LINE
1-8
PAGE
A-Z (remapped to 0-25)
LEADING
A/a = Immediate (Image will be immediately disappeared)
B/b = Xopen (Image will be disappeared from center and extend to 4 side)
C/c = Curtain UP (Image will be disappeared one line by one line from bottom to top).
D/d = Curtain Down(Image will be disappeared one line by one Line from Top to Bottom
E/e = Scroll Left (Image will be scrolled from Right to Left and disappeared )
F/f = Scroll Right (Image will be scrolled from Right to Left and disappeared)
G/g = Vopen (Image will be disappeared from center to top and Bottom one line by one line)
H/h = Vclose(Image will be disappeared from Top and Bottom to Center one line by one line.)
I/i = Scroll Up(Image will be scrolled from Bottom to Top and disappeared)
J/j = Scroll Down (Image will be scrolled from Bottom to Top and disappeared)
K/k = Hold (Screen will be kept)
"""
def get_message_cmd(
message,
line = '1',
page = 0,
leading = 'E',
method = 'A',
wait = 'C',
lagging = 'E'):
""" returns the command to send a message into a line of a page """
return '<L%s><P%s><F%s><M%s><W%s><F%s>%s' % (
line,
_num_to_code(page),
leading,
method,
wait,
lagging,
message
)
def get_schedule_cmd(pages):
""" returns the command to set the schedule (order) of the pages """
# no support for start date / end date
return '<TA>00010100009912302359' + _nums_to_codestr(pages)
def _num_to_code(n):
# converts 0 -> A, 1 -> B
# using 'A', 'B', 'C' ... for pages is uncomfortable
return chr(ord('A') + n)
def _nums_to_codestr(numbers):
return "".join(map(_num_to_code, numbers))
|
"""
Some of the options of the protocol specification
LINE
1-8
PAGE
A-Z (remapped to 0-25)
LEADING
A/a = Immediate (Image will be immediately disappeared)
B/b = Xopen (Image will be disappeared from center and extend to 4 side)
C/c = Curtain UP (Image will be disappeared one line by one line from bottom to top).
D/d = Curtain Down(Image will be disappeared one line by one Line from Top to Bottom
E/e = Scroll Left (Image will be scrolled from Right to Left and disappeared )
F/f = Scroll Right (Image will be scrolled from Right to Left and disappeared)
G/g = Vopen (Image will be disappeared from center to top and Bottom one line by one line)
H/h = Vclose(Image will be disappeared from Top and Bottom to Center one line by one line.)
I/i = Scroll Up(Image will be scrolled from Bottom to Top and disappeared)
J/j = Scroll Down (Image will be scrolled from Bottom to Top and disappeared)
K/k = Hold (Screen will be kept)
"""
def get_message_cmd(message, line='1', page=0, leading='E', method='A', wait='C', lagging='E'):
""" returns the command to send a message into a line of a page """
return '<L%s><P%s><F%s><M%s><W%s><F%s>%s' % (line, _num_to_code(page), leading, method, wait, lagging, message)
def get_schedule_cmd(pages):
""" returns the command to set the schedule (order) of the pages """
return '<TA>00010100009912302359' + _nums_to_codestr(pages)
def _num_to_code(n):
return chr(ord('A') + n)
def _nums_to_codestr(numbers):
return ''.join(map(_num_to_code, numbers))
|
fig, ax = create_map_background()
# Contour 1 - Temperature, dotted
cs2 = ax.contour(lon, lat, tmpk_850.to('degC'), range(-50, 50, 2),
colors='grey', linestyles='dotted', transform=dataproj)
plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=10, fmt='%i',
rightside_up=True, use_clabeltext=True)
# Contour 2
clev850 = np.arange(0, 4000, 30)
cs = ax.contour(lon, lat, hght_850, clev850, colors='k',
linewidths=1.0, linestyles='solid', transform=dataproj)
plt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i',
rightside_up=True, use_clabeltext=True)
# Filled contours - Temperature advection
contours = [-3, -2.2, -2, -1.5, -1, -0.5, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
cf = ax.contourf(lon, lat, tmpc_adv_850*3600, contours,
cmap='bwr', extend='both', transform=dataproj)
plt.colorbar(cf, orientation='horizontal', pad=0, aspect=50,
extendrect=True, ticks=contours)
# Vector
ax.barbs(lon, lat, uwnd_850.to('kts').m, vwnd_850.to('kts').m,
regrid_shape=15, transform=dataproj)
# Titles
plt.title('850-hPa Geopotential Heights, Temperature (C), \
Temp Adv (C/h), and Wind Barbs (kts)', loc='left')
plt.title('VALID: {}'.format(vtime), loc='right')
plt.tight_layout()
plt.show()
|
(fig, ax) = create_map_background()
cs2 = ax.contour(lon, lat, tmpk_850.to('degC'), range(-50, 50, 2), colors='grey', linestyles='dotted', transform=dataproj)
plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabeltext=True)
clev850 = np.arange(0, 4000, 30)
cs = ax.contour(lon, lat, hght_850, clev850, colors='k', linewidths=1.0, linestyles='solid', transform=dataproj)
plt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabeltext=True)
contours = [-3, -2.2, -2, -1.5, -1, -0.5, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
cf = ax.contourf(lon, lat, tmpc_adv_850 * 3600, contours, cmap='bwr', extend='both', transform=dataproj)
plt.colorbar(cf, orientation='horizontal', pad=0, aspect=50, extendrect=True, ticks=contours)
ax.barbs(lon, lat, uwnd_850.to('kts').m, vwnd_850.to('kts').m, regrid_shape=15, transform=dataproj)
plt.title('850-hPa Geopotential Heights, Temperature (C), Temp Adv (C/h), and Wind Barbs (kts)', loc='left')
plt.title('VALID: {}'.format(vtime), loc='right')
plt.tight_layout()
plt.show()
|
#Ejercicio 01
def binarySearch(arr, valor):
#Dado un arreglo y un elemento
#Busca el elemento dado en el arreglo
inicio = 0
final = len(arr) - 1
while inicio <= final:
medio = (inicio + final) // 2
if arr[medio] == valor:
return True
elif arr[medio] < valor:
inicio = medio + 1
elif arr[medio] > valor:
final = medio -1
return False
arreglo = [2,4,8,9,10,22,25,26,28,29,30,42,45,56]
print(binarySearch(arreglo,22))
print(binarySearch(arreglo,24))
|
def binary_search(arr, valor):
inicio = 0
final = len(arr) - 1
while inicio <= final:
medio = (inicio + final) // 2
if arr[medio] == valor:
return True
elif arr[medio] < valor:
inicio = medio + 1
elif arr[medio] > valor:
final = medio - 1
return False
arreglo = [2, 4, 8, 9, 10, 22, 25, 26, 28, 29, 30, 42, 45, 56]
print(binary_search(arreglo, 22))
print(binary_search(arreglo, 24))
|
# William Thompson (wtt53)
# Software Testing and QA
# Assignment 1: Test Driven Development
# Retirement: Takes current age (int), annual salary (float),
# percent of annual salary saved (float), and savings goal (float)
# and outputs what age savings goal will be met
def calc_retirement(age, salary, percent, goal):
# cast each variable as its proper data type
try:
age = int(age)
salary = float(salary)
percent = float(percent)
goal = float(goal)
except Exception:
return (False)
# check each value to make sure it is in the proper range
if ((age < 15 or age > 99)
or (salary <= 0)
or (percent <= 0)
or (goal <= 0)):
return (False)
# savings from salary without employer's 35%
rawAnnualSavings = salary * (percent / 100)
# total annual savings including employer's 35%
annualSavings = rawAnnualSavings + (rawAnnualSavings * 0.35)
# total savings so far
currentSavings = 0.00
# add annual savings to total savings for each year until age 100
for i in range(age, 100):
currentSavings += annualSavings
if currentSavings >= goal:
return("You will meet your savings goal at age "+str(i))
# Notify user if they will not meet their goal
return("Sorry, your goal won't be met.")
|
def calc_retirement(age, salary, percent, goal):
try:
age = int(age)
salary = float(salary)
percent = float(percent)
goal = float(goal)
except Exception:
return False
if (age < 15 or age > 99) or salary <= 0 or percent <= 0 or (goal <= 0):
return False
raw_annual_savings = salary * (percent / 100)
annual_savings = rawAnnualSavings + rawAnnualSavings * 0.35
current_savings = 0.0
for i in range(age, 100):
current_savings += annualSavings
if currentSavings >= goal:
return 'You will meet your savings goal at age ' + str(i)
return "Sorry, your goal won't be met."
|
"""
this module provides encryption and decryption of strings
"""
_eng_alphabet = [chr(i) for i in range(97, 123)] + [chr(i) for i in range(65, 91)]
_rus_alphabet = [chr(i) for i in range(1072, 1104)] + [chr(i) for i in range(1040, 1072)]
_alphabets = {'en': _eng_alphabet, 'rus': _rus_alphabet}
def _add_encrypted_char(string, original_char, step):
if char.isupper():
required_index = (alphabet.index(char) + step) % (alphabet_len // 2) + (alphabet_len // 2)
encoded_str += alphabet[required_index]
else:
required_index = (alphabet.index(char) + step) % (alphabet_len // 2)
encoded_str += alphabet[required_index]
def encode(original_str, lang='en', step=1):
'''Return the string with encoding chars according the chosen language.
Numbers and other signs do not change.'''
encoded_str = ''
alphabet = _alphabets[lang]
alphabet_len = len(alphabet)
for char in original_str:
if char in alphabet:
add_encrypted_char(original_str, char, step)
else:
encoded_str += char
return encoded_str
def encode_all_lang(original_str, step=1):
'''Return the string with encoding chars.
Numbers and other signs do not change.'''
encoded_str = ''
for char in original_str:
if not char.isalpha():
encoded_str += char
for alphabet in _alphabets.values():
if char in alphabet:
alphabet_len = len(alphabet)
add_encrypted_char(original_str, char, step=step)
return encoded_str
def encode_pro(original_str, lang='en'):
'''Return the string with encoding chars according the chosen language.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word.'''
encoded_str = ''
for word in original_str.split():
encoded_str += encode(word, lang=lang, step=len(word)) + ' '
return encoded_str
def encode_pro_all_lang(original_str):
'''Return the string with encoding chars.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word.'''
encoded_str = ''
for word in original_str.split():
encoded_str += encode_all_lang(word, step=len(word)) + ' '
return encoded_str
def decode(original_str, lang='en', step=1):
'''Return the string with decoding chars according the chosen language.
Numbers and other signs do not change.'''
return encode(original_str, lang=lang, step=-step)
def decode_all_lang(original_str, step=1):
'''Return the string with decoding chars.
Numbers and other signs do not change.'''
return encode_all_lang(original_str, step=-step)
def decode_pro(original_str, lang='en'):
'''Return the string with decoding chars according the chosen language.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word.'''
encoded_str = ''
for word in original_str.split():
encoded_str += encode(word, step=-len(word)) + ' '
return encoded_str
def decode_pro_all_lang(original_str):
'''Return the string with decoding chars according the chosen language.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word.'''
encoded_str = ''
for word in original_str.split():
encoded_str += encode_all_lang(word, step=-len(word)) + ' '
return encoded_str
|
"""
this module provides encryption and decryption of strings
"""
_eng_alphabet = [chr(i) for i in range(97, 123)] + [chr(i) for i in range(65, 91)]
_rus_alphabet = [chr(i) for i in range(1072, 1104)] + [chr(i) for i in range(1040, 1072)]
_alphabets = {'en': _eng_alphabet, 'rus': _rus_alphabet}
def _add_encrypted_char(string, original_char, step):
if char.isupper():
required_index = (alphabet.index(char) + step) % (alphabet_len // 2) + alphabet_len // 2
encoded_str += alphabet[required_index]
else:
required_index = (alphabet.index(char) + step) % (alphabet_len // 2)
encoded_str += alphabet[required_index]
def encode(original_str, lang='en', step=1):
"""Return the string with encoding chars according the chosen language.
Numbers and other signs do not change."""
encoded_str = ''
alphabet = _alphabets[lang]
alphabet_len = len(alphabet)
for char in original_str:
if char in alphabet:
add_encrypted_char(original_str, char, step)
else:
encoded_str += char
return encoded_str
def encode_all_lang(original_str, step=1):
"""Return the string with encoding chars.
Numbers and other signs do not change."""
encoded_str = ''
for char in original_str:
if not char.isalpha():
encoded_str += char
for alphabet in _alphabets.values():
if char in alphabet:
alphabet_len = len(alphabet)
add_encrypted_char(original_str, char, step=step)
return encoded_str
def encode_pro(original_str, lang='en'):
"""Return the string with encoding chars according the chosen language.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word."""
encoded_str = ''
for word in original_str.split():
encoded_str += encode(word, lang=lang, step=len(word)) + ' '
return encoded_str
def encode_pro_all_lang(original_str):
"""Return the string with encoding chars.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word."""
encoded_str = ''
for word in original_str.split():
encoded_str += encode_all_lang(word, step=len(word)) + ' '
return encoded_str
def decode(original_str, lang='en', step=1):
"""Return the string with decoding chars according the chosen language.
Numbers and other signs do not change."""
return encode(original_str, lang=lang, step=-step)
def decode_all_lang(original_str, step=1):
"""Return the string with decoding chars.
Numbers and other signs do not change."""
return encode_all_lang(original_str, step=-step)
def decode_pro(original_str, lang='en'):
"""Return the string with decoding chars according the chosen language.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word."""
encoded_str = ''
for word in original_str.split():
encoded_str += encode(word, step=-len(word)) + ' '
return encoded_str
def decode_pro_all_lang(original_str):
"""Return the string with decoding chars according the chosen language.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word."""
encoded_str = ''
for word in original_str.split():
encoded_str += encode_all_lang(word, step=-len(word)) + ' '
return encoded_str
|
def solution(value):
print("Solution: {}".format(value))
|
def solution(value):
print('Solution: {}'.format(value))
|
# See LICENSE for licensing information.
#
# Copyright (c) 2021 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
class test_bench:
"""
Class to generate the test bench file for simulation.
"""
def __init__(self, cache_config, name):
cache_config.set_local_config(self)
self.name = name
self.success_message = "Simulation successful."
self.failure_message = "Simulation failed."
def test_bench_write(self, tb_path):
""" Write the test bench file. """
self.tbf = open(tb_path, "w")
self.tbf.write("// Timescale is overwritten when running the EDA tool to prevent bugs\n")
self.tbf.write("// `timescale 1ns / 1ps\n\n")
self.tbf.write("module test_bench;\n\n")
self.write_parameters()
self.write_registers()
self.write_dumps()
self.write_clock_generator()
self.write_reset_block()
self.write_instances()
self.write_tasks()
self.tbf.write(" initial begin\n")
self.tbf.write(" `include \"test_data.v\"\n")
self.tbf.write(" end\n\n")
self.tbf.write("endmodule\n")
self.tbf.close()
def write_parameters(self):
""" Write the parameters of the test bench. """
self.tbf.write(" parameter TAG_WIDTH = {};\n".format(self.tag_size))
# TODO: Fully associative cache's set_size = 0.
self.tbf.write(" parameter SET_WIDTH = {};\n".format(self.set_size))
self.tbf.write(" parameter OFFSET_WIDTH = {};\n\n".format(self.offset_size))
self.tbf.write(" parameter WORD_WIDTH = {};\n".format(self.word_size))
if self.num_masks:
self.tbf.write(" parameter MASK_COUNT = {};\n".format(self.num_masks))
self.tbf.write(" parameter WORD_COUNT = {};\n".format(self.words_per_line))
self.tbf.write(" localparam LINE_WIDTH = WORD_WIDTH * WORD_COUNT;\n\n")
self.tbf.write(" localparam ADDR_WIDTH = TAG_WIDTH + SET_WIDTH + OFFSET_WIDTH;\n\n")
self.tbf.write(" parameter CLOCK_DELAY = 5;\n")
self.tbf.write(" // Reset is asserted for 1.5 cycles\n")
self.tbf.write(" parameter RESET_DELAY = 15;\n")
self.tbf.write(" parameter DELAY = 3;\n")
self.tbf.write(" parameter MAX_TEST_SIZE = 64;\n\n")
def write_registers(self):
""" Write the registers of the test bench. """
self.tbf.write(" reg clk;\n")
self.tbf.write(" reg rst;\n\n")
self.tbf.write(" // Cache input pins\n")
self.tbf.write(" reg cache_flush;\n")
self.tbf.write(" reg cache_csb;\n")
self.tbf.write(" reg cache_web;\n")
if self.num_masks:
self.tbf.write(" reg [MASK_COUNT-1:0] cache_wmask;\n")
self.tbf.write(" reg [ADDR_WIDTH-1:0] cache_addr;\n")
self.tbf.write(" reg [WORD_WIDTH-1:0] cache_din;\n\n")
self.tbf.write(" // Cache output pins\n")
self.tbf.write(" wire [WORD_WIDTH-1:0] cache_dout;\n\n")
self.tbf.write(" wire cache_stall;\n")
self.tbf.write(" // DRAM input pins\n")
self.tbf.write(" wire dram_csb;\n")
self.tbf.write(" wire dram_web;\n")
self.tbf.write(" wire [ADDR_WIDTH-OFFSET_WIDTH-1:0] dram_addr;\n")
self.tbf.write(" wire [LINE_WIDTH-1:0] dram_din;\n\n")
self.tbf.write(" // DRAM output pins\n")
self.tbf.write(" wire [LINE_WIDTH-1:0] dram_dout;\n\n")
self.tbf.write(" wire dram_stall;\n")
self.tbf.write(" // Test registers\n")
self.tbf.write(" reg [MAX_TEST_SIZE-1:0] error_count;\n\n")
def write_dumps(self):
""" Write the $dumpfile and $dumpvars system functions for waveforms. """
self.tbf.write(" initial begin\n")
self.tbf.write(" $dumpfile(\"waves.vcd\");\n")
self.tbf.write(" $dumpvars;\n")
self.tbf.write(" end\n\n")
def write_clock_generator(self):
""" Write the clock generator of the test bench. """
self.tbf.write(" // Clock generator\n")
self.tbf.write(" initial begin\n")
self.tbf.write(" clk = 1;\n")
self.tbf.write(" forever #(CLOCK_DELAY) clk = !clk;\n")
self.tbf.write(" end\n\n")
def write_reset_block(self):
""" Write the reset block of the test bench. """
self.tbf.write(" // Reset registers\n")
self.tbf.write(" initial begin\n")
self.tbf.write(" rst = 0;\n")
self.tbf.write(" cache_flush = 0;\n")
self.tbf.write(" cache_csb = 1;\n")
self.tbf.write(" cache_web = 1;\n")
if self.num_masks:
self.tbf.write(" cache_wmask = 0;\n")
self.tbf.write(" error_count = 0;\n")
self.tbf.write(" end\n\n")
def write_instances(self):
""" Write the module instances of the cache and DRAM. """
self.tbf.write(" {} cache_instance (\n".format(self.name))
self.tbf.write(" .clk (clk),\n")
self.tbf.write(" .rst (rst),\n")
self.tbf.write(" .flush (cache_flush),\n")
self.tbf.write(" .csb (cache_csb),\n")
self.tbf.write(" .web (cache_web),\n")
if self.num_masks:
self.tbf.write(" .wmask (cache_wmask),\n")
self.tbf.write(" .addr (cache_addr),\n")
self.tbf.write(" .din (cache_din),\n")
self.tbf.write(" .dout (cache_dout),\n")
self.tbf.write(" .stall (cache_stall),\n")
self.tbf.write(" .main_csb (dram_csb),\n")
self.tbf.write(" .main_web (dram_web),\n")
self.tbf.write(" .main_addr (dram_addr),\n")
self.tbf.write(" .main_din (dram_din),\n")
self.tbf.write(" .main_dout (dram_dout),\n")
self.tbf.write(" .main_stall (dram_stall)\n")
self.tbf.write(" );\n\n")
self.tbf.write(" dram dram_instance (\n")
self.tbf.write(" .clk (clk),\n")
self.tbf.write(" .rst (rst),\n")
self.tbf.write(" .csb (dram_csb),\n")
self.tbf.write(" .web (dram_web),\n")
self.tbf.write(" .addr (dram_addr),\n")
self.tbf.write(" .din (dram_din),\n")
self.tbf.write(" .dout (dram_dout),\n")
self.tbf.write(" .stall (dram_stall)\n")
self.tbf.write(" );\n\n")
def write_tasks(self):
""" Write the tasks of the test bench. """
self.tbf.write(" // Assert the reset signal\n")
self.tbf.write(" task assert_reset;\n")
self.tbf.write(" begin\n")
self.tbf.write(" // Reset is asserted just before a posedge of the clock.\n")
self.tbf.write(" // Therefore, it is enough to assert it for DELAY.\n")
self.tbf.write(" rst <= 1;\n")
self.tbf.write(" rst <= #(DELAY) 0;\n")
self.tbf.write(" end\n")
self.tbf.write(" endtask\n\n")
self.tbf.write(" // Assert the flush signal\n")
self.tbf.write(" task assert_flush;\n")
self.tbf.write(" begin\n")
self.tbf.write(" // Flush is asserted just before a posedge of the clock.\n")
self.tbf.write(" // Therefore, it is enough to assert it for DELAY.\n")
self.tbf.write(" cache_flush <= 1;\n")
self.tbf.write(" cache_flush <= #(DELAY) 0;\n")
self.tbf.write(" end\n")
self.tbf.write(" endtask\n\n")
self.tbf.write(" // Check for a number of stall cycles starting from the current cycle\n")
self.tbf.write(" task check_stall;\n")
self.tbf.write(" input integer cycle_count;\n")
self.tbf.write(" input [MAX_TEST_SIZE-1:0] test_count;\n")
self.tbf.write(" integer i;\n")
self.tbf.write(" begin\n")
self.tbf.write(" for (i = 1; i <= cycle_count; i = i + 1) begin\n")
self.tbf.write(" if (!cache_stall) begin\n")
self.tbf.write(" $display(\"Error at test #%0d! Cache stall #%0d is expected to be high but it is low.\", test_count, i);\n")
self.tbf.write(" error_count = error_count + 1;\n")
self.tbf.write(" end\n")
self.tbf.write(" #(CLOCK_DELAY * 2);\n")
self.tbf.write(" end\n")
self.tbf.write(" end\n")
self.tbf.write(" endtask\n\n")
self.tbf.write(" // Output of the cache must match the expected\n")
self.tbf.write(" task check_dout;\n")
self.tbf.write(" input [WORD_WIDTH-1:0] dout_expected;\n")
self.tbf.write(" input [MAX_TEST_SIZE-1:0] test_count;\n")
self.tbf.write(" begin\n")
self.tbf.write(" if (cache_dout !== dout_expected) begin\n")
self.tbf.write(" $display(\"Error at test #%0d! Expected: %d, Received: %d\", test_count, dout_expected, cache_dout);\n")
self.tbf.write(" error_count = error_count + 1;\n")
self.tbf.write(" end\n")
self.tbf.write(" end\n")
self.tbf.write(" endtask\n\n")
self.tbf.write(" // Print simulation result\n")
self.tbf.write(" task end_simulation;\n")
self.tbf.write(" begin\n")
self.tbf.write(" if (!error_count) begin\n")
self.tbf.write(" $display(\"{}\");\n".format(self.success_message))
self.tbf.write(" end else begin\n")
self.tbf.write(" $display(\"{} Error count: %0d\", error_count);\n".format(self.failure_message))
self.tbf.write(" end\n")
self.tbf.write(" end\n")
self.tbf.write(" endtask\n\n")
|
class Test_Bench:
"""
Class to generate the test bench file for simulation.
"""
def __init__(self, cache_config, name):
cache_config.set_local_config(self)
self.name = name
self.success_message = 'Simulation successful.'
self.failure_message = 'Simulation failed.'
def test_bench_write(self, tb_path):
""" Write the test bench file. """
self.tbf = open(tb_path, 'w')
self.tbf.write('// Timescale is overwritten when running the EDA tool to prevent bugs\n')
self.tbf.write('// `timescale 1ns / 1ps\n\n')
self.tbf.write('module test_bench;\n\n')
self.write_parameters()
self.write_registers()
self.write_dumps()
self.write_clock_generator()
self.write_reset_block()
self.write_instances()
self.write_tasks()
self.tbf.write(' initial begin\n')
self.tbf.write(' `include "test_data.v"\n')
self.tbf.write(' end\n\n')
self.tbf.write('endmodule\n')
self.tbf.close()
def write_parameters(self):
""" Write the parameters of the test bench. """
self.tbf.write(' parameter TAG_WIDTH = {};\n'.format(self.tag_size))
self.tbf.write(' parameter SET_WIDTH = {};\n'.format(self.set_size))
self.tbf.write(' parameter OFFSET_WIDTH = {};\n\n'.format(self.offset_size))
self.tbf.write(' parameter WORD_WIDTH = {};\n'.format(self.word_size))
if self.num_masks:
self.tbf.write(' parameter MASK_COUNT = {};\n'.format(self.num_masks))
self.tbf.write(' parameter WORD_COUNT = {};\n'.format(self.words_per_line))
self.tbf.write(' localparam LINE_WIDTH = WORD_WIDTH * WORD_COUNT;\n\n')
self.tbf.write(' localparam ADDR_WIDTH = TAG_WIDTH + SET_WIDTH + OFFSET_WIDTH;\n\n')
self.tbf.write(' parameter CLOCK_DELAY = 5;\n')
self.tbf.write(' // Reset is asserted for 1.5 cycles\n')
self.tbf.write(' parameter RESET_DELAY = 15;\n')
self.tbf.write(' parameter DELAY = 3;\n')
self.tbf.write(' parameter MAX_TEST_SIZE = 64;\n\n')
def write_registers(self):
""" Write the registers of the test bench. """
self.tbf.write(' reg clk;\n')
self.tbf.write(' reg rst;\n\n')
self.tbf.write(' // Cache input pins\n')
self.tbf.write(' reg cache_flush;\n')
self.tbf.write(' reg cache_csb;\n')
self.tbf.write(' reg cache_web;\n')
if self.num_masks:
self.tbf.write(' reg [MASK_COUNT-1:0] cache_wmask;\n')
self.tbf.write(' reg [ADDR_WIDTH-1:0] cache_addr;\n')
self.tbf.write(' reg [WORD_WIDTH-1:0] cache_din;\n\n')
self.tbf.write(' // Cache output pins\n')
self.tbf.write(' wire [WORD_WIDTH-1:0] cache_dout;\n\n')
self.tbf.write(' wire cache_stall;\n')
self.tbf.write(' // DRAM input pins\n')
self.tbf.write(' wire dram_csb;\n')
self.tbf.write(' wire dram_web;\n')
self.tbf.write(' wire [ADDR_WIDTH-OFFSET_WIDTH-1:0] dram_addr;\n')
self.tbf.write(' wire [LINE_WIDTH-1:0] dram_din;\n\n')
self.tbf.write(' // DRAM output pins\n')
self.tbf.write(' wire [LINE_WIDTH-1:0] dram_dout;\n\n')
self.tbf.write(' wire dram_stall;\n')
self.tbf.write(' // Test registers\n')
self.tbf.write(' reg [MAX_TEST_SIZE-1:0] error_count;\n\n')
def write_dumps(self):
""" Write the $dumpfile and $dumpvars system functions for waveforms. """
self.tbf.write(' initial begin\n')
self.tbf.write(' $dumpfile("waves.vcd");\n')
self.tbf.write(' $dumpvars;\n')
self.tbf.write(' end\n\n')
def write_clock_generator(self):
""" Write the clock generator of the test bench. """
self.tbf.write(' // Clock generator\n')
self.tbf.write(' initial begin\n')
self.tbf.write(' clk = 1;\n')
self.tbf.write(' forever #(CLOCK_DELAY) clk = !clk;\n')
self.tbf.write(' end\n\n')
def write_reset_block(self):
""" Write the reset block of the test bench. """
self.tbf.write(' // Reset registers\n')
self.tbf.write(' initial begin\n')
self.tbf.write(' rst = 0;\n')
self.tbf.write(' cache_flush = 0;\n')
self.tbf.write(' cache_csb = 1;\n')
self.tbf.write(' cache_web = 1;\n')
if self.num_masks:
self.tbf.write(' cache_wmask = 0;\n')
self.tbf.write(' error_count = 0;\n')
self.tbf.write(' end\n\n')
def write_instances(self):
""" Write the module instances of the cache and DRAM. """
self.tbf.write(' {} cache_instance (\n'.format(self.name))
self.tbf.write(' .clk (clk),\n')
self.tbf.write(' .rst (rst),\n')
self.tbf.write(' .flush (cache_flush),\n')
self.tbf.write(' .csb (cache_csb),\n')
self.tbf.write(' .web (cache_web),\n')
if self.num_masks:
self.tbf.write(' .wmask (cache_wmask),\n')
self.tbf.write(' .addr (cache_addr),\n')
self.tbf.write(' .din (cache_din),\n')
self.tbf.write(' .dout (cache_dout),\n')
self.tbf.write(' .stall (cache_stall),\n')
self.tbf.write(' .main_csb (dram_csb),\n')
self.tbf.write(' .main_web (dram_web),\n')
self.tbf.write(' .main_addr (dram_addr),\n')
self.tbf.write(' .main_din (dram_din),\n')
self.tbf.write(' .main_dout (dram_dout),\n')
self.tbf.write(' .main_stall (dram_stall)\n')
self.tbf.write(' );\n\n')
self.tbf.write(' dram dram_instance (\n')
self.tbf.write(' .clk (clk),\n')
self.tbf.write(' .rst (rst),\n')
self.tbf.write(' .csb (dram_csb),\n')
self.tbf.write(' .web (dram_web),\n')
self.tbf.write(' .addr (dram_addr),\n')
self.tbf.write(' .din (dram_din),\n')
self.tbf.write(' .dout (dram_dout),\n')
self.tbf.write(' .stall (dram_stall)\n')
self.tbf.write(' );\n\n')
def write_tasks(self):
""" Write the tasks of the test bench. """
self.tbf.write(' // Assert the reset signal\n')
self.tbf.write(' task assert_reset;\n')
self.tbf.write(' begin\n')
self.tbf.write(' // Reset is asserted just before a posedge of the clock.\n')
self.tbf.write(' // Therefore, it is enough to assert it for DELAY.\n')
self.tbf.write(' rst <= 1;\n')
self.tbf.write(' rst <= #(DELAY) 0;\n')
self.tbf.write(' end\n')
self.tbf.write(' endtask\n\n')
self.tbf.write(' // Assert the flush signal\n')
self.tbf.write(' task assert_flush;\n')
self.tbf.write(' begin\n')
self.tbf.write(' // Flush is asserted just before a posedge of the clock.\n')
self.tbf.write(' // Therefore, it is enough to assert it for DELAY.\n')
self.tbf.write(' cache_flush <= 1;\n')
self.tbf.write(' cache_flush <= #(DELAY) 0;\n')
self.tbf.write(' end\n')
self.tbf.write(' endtask\n\n')
self.tbf.write(' // Check for a number of stall cycles starting from the current cycle\n')
self.tbf.write(' task check_stall;\n')
self.tbf.write(' input integer cycle_count;\n')
self.tbf.write(' input [MAX_TEST_SIZE-1:0] test_count;\n')
self.tbf.write(' integer i;\n')
self.tbf.write(' begin\n')
self.tbf.write(' for (i = 1; i <= cycle_count; i = i + 1) begin\n')
self.tbf.write(' if (!cache_stall) begin\n')
self.tbf.write(' $display("Error at test #%0d! Cache stall #%0d is expected to be high but it is low.", test_count, i);\n')
self.tbf.write(' error_count = error_count + 1;\n')
self.tbf.write(' end\n')
self.tbf.write(' #(CLOCK_DELAY * 2);\n')
self.tbf.write(' end\n')
self.tbf.write(' end\n')
self.tbf.write(' endtask\n\n')
self.tbf.write(' // Output of the cache must match the expected\n')
self.tbf.write(' task check_dout;\n')
self.tbf.write(' input [WORD_WIDTH-1:0] dout_expected;\n')
self.tbf.write(' input [MAX_TEST_SIZE-1:0] test_count;\n')
self.tbf.write(' begin\n')
self.tbf.write(' if (cache_dout !== dout_expected) begin\n')
self.tbf.write(' $display("Error at test #%0d! Expected: %d, Received: %d", test_count, dout_expected, cache_dout);\n')
self.tbf.write(' error_count = error_count + 1;\n')
self.tbf.write(' end\n')
self.tbf.write(' end\n')
self.tbf.write(' endtask\n\n')
self.tbf.write(' // Print simulation result\n')
self.tbf.write(' task end_simulation;\n')
self.tbf.write(' begin\n')
self.tbf.write(' if (!error_count) begin\n')
self.tbf.write(' $display("{}");\n'.format(self.success_message))
self.tbf.write(' end else begin\n')
self.tbf.write(' $display("{} Error count: %0d", error_count);\n'.format(self.failure_message))
self.tbf.write(' end\n')
self.tbf.write(' end\n')
self.tbf.write(' endtask\n\n')
|
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the message will be displayed
assert not world_df is None, "Your answer for world_df does not exist. Have you loaded the TopoJSON data to the correct variable name?"
assert "topo_feature" in __solution__, "The loaded data should be in TopoJSON format. In order to read TopoJSON file correctly, you need to use the alt.topo_feature() function."
assert (
"quantitative" in __solution__ or
"pop_density:Q" in __solution__
), "Make sure you use pop_density column from gapminder_df for the color encoding. Hint: since pop_density column does not exist in world_df, Altair can't infer its data type and you need to specify that it is quantitative data."
assert type(world_df) == alt.UrlData, "world_df does not appear to be an Altair UrlData object. Have you assigned the Altair UrlData object for the TopoJSON data to the correct variable?"
assert world_df.url == data.world_110m.url, "Make sure you are loading the data from correct url."
assert (world_df.format != alt.utils.schemapi.Undefined and
world_df.format.type == 'topojson'
), "The loaded data should be in TopoJSON format. In order to read TopoJSON file correctly, you need to use the alt.topo_feature() function."
assert world_df.format.feature == "countries", "Make sure to specify 'countries' feature when loading the TopoJSON file using alt.topo_feature()."
assert not pop_dense_plot is None, "Your answer for pop_dense_plot does not exist. Have you assigned the plot to the correct variable name?"
assert type(pop_dense_plot) == alt.Chart, "pop_dense_plot does not appear to be an Altair Chart object. Have you assigned the Altair Chart object for the plot to the correct variable?"
assert pop_dense_plot.mark == 'geoshape', "Make sure you are using mark_geoshape for pop_dense_plot."
assert pop_dense_plot.encoding.color != alt.utils.schemapi.Undefined and (
pop_dense_plot.encoding.color.shorthand in {'pop_density:quantitative', 'pop_density:Q'} or
(pop_dense_plot.encoding.color.shorthand == 'pop_density' and pop_dense_plot.encoding.color.type == 'quantitative') or
pop_dense_plot.encoding.color.field in {'pop_density:quantitative', 'pop_density:Q'} or
(pop_dense_plot.encoding.color.field == 'pop_density' and pop_dense_plot.encoding.color.type == 'quantitative')
), "Make sure you use pop_density column from gapminder_df for the color encoding. Hint: since pop_density column does not exist in world_df, Altair can't infer its data type and you need to specify that it is quantitative data."
assert pop_dense_plot.encoding.color.scale != alt.utils.schemapi.Undefined and (
pop_dense_plot.encoding.color.scale.scheme != alt.utils.schemapi.Undefined
), "Make sure to specify a colour scheme."
assert pop_dense_plot.encoding.color.scale.domainMid == 81, "Make sure you set the domainMid of the color scale as the global median (81)."
assert type(pop_dense_plot.transform) == list and (
len(pop_dense_plot.transform) == 1 and
pop_dense_plot.transform[0]['from'] != alt.utils.schemapi.Undefined and
pop_dense_plot.transform[0]['from'].fields == ['pop_density'] and
pop_dense_plot.transform[0]['from'].key
), "Make sure you use .transform_lookup() to lookup the column 'pop_density' from the gapminder_df data using 'id' as the connecting column. Hint: 'pop_density' should be inside a list."
assert pop_dense_plot.projection != alt.utils.schemapi.Undefined and (
pop_dense_plot.projection.scale == 80
), "Make sure you use 'equalEarth' projection. Hint: you can use .project() method with type argument to specify projection type."
__msg__.good("You're correct, well done!")
|
def test():
assert not world_df is None, 'Your answer for world_df does not exist. Have you loaded the TopoJSON data to the correct variable name?'
assert 'topo_feature' in __solution__, 'The loaded data should be in TopoJSON format. In order to read TopoJSON file correctly, you need to use the alt.topo_feature() function.'
assert 'quantitative' in __solution__ or 'pop_density:Q' in __solution__, "Make sure you use pop_density column from gapminder_df for the color encoding. Hint: since pop_density column does not exist in world_df, Altair can't infer its data type and you need to specify that it is quantitative data."
assert type(world_df) == alt.UrlData, 'world_df does not appear to be an Altair UrlData object. Have you assigned the Altair UrlData object for the TopoJSON data to the correct variable?'
assert world_df.url == data.world_110m.url, 'Make sure you are loading the data from correct url.'
assert world_df.format != alt.utils.schemapi.Undefined and world_df.format.type == 'topojson', 'The loaded data should be in TopoJSON format. In order to read TopoJSON file correctly, you need to use the alt.topo_feature() function.'
assert world_df.format.feature == 'countries', "Make sure to specify 'countries' feature when loading the TopoJSON file using alt.topo_feature()."
assert not pop_dense_plot is None, 'Your answer for pop_dense_plot does not exist. Have you assigned the plot to the correct variable name?'
assert type(pop_dense_plot) == alt.Chart, 'pop_dense_plot does not appear to be an Altair Chart object. Have you assigned the Altair Chart object for the plot to the correct variable?'
assert pop_dense_plot.mark == 'geoshape', 'Make sure you are using mark_geoshape for pop_dense_plot.'
assert pop_dense_plot.encoding.color != alt.utils.schemapi.Undefined and (pop_dense_plot.encoding.color.shorthand in {'pop_density:quantitative', 'pop_density:Q'} or (pop_dense_plot.encoding.color.shorthand == 'pop_density' and pop_dense_plot.encoding.color.type == 'quantitative') or pop_dense_plot.encoding.color.field in {'pop_density:quantitative', 'pop_density:Q'} or (pop_dense_plot.encoding.color.field == 'pop_density' and pop_dense_plot.encoding.color.type == 'quantitative')), "Make sure you use pop_density column from gapminder_df for the color encoding. Hint: since pop_density column does not exist in world_df, Altair can't infer its data type and you need to specify that it is quantitative data."
assert pop_dense_plot.encoding.color.scale != alt.utils.schemapi.Undefined and pop_dense_plot.encoding.color.scale.scheme != alt.utils.schemapi.Undefined, 'Make sure to specify a colour scheme.'
assert pop_dense_plot.encoding.color.scale.domainMid == 81, 'Make sure you set the domainMid of the color scale as the global median (81).'
assert type(pop_dense_plot.transform) == list and (len(pop_dense_plot.transform) == 1 and pop_dense_plot.transform[0]['from'] != alt.utils.schemapi.Undefined and (pop_dense_plot.transform[0]['from'].fields == ['pop_density']) and pop_dense_plot.transform[0]['from'].key), "Make sure you use .transform_lookup() to lookup the column 'pop_density' from the gapminder_df data using 'id' as the connecting column. Hint: 'pop_density' should be inside a list."
assert pop_dense_plot.projection != alt.utils.schemapi.Undefined and pop_dense_plot.projection.scale == 80, "Make sure you use 'equalEarth' projection. Hint: you can use .project() method with type argument to specify projection type."
__msg__.good("You're correct, well done!")
|
class SimpleSpriteList:
def __init__(self) -> None:
self.sprites = list()
def draw(self) -> None:
for sprite in self.sprites:
sprite.draw()
def update(self) -> None:
for sprite in self.sprites:
sprite.update()
def append(self, sprite) -> None:
self.sprites.append(sprite)
def remove(self, sprite) -> None:
self.sprites.remove(sprite)
def pop(self, index: int = -1):
self.sprites.pop(index)
def clear(self) -> None:
self.sprites.clear()
|
class Simplespritelist:
def __init__(self) -> None:
self.sprites = list()
def draw(self) -> None:
for sprite in self.sprites:
sprite.draw()
def update(self) -> None:
for sprite in self.sprites:
sprite.update()
def append(self, sprite) -> None:
self.sprites.append(sprite)
def remove(self, sprite) -> None:
self.sprites.remove(sprite)
def pop(self, index: int=-1):
self.sprites.pop(index)
def clear(self) -> None:
self.sprites.clear()
|
"""
Problem: https://www.hackerrank.com/challenges/nested-list/problem
Max Score: 10
Difficulty: Easy
Author: Ric
Date: Nov 13, 2019
"""
def secondLow(classList):
secondLowScore = sorted(set(m[1] for m in classList))[1]
result = sorted([m[0] for m in classList if m[1] == secondLowScore])
return result
n = int(input())
classList = []
for i in range(n):
classList.append([str(input()), float(input())])
# print(classList)
print('\n'.join(secondLow(classList)))
|
"""
Problem: https://www.hackerrank.com/challenges/nested-list/problem
Max Score: 10
Difficulty: Easy
Author: Ric
Date: Nov 13, 2019
"""
def second_low(classList):
second_low_score = sorted(set((m[1] for m in classList)))[1]
result = sorted([m[0] for m in classList if m[1] == secondLowScore])
return result
n = int(input())
class_list = []
for i in range(n):
classList.append([str(input()), float(input())])
print('\n'.join(second_low(classList)))
|
numberLines = int(input())
while 0 < numberLines:
number = int(input())
sum = 0
for i in range(number):
if i%3 == 0 or i%5 == 0:
sum = sum + i
print(sum)
numberLines = numberLines - 1
|
number_lines = int(input())
while 0 < numberLines:
number = int(input())
sum = 0
for i in range(number):
if i % 3 == 0 or i % 5 == 0:
sum = sum + i
print(sum)
number_lines = numberLines - 1
|
#!/usr/bin/env python3
#bpm to millisecond for compressor release
def compressor_release(bpm, note_length):
'''
Inputs: BPM, note length
Output: compression release time
Note: Function returns perfect compression release time for standard note lengths. Electronic music is not standard mus ic so this does not have much of an application
'''
# using a tuple because
standard_lengths = ('1/4', '1/8', '1/16', '1/32', '1/64', '1/128', '1/256')
return round((float(60)/bpm)*(10**3)/2**int(standard_lengths.index(note_length)))
beep = int(input('BPM: '))
length = input('Note length: ')
j = compressor_release(int(beep),length)
print(j)
# ~THIS IS OLD CODE~
"""
if note == '1/4':
desireBe = (60/bpm)*(10**3)
print(f'{round(desireBe,1)}ms')
elif note == '1/8':
desireBe = (60/bpm)*(10**3)/2
print(f'{round(desireBe,1)}ms')
elif note == '1/16':
desireBe = (60/bpm)*(10**3)/4
print(f'{round(desireBe,1)}ms')
elif note == '1/32':
desireBe = (60/bpm)*(10**3)/8
print(f'{round(desireBe,1)}ms')
elif note == '1/64':
desireBe = (60/bpm)*(10**3)/16
print(f'{round(desireBe,1)}ms')
elif note == '1/128':
desireBe = (60/bpm)*(10**3)/32
print(f'{round(desireBe,1)}ms')
elif note == '1/256':
desireBe = (60/bpm)*(10**3)/64
print(f'{round(desireBe,1)}ms')
else: print("invaled note length")
"""
|
def compressor_release(bpm, note_length):
"""
Inputs: BPM, note length
Output: compression release time
Note: Function returns perfect compression release time for standard note lengths. Electronic music is not standard mus ic so this does not have much of an application
"""
standard_lengths = ('1/4', '1/8', '1/16', '1/32', '1/64', '1/128', '1/256')
return round(float(60) / bpm * 10 ** 3 / 2 ** int(standard_lengths.index(note_length)))
beep = int(input('BPM: '))
length = input('Note length: ')
j = compressor_release(int(beep), length)
print(j)
'\nif note == \'1/4\':\n desireBe = (60/bpm)*(10**3)\n print(f\'{round(desireBe,1)}ms\')\nelif note == \'1/8\':\n desireBe = (60/bpm)*(10**3)/2\n print(f\'{round(desireBe,1)}ms\')\nelif note == \'1/16\':\n desireBe = (60/bpm)*(10**3)/4\n print(f\'{round(desireBe,1)}ms\')\nelif note == \'1/32\':\n desireBe = (60/bpm)*(10**3)/8\n print(f\'{round(desireBe,1)}ms\')\nelif note == \'1/64\':\n desireBe = (60/bpm)*(10**3)/16\n print(f\'{round(desireBe,1)}ms\')\nelif note == \'1/128\':\n desireBe = (60/bpm)*(10**3)/32\n print(f\'{round(desireBe,1)}ms\')\nelif note == \'1/256\':\n desireBe = (60/bpm)*(10**3)/64\n print(f\'{round(desireBe,1)}ms\')\nelse: print("invaled note length")\n'
|
#Mock class for GPIO
BOARD = 1
BCM = 2
OUT = 1
IN = 1
HIGH = 1
LOW = 0
def setmode(a):
print ("setmode GPIO",a)
def setup(a, b):
print ("setup GPIO", a, b)
def output(a, b):
print ("output GPIO", a, b)
def cleanup():
print ("cleanup GPIO", a, b)
def setwarnings(flag):
print ("setwarnings", flag)
|
board = 1
bcm = 2
out = 1
in = 1
high = 1
low = 0
def setmode(a):
print('setmode GPIO', a)
def setup(a, b):
print('setup GPIO', a, b)
def output(a, b):
print('output GPIO', a, b)
def cleanup():
print('cleanup GPIO', a, b)
def setwarnings(flag):
print('setwarnings', flag)
|
__author__ = 'yinjun'
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
# write your code here
if n<=2 :
return n
stairs = [0 for i in range(n)]
stairs[0] = 1
stairs[1] = 2
for i in range(2, n):
stairs[i] = stairs[i-1] + stairs[i-2]
return stairs[n-1]
|
__author__ = 'yinjun'
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climb_stairs(self, n):
if n <= 2:
return n
stairs = [0 for i in range(n)]
stairs[0] = 1
stairs[1] = 2
for i in range(2, n):
stairs[i] = stairs[i - 1] + stairs[i - 2]
return stairs[n - 1]
|
# Damage Skin - Violetta
success = sm.addDamageSkin(2433197)
if success:
sm.chat("The Damage Skin - Violetta has been added to your account's damage skin collection.")
|
success = sm.addDamageSkin(2433197)
if success:
sm.chat("The Damage Skin - Violetta has been added to your account's damage skin collection.")
|
#!/usr/bin/env python3
formulas = [
"XNd perr",
"PNd (PNd (call And (XNu exc)))",
"PNd (han And (XNd (exc And (XBu call))))",
"G (exc --> XBu call)",
"T Ud exc",
"PNd (PNd (T Ud exc))",
"G ((call And pa And ((~ ret) Ud WRx)) --> XNu exc)",
"PNd (PBu call)",
"PNd (PNd (PNd (PBu call)))",
"XNd (PNd (PBu call))",
"G ((call And pa And (PNu exc Or XNu exc)) --> (PNu eb Or XNu eb))",
"F (HNd pb)",
"F (HBd pb)",
"F (pa And (call HUd pc))",
"F (pc And (call HSd pa))",
"G ((pc And (XNu exc)) --> ((~ pa) HSd pb))",
"G ((call And pb) --> (~ pc) HUu perr)",
"F (HNu perr)",
"F (HBu perr)",
"F (pa And (call HUu pb))",
"F (pb And (call HSu pa))",
"G (call --> XNd ret)",
"G (call --> Not (PNu exc))",
"G ((call And pa) --> ~ (PNu exc Or XNu exc))",
"G (exc --> ~ (PBu (call And pa) Or XBu (call And pa)))",
"G ((call And pb And (call Sd (call And pa))) --> (PNu exc Or XNu exc))",
"G (han --> XNu ret)",
"T Uu exc",
"PNd (PNd (T Uu exc))",
"PNd (PNd (PNd (T Uu exc)))",
"G (call And pc --> (T Uu (exc And XBd han)))",
"call Ud (ret And perr)",
"XNd (call And ((call Or exc) Su pb))",
"PNd (PNd ((call Or exc) Uu ret))"]
n = 11
for form in formulas:
with open(str(n) + '-generic-larger.pomc', 'w') as f:
f.write('formulas = ' + form + ';\n')
f.write('include = "../../Mcall.inc";\n\n')
f.write('include = "opa.inc";')
n += 1
|
formulas = ['XNd perr', 'PNd (PNd (call And (XNu exc)))', 'PNd (han And (XNd (exc And (XBu call))))', 'G (exc --> XBu call)', 'T Ud exc', 'PNd (PNd (T Ud exc))', 'G ((call And pa And ((~ ret) Ud WRx)) --> XNu exc)', 'PNd (PBu call)', 'PNd (PNd (PNd (PBu call)))', 'XNd (PNd (PBu call))', 'G ((call And pa And (PNu exc Or XNu exc)) --> (PNu eb Or XNu eb))', 'F (HNd pb)', 'F (HBd pb)', 'F (pa And (call HUd pc))', 'F (pc And (call HSd pa))', 'G ((pc And (XNu exc)) --> ((~ pa) HSd pb))', 'G ((call And pb) --> (~ pc) HUu perr)', 'F (HNu perr)', 'F (HBu perr)', 'F (pa And (call HUu pb))', 'F (pb And (call HSu pa))', 'G (call --> XNd ret)', 'G (call --> Not (PNu exc))', 'G ((call And pa) --> ~ (PNu exc Or XNu exc))', 'G (exc --> ~ (PBu (call And pa) Or XBu (call And pa)))', 'G ((call And pb And (call Sd (call And pa))) --> (PNu exc Or XNu exc))', 'G (han --> XNu ret)', 'T Uu exc', 'PNd (PNd (T Uu exc))', 'PNd (PNd (PNd (T Uu exc)))', 'G (call And pc --> (T Uu (exc And XBd han)))', 'call Ud (ret And perr)', 'XNd (call And ((call Or exc) Su pb))', 'PNd (PNd ((call Or exc) Uu ret))']
n = 11
for form in formulas:
with open(str(n) + '-generic-larger.pomc', 'w') as f:
f.write('formulas = ' + form + ';\n')
f.write('include = "../../Mcall.inc";\n\n')
f.write('include = "opa.inc";')
n += 1
|
class Iterator(object):
def __init__(self, iterable, looping: bool = False):
self.iterable = iterable
self.lastPos = 0
self.looping = looping
def __next__(self):
pos = self.lastPos
self.lastPos += 1
if self.lastPos >= len(self.iterable):
if self.looping:
self.lastPos = 0
else:
raise StopIteration
return self.iterable[pos]
|
class Iterator(object):
def __init__(self, iterable, looping: bool=False):
self.iterable = iterable
self.lastPos = 0
self.looping = looping
def __next__(self):
pos = self.lastPos
self.lastPos += 1
if self.lastPos >= len(self.iterable):
if self.looping:
self.lastPos = 0
else:
raise StopIteration
return self.iterable[pos]
|
##################################################################################
#### Runtime configuration
##################################################################################
sampleCounter = 0
##################################################################################
#### General configuration
##################################################################################
version = "1.0.2103.0401"
##################################################################################
#### LCD configuration
##################################################################################
lcdI2cExpanderType = "PCF8574"
lcdI2cAddress = 0x27
lcdColumnCount = 20
lcdRowCount = 4
|
sample_counter = 0
version = '1.0.2103.0401'
lcd_i2c_expander_type = 'PCF8574'
lcd_i2c_address = 39
lcd_column_count = 20
lcd_row_count = 4
|
# REPLACE EVERYTHING IN CURLY BRACKETS {}, INCLUDING THE BRACKETS THEMSELVES.
# THEN RENAME THIS FILE TO constants.py AND MOVE IT INTO YOUR PROJECT'S ROOT
CONNECT_BASE_URL = '{YOUR BASE URL}/api/xml?action='
CONNECT_LOGIN = '{YOUR LOGIN}'
CONNECT_PWD = '{YOUR PASSWORD}'
# USERS YOU WANT TO BE ABLE TO EXCLUDE FROM REPORTS
CONNECT_ADMIN_USERS = ['{USER1LOGIN}',
'{USER2LOGIN}',
'{USER3LOGIN}'
]
|
connect_base_url = '{YOUR BASE URL}/api/xml?action='
connect_login = '{YOUR LOGIN}'
connect_pwd = '{YOUR PASSWORD}'
connect_admin_users = ['{USER1LOGIN}', '{USER2LOGIN}', '{USER3LOGIN}']
|
# -*- coding: utf-8 -*-
def crearCombinaciones(abecedario):
for d1 in abecedario:
for d2 in abecedario:
for d3 in abecedario:
for d4 in abecedario:
#print(d1 + '' + d2 + '' + d3 + '' + d4)
f.write(d1 + '' + d2 + '' + d3 + '' + d4)
f.write('\n')
abecedario = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
f = open("dico.txt", "w")
crearCombinaciones(abecedario)
f.close()
|
def crear_combinaciones(abecedario):
for d1 in abecedario:
for d2 in abecedario:
for d3 in abecedario:
for d4 in abecedario:
f.write(d1 + '' + d2 + '' + d3 + '' + d4)
f.write('\n')
abecedario = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
f = open('dico.txt', 'w')
crear_combinaciones(abecedario)
f.close()
|
set_name(0x8009CFEC, "VID_OpenModule__Fv", SN_NOWARN)
set_name(0x8009D0AC, "InitScreens__Fv", SN_NOWARN)
set_name(0x8009D19C, "MEM_SetupMem__Fv", SN_NOWARN)
set_name(0x8009D1C8, "SetupWorkRam__Fv", SN_NOWARN)
set_name(0x8009D258, "SYSI_Init__Fv", SN_NOWARN)
set_name(0x8009D364, "GM_Open__Fv", SN_NOWARN)
set_name(0x8009D388, "PA_Open__Fv", SN_NOWARN)
set_name(0x8009D3C0, "PAD_Open__Fv", SN_NOWARN)
set_name(0x8009D404, "OVR_Open__Fv", SN_NOWARN)
set_name(0x8009D424, "SCR_Open__Fv", SN_NOWARN)
set_name(0x8009D454, "DEC_Open__Fv", SN_NOWARN)
|
set_name(2148126700, 'VID_OpenModule__Fv', SN_NOWARN)
set_name(2148126892, 'InitScreens__Fv', SN_NOWARN)
set_name(2148127132, 'MEM_SetupMem__Fv', SN_NOWARN)
set_name(2148127176, 'SetupWorkRam__Fv', SN_NOWARN)
set_name(2148127320, 'SYSI_Init__Fv', SN_NOWARN)
set_name(2148127588, 'GM_Open__Fv', SN_NOWARN)
set_name(2148127624, 'PA_Open__Fv', SN_NOWARN)
set_name(2148127680, 'PAD_Open__Fv', SN_NOWARN)
set_name(2148127748, 'OVR_Open__Fv', SN_NOWARN)
set_name(2148127780, 'SCR_Open__Fv', SN_NOWARN)
set_name(2148127828, 'DEC_Open__Fv', SN_NOWARN)
|
class MusicTextView:
"""This class represents one instance of a view for the music maze. The
purpose of this class is to represent the maze through text and also to
create a basis on the methods needed to cover all of the view's expected
features for sanity checking purposes."""
|
class Musictextview:
"""This class represents one instance of a view for the music maze. The
purpose of this class is to represent the maze through text and also to
create a basis on the methods needed to cover all of the view's expected
features for sanity checking purposes."""
|
lr_scheduler = dict(
name='poly_scheduler',
epochs=30,
power=0.9
)
|
lr_scheduler = dict(name='poly_scheduler', epochs=30, power=0.9)
|
size(800, 600)
background(255)
triangle(20, 20, 20, 50, 50, 20)
triangle(200, 100, 200, 150, 300, 320)
triangle(700, 500, 800, 550, 600, 600)
|
size(800, 600)
background(255)
triangle(20, 20, 20, 50, 50, 20)
triangle(200, 100, 200, 150, 300, 320)
triangle(700, 500, 800, 550, 600, 600)
|
def get_bit_mask(bit_num):
"""Returns as bit mask with bit_num set.
:param bit_num: The bit number.
:type bit_num: int
:returns: int -- the bit mask
:raises: RangeError
>>> bin(pifacecommon.core.get_bit_mask(0))
1
>>> pifacecommon.core.get_bit_mask(1)
2
>>> bin(pifacecommon.core.get_bit_mask(3))
'0b1000'
"""
return 1 << (bit_num)
def get_bit_num(bit_pattern):
"""Returns the lowest bit num from a given bit pattern. Returns None if no
bits set.
:param bit_pattern: The bit pattern.
:type bit_pattern: int
:returns: int -- the bit number
:returns: None -- no bits set
>>> pifacecommon.core.get_bit_num(0)
None
>>> pifacecommon.core.get_bit_num(0b1)
0
>>> pifacecommon.core.get_bit_num(0b11000)
3
"""
if bit_pattern == 0:
return None
bit_num = 0 # assume bit 0
while (bit_pattern & 1) == 0:
bit_pattern = bit_pattern >> 1
bit_num += 1
if bit_num > 7:
bit_num = 0
break
return bit_num
def sleep_microseconds(microseconds):
"""Sleeps for the given number of microseconds.
:param microseconds: Number of microseconds to sleep for.
:type microseconds: int
"""
# divide microseconds by 1 million for seconds
seconds = microseconds / float(1000000)
time.sleep(seconds)
|
def get_bit_mask(bit_num):
"""Returns as bit mask with bit_num set.
:param bit_num: The bit number.
:type bit_num: int
:returns: int -- the bit mask
:raises: RangeError
>>> bin(pifacecommon.core.get_bit_mask(0))
1
>>> pifacecommon.core.get_bit_mask(1)
2
>>> bin(pifacecommon.core.get_bit_mask(3))
'0b1000'
"""
return 1 << bit_num
def get_bit_num(bit_pattern):
"""Returns the lowest bit num from a given bit pattern. Returns None if no
bits set.
:param bit_pattern: The bit pattern.
:type bit_pattern: int
:returns: int -- the bit number
:returns: None -- no bits set
>>> pifacecommon.core.get_bit_num(0)
None
>>> pifacecommon.core.get_bit_num(0b1)
0
>>> pifacecommon.core.get_bit_num(0b11000)
3
"""
if bit_pattern == 0:
return None
bit_num = 0
while bit_pattern & 1 == 0:
bit_pattern = bit_pattern >> 1
bit_num += 1
if bit_num > 7:
bit_num = 0
break
return bit_num
def sleep_microseconds(microseconds):
"""Sleeps for the given number of microseconds.
:param microseconds: Number of microseconds to sleep for.
:type microseconds: int
"""
seconds = microseconds / float(1000000)
time.sleep(seconds)
|
"""
Module: 'lidar' on M5 FlowUI v1.4.0-beta
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32')
# Stubber: 1.3.1
def deinit():
pass
def distance():
pass
def draw_map():
pass
def get_distance():
pass
def get_frame():
pass
def init():
pass
|
"""
Module: 'lidar' on M5 FlowUI v1.4.0-beta
"""
def deinit():
pass
def distance():
pass
def draw_map():
pass
def get_distance():
pass
def get_frame():
pass
def init():
pass
|
"""Functions for determining micrograph scaling.
"""
def determine_scaling(image, bar_length_um, bar_frac):
r"""Determine um per pixels scaling for an image provided the bar length in um and the fraction of the image for
which it occupies.
Parameters
----------
image : ndarray
Input image. Must be grayscale.
bar_length_um : float
Length of scale bar (:math:`\mu \text{m}`).
bar_frac : float
Fraction of the image width occupied by the scale bar.
Returns
-------
um_per_px : float
Scaling (:math:`\mu \text{m}` per px).
"""
# Convert bar length from um to pixels
bar_length_px = bar_frac * image.shape[1]
# Determine conversion
um_per_px = bar_length_um / bar_length_px
return um_per_px
|
"""Functions for determining micrograph scaling.
"""
def determine_scaling(image, bar_length_um, bar_frac):
"""Determine um per pixels scaling for an image provided the bar length in um and the fraction of the image for
which it occupies.
Parameters
----------
image : ndarray
Input image. Must be grayscale.
bar_length_um : float
Length of scale bar (:math:`\\mu \\text{m}`).
bar_frac : float
Fraction of the image width occupied by the scale bar.
Returns
-------
um_per_px : float
Scaling (:math:`\\mu \\text{m}` per px).
"""
bar_length_px = bar_frac * image.shape[1]
um_per_px = bar_length_um / bar_length_px
return um_per_px
|
black = (0, 0, 0)
red = (255, 0, 0)
orange = (255, 152, 0)
deep_orange = (255, 87, 34)
brown = (121, 85, 72)
green = (0, 128, 0)
light_green = (139, 195, 74)
teal = (0, 150, 136)
blue = (33, 150, 136)
purple = (156, 39, 176)
pink = (234, 30, 99)
deep_purple = (103, 58, 183)
color_dict = {
0: black,
2: red,
4: green,
8: purple,
16: deep_purple,
32: deep_orange,
64: teal,
128: light_green,
256: pink,
512: orange,
1024: black,
2048: brown
}
def getColor(tile_number):
"""
Returns the color for specific number.
Arguments:\n
:tileNumber: the tile for which you require color.
"""
return color_dict[tile_number]
|
black = (0, 0, 0)
red = (255, 0, 0)
orange = (255, 152, 0)
deep_orange = (255, 87, 34)
brown = (121, 85, 72)
green = (0, 128, 0)
light_green = (139, 195, 74)
teal = (0, 150, 136)
blue = (33, 150, 136)
purple = (156, 39, 176)
pink = (234, 30, 99)
deep_purple = (103, 58, 183)
color_dict = {0: black, 2: red, 4: green, 8: purple, 16: deep_purple, 32: deep_orange, 64: teal, 128: light_green, 256: pink, 512: orange, 1024: black, 2048: brown}
def get_color(tile_number):
"""
Returns the color for specific number.
Arguments:
:tileNumber: the tile for which you require color.
"""
return color_dict[tile_number]
|
#part 1
count = 0
expected_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}
received_fields = set()
with open("input.txt") as f:
for line in f:
if line != '\n':
fields = {i[:3] for i in line.split(' ')}
received_fields.update(fields)
else:
difference = expected_fields - received_fields
if not difference:
count += 1
received_fields.clear()
print(count)
#part 2
count = 0
expected_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}
received_fields = set()
received_pairs = {}
with open("input.txt") as f:
for line in f:
if line != '\n':
for pair in line.split(' '):
key, value = pair.split(':')
received_pairs[key.strip()] = value.strip()
received_fields.add(key)
else:
difference = expected_fields - received_fields
if not difference:
rules = {
'byr': lambda x: 1920 <= int(x) <= 2002,
'iyr': lambda x: 2010 <= int(x) <= 2020,
'eyr': lambda x: 2020 <= int(x) <= 2030,
'hgt': lambda x: 150 <= int(x[:-2]) <= 193 if x[-2:] == 'cm' \
else 59 <= int(x[:-2]) <= 76 if x[-2:] == 'in' else False,
'hcl': lambda x: x[0] == '#' and len(x) == 7 and \
all(map(lambda y: '0' <= y <= '9' or 'a' <= y <= 'f', x[1:])),
'ecl': lambda x: x in {'amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'},
'pid': lambda x: len(x) == 9 and all(map(lambda y: '0' <= y <= '9', x)),
'cid': lambda x: True
}
for key in received_pairs:
if not rules[key](received_pairs[key]):
break
else:
count += 1
received_fields.clear()
received_pairs.clear()
print(count)
|
count = 0
expected_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}
received_fields = set()
with open('input.txt') as f:
for line in f:
if line != '\n':
fields = {i[:3] for i in line.split(' ')}
received_fields.update(fields)
else:
difference = expected_fields - received_fields
if not difference:
count += 1
received_fields.clear()
print(count)
count = 0
expected_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}
received_fields = set()
received_pairs = {}
with open('input.txt') as f:
for line in f:
if line != '\n':
for pair in line.split(' '):
(key, value) = pair.split(':')
received_pairs[key.strip()] = value.strip()
received_fields.add(key)
else:
difference = expected_fields - received_fields
if not difference:
rules = {'byr': lambda x: 1920 <= int(x) <= 2002, 'iyr': lambda x: 2010 <= int(x) <= 2020, 'eyr': lambda x: 2020 <= int(x) <= 2030, 'hgt': lambda x: 150 <= int(x[:-2]) <= 193 if x[-2:] == 'cm' else 59 <= int(x[:-2]) <= 76 if x[-2:] == 'in' else False, 'hcl': lambda x: x[0] == '#' and len(x) == 7 and all(map(lambda y: '0' <= y <= '9' or 'a' <= y <= 'f', x[1:])), 'ecl': lambda x: x in {'amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'}, 'pid': lambda x: len(x) == 9 and all(map(lambda y: '0' <= y <= '9', x)), 'cid': lambda x: True}
for key in received_pairs:
if not rules[key](received_pairs[key]):
break
else:
count += 1
received_fields.clear()
received_pairs.clear()
print(count)
|
ACTION_CREATED = 'created'
ACTION_UPDATED = 'updated'
ACTION_DELETED = 'deleted'
ACTION_OTHER = 'other'
ACTION_CHOICES = (
(ACTION_CREATED, ACTION_CREATED),
(ACTION_UPDATED, ACTION_UPDATED),
(ACTION_DELETED, ACTION_DELETED),
(ACTION_OTHER, ACTION_OTHER),
)
LOG_LEVEL_CRITICAL = 'CRITICAL'
LOG_LEVEL_ERROR = 'ERROR'
LOG_LEVEL_WARNING = 'WARNING'
LOG_LEVEL_INFO = 'INFO'
LOG_LEVEL_DEBUG = 'DEBUG'
LOG_LEVEL_NOTSET = 'NOTSET'
LOG_LEVEL_CHOICES = (
(LOG_LEVEL_CRITICAL, LOG_LEVEL_CRITICAL),
(LOG_LEVEL_ERROR, LOG_LEVEL_ERROR),
(LOG_LEVEL_WARNING, LOG_LEVEL_WARNING),
(LOG_LEVEL_INFO, LOG_LEVEL_INFO),
(LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG),
(LOG_LEVEL_NOTSET, LOG_LEVEL_NOTSET),
)
|
action_created = 'created'
action_updated = 'updated'
action_deleted = 'deleted'
action_other = 'other'
action_choices = ((ACTION_CREATED, ACTION_CREATED), (ACTION_UPDATED, ACTION_UPDATED), (ACTION_DELETED, ACTION_DELETED), (ACTION_OTHER, ACTION_OTHER))
log_level_critical = 'CRITICAL'
log_level_error = 'ERROR'
log_level_warning = 'WARNING'
log_level_info = 'INFO'
log_level_debug = 'DEBUG'
log_level_notset = 'NOTSET'
log_level_choices = ((LOG_LEVEL_CRITICAL, LOG_LEVEL_CRITICAL), (LOG_LEVEL_ERROR, LOG_LEVEL_ERROR), (LOG_LEVEL_WARNING, LOG_LEVEL_WARNING), (LOG_LEVEL_INFO, LOG_LEVEL_INFO), (LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG), (LOG_LEVEL_NOTSET, LOG_LEVEL_NOTSET))
|
"""
A command line interface to the qcfractal.
"""
# from tornado.options import options, define
# import tornado.ioloop
# import tornado.web
# define("port", default=8888, help="Run on the given port.", type=int)
# define("mongod_ip", default="127.0.0.1", help="The Mongod instances IP.", type=str)
# define("mongod_port", default=27017, help="The Mongod instances port.", type=int)
# define("mongod_username", default="", help="The Mongod instance username.", type=str)
# define("mongod_password", default="", help="The Mongod instances password.", type=str)
# define("dask_ip", default="", help="The Dask instances IP. If blank starts a local cluster.", type=str)
# define("dask_port", default=8786, help="The Dask instances port.", type=int)
# # define("fireworks_ip", default="", help="The Fireworks instances IP. If blank starts a local cluster.", type=str)
# # define("fireworks_port", default=None, help="The Fireworks instances port.", type=int)
# define("logfile", default="qcdb_server.log", help="The logfile to write to.", type=str)
# define("queue", default="fireworks", help="The type of queue to use dask or fireworks", type=str)
#
#
#
# queues = ["fireworks", "dask"]
# if options.queue not in queues:
# raise KeyError("Queue of type {} not understood".format(options.queue))
#
# if options.queue == "dask":
# import distributed
# dask_dir_geuss = os.getcwd() + '/dask_scratch/'
# define("dask_dir", default=dask_dir_geuss, help="The Dask workers working director", type=str)
# dask_working_dir = options.dask_dir
# elif options.queue == "fireworks":
# import fireworks
#
# tornado.options.options.parse_command_line()
# tornado.options.parse_command_line()
# class DQMServer(object):
# def __init__(self, logfile_name="qcfractal.log"):
# self.logger = logging.getLogger(__name__)
# self.logger.setLevel(logging.INFO)
# handler = logging.FileHandler(options.logfile)
# handler.setLevel(logging.INFO)
# myFormatter = logging.Formatter('[%(asctime)s] %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
# handler.setFormatter(myFormatter)
# self.logger.addHandler(handler)
# self.logger.info("Logfile set to {}\n".format(options.logfile))
# mongo_username = None
# mongo_password = None
# if options.mongod_username:
# mongo_username = options.mongod_username
# if options.mongod_password:
# mongo_password = options.mongod_password
# # Build mongo socket
# self.mongod_socket = dqm.mongo_helper.MongoSocket(options.mongod_ip, options.mongod_port, username=mongo_username, password=mongo_password, globalAuth=True)
# self.logger.info("Mongod Socket Info:")
# self.logger.info(str(self.mongod_socket) + "\n")
# loop = tornado.ioloop.IOLoop.current()
# self.local_cluster = None
# if options.queue == "dask":
# # Grab the Dask Scheduler
# if options.dask_ip == "":
# self.local_cluster = distributed.LocalCluster(nanny=None)
# self.queue_socket = distributed.Client(self.local_cluster)
# else:
# self.queue_socket = distributed.Client(options.dask_ip + ":" + str(options.dask_port))
# self.logger.info("Dask Scheduler Info:")
# self.logger.info(str(self.queue_socket) + "\n")
# # Make sure the scratch is there
# if not os.path.exists(dask_working_dir):
# os.makedirs(dask_working_dir)
# # Dask Nanny
# self.queue_nanny = dqm.handlers.DaskNanny(self.queue_socket, self.mongod_socket, logger=self.logger)
# scheduler = dqm.handlers.DaskScheduler
# else:
# self.queue_socket = fireworks.LaunchPad.auto_load()
# self.queue_nanny = dqm.handlers.FireworksNanny(self.queue_socket, self.mongod_socket, logger=self.logger)
# self.logger.info("Fireworks Scheduler Info:")
# self.logger.info(str(self.queue_socket.host) + ":" + str(self.queue_socket.port) + "\n")
# scheduler = dqm.handlers.FireworksScheduler
# tornado_args = {
# "mongod_socket": self.mongod_socket,
# "queue_socket": self.queue_socket,
# "queue_nanny": self.queue_nanny,
# "logger": self.logger,
# }
# # Start up the app
# app = tornado.web.Application([
# (r"/information", dqm.handlers.Information, tornado_args),
# (r"/scheduler", scheduler, tornado_args),
# (r"/mongod", dqm.handlers.Mongod, tornado_args),
# ])
# app.listen(options.port)
# # Query Dask Nanny on loop
# tornado.ioloop.PeriodicCallback(self.queue_nanny.update, 2000).start()
# # This is for testing
# #loop.add_callback(get, "{data}")
# #loop.add_callback(post, json_data)
# #loop.run_sync(lambda: post(data))
# self.loop = loop
# self.logger.info("QCDB Client successfully initialized at https://localhost:{0:d}.\n".format(options.port))
# def start(self):
# self.logger.info("QCDB Client successfully started. Starting IOLoop.\n")
# # Soft quit at the end of a loop
# try:
# self.loop.start()
# except KeyboardInterrupt:
# if options.queue == "dask":
# self.queue_socket.shutdown()
# if self.local_cluster:
# self.local_cluster.close()
# self.loop.stop()
# self.logger.info("QCDB Client stopping gracefully. Stopped IOLoop.\n")
# def stop(self):
if __name__ == "__main__":
server = QCDBServer()
server.start()
def main():
server = qcfractal.server()
server.start()
if __name__ == '__main__':
main()
|
"""
A command line interface to the qcfractal.
"""
if __name__ == '__main__':
server = qcdb_server()
server.start()
def main():
server = qcfractal.server()
server.start()
if __name__ == '__main__':
main()
|
def interest(n, principle_amount):
def years(x):
return principle_amount + (n * principle_amount * x) / 100
return years
principle = 100000
home_loan = interest(7, principle) # percentage of 7
personal_loan = interest(11, principle) # percentage of 11
print(home_loan(20)) # for 20 years
print(personal_loan(3)) # for 3 years
|
def interest(n, principle_amount):
def years(x):
return principle_amount + n * principle_amount * x / 100
return years
principle = 100000
home_loan = interest(7, principle)
personal_loan = interest(11, principle)
print(home_loan(20))
print(personal_loan(3))
|
class ProducerEvent:
timestamp = 0
csvName = ""
houseId = 0
deviceId = 0
id = 0
def __init__(self, timestamp, ids, csv_name):
self.timestamp = int(timestamp)
self.csvName = csv_name
# ids_list = list(map(int, ids.replace("[", "").replace("]", "").replace("pv_producer", "").split(":")))
# self.houseId = int(ids_list[0])
# self.deviceId = int(ids_list[1])
ids_list = csv_name.split("_")
self.houseId = int(ids_list[0])
self.deviceId = int(ids_list[1])
self.id = int(ids_list[2].split(".")[0])
def __str__(self):
return "timestamp %r, csvName %r, houseId %r, deviceId %r, Id %r" %\
(self.timestamp, self.csvName, self.houseId, self.deviceId, self.id)
|
class Producerevent:
timestamp = 0
csv_name = ''
house_id = 0
device_id = 0
id = 0
def __init__(self, timestamp, ids, csv_name):
self.timestamp = int(timestamp)
self.csvName = csv_name
ids_list = csv_name.split('_')
self.houseId = int(ids_list[0])
self.deviceId = int(ids_list[1])
self.id = int(ids_list[2].split('.')[0])
def __str__(self):
return 'timestamp %r, csvName %r, houseId %r, deviceId %r, Id %r' % (self.timestamp, self.csvName, self.houseId, self.deviceId, self.id)
|
# some mnemonics as specific to capstone
CJMP_INS = ["je", "jne", "js", "jns", "jp", "jnp", "jo", "jno", "jl", "jle", "jg", "jge", "jb", "jbe", "ja", "jae", "jcxz", "jecxz", "jrcxz"]
LOOP_INS = ["loop", "loopne", "loope"]
JMP_INS = ["jmp", "ljmp"]
CALL_INS = ["call", "lcall"]
RET_INS = ["ret", "retn", "retf", "iret"]
END_INS = ["ret", "retn", "retf", "iret", "int3"]
REGS_32BIT = ["eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp"]
DOUBLE_ZERO = bytearray(b"\x00\x00")
DEFAULT_PROLOGUES = [
b"\x8B\xFF\x55\x8B\xEC",
b"\x89\xFF\x55\x8B\xEC",
b"\x55\x8B\xEC"
]
# these cover 80%+ of manually confirmed function starts in the reference data set
COMMON_PROLOGUES = {
"5": {
32: {
b"\x8B\xFF\x55\x8B\xEC": 5, # mov edi, edi, push ebp, mov ebp, esp
b"\x89\xFF\x55\x8B\xEC": 3, # mov edi, edi, push ebp, mov ebp, esp
},
64: {}
},
"3": {
32: {
b"\x55\x8B\xEC": 3, # push ebp, mov ebp, esp
},
64: {}
},
"2": {
32: {
b"\x8B\xFF": 3, # mov edi, edi
b"\xFF\x25": 3, # jmp dword ptr <addr>
b"\x33\xC0": 2, # xor eax, eax
b"\x83\xEC": 2, # sub esp, <byte>
b"\x8B\x44": 2, # mov eax, dword ptr <esp + byte>
b"\x81\xEC": 2, # sub esp, <byte>
b"\x8D\x4D": 2, # lea ecx, dword ptr <ebp/esp +- byte>
b"\x8D\x8D": 2, # lea ecx, dword ptr <ebp/esp +- byte>
b"\xFF\x74": 2, # push dword ptr <addr>
},
64: {}
},
"1": {
32: {
b"\x6a": 3, # push <const byte>
b"\x56": 3, # push esi
b"\x53": 2, # push ebx
b"\x51": 2, # push ecx
b"\x57": 2, # push edi
b"\xE8": 1, # call <offset>
b"\xc3": 1 # ret
},
64: {
b"\x40": 1, # x64 - push rxx
b"\x44": 1, # x64 - mov rxx, ptr
b"\x48": 1, # x64 - mov *, *
b"\x33": 1, # xor, eax, *
b"\x4c": 1, # x64 - mov reg, reg
b"\xb8": 1, # mov reg, const
b"\x8b": 1, # mov dword ptr, reg
b"\x89": 1, # mov dword ptr, reg
b"\x45": 1, # x64 - xor, reg, reg
b"\xc3": 1 # retn
}
}
}
#TODO: 2018-06-27 expand the coverage in this list
# https://stackoverflow.com/questions/25545470/long-multi-byte-nops-commonly-understood-macros-or-other-notation
GAP_SEQUENCES = {
1: [
"\x90", # NOP1_OVERRIDE_NOP - AMD / nop - INTEL
"\xCC" # int3
],
2: [
b"\x66\x90", # NOP2_OVERRIDE_NOP - AMD / nop - INTEL
b"\x8b\xc0",
b"\x8b\xff", # mov edi, edi
b"\x8d\x00", # lea eax, dword ptr [eax]
b"\x86\xc0", # xchg al, al
],
3: [
b"\x0f\x1f\x00", # NOP3_OVERRIDE_NOP - AMD / nop - INTEL
b"\x8d\x40\x00", # lea eax, dword ptr [eax]
b"\x8d\x00\x00", # lea eax, dword ptr [eax]
b"\x8d\x49\x00", # lea ecx, dword ptr [ecx]
b"\x8d\x64\x24", # lea esp, dword ptr [esp]
b"\x8d\x76\x00",
b"\x66\x66\x90"
],
4: [
b"\x0f\x1f\x40\x00", # NOP4_OVERRIDE_NOP - AMD / nop - INTEL
b"\x8d\x74\x26\x00",
b"\x66\x66\x66\x90"
],
5: [
b"\x0f\x1f\x44\x00\x00", # NOP5_OVERRIDE_NOP - AMD / nop - INTEL
b"\x90\x8d\x74\x26\x00"
],
6: [
b"\x66\x0f\x1f\x44\x00\x00", # NOP6_OVERRIDE_NOP - AMD / nop - INTEL
b"\x8d\xb6\x00\x00\x00\x00"
],
7: [
b"\x0f\x1f\x80\x00\x00\x00\x00", # NOP7_OVERRIDE_NOP - AMD / nop - INTEL,
b"\x8d\xb4\x26\x00\x00\x00\x00",
b"\x8D\xBC\x27\x00\x00\x00\x00"
],
8: [
b"\x0f\x1f\x84\x00\x00\x00\x00\x00", # NOP8_OVERRIDE_NOP - AMD / nop - INTEL
b"\x90\x8d\xb4\x26\x00\x00\x00\x00"
],
9: [
b"\x66\x0f\x1f\x84\x00\x00\x00\x00\x00", # NOP9_OVERRIDE_NOP - AMD / nop - INTEL
b"\x89\xf6\x8d\xbc\x27\x00\x00\x00\x00"
],
10: [
b"\x66\x66\x0f\x1f\x84\x00\x00\x00\x00\x00", # NOP10_OVERRIDE_NOP - AMD
b"\x8d\x76\x00\x8d\xbc\x27\x00\x00\x00\x00",
b"\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00"
],
11: [
b"\x66\x66\x66\x0f\x1f\x84\x00\x00\x00\x00\x00", # NOP11_OVERRIDE_NOP - AMD
b"\x8d\x74\x26\x00\x8d\xbc\x27\x00\x00\x00\x00",
b"\x66\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00"
],
12: [
b"\x8d\xb6\x00\x00\x00\x00\x8d\xbf\x00\x00\x00\x00",
b"\x66\x66\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00"
],
13: [
b"\x8d\xb6\x00\x00\x00\x00\x8d\xbc\x27\x00\x00\x00\x00",
b"\x66\x66\x66\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00"
],
14: [
b"\x8d\xb4\x26\x00\x00\x00\x00\x8d\xbc\x27\x00\x00\x00\x00",
b"\x66\x66\x66\x66\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00"
],
15: [
b"\x66\x66\x66\x66\x66\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00"
]
}
COMMON_START_BYTES = {
"32": {
"55": 8334,
"6a": 758,
"56": 756,
"51": 312,
"8d": 566,
"83": 558,
"53": 548
},
"64": {
"48": 1341,
"40": 349,
"4c": 59,
"33": 56,
"44": 18,
"45": 17,
"e9": 16
}
}
|
cjmp_ins = ['je', 'jne', 'js', 'jns', 'jp', 'jnp', 'jo', 'jno', 'jl', 'jle', 'jg', 'jge', 'jb', 'jbe', 'ja', 'jae', 'jcxz', 'jecxz', 'jrcxz']
loop_ins = ['loop', 'loopne', 'loope']
jmp_ins = ['jmp', 'ljmp']
call_ins = ['call', 'lcall']
ret_ins = ['ret', 'retn', 'retf', 'iret']
end_ins = ['ret', 'retn', 'retf', 'iret', 'int3']
regs_32_bit = ['eax', 'ebx', 'ecx', 'edx', 'esi', 'edi', 'ebp', 'esp']
double_zero = bytearray(b'\x00\x00')
default_prologues = [b'\x8b\xffU\x8b\xec', b'\x89\xffU\x8b\xec', b'U\x8b\xec']
common_prologues = {'5': {32: {b'\x8b\xffU\x8b\xec': 5, b'\x89\xffU\x8b\xec': 3}, 64: {}}, '3': {32: {b'U\x8b\xec': 3}, 64: {}}, '2': {32: {b'\x8b\xff': 3, b'\xff%': 3, b'3\xc0': 2, b'\x83\xec': 2, b'\x8bD': 2, b'\x81\xec': 2, b'\x8dM': 2, b'\x8d\x8d': 2, b'\xfft': 2}, 64: {}}, '1': {32: {b'j': 3, b'V': 3, b'S': 2, b'Q': 2, b'W': 2, b'\xe8': 1, b'\xc3': 1}, 64: {b'@': 1, b'D': 1, b'H': 1, b'3': 1, b'L': 1, b'\xb8': 1, b'\x8b': 1, b'\x89': 1, b'E': 1, b'\xc3': 1}}}
gap_sequences = {1: ['\x90', 'Ì'], 2: [b'f\x90', b'\x8b\xc0', b'\x8b\xff', b'\x8d\x00', b'\x86\xc0'], 3: [b'\x0f\x1f\x00', b'\x8d@\x00', b'\x8d\x00\x00', b'\x8dI\x00', b'\x8dd$', b'\x8dv\x00', b'ff\x90'], 4: [b'\x0f\x1f@\x00', b'\x8dt&\x00', b'fff\x90'], 5: [b'\x0f\x1fD\x00\x00', b'\x90\x8dt&\x00'], 6: [b'f\x0f\x1fD\x00\x00', b'\x8d\xb6\x00\x00\x00\x00'], 7: [b'\x0f\x1f\x80\x00\x00\x00\x00', b'\x8d\xb4&\x00\x00\x00\x00', b"\x8d\xbc'\x00\x00\x00\x00"], 8: [b'\x0f\x1f\x84\x00\x00\x00\x00\x00', b'\x90\x8d\xb4&\x00\x00\x00\x00'], 9: [b'f\x0f\x1f\x84\x00\x00\x00\x00\x00', b"\x89\xf6\x8d\xbc'\x00\x00\x00\x00"], 10: [b'ff\x0f\x1f\x84\x00\x00\x00\x00\x00', b"\x8dv\x00\x8d\xbc'\x00\x00\x00\x00", b'f.\x0f\x1f\x84\x00\x00\x00\x00\x00'], 11: [b'fff\x0f\x1f\x84\x00\x00\x00\x00\x00', b"\x8dt&\x00\x8d\xbc'\x00\x00\x00\x00", b'ff.\x0f\x1f\x84\x00\x00\x00\x00\x00'], 12: [b'\x8d\xb6\x00\x00\x00\x00\x8d\xbf\x00\x00\x00\x00', b'fff.\x0f\x1f\x84\x00\x00\x00\x00\x00'], 13: [b"\x8d\xb6\x00\x00\x00\x00\x8d\xbc'\x00\x00\x00\x00", b'ffff.\x0f\x1f\x84\x00\x00\x00\x00\x00'], 14: [b"\x8d\xb4&\x00\x00\x00\x00\x8d\xbc'\x00\x00\x00\x00", b'fffff.\x0f\x1f\x84\x00\x00\x00\x00\x00'], 15: [b'ffffff.\x0f\x1f\x84\x00\x00\x00\x00\x00']}
common_start_bytes = {'32': {'55': 8334, '6a': 758, '56': 756, '51': 312, '8d': 566, '83': 558, '53': 548}, '64': {'48': 1341, '40': 349, '4c': 59, '33': 56, '44': 18, '45': 17, 'e9': 16}}
|
def main():
# input
N = int(input())
# compute
N = int(1.08*N)
# output
if N < 206:
print('Yay!')
elif N == 206:
print('so-so')
else:
print(':(')
if __name__ == '__main__':
main()
|
def main():
n = int(input())
n = int(1.08 * N)
if N < 206:
print('Yay!')
elif N == 206:
print('so-so')
else:
print(':(')
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
strings = {
'test.fallback': 'A fallback string'
}
|
strings = {'test.fallback': 'A fallback string'}
|
def climb_stairs2(n: int) -> int:
if n == 1 or n == 2:
return n
n1 = 1
n2 = 2
t = 0
for i in range(3, n + 1):
t = n1 + n2
n1 = n2
n2 = t
return t
class StairClimber:
# total variable needed for the recursive solution
total = 0
# recursive, mathy way that's slow for sufficiently big numbers
def climb_stairs(self, n: int) -> int:
if n == 0:
self.total += 1
if n >= 1:
self.climb_stairs(n - 1)
if n >= 2:
self.climb_stairs(n - 2)
return self.total
# standard, boring dynamic programming way
print(climb_stairs2(3))
print(climb_stairs2(38))
|
def climb_stairs2(n: int) -> int:
if n == 1 or n == 2:
return n
n1 = 1
n2 = 2
t = 0
for i in range(3, n + 1):
t = n1 + n2
n1 = n2
n2 = t
return t
class Stairclimber:
total = 0
def climb_stairs(self, n: int) -> int:
if n == 0:
self.total += 1
if n >= 1:
self.climb_stairs(n - 1)
if n >= 2:
self.climb_stairs(n - 2)
return self.total
print(climb_stairs2(3))
print(climb_stairs2(38))
|
#!usr/bin/python
# -*- coding:utf8 -*-
def gen_func():
try:
yield "http://projectesdu.com"
except GeneratorExit:
pass
yield 2
yield 3
return "bobby"
if __name__ == "__main__":
gen = gen_func()
next(gen)
gen.close()
next(gen)
|
def gen_func():
try:
yield 'http://projectesdu.com'
except GeneratorExit:
pass
yield 2
yield 3
return 'bobby'
if __name__ == '__main__':
gen = gen_func()
next(gen)
gen.close()
next(gen)
|
list_images = [
".jpeg",".jpg",".png",".gif",".webp",".tiff",".psd",".raw",".bmp",".heif",".indd",".svg",".ico"
]
list_documents = [
".doc",".txt",".pdf",".xlsx",".docx",".xls",".rtf",".md",".ods",".ppt",".pptx"
]
list_videos = [
".mp4",".m4v",".f4v",".f4a",".m4b",".m4r",".f4b",".mov",".3gp",
".3gp2",".3g2",".3gpp",".3gpp2",".ogg",".oga",".ogv",".ogx",".wmv",
".asf*",".webm",".flv",".avi",".QuickTime",".HDV",".OP1a",".OP-Atom",".MPEG-TS",".wav",".lxf",".gxf"
]
list_audio = [
".mp3",".wav",".m4a",".aac",".he-aac",".ac3",".eac3",".vorbis",".wma",".pcm"
]
list_applications = [
".exe",".lnk"
]
list_codes = [
".c",".py",".java",".cpp",".js",".html",".css",".php"
]
list_archives = [
".zip",".7-zip",".7z",".bz2",".gz",".rar",".tar"
]
extensions = {
"Images" : list_images,
"Documents" : list_documents,
"Videos" : list_videos,
"Audio" : list_audio,
"Applications" : list_applications,
"Code" : list_codes,
"Archives" : list_archives
}
|
list_images = ['.jpeg', '.jpg', '.png', '.gif', '.webp', '.tiff', '.psd', '.raw', '.bmp', '.heif', '.indd', '.svg', '.ico']
list_documents = ['.doc', '.txt', '.pdf', '.xlsx', '.docx', '.xls', '.rtf', '.md', '.ods', '.ppt', '.pptx']
list_videos = ['.mp4', '.m4v', '.f4v', '.f4a', '.m4b', '.m4r', '.f4b', '.mov', '.3gp', '.3gp2', '.3g2', '.3gpp', '.3gpp2', '.ogg', '.oga', '.ogv', '.ogx', '.wmv', '.asf*', '.webm', '.flv', '.avi', '.QuickTime', '.HDV', '.OP1a', '.OP-Atom', '.MPEG-TS', '.wav', '.lxf', '.gxf']
list_audio = ['.mp3', '.wav', '.m4a', '.aac', '.he-aac', '.ac3', '.eac3', '.vorbis', '.wma', '.pcm']
list_applications = ['.exe', '.lnk']
list_codes = ['.c', '.py', '.java', '.cpp', '.js', '.html', '.css', '.php']
list_archives = ['.zip', '.7-zip', '.7z', '.bz2', '.gz', '.rar', '.tar']
extensions = {'Images': list_images, 'Documents': list_documents, 'Videos': list_videos, 'Audio': list_audio, 'Applications': list_applications, 'Code': list_codes, 'Archives': list_archives}
|
# Least Common Multiple (LCM) Calculator - Burak Karabey
def LCM(x, y):
if x > y:
limit = x
else:
limit = y
prime_numbers = [] # Start of Finding Prime Number
if limit < 2:
return prime_numbers.append(0)
elif limit == 2:
return prime_numbers.append(2)
else:
prime_numbers.append(2)
for t in range(3, limit):
find_prime = False
for r in range(2, t):
if t % r == 0:
find_prime = True
break
if not find_prime:
prime_numbers.append(t)
prime_numbers.sort() # End of Finding Prime Number
i = 0
least_common_multiple = 1
while x != 1 or y != 1:
if x % prime_numbers[i] == 0 or y % prime_numbers[i] == 0:
least_common_multiple = least_common_multiple * prime_numbers[i]
if x % prime_numbers[i] == 0:
x = x / prime_numbers[i]
if y % prime_numbers[i] == 0:
y = y / prime_numbers[i]
else:
i += 1
return print("LCM=", least_common_multiple)
# USAGE
LCM(12,15)
|
def lcm(x, y):
if x > y:
limit = x
else:
limit = y
prime_numbers = []
if limit < 2:
return prime_numbers.append(0)
elif limit == 2:
return prime_numbers.append(2)
else:
prime_numbers.append(2)
for t in range(3, limit):
find_prime = False
for r in range(2, t):
if t % r == 0:
find_prime = True
break
if not find_prime:
prime_numbers.append(t)
prime_numbers.sort()
i = 0
least_common_multiple = 1
while x != 1 or y != 1:
if x % prime_numbers[i] == 0 or y % prime_numbers[i] == 0:
least_common_multiple = least_common_multiple * prime_numbers[i]
if x % prime_numbers[i] == 0:
x = x / prime_numbers[i]
if y % prime_numbers[i] == 0:
y = y / prime_numbers[i]
else:
i += 1
return print('LCM=', least_common_multiple)
lcm(12, 15)
|
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
T = int(input())
for _ in range(T):
if is_prime(int(input())):
print("Prime")
else:
print("Not prime")
|
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
t = int(input())
for _ in range(T):
if is_prime(int(input())):
print('Prime')
else:
print('Not prime')
|
#!/usr/bin/env python3
sum=0
a=1
while a<=100:
sum +=a
a+=1
print(sum)
|
sum = 0
a = 1
while a <= 100:
sum += a
a += 1
print(sum)
|
class PositionedObjectError(Exception):
def __init__(self, *args):
super().__init__(*args)
class RelativePositionNotSettableError(PositionedObjectError):
pass
class RelativeXNotSettableError(RelativePositionNotSettableError):
pass
class RelativeYNotSettableError(RelativePositionNotSettableError):
pass
class Positioned(object):
def __init__(self, relative_x=None, relative_y=None, *args, **kwargs):
self._relative_x = None
self._relative_y = None
self.relative_x = relative_x
self.relative_y = relative_y
super().__init__(*args, **kwargs)
@property
def relative_x(self):
if self._relative_x is None:
return 0
return self._relative_x
@relative_x.setter
def relative_x(self, val):
self._relative_x = val
@property
def relative_y(self):
if self._relative_y is None:
return 0
return self._relative_y
@relative_y.setter
def relative_y(self, val):
self._relative_y = val
|
class Positionedobjecterror(Exception):
def __init__(self, *args):
super().__init__(*args)
class Relativepositionnotsettableerror(PositionedObjectError):
pass
class Relativexnotsettableerror(RelativePositionNotSettableError):
pass
class Relativeynotsettableerror(RelativePositionNotSettableError):
pass
class Positioned(object):
def __init__(self, relative_x=None, relative_y=None, *args, **kwargs):
self._relative_x = None
self._relative_y = None
self.relative_x = relative_x
self.relative_y = relative_y
super().__init__(*args, **kwargs)
@property
def relative_x(self):
if self._relative_x is None:
return 0
return self._relative_x
@relative_x.setter
def relative_x(self, val):
self._relative_x = val
@property
def relative_y(self):
if self._relative_y is None:
return 0
return self._relative_y
@relative_y.setter
def relative_y(self, val):
self._relative_y = val
|
# Image types
INTENSITY = 'intensity'
LABEL = 'label'
SAMPLING_MAP = 'sampling_map'
# Keys for dataset samples
PATH = 'path'
TYPE = 'type'
STEM = 'stem'
DATA = 'data'
AFFINE = 'affine'
# For aggregator
IMAGE = 'image'
LOCATION = 'location'
# In PyTorch convention
CHANNELS_DIMENSION = 1
# Code repository
REPO_URL = 'https://github.com/fepegar/torchio/'
# Data repository
DATA_REPO = 'https://github.com/fepegar/torchio-data/raw/master/data/'
|
intensity = 'intensity'
label = 'label'
sampling_map = 'sampling_map'
path = 'path'
type = 'type'
stem = 'stem'
data = 'data'
affine = 'affine'
image = 'image'
location = 'location'
channels_dimension = 1
repo_url = 'https://github.com/fepegar/torchio/'
data_repo = 'https://github.com/fepegar/torchio-data/raw/master/data/'
|
#!/usr/local/bin/python3
# Copyright 2019 NineFx Inc.
# Justin Baum
# 3 June 2019
# Precis Code-Generator ReasonML
# https://github.com/NineFX/smeagol/blob/master/spec/code_gen/precis_cp.txt
fp = open('precis_cp.txt', 'r')
ranges = []
line = fp.readline()
code = "DISALLOWED"
prev = "DISALLOWED"
firstOccurence = 0
count = 0
while line:
count += 1
line = fp.readline()
if len(line) < 2: break
linesplit = line.split(";")
codepoint = int(linesplit[0])
code = linesplit[1][:-1]
if code != prev:
ranges.append([firstOccurence, codepoint - 1, prev])
firstOccurence = count
prev = code
ranges.append([firstOccurence, count, code])
# Binary Tree
def splitHalf(listy):
if(len(listy) <= 2):
print("switch (point) { ")
for item in listy:
print("| point when (point >= " + str(item[0]) + ") && (point <= " + str(item[1]) + ") =>" + item[2])
print("| _point => DISALLOWED")
print("}")
return
splitValue = listy[len(listy)//2]
firstHalf = listy[:(len(listy))//2]
secondHalf = listy[(len(listy))//2:]
print("if (point < "+str(splitValue[0]) +")")
print("{")
splitHalf(firstHalf)
print("} else {")
splitHalf(secondHalf)
print("}")
splitHalf(ranges)
|
fp = open('precis_cp.txt', 'r')
ranges = []
line = fp.readline()
code = 'DISALLOWED'
prev = 'DISALLOWED'
first_occurence = 0
count = 0
while line:
count += 1
line = fp.readline()
if len(line) < 2:
break
linesplit = line.split(';')
codepoint = int(linesplit[0])
code = linesplit[1][:-1]
if code != prev:
ranges.append([firstOccurence, codepoint - 1, prev])
first_occurence = count
prev = code
ranges.append([firstOccurence, count, code])
def split_half(listy):
if len(listy) <= 2:
print('switch (point) { ')
for item in listy:
print('| point when (point >= ' + str(item[0]) + ') && (point <= ' + str(item[1]) + ') =>' + item[2])
print('| _point => DISALLOWED')
print('}')
return
split_value = listy[len(listy) // 2]
first_half = listy[:len(listy) // 2]
second_half = listy[len(listy) // 2:]
print('if (point < ' + str(splitValue[0]) + ')')
print('{')
split_half(firstHalf)
print('} else {')
split_half(secondHalf)
print('}')
split_half(ranges)
|
"""Search filters for ExploreCourses queries"""
# Term offered
AUTUMN = "filter-term-Autumn"
WINTER = "filter-term-Winter"
SPRING = "filter-term-Spring"
SUMMER = "filter-term-Summer"
# Teaching presence
INPERSON = "filter-instructionmode-INPERSON"
ONLINEASYNC = "filter-instructionmode-ONLINEASYNC"
ONLINESYNC = "filter-instructionmode-ONLINESYNC"
REMOTEASYNC = "filter-instructionmode-REMOTEASYNC"
REMOTESYNC = "filter-instructionmode-REMOTESYNC"
INDEPENDENTSTDY = "filter-instructionmode-INDEPENDENTSTDY"
# Number of units
UNITS_1 = "filter-units-1"
UNITS_2 = "filter-units-2"
UNITS_3 = "filter-units-3"
UNITS_4 = "filter-units-4"
UNITS_5 = "filter-units-5"
UNITS_GT5 = "filter-units-gt5" # Greater than 5 units
# Time offered
EARLY_MORNING = "filter-time-0" # before 10am
MORNING = "filter-time-1" # 10am-12pm
LUNCHTIME = "filter-time-2" # 12pm-2pm
AFTERNOON = "filter-time-3" # 2pm-5pm
EVENING = "filter-time-4" # after 5pm
# Days
SUNDAY = "filter-day-1"
MONDAY = "filter-day-2"
TUESDAY = "filter-day-3"
WEDNESDAY = "filter-day-4"
THURSDAY = "filter-day-5"
FRIDAY = "filter-day-6"
SATURDAY = "filter-day-7"
# UG Requirements
WAY_AII = "filter-ger-WAYAII" # Aesthetic and Interpretive Inquiry
WAY_AQR = "filter-ger-WAYAQR" # Applied Quantitative Reasoning
WAY_CE = "filter-ger-WAYCE" # Creative Expression
WAY_ED = "filter-ger-WAYED" # Engaging Diversity
WAY_ER = "filter-ger-WAYER" # Ethical Reasoning
WAY_FR = "filter-ger-WAYFR" # Formal Reasoning
WAY_SI = "filter-ger-WAYSI" # Social Inquiry
WAY_SMA = "filter-ger-WAYSMA" # Scientific Method and Analysis
LANGUAGE = "filter-ger-Language"
WRITING1 = "filter-ger-Writing1"
WRITING2 = "filter-ger-Writing2"
WRITINGSLE = "filter-ger-WritingSLE"
DBHUM = "filter-ger-GERDBHum"
DBMATH = "filter-ger-GERDBMath"
DBSOCSCI = "filter-ger-GERDBSocSci"
DBENGRAPPSCI = "filter-ger-GERDBEngrAppSci"
DBNATSCI = "filter-ger-GERDBNatSci"
ECETHICREAS = "filter-ger-GERECEthicReas"
ECGLOBALCOM = "filter-ger-GERECGlobalCom"
ECAMERCUL = "filter-ger-GERECAmerCul"
ECGENDER = "filter-ger-GERECGender"
IHUM1 = "filter-ger-GERIHUM1"
IHUM2 = "filter-ger-GERIHUM2"
IHUM3 = "filter-ger-GERIHUM3"
# Component
LEC = "filter-component-LEC" # Lecture
SEM = "filter-component-SEM" # Seminar
DIS = "filter-component-DIS" # Discussion Section
LAB = "filter-component-LAB" # Laboratory
LBS = "filter-component-LBS" # Lab Section
ACT = "filter-component-ACT" # Activity
CAS = "filter-component-CAS" # Case Study
COL = "filter-component-COL" # Colloquium
WKS = "filter-component-WKS" # Workshop
INS = "filter-component-INS" # Independent Study
IDS = "filter-component-IDS" # Intro Dial, Sophomore
ISF = "filter-component-ISF" # Intro Sem, Freshman
ISS = "filter-component-ISS" # Intro Sem, Sophomore
ITR = "filter-component-ITR" # Internship
API = "filter-component-API" # Arts Intensive Program
LNG = "filter-component-LNG" # Language
CLK = "filter-component-CLK" # Clerkship
PRA = "filter-component-PRA" # Practicum
PRC = "filter-component-PRC" # Practicum
RES = "filter-component-RES" # Research
SCS = "filter-component-SCS" # Sophomore College
TD = "filter-component-TD" # Thesis/Dissertation
# Career
UG = "filter-academiclevel-UG" # Undergraduate
GR = "filter-academiclevel-GR" # Graduate
GSB = "filter-academiclevel-GSB" # Graduate School of Business
LAW = "filter-academiclevel-LAW" # Law School
MED = "filter-academiclevel-MED" # Medical School
|
"""Search filters for ExploreCourses queries"""
autumn = 'filter-term-Autumn'
winter = 'filter-term-Winter'
spring = 'filter-term-Spring'
summer = 'filter-term-Summer'
inperson = 'filter-instructionmode-INPERSON'
onlineasync = 'filter-instructionmode-ONLINEASYNC'
onlinesync = 'filter-instructionmode-ONLINESYNC'
remoteasync = 'filter-instructionmode-REMOTEASYNC'
remotesync = 'filter-instructionmode-REMOTESYNC'
independentstdy = 'filter-instructionmode-INDEPENDENTSTDY'
units_1 = 'filter-units-1'
units_2 = 'filter-units-2'
units_3 = 'filter-units-3'
units_4 = 'filter-units-4'
units_5 = 'filter-units-5'
units_gt5 = 'filter-units-gt5'
early_morning = 'filter-time-0'
morning = 'filter-time-1'
lunchtime = 'filter-time-2'
afternoon = 'filter-time-3'
evening = 'filter-time-4'
sunday = 'filter-day-1'
monday = 'filter-day-2'
tuesday = 'filter-day-3'
wednesday = 'filter-day-4'
thursday = 'filter-day-5'
friday = 'filter-day-6'
saturday = 'filter-day-7'
way_aii = 'filter-ger-WAYAII'
way_aqr = 'filter-ger-WAYAQR'
way_ce = 'filter-ger-WAYCE'
way_ed = 'filter-ger-WAYED'
way_er = 'filter-ger-WAYER'
way_fr = 'filter-ger-WAYFR'
way_si = 'filter-ger-WAYSI'
way_sma = 'filter-ger-WAYSMA'
language = 'filter-ger-Language'
writing1 = 'filter-ger-Writing1'
writing2 = 'filter-ger-Writing2'
writingsle = 'filter-ger-WritingSLE'
dbhum = 'filter-ger-GERDBHum'
dbmath = 'filter-ger-GERDBMath'
dbsocsci = 'filter-ger-GERDBSocSci'
dbengrappsci = 'filter-ger-GERDBEngrAppSci'
dbnatsci = 'filter-ger-GERDBNatSci'
ecethicreas = 'filter-ger-GERECEthicReas'
ecglobalcom = 'filter-ger-GERECGlobalCom'
ecamercul = 'filter-ger-GERECAmerCul'
ecgender = 'filter-ger-GERECGender'
ihum1 = 'filter-ger-GERIHUM1'
ihum2 = 'filter-ger-GERIHUM2'
ihum3 = 'filter-ger-GERIHUM3'
lec = 'filter-component-LEC'
sem = 'filter-component-SEM'
dis = 'filter-component-DIS'
lab = 'filter-component-LAB'
lbs = 'filter-component-LBS'
act = 'filter-component-ACT'
cas = 'filter-component-CAS'
col = 'filter-component-COL'
wks = 'filter-component-WKS'
ins = 'filter-component-INS'
ids = 'filter-component-IDS'
isf = 'filter-component-ISF'
iss = 'filter-component-ISS'
itr = 'filter-component-ITR'
api = 'filter-component-API'
lng = 'filter-component-LNG'
clk = 'filter-component-CLK'
pra = 'filter-component-PRA'
prc = 'filter-component-PRC'
res = 'filter-component-RES'
scs = 'filter-component-SCS'
td = 'filter-component-TD'
ug = 'filter-academiclevel-UG'
gr = 'filter-academiclevel-GR'
gsb = 'filter-academiclevel-GSB'
law = 'filter-academiclevel-LAW'
med = 'filter-academiclevel-MED'
|
# https://leetcode.com/problems/unique-morse-code-words/
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
dictx = {"a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.",
"h": "....", "i": "..", "j": ".---", "k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---",
"p": ".--.", "q": "--.-", "r": ".-.", "s": "...", "t": "-", "u": "..-", "v": "...-",
"w": ".--", "x": "-..-", "y": "-.--", "z": "--.."}
keys = {}
for each in words:
res = ""
for i in range(0, len(each)):
res += dictx[each[i]]
if res in keys:
keys[res] += 1
else:
keys[res] = 1
return len(keys.values())
|
class Solution:
def unique_morse_representations(self, words: List[str]) -> int:
dictx = {'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..'}
keys = {}
for each in words:
res = ''
for i in range(0, len(each)):
res += dictx[each[i]]
if res in keys:
keys[res] += 1
else:
keys[res] = 1
return len(keys.values())
|
class BadBatchRequestException(Exception):
def __init__(self, org, repo, message=None):
super()
self.org = org
self.repo = repo
self.message = message
class UnknownBatchOperationException(Exception):
def __init__(self, org, repo, operation, message=None):
super()
self.org = org
self.repo = repo
self.operation = operation
class StorageException(Exception):
def __init__(self, org, repo, oid, operation, message=None):
super()
self.org = org
self.repo = repo
self.oid = oid
self.operation = operation
self.message = message
class AuthException(Exception):
def __init__(self, message=None):
self.message = message
|
class Badbatchrequestexception(Exception):
def __init__(self, org, repo, message=None):
super()
self.org = org
self.repo = repo
self.message = message
class Unknownbatchoperationexception(Exception):
def __init__(self, org, repo, operation, message=None):
super()
self.org = org
self.repo = repo
self.operation = operation
class Storageexception(Exception):
def __init__(self, org, repo, oid, operation, message=None):
super()
self.org = org
self.repo = repo
self.oid = oid
self.operation = operation
self.message = message
class Authexception(Exception):
def __init__(self, message=None):
self.message = message
|
class Agent:
def __init__(self, name):
self.name = name
def reset(self, state):
# Completely resets the state of the Agent for a new game
return
def make_action(self, state):
# Returns a valid move in (row, column) format where 0 <= row, column < board_len
move = (0, 0)
return move
def update_state(self, move):
# Update the internal state of an agent according to the move made by the opponent (if necessary)
return
@staticmethod
def get_params():
# Get agent parameters from command line input and return in tuple form
return ()
|
class Agent:
def __init__(self, name):
self.name = name
def reset(self, state):
return
def make_action(self, state):
move = (0, 0)
return move
def update_state(self, move):
return
@staticmethod
def get_params():
return ()
|
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n=c=0;r=[]
for x in map(int,[*open(0)][1].split()):
if x<0:
if n==2:
r+=[c]
n=1
c=0
else:n+=1
c+=1
r+=[c]
print(len(r))
print(*r)
|
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n = c = 0
r = []
for x in map(int, [*open(0)][1].split()):
if x < 0:
if n == 2:
r += [c]
n = 1
c = 0
else:
n += 1
c += 1
r += [c]
print(len(r))
print(*r)
|
#
# PySNMP MIB module ONEACCESS-SYS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-SYS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:25:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection")
oacExpIMSystem, oacMIBModules = mibBuilder.importSymbols("ONEACCESS-GLOBAL-REG", "oacExpIMSystem", "oacMIBModules")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
Bits, IpAddress, Gauge32, Integer32, TimeTicks, MibIdentifier, Unsigned32, Counter32, Counter64, iso, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "IpAddress", "Gauge32", "Integer32", "TimeTicks", "MibIdentifier", "Unsigned32", "Counter32", "Counter64", "iso", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "NotificationType")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
oacSysMIBModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 13191, 1, 100, 671))
oacSysMIBModule.setRevisions(('2014-05-05 00:01', '2011-06-15 00:00', '2010-12-14 00:01', '2010-08-11 10:00', '2010-07-08 10:00',))
if mibBuilder.loadTexts: oacSysMIBModule.setLastUpdated('201405050001Z')
if mibBuilder.loadTexts: oacSysMIBModule.setOrganization(' OneAccess ')
class OASysHwcClass(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2))
namedValues = NamedValues(("board", 0), ("cpu", 1), ("slot", 2))
class OASysHwcType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))
namedValues = NamedValues(("mainboard", 0), ("microprocessor", 1), ("ram", 2), ("flash", 3), ("dsp", 4), ("uplink", 5), ("module", 6))
class OASysCoreType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))
namedValues = NamedValues(("controlplane", 0), ("dataforwarding", 1), ("application", 2), ("mixed", 3))
oacExpIMSysStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1))
oacExpIMSysHardwareDescription = MibIdentifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2))
oacSysMemStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 1))
oacSysCpuStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2))
oacSysSecureCrashlogCount = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 100), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysSecureCrashlogCount.setStatus('current')
oacSysStartCaused = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 200), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysStartCaused.setStatus('current')
oacSysIMSysMainBoard = MibIdentifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1))
oacExpIMSysHwComponents = MibIdentifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2))
oacExpIMSysFactory = MibIdentifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 3))
oacSysIMSysMainIdentifier = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 1), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysIMSysMainIdentifier.setStatus('current')
oacSysIMSysMainManufacturedIdentity = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysIMSysMainManufacturedIdentity.setStatus('current')
oacSysIMSysMainManufacturedDate = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysIMSysMainManufacturedDate.setStatus('current')
oacSysIMSysMainCPU = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysIMSysMainCPU.setStatus('current')
oacSysIMSysMainBSPVersion = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysIMSysMainBSPVersion.setStatus('current')
oacSysIMSysMainBootVersion = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysIMSysMainBootVersion.setStatus('current')
oacSysIMSysMainBootDateCreation = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysIMSysMainBootDateCreation.setStatus('current')
oacSysMemoryFree = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 1, 1), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysMemoryFree.setStatus('current')
oacSysMemoryAllocated = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysMemoryAllocated.setStatus('current')
oacSysMemoryTotal = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysMemoryTotal.setStatus('current')
oacSysMemoryUsed = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysMemoryUsed.setStatus('current')
oacSysCpuUsed = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 1), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysCpuUsed.setStatus('current')
oacSysCpuUsedCoresCount = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysCpuUsedCoresCount.setStatus('current')
oacSysCpuUsedCoresTable = MibTable((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3), )
if mibBuilder.loadTexts: oacSysCpuUsedCoresTable.setStatus('current')
oacSysCpuUsedCoresEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3, 1), ).setIndexNames((0, "ONEACCESS-SYS-MIB", "oacSysCpuUsedIndex"))
if mibBuilder.loadTexts: oacSysCpuUsedCoresEntry.setStatus('current')
oacSysCpuUsedIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3, 1, 1), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysCpuUsedIndex.setStatus('current')
oacSysCpuUsedCoreType = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3, 1, 2), OASysCoreType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysCpuUsedCoreType.setStatus('current')
oacSysCpuUsedValue = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysCpuUsedValue.setStatus('current')
oacSysCpuUsedOneMinuteValue = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysCpuUsedOneMinuteValue.setStatus('current')
oacSysLastRebootCause = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacSysLastRebootCause.setStatus('current')
oacExpIMSysHwComponentsCount = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 1), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysHwComponentsCount.setStatus('current')
oacExpIMSysHwComponentsTable = MibTable((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2), )
if mibBuilder.loadTexts: oacExpIMSysHwComponentsTable.setStatus('current')
oacExpIMSysHwComponentsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1), ).setIndexNames((0, "ONEACCESS-SYS-MIB", "oacExpIMSysHwcIndex"))
if mibBuilder.loadTexts: oacExpIMSysHwComponentsEntry.setStatus('current')
oacExpIMSysHwcIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 1), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysHwcIndex.setStatus('current')
oacExpIMSysHwcClass = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 2), OASysHwcClass()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysHwcClass.setStatus('current')
oacExpIMSysHwcType = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 3), OASysHwcType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysHwcType.setStatus('current')
oacExpIMSysHwcDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 4), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysHwcDescription.setStatus('current')
oacExpIMSysHwcSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysHwcSerialNumber.setStatus('current')
oacExpIMSysHwcManufacturer = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 6), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysHwcManufacturer.setStatus('current')
oacExpIMSysHwcManufacturedDate = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 10))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysHwcManufacturedDate.setStatus('current')
oacExpIMSysHwcProductName = MibTableColumn((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysHwcProductName.setStatus('current')
oacExpIMSysFactorySupplierID = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 3, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 14))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysFactorySupplierID.setStatus('current')
oacExpIMSysFactoryProductSalesCode = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 3, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 22))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysFactoryProductSalesCode.setStatus('current')
oacExpIMSysFactoryHwRevision = MibScalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 3, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(2, 7))).setMaxAccess("readonly")
if mibBuilder.loadTexts: oacExpIMSysFactoryHwRevision.setStatus('current')
mibBuilder.exportSymbols("ONEACCESS-SYS-MIB", oacSysCpuUsed=oacSysCpuUsed, oacSysCpuUsedValue=oacSysCpuUsedValue, OASysCoreType=OASysCoreType, oacSysCpuUsedIndex=oacSysCpuUsedIndex, oacExpIMSysHwcManufacturedDate=oacExpIMSysHwcManufacturedDate, oacSysCpuUsedOneMinuteValue=oacSysCpuUsedOneMinuteValue, oacSysIMSysMainIdentifier=oacSysIMSysMainIdentifier, oacSysCpuUsedCoresEntry=oacSysCpuUsedCoresEntry, oacSysCpuStatistics=oacSysCpuStatistics, oacExpIMSysFactorySupplierID=oacExpIMSysFactorySupplierID, OASysHwcClass=OASysHwcClass, oacSysIMSysMainCPU=oacSysIMSysMainCPU, oacExpIMSysHwcProductName=oacExpIMSysHwcProductName, oacExpIMSysStatistics=oacExpIMSysStatistics, oacSysMemoryFree=oacSysMemoryFree, oacSysMIBModule=oacSysMIBModule, oacSysMemoryAllocated=oacSysMemoryAllocated, oacSysMemStatistics=oacSysMemStatistics, oacExpIMSysHwcSerialNumber=oacExpIMSysHwcSerialNumber, oacSysMemoryUsed=oacSysMemoryUsed, oacExpIMSysHwComponentsTable=oacExpIMSysHwComponentsTable, oacSysMemoryTotal=oacSysMemoryTotal, oacSysCpuUsedCoresTable=oacSysCpuUsedCoresTable, oacExpIMSysHardwareDescription=oacExpIMSysHardwareDescription, oacSysIMSysMainManufacturedIdentity=oacSysIMSysMainManufacturedIdentity, oacSysIMSysMainBoard=oacSysIMSysMainBoard, oacSysIMSysMainBootDateCreation=oacSysIMSysMainBootDateCreation, oacExpIMSysHwcDescription=oacExpIMSysHwcDescription, oacSysIMSysMainBootVersion=oacSysIMSysMainBootVersion, oacExpIMSysHwcClass=oacExpIMSysHwcClass, PYSNMP_MODULE_ID=oacSysMIBModule, oacSysCpuUsedCoreType=oacSysCpuUsedCoreType, oacExpIMSysHwComponentsCount=oacExpIMSysHwComponentsCount, oacExpIMSysFactoryProductSalesCode=oacExpIMSysFactoryProductSalesCode, oacSysIMSysMainBSPVersion=oacSysIMSysMainBSPVersion, oacSysStartCaused=oacSysStartCaused, oacExpIMSysHwComponents=oacExpIMSysHwComponents, oacExpIMSysFactory=oacExpIMSysFactory, oacSysIMSysMainManufacturedDate=oacSysIMSysMainManufacturedDate, oacSysCpuUsedCoresCount=oacSysCpuUsedCoresCount, oacExpIMSysHwcIndex=oacExpIMSysHwcIndex, OASysHwcType=OASysHwcType, oacSysLastRebootCause=oacSysLastRebootCause, oacExpIMSysFactoryHwRevision=oacExpIMSysFactoryHwRevision, oacExpIMSysHwComponentsEntry=oacExpIMSysHwComponentsEntry, oacExpIMSysHwcType=oacExpIMSysHwcType, oacExpIMSysHwcManufacturer=oacExpIMSysHwcManufacturer, oacSysSecureCrashlogCount=oacSysSecureCrashlogCount)
|
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection')
(oac_exp_im_system, oac_mib_modules) = mibBuilder.importSymbols('ONEACCESS-GLOBAL-REG', 'oacExpIMSystem', 'oacMIBModules')
(module_compliance, object_group, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'ObjectGroup', 'NotificationGroup')
(bits, ip_address, gauge32, integer32, time_ticks, mib_identifier, unsigned32, counter32, counter64, iso, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'IpAddress', 'Gauge32', 'Integer32', 'TimeTicks', 'MibIdentifier', 'Unsigned32', 'Counter32', 'Counter64', 'iso', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'NotificationType')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
oac_sys_mib_module = module_identity((1, 3, 6, 1, 4, 1, 13191, 1, 100, 671))
oacSysMIBModule.setRevisions(('2014-05-05 00:01', '2011-06-15 00:00', '2010-12-14 00:01', '2010-08-11 10:00', '2010-07-08 10:00'))
if mibBuilder.loadTexts:
oacSysMIBModule.setLastUpdated('201405050001Z')
if mibBuilder.loadTexts:
oacSysMIBModule.setOrganization(' OneAccess ')
class Oasyshwcclass(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1, 2))
named_values = named_values(('board', 0), ('cpu', 1), ('slot', 2))
class Oasyshwctype(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6))
named_values = named_values(('mainboard', 0), ('microprocessor', 1), ('ram', 2), ('flash', 3), ('dsp', 4), ('uplink', 5), ('module', 6))
class Oasyscoretype(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1, 2, 3))
named_values = named_values(('controlplane', 0), ('dataforwarding', 1), ('application', 2), ('mixed', 3))
oac_exp_im_sys_statistics = mib_identifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1))
oac_exp_im_sys_hardware_description = mib_identifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2))
oac_sys_mem_statistics = mib_identifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 1))
oac_sys_cpu_statistics = mib_identifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2))
oac_sys_secure_crashlog_count = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 100), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysSecureCrashlogCount.setStatus('current')
oac_sys_start_caused = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 200), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysStartCaused.setStatus('current')
oac_sys_im_sys_main_board = mib_identifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1))
oac_exp_im_sys_hw_components = mib_identifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2))
oac_exp_im_sys_factory = mib_identifier((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 3))
oac_sys_im_sys_main_identifier = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 1), object_identifier()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysIMSysMainIdentifier.setStatus('current')
oac_sys_im_sys_main_manufactured_identity = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysIMSysMainManufacturedIdentity.setStatus('current')
oac_sys_im_sys_main_manufactured_date = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysIMSysMainManufacturedDate.setStatus('current')
oac_sys_im_sys_main_cpu = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysIMSysMainCPU.setStatus('current')
oac_sys_im_sys_main_bsp_version = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 5), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysIMSysMainBSPVersion.setStatus('current')
oac_sys_im_sys_main_boot_version = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 6), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysIMSysMainBootVersion.setStatus('current')
oac_sys_im_sys_main_boot_date_creation = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 1, 7), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysIMSysMainBootDateCreation.setStatus('current')
oac_sys_memory_free = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 1, 1), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysMemoryFree.setStatus('current')
oac_sys_memory_allocated = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 1, 2), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysMemoryAllocated.setStatus('current')
oac_sys_memory_total = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 1, 3), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysMemoryTotal.setStatus('current')
oac_sys_memory_used = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 1, 4), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysMemoryUsed.setStatus('current')
oac_sys_cpu_used = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 1), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysCpuUsed.setStatus('current')
oac_sys_cpu_used_cores_count = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 2), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysCpuUsedCoresCount.setStatus('current')
oac_sys_cpu_used_cores_table = mib_table((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3))
if mibBuilder.loadTexts:
oacSysCpuUsedCoresTable.setStatus('current')
oac_sys_cpu_used_cores_entry = mib_table_row((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3, 1)).setIndexNames((0, 'ONEACCESS-SYS-MIB', 'oacSysCpuUsedIndex'))
if mibBuilder.loadTexts:
oacSysCpuUsedCoresEntry.setStatus('current')
oac_sys_cpu_used_index = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3, 1, 1), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysCpuUsedIndex.setStatus('current')
oac_sys_cpu_used_core_type = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3, 1, 2), oa_sys_core_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysCpuUsedCoreType.setStatus('current')
oac_sys_cpu_used_value = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3, 1, 3), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysCpuUsedValue.setStatus('current')
oac_sys_cpu_used_one_minute_value = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 2, 3, 1, 4), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysCpuUsedOneMinuteValue.setStatus('current')
oac_sys_last_reboot_cause = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 1, 3), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacSysLastRebootCause.setStatus('current')
oac_exp_im_sys_hw_components_count = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 1), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysHwComponentsCount.setStatus('current')
oac_exp_im_sys_hw_components_table = mib_table((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2))
if mibBuilder.loadTexts:
oacExpIMSysHwComponentsTable.setStatus('current')
oac_exp_im_sys_hw_components_entry = mib_table_row((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1)).setIndexNames((0, 'ONEACCESS-SYS-MIB', 'oacExpIMSysHwcIndex'))
if mibBuilder.loadTexts:
oacExpIMSysHwComponentsEntry.setStatus('current')
oac_exp_im_sys_hwc_index = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 1), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysHwcIndex.setStatus('current')
oac_exp_im_sys_hwc_class = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 2), oa_sys_hwc_class()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysHwcClass.setStatus('current')
oac_exp_im_sys_hwc_type = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 3), oa_sys_hwc_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysHwcType.setStatus('current')
oac_exp_im_sys_hwc_description = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 4), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysHwcDescription.setStatus('current')
oac_exp_im_sys_hwc_serial_number = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 5), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysHwcSerialNumber.setStatus('current')
oac_exp_im_sys_hwc_manufacturer = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 6), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysHwcManufacturer.setStatus('current')
oac_exp_im_sys_hwc_manufactured_date = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 7), display_string().subtype(subtypeSpec=value_size_constraint(0, 10))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysHwcManufacturedDate.setStatus('current')
oac_exp_im_sys_hwc_product_name = mib_table_column((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 2, 2, 1, 8), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysHwcProductName.setStatus('current')
oac_exp_im_sys_factory_supplier_id = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 3, 1), display_string().subtype(subtypeSpec=value_size_constraint(0, 14))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysFactorySupplierID.setStatus('current')
oac_exp_im_sys_factory_product_sales_code = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 3, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 22))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysFactoryProductSalesCode.setStatus('current')
oac_exp_im_sys_factory_hw_revision = mib_scalar((1, 3, 6, 1, 4, 1, 13191, 10, 3, 3, 2, 3, 3), display_string().subtype(subtypeSpec=value_size_constraint(2, 7))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
oacExpIMSysFactoryHwRevision.setStatus('current')
mibBuilder.exportSymbols('ONEACCESS-SYS-MIB', oacSysCpuUsed=oacSysCpuUsed, oacSysCpuUsedValue=oacSysCpuUsedValue, OASysCoreType=OASysCoreType, oacSysCpuUsedIndex=oacSysCpuUsedIndex, oacExpIMSysHwcManufacturedDate=oacExpIMSysHwcManufacturedDate, oacSysCpuUsedOneMinuteValue=oacSysCpuUsedOneMinuteValue, oacSysIMSysMainIdentifier=oacSysIMSysMainIdentifier, oacSysCpuUsedCoresEntry=oacSysCpuUsedCoresEntry, oacSysCpuStatistics=oacSysCpuStatistics, oacExpIMSysFactorySupplierID=oacExpIMSysFactorySupplierID, OASysHwcClass=OASysHwcClass, oacSysIMSysMainCPU=oacSysIMSysMainCPU, oacExpIMSysHwcProductName=oacExpIMSysHwcProductName, oacExpIMSysStatistics=oacExpIMSysStatistics, oacSysMemoryFree=oacSysMemoryFree, oacSysMIBModule=oacSysMIBModule, oacSysMemoryAllocated=oacSysMemoryAllocated, oacSysMemStatistics=oacSysMemStatistics, oacExpIMSysHwcSerialNumber=oacExpIMSysHwcSerialNumber, oacSysMemoryUsed=oacSysMemoryUsed, oacExpIMSysHwComponentsTable=oacExpIMSysHwComponentsTable, oacSysMemoryTotal=oacSysMemoryTotal, oacSysCpuUsedCoresTable=oacSysCpuUsedCoresTable, oacExpIMSysHardwareDescription=oacExpIMSysHardwareDescription, oacSysIMSysMainManufacturedIdentity=oacSysIMSysMainManufacturedIdentity, oacSysIMSysMainBoard=oacSysIMSysMainBoard, oacSysIMSysMainBootDateCreation=oacSysIMSysMainBootDateCreation, oacExpIMSysHwcDescription=oacExpIMSysHwcDescription, oacSysIMSysMainBootVersion=oacSysIMSysMainBootVersion, oacExpIMSysHwcClass=oacExpIMSysHwcClass, PYSNMP_MODULE_ID=oacSysMIBModule, oacSysCpuUsedCoreType=oacSysCpuUsedCoreType, oacExpIMSysHwComponentsCount=oacExpIMSysHwComponentsCount, oacExpIMSysFactoryProductSalesCode=oacExpIMSysFactoryProductSalesCode, oacSysIMSysMainBSPVersion=oacSysIMSysMainBSPVersion, oacSysStartCaused=oacSysStartCaused, oacExpIMSysHwComponents=oacExpIMSysHwComponents, oacExpIMSysFactory=oacExpIMSysFactory, oacSysIMSysMainManufacturedDate=oacSysIMSysMainManufacturedDate, oacSysCpuUsedCoresCount=oacSysCpuUsedCoresCount, oacExpIMSysHwcIndex=oacExpIMSysHwcIndex, OASysHwcType=OASysHwcType, oacSysLastRebootCause=oacSysLastRebootCause, oacExpIMSysFactoryHwRevision=oacExpIMSysFactoryHwRevision, oacExpIMSysHwComponentsEntry=oacExpIMSysHwComponentsEntry, oacExpIMSysHwcType=oacExpIMSysHwcType, oacExpIMSysHwcManufacturer=oacExpIMSysHwcManufacturer, oacSysSecureCrashlogCount=oacSysSecureCrashlogCount)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class GitCommandError(Exception):
""" Exception which can be raised when git exits with a non-zero exit code.
"""
pass
class InvalidUpgradePath(Exception):
"""
Exception which is thrown if an invalid upgrade path is detected. This
is usually when attempting to upgrade to a version before the one that is
already the latest version.
"""
pass
class DuplicateGitReference(Exception):
"""
Exception which is thrown when unable to create a tag/branch/etc. as it
already exists in the repo.
"""
pass
class InvalidGitReference(Exception):
"""
Exception which is thrown when unable to find a given git reference in the
repo.
"""
pass
|
class Gitcommanderror(Exception):
""" Exception which can be raised when git exits with a non-zero exit code.
"""
pass
class Invalidupgradepath(Exception):
"""
Exception which is thrown if an invalid upgrade path is detected. This
is usually when attempting to upgrade to a version before the one that is
already the latest version.
"""
pass
class Duplicategitreference(Exception):
"""
Exception which is thrown when unable to create a tag/branch/etc. as it
already exists in the repo.
"""
pass
class Invalidgitreference(Exception):
"""
Exception which is thrown when unable to find a given git reference in the
repo.
"""
pass
|
TOKEN = b'd4r3d3v!l'
def chall():
s = Sign()
while True:
choice = input("> ").rstrip()
if choice == 'P':
print("\nN : {}".format(hex(s.n)))
print("\ne : {}".format(hex(s.e)))
elif choice == 'S':
try:
msg = bytes.fromhex(input('msg to sign : '))
if TOKEN in msg:
print('[!] NOT ALLOWED')
else:
m = bytes_to_long(msg)
print("\nsignature : {}".format(hex(s.sign(m)))) #pow(msg,d,n)
print('\n')
except:
print('\n[!] ERROR (invalid input)')
elif choice == 'V':
try:
msg = bytes.fromhex(input("msg : "))
m = bytes_to_long(msg)
signature = int(input("signature : "),16)
if m < 0 or m > s.n:
print('[!] ERROR')
if s.verify(m, signature): #pow(sign, e, n) == msg
if long_to_bytes(m) == TOKEN:
print(SECRET)
else:
print('\n[+] Valid signature')
else:
print('\n[!]Invalid signature')
except:
print('\n[!] ERROR(invalid input)')
elif choice == 'Q':
print('OK BYE :)')
exit(0)
else:
print('\n[*] SEE OPTIONS')
|
token = b'd4r3d3v!l'
def chall():
s = sign()
while True:
choice = input('> ').rstrip()
if choice == 'P':
print('\nN : {}'.format(hex(s.n)))
print('\ne : {}'.format(hex(s.e)))
elif choice == 'S':
try:
msg = bytes.fromhex(input('msg to sign : '))
if TOKEN in msg:
print('[!] NOT ALLOWED')
else:
m = bytes_to_long(msg)
print('\nsignature : {}'.format(hex(s.sign(m))))
print('\n')
except:
print('\n[!] ERROR (invalid input)')
elif choice == 'V':
try:
msg = bytes.fromhex(input('msg : '))
m = bytes_to_long(msg)
signature = int(input('signature : '), 16)
if m < 0 or m > s.n:
print('[!] ERROR')
if s.verify(m, signature):
if long_to_bytes(m) == TOKEN:
print(SECRET)
else:
print('\n[+] Valid signature')
else:
print('\n[!]Invalid signature')
except:
print('\n[!] ERROR(invalid input)')
elif choice == 'Q':
print('OK BYE :)')
exit(0)
else:
print('\n[*] SEE OPTIONS')
|
# Python Class 2406
# Lesson 12 Problem 1
# Author: snowapple (471208)
class Game:
def __init__(self, n):
'''__init__(n) -> Game
creates an instance of the Game class'''
if n% 2 == 0: #n has to be odd
print('Please enter an odd n!')
raise ValueError
self.n = n #size of side of board
self.board = [[0 for x in range(self.n)] for x in range(self.n)] #holds current state of the board, list of columns
self.is_won = 0#is_won is 0 if game is not won, and 1 or 2 if won by player 1 or 2 respectively
def __str__(self):
'''__str__() -> str
returns a str representation of the current state of the board'''
ans = ""
print_dict = {0:'. ', 1:'X ', 2:'O '} #On the board, these numbers represent the pieces
for i in range(self.n):#row
row = ""
for j in range(self.n):#column
row += print_dict[self.board[j][i]] #prints the board piece to where the player puts it
ans = row + "\n" + ans
title = ""
for i in range(self.n):
title += str(i) + " "
ans = '\n' + title + '\n' +ans
return ans
def clear_board(self):
'''clear_board() -> none
clears the board by setting all entries to 0'''
self.is_won = 0
self.board = [[0 for x in range(self.n)] for x in range(self.n)]
def put(self,player_num,column):#takes care of errors
'''put(player_num,column) -> boolean
puts a piece of type player_num in the specified column,
returns boolean which is true if the put was successful, otherwise false'''
if self.is_won != 0: #if the game has been won
print('Please start a new game as player ' + str(self.is_won) + ' has already won!')
return False
if player_num not in [1,2]: #if a valid player number is not entered
print('Please enter 1 or 2 for the player number!')
return False
if column < 0 or column >= self.n: #if a valid column is not entered
print('Please enter a valid column!')
return False
try:
row = self.board[column].index(0)
self.board[column][row]= player_num
self.is_won = self.win_index(column,row)
return True
except ValueError:
print('Column is full!')
return False
def win_index(self,column_index,row_index):
'''win_index(column_index,row_index) -> int
checks if piece at (column_index, row_index) is part of a connect 4
returns player_num if the piece is part of a connect4, and 0 otherwise'''
#uses axis_check to check all of the axes
player_num = self.board[column_index][row_index]
#check up/down axis
col = self.board[column_index]
col_win = self.axis_check(col,row_index,player_num) #checks the row since it goes up/down
if col_win != 0: #checks to see if won
return col_win
#check left/right axis
row = [self.board[i][row_index] for i in range(self.n)]
row_win = self.axis_check(row,column_index,player_num) #checks column since it goes left/right
if row_win != 0: #checks to see if won
return row_win
#down-left/up-right diagonal axis
axis = [player_num]
index = 0
#down-left part
curr_col_index = column_index - 1 #goes left so subtract one
curr_row_index = row_index - 1 #goes down so subtract one
while curr_row_index >= 0 and curr_col_index >= 0: #until you go to the most down-left part of the board
axis = [self.board[curr_col_index][curr_row_index]] + axis
curr_col_index -= 1
curr_row_index -= 1
index += 1
#up-right part
curr_col_index = column_index + 1 #goes right so add one
curr_row_index = row_index + 1 #goes up so add one
while curr_row_index < self.n and curr_col_index < self.n: #until you go to the most up-right part of the board
axis = axis +[self.board[curr_col_index][curr_row_index]]
curr_col_index += 1
curr_row_index += 1
diag_win = self.axis_check(axis,index,player_num)
if diag_win != 0: #checks to see if won
return diag_win
#up-left/down-right diagonal axis
axis = [player_num]
index = 0
#up-left part
curr_col_index = column_index - 1 #goes left so minus one
curr_row_index = row_index + 1 #goes up so plus one
while curr_row_index < self.n and curr_col_index >= 0: #until you go to the most up-left part of the board
axis = [self.board[curr_col_index][curr_row_index]] + axis
curr_col_index -= 1
curr_row_index += 1
index += 1
#down-right part
curr_col_index = column_index + 1 #goes right so plus one
curr_row_index = row_index - 1 # goes down so minus one
while curr_row_index >= 0 and curr_col_index < self.n: #until you go to the most down-right part of the board
axis = axis +[self.board[curr_col_index][curr_row_index]]
curr_col_index += 1
curr_row_index -= 1
diag_win = self.axis_check(axis,index,player_num)
if diag_win != 0: #checks to see if won
return diag_win
return 0
def axis_check(self,axis, index, player_num):
'''axis_check(axis, index, player_num) -> int
checks if index in axis (list) is part of a connect4
returns player_num if the index is indeed part of a connect4 and 0 otherwise'''
#takes the index and sees if the piece is part of a connect four and generalizes it for the four axes(up/down, left/right, two diagonals)
down = index
up = index
for i in range(index,-1, -1):
if axis[i] == player_num:
down = i
else:
break
for i in range(index,len(axis)):
if axis[i] == player_num:
up = i
else:
break
if up - down + 1 >= 4:
# print('Player ' + str(player_num) + ' has won the game!')
return player_num
return 0
game = Game(7)
labels = {1:'X', 2:'O'}
play = True
while play:
#setting up the board and players
game.clear_board()
name1 = input('Player ' + labels[1] + ' , enter your name: ')
name2 = input('Player ' + labels[2] + ' , enter your name: ')
names = {1:name1, 2:name2}
print(game)
turn = 1
while game.is_won == 0:
success = False
while not success:
#until someone wins each player takes turns
col_choice = int(input(names[turn] + ", you're " + labels[turn] + ". What column do you want to play in? "))
success = game.put(turn,col_choice)
print(game)
turn = turn % 2 +1 #to take turns between players
print("Congratulations, " + names[game.is_won]+", you won!")
#if players want to play again
play_another = ""
while play_another not in ['y','n']:
play_another = input("Do you want to play another game? [Enter 'y' for yes, 'n' for no]: ")
if play_another == 'n':
play = False
|
class Game:
def __init__(self, n):
"""__init__(n) -> Game
creates an instance of the Game class"""
if n % 2 == 0:
print('Please enter an odd n!')
raise ValueError
self.n = n
self.board = [[0 for x in range(self.n)] for x in range(self.n)]
self.is_won = 0
def __str__(self):
"""__str__() -> str
returns a str representation of the current state of the board"""
ans = ''
print_dict = {0: '. ', 1: 'X ', 2: 'O '}
for i in range(self.n):
row = ''
for j in range(self.n):
row += print_dict[self.board[j][i]]
ans = row + '\n' + ans
title = ''
for i in range(self.n):
title += str(i) + ' '
ans = '\n' + title + '\n' + ans
return ans
def clear_board(self):
"""clear_board() -> none
clears the board by setting all entries to 0"""
self.is_won = 0
self.board = [[0 for x in range(self.n)] for x in range(self.n)]
def put(self, player_num, column):
"""put(player_num,column) -> boolean
puts a piece of type player_num in the specified column,
returns boolean which is true if the put was successful, otherwise false"""
if self.is_won != 0:
print('Please start a new game as player ' + str(self.is_won) + ' has already won!')
return False
if player_num not in [1, 2]:
print('Please enter 1 or 2 for the player number!')
return False
if column < 0 or column >= self.n:
print('Please enter a valid column!')
return False
try:
row = self.board[column].index(0)
self.board[column][row] = player_num
self.is_won = self.win_index(column, row)
return True
except ValueError:
print('Column is full!')
return False
def win_index(self, column_index, row_index):
"""win_index(column_index,row_index) -> int
checks if piece at (column_index, row_index) is part of a connect 4
returns player_num if the piece is part of a connect4, and 0 otherwise"""
player_num = self.board[column_index][row_index]
col = self.board[column_index]
col_win = self.axis_check(col, row_index, player_num)
if col_win != 0:
return col_win
row = [self.board[i][row_index] for i in range(self.n)]
row_win = self.axis_check(row, column_index, player_num)
if row_win != 0:
return row_win
axis = [player_num]
index = 0
curr_col_index = column_index - 1
curr_row_index = row_index - 1
while curr_row_index >= 0 and curr_col_index >= 0:
axis = [self.board[curr_col_index][curr_row_index]] + axis
curr_col_index -= 1
curr_row_index -= 1
index += 1
curr_col_index = column_index + 1
curr_row_index = row_index + 1
while curr_row_index < self.n and curr_col_index < self.n:
axis = axis + [self.board[curr_col_index][curr_row_index]]
curr_col_index += 1
curr_row_index += 1
diag_win = self.axis_check(axis, index, player_num)
if diag_win != 0:
return diag_win
axis = [player_num]
index = 0
curr_col_index = column_index - 1
curr_row_index = row_index + 1
while curr_row_index < self.n and curr_col_index >= 0:
axis = [self.board[curr_col_index][curr_row_index]] + axis
curr_col_index -= 1
curr_row_index += 1
index += 1
curr_col_index = column_index + 1
curr_row_index = row_index - 1
while curr_row_index >= 0 and curr_col_index < self.n:
axis = axis + [self.board[curr_col_index][curr_row_index]]
curr_col_index += 1
curr_row_index -= 1
diag_win = self.axis_check(axis, index, player_num)
if diag_win != 0:
return diag_win
return 0
def axis_check(self, axis, index, player_num):
"""axis_check(axis, index, player_num) -> int
checks if index in axis (list) is part of a connect4
returns player_num if the index is indeed part of a connect4 and 0 otherwise"""
down = index
up = index
for i in range(index, -1, -1):
if axis[i] == player_num:
down = i
else:
break
for i in range(index, len(axis)):
if axis[i] == player_num:
up = i
else:
break
if up - down + 1 >= 4:
return player_num
return 0
game = game(7)
labels = {1: 'X', 2: 'O'}
play = True
while play:
game.clear_board()
name1 = input('Player ' + labels[1] + ' , enter your name: ')
name2 = input('Player ' + labels[2] + ' , enter your name: ')
names = {1: name1, 2: name2}
print(game)
turn = 1
while game.is_won == 0:
success = False
while not success:
col_choice = int(input(names[turn] + ", you're " + labels[turn] + '. What column do you want to play in? '))
success = game.put(turn, col_choice)
print(game)
turn = turn % 2 + 1
print('Congratulations, ' + names[game.is_won] + ', you won!')
play_another = ''
while play_another not in ['y', 'n']:
play_another = input("Do you want to play another game? [Enter 'y' for yes, 'n' for no]: ")
if play_another == 'n':
play = False
|
""" Challenge - Program Flow
# TODO: Create a program that takes an IP address entered at the keyboard and prints out the number of segments it contains, and the length of each segment.
An IP address consists of 4 numbers, separated from each other with a full stop.
But your program should just count however many are entered. Examples of the input
you may get are:
127.0.0.1
.192.168.0.1
10.0.123456.255
172.16
255
So your program should work even with invalid IP Addresses. We're just interested
in the number of segments and how long each one is.
Once you have a working program, here are some more suggestions for invalid input
to test:
.123.45.678.91
123.4567.8.9.
123.156.289.10123456
10.10t.10.10
12.9.34.6.12.90
'' - that is, press enter without typing anything
# *! This challenge is intended to practise for loops and if/else statements, so although you could use other techniques (such as splitting the string up), that's not the approach we're looking for here.
"""
print("An IP address consists of 4 numbers, separated from each other with a full stop.\n")
ip = input("Enter IP address: ")
if ip[-1] != ".":
ip += "."
segment = 1
segment_lenght = 0
character = ""
for character in ip:
if character == ".":
print("Segment {} contains {} characters".format(segment, segment_lenght))
segment += 1
segment_lenght = 0
else:
segment_lenght += 1
|
""" Challenge - Program Flow
# TODO: Create a program that takes an IP address entered at the keyboard and prints out the number of segments it contains, and the length of each segment.
An IP address consists of 4 numbers, separated from each other with a full stop.
But your program should just count however many are entered. Examples of the input
you may get are:
127.0.0.1
.192.168.0.1
10.0.123456.255
172.16
255
So your program should work even with invalid IP Addresses. We're just interested
in the number of segments and how long each one is.
Once you have a working program, here are some more suggestions for invalid input
to test:
.123.45.678.91
123.4567.8.9.
123.156.289.10123456
10.10t.10.10
12.9.34.6.12.90
'' - that is, press enter without typing anything
# *! This challenge is intended to practise for loops and if/else statements, so although you could use other techniques (such as splitting the string up), that's not the approach we're looking for here.
"""
print('An IP address consists of 4 numbers, separated from each other with a full stop.\n')
ip = input('Enter IP address: ')
if ip[-1] != '.':
ip += '.'
segment = 1
segment_lenght = 0
character = ''
for character in ip:
if character == '.':
print('Segment {} contains {} characters'.format(segment, segment_lenght))
segment += 1
segment_lenght = 0
else:
segment_lenght += 1
|
def BFS(graph,root,p1,max1):
checked = []
visited=[]
energy=[]
level=[]
l=[]
l.append(root)
level.append(l)
checked.append(root)
inienergy=14600
threshold=10
l1=0
flag=0
energy.append(inienergy)
while(len(checked)>0):
l1=l1+1
#print "level"+str(l1)
v=checked.pop(0)
e1=energy.pop(0)
while v in visited:
#print "ll"
if(len(checked)>0):
v=checked.pop(0)
if len(checked)==0:
flag=1
break
if(flag==1):
break
# print "kk"
visited.append(v)
l=[]
#print str(v)+"-->"
if(float(e1)/float(len(graph[v])) >= float(threshold)):
for edge in graph[v]:
#print edge
if edge not in checked:
checked.append(edge)
energy.append(float(e1*A[v][edge]/(len(graph[v])*max1)))
str1="v"+str(v)+","+"v"+str(edge)+","+"false"+","+str(A[v][edge])+","+"true\n"
fil_out.write(str1)
for edge in level[(len(level)-1)]:
l=list(set(graph[edge])|set(l))
#print "l "+str(l)
for i in range(len(level)):
for j in level[i]:
if j in l:
l.remove(j)
if len(l)>0:
level.append(l)
f = open('dsfull1.gdf')
text=f.read()
p1=text.split('\n')
V=[]
flag=0
for each_line in p1:
l=each_line.split(',')
if len(l)==2:
if flag!=0:
#print(l[0])
V.append(int(l[0][1:]))
flag=1
else:
break
A = [[0 for x in range(len(V))] for x in range(len(V))]
flag=0
max1=-1
for each_line in p1:
l=each_line.split(',')
if len(l)==5:
if flag!=0:
#print(l[0],l[1],l[3])
A[int(l[0][1:])][int(l[1][1:])]=float(l[3])
#if(float(l[3]>max)):
# max1=float(l[3])
flag=1
else:
continue
#print max1
graph = [[] for x in range(len(V))]
flag=0
i=0
x=0
for each_line in p1:
l=each_line.split(',')
if len(l)==5:
if flag!=0:
#print(l[0],l[1],l[3])
#A[int(l[0][1:])][int(l[1][1:])]=float(l[3])
graph[int(l[0][1:])].append(int(l[1][1:]))
flag=1
else:
continue
root=154
#print(len(graph[root]))
fil_out=open("sub5.gdf",'w')
fil_out1=open("ds2.txt","w")
fil_out.write("nodedef> name,label\n")
for i in range(0,len(V)):
fil_out.write(p1[i+1]+'\n')
fil_out.write("edgedef>node1,node2,directed,weight,labelvisible\n")
h=p1[root+1].split(',')
fil_out1.write(str(h[1])+",")
BFS(graph,root,p1,max1)
fil_out.close()
f.close()
|
def bfs(graph, root, p1, max1):
checked = []
visited = []
energy = []
level = []
l = []
l.append(root)
level.append(l)
checked.append(root)
inienergy = 14600
threshold = 10
l1 = 0
flag = 0
energy.append(inienergy)
while len(checked) > 0:
l1 = l1 + 1
v = checked.pop(0)
e1 = energy.pop(0)
while v in visited:
if len(checked) > 0:
v = checked.pop(0)
if len(checked) == 0:
flag = 1
break
if flag == 1:
break
visited.append(v)
l = []
if float(e1) / float(len(graph[v])) >= float(threshold):
for edge in graph[v]:
if edge not in checked:
checked.append(edge)
energy.append(float(e1 * A[v][edge] / (len(graph[v]) * max1)))
str1 = 'v' + str(v) + ',' + 'v' + str(edge) + ',' + 'false' + ',' + str(A[v][edge]) + ',' + 'true\n'
fil_out.write(str1)
for edge in level[len(level) - 1]:
l = list(set(graph[edge]) | set(l))
for i in range(len(level)):
for j in level[i]:
if j in l:
l.remove(j)
if len(l) > 0:
level.append(l)
f = open('dsfull1.gdf')
text = f.read()
p1 = text.split('\n')
v = []
flag = 0
for each_line in p1:
l = each_line.split(',')
if len(l) == 2:
if flag != 0:
V.append(int(l[0][1:]))
flag = 1
else:
break
a = [[0 for x in range(len(V))] for x in range(len(V))]
flag = 0
max1 = -1
for each_line in p1:
l = each_line.split(',')
if len(l) == 5:
if flag != 0:
A[int(l[0][1:])][int(l[1][1:])] = float(l[3])
flag = 1
else:
continue
graph = [[] for x in range(len(V))]
flag = 0
i = 0
x = 0
for each_line in p1:
l = each_line.split(',')
if len(l) == 5:
if flag != 0:
graph[int(l[0][1:])].append(int(l[1][1:]))
flag = 1
else:
continue
root = 154
fil_out = open('sub5.gdf', 'w')
fil_out1 = open('ds2.txt', 'w')
fil_out.write('nodedef> name,label\n')
for i in range(0, len(V)):
fil_out.write(p1[i + 1] + '\n')
fil_out.write('edgedef>node1,node2,directed,weight,labelvisible\n')
h = p1[root + 1].split(',')
fil_out1.write(str(h[1]) + ',')
bfs(graph, root, p1, max1)
fil_out.close()
f.close()
|
s="this this is a a cat cat cat ram ram jai it"
l=[]
count=[]
i=0
#j=0
str=""
for i in s:
#print(i,end="")
if i==" ":
if str in l:
for j in range(len(l)):
if str == l[j]:
count[j] += 1
str=""
continue
else:
l.append(str)
count.append(1)
str=""
continue
str=str+i
print(l)
print(count)
|
s = 'this this is a a cat cat cat ram ram jai it'
l = []
count = []
i = 0
str = ''
for i in s:
if i == ' ':
if str in l:
for j in range(len(l)):
if str == l[j]:
count[j] += 1
str = ''
continue
else:
l.append(str)
count.append(1)
str = ''
continue
str = str + i
print(l)
print(count)
|
class LRUCache:
def __init__(self, capacity: int):
self.db = dict()
self.capacity = capacity
self.time = 0
def get(self, key: int) -> int:
if key in self.db:
self.db[key][1] = self.time
self.time += 1
return self.db[key][0]
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.db:
self.db[key] = [value, self.time]
else:
if len(self.db.keys()) < self.capacity:
self.db[key] = [value, self.time]
else:
# evict LRU
evict_key = sorted(self.db.items(), key=lambda x: x[1][1])[0][0]
del self.db[evict_key]
self.db[key] = [value, self.time]
self.time += 1
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
|
class Lrucache:
def __init__(self, capacity: int):
self.db = dict()
self.capacity = capacity
self.time = 0
def get(self, key: int) -> int:
if key in self.db:
self.db[key][1] = self.time
self.time += 1
return self.db[key][0]
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.db:
self.db[key] = [value, self.time]
elif len(self.db.keys()) < self.capacity:
self.db[key] = [value, self.time]
else:
evict_key = sorted(self.db.items(), key=lambda x: x[1][1])[0][0]
del self.db[evict_key]
self.db[key] = [value, self.time]
self.time += 1
|
# 2021.04.14
# Problem Statement:
# https://leetcode.com/problems/majority-element/
class Solution:
def majorityElement(self, nums: List[int]) -> int:
# trivial question, no need to explain
if len(nums) == 1: return nums[0]
dict = {}
for element in nums:
if element not in dict.keys():
dict[element] = 1
else:
dict[element] = dict[element] + 1
if dict[element] >= (len(nums)//2 + 1):
return element
|
class Solution:
def majority_element(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
dict = {}
for element in nums:
if element not in dict.keys():
dict[element] = 1
else:
dict[element] = dict[element] + 1
if dict[element] >= len(nums) // 2 + 1:
return element
|
def ParseGraphVertexEdge(file):
with open(file, 'r') as fw:
read_data = fw.read()
res = read_data.splitlines(False)
def ParseV(v_str):
'''
@type v_str: string
:param v_str:
:return:
'''
return [int(i) for i in v_str.split()]
v = int(res[0])
edges = [ParseV(vstr) for vstr in res[1:]]
return v, edges
if __name__ == '__main__':
v, edges = ParseGraphVertexEdge('graph.in')
print(v, edges)
|
def parse_graph_vertex_edge(file):
with open(file, 'r') as fw:
read_data = fw.read()
res = read_data.splitlines(False)
def parse_v(v_str):
"""
@type v_str: string
:param v_str:
:return:
"""
return [int(i) for i in v_str.split()]
v = int(res[0])
edges = [parse_v(vstr) for vstr in res[1:]]
return (v, edges)
if __name__ == '__main__':
(v, edges) = parse_graph_vertex_edge('graph.in')
print(v, edges)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 3 13:54:22 2018
@author: David
"""
mainmenu = ["1:Add a new item ", "2:Move an item", "3:search an item",
"4:view the inventory of a warehouse", "0: exit the system"]
def menu():
# display a main menu
for i in mainmenu:
print(i)
# get the choice from the keyboard
c = input("please choose a number or press any other key to return:")
if c == '1':
addNewItem()
elif c == '2':
moveItem()
elif c == '3':
searchItem()
elif c == '4':
viewInventory()
elif c == '0':
exit(0)
else:
menu()
def viewInventory():
c = input("choose the warehouse that you want ro view or press any other key to go back to main menu")
if c == 'A':
print(WarehouseA)
elif c == 'B':
print(WarehouseB)
elif c == 'C':
print(WarehouseC)
elif c == 'D':
print(WarehouseD)
else:
menu()
|
"""
Created on Sat Nov 3 13:54:22 2018
@author: David
"""
mainmenu = ['1:Add a new item ', '2:Move an item', '3:search an item', '4:view the inventory of a warehouse', '0: exit the system']
def menu():
for i in mainmenu:
print(i)
c = input('please choose a number or press any other key to return:')
if c == '1':
add_new_item()
elif c == '2':
move_item()
elif c == '3':
search_item()
elif c == '4':
view_inventory()
elif c == '0':
exit(0)
else:
menu()
def view_inventory():
c = input('choose the warehouse that you want ro view or press any other key to go back to main menu')
if c == 'A':
print(WarehouseA)
elif c == 'B':
print(WarehouseB)
elif c == 'C':
print(WarehouseC)
elif c == 'D':
print(WarehouseD)
else:
menu()
|
"""Tools to manage census tables."""
POSTGRES_COLUMN_NAME_LIMIT = 63
def _verified_column_name(column_name, limit=POSTGRES_COLUMN_NAME_LIMIT):
if len(column_name) > limit:
raise Exception('Column name {} is too long. Postgres limit is {}.'.format(
column_name, limit))
return column_name
def readable_columns_from_census_mapping(census_mapping):
census_columns = [
'{key} AS {unique_column_name}'.format(
key=group,
unique_column_name=_verified_column_name(
census_mapping[category][group]['joined_column_name']
)
) for category in census_mapping
for group in census_mapping[category]
]
return census_columns
|
"""Tools to manage census tables."""
postgres_column_name_limit = 63
def _verified_column_name(column_name, limit=POSTGRES_COLUMN_NAME_LIMIT):
if len(column_name) > limit:
raise exception('Column name {} is too long. Postgres limit is {}.'.format(column_name, limit))
return column_name
def readable_columns_from_census_mapping(census_mapping):
census_columns = ['{key} AS {unique_column_name}'.format(key=group, unique_column_name=_verified_column_name(census_mapping[category][group]['joined_column_name'])) for category in census_mapping for group in census_mapping[category]]
return census_columns
|
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
n = len(nums1)
m = len(nums2)
if (n > m):
return self.findMedianSortedArrays(nums2, nums1)
start = 0
end = n
realmidinmergedarray = (n + m + 1) // 2
while (start <= end):
mid = (start + end) // 2
leftAsize = mid
leftBsize = realmidinmergedarray - mid
leftA = nums1[leftAsize - 1] if (leftAsize > 0) else float('-inf')
leftB = nums2[leftAsize - 1] if (leftBsize > 0) else float('-inf')
rightA = nums1[leftAsize] if (leftAsize < n) else float('inf')
rightB = nums2[leftAsize] if (leftBsize < m) else float('inf')
if leftA <= rightB and leftB <= rightA:
if ((m + n) % 2 == 0):
return (max(leftA, leftB) + min(rightA, rightB)) / 2.0
return max(leftA, leftB)
elif (leftA > rightB):
end = mid - 1
else:
start = mid + 1
# Driver code
ans = Solution()
arr1 = [-5, 3, 6, 12, 15]
arr2 = [-12, -10, -6, -3, 4, 10]
print("Median of the two arrays is {}".format(ans.Median(arr1, arr2)))
|
class Solution:
def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
n = len(nums1)
m = len(nums2)
if n > m:
return self.findMedianSortedArrays(nums2, nums1)
start = 0
end = n
realmidinmergedarray = (n + m + 1) // 2
while start <= end:
mid = (start + end) // 2
left_asize = mid
left_bsize = realmidinmergedarray - mid
left_a = nums1[leftAsize - 1] if leftAsize > 0 else float('-inf')
left_b = nums2[leftAsize - 1] if leftBsize > 0 else float('-inf')
right_a = nums1[leftAsize] if leftAsize < n else float('inf')
right_b = nums2[leftAsize] if leftBsize < m else float('inf')
if leftA <= rightB and leftB <= rightA:
if (m + n) % 2 == 0:
return (max(leftA, leftB) + min(rightA, rightB)) / 2.0
return max(leftA, leftB)
elif leftA > rightB:
end = mid - 1
else:
start = mid + 1
ans = solution()
arr1 = [-5, 3, 6, 12, 15]
arr2 = [-12, -10, -6, -3, 4, 10]
print('Median of the two arrays is {}'.format(ans.Median(arr1, arr2)))
|
data_rows = [2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, 25, 27]
data_rows_cool = [2, 3, 4, 6, 7, 8, 10, 12, 14]
hig_temp_techs = [2, 7, 8, 13, 14, 16, 18, 20, 22]
med_temp_techs = [3, 4, 5, 9, 10, 11]
low_temp_techs = [24, 25]
no_imput_rows_color = [232, 232, 232]
|
data_rows = [2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, 25, 27]
data_rows_cool = [2, 3, 4, 6, 7, 8, 10, 12, 14]
hig_temp_techs = [2, 7, 8, 13, 14, 16, 18, 20, 22]
med_temp_techs = [3, 4, 5, 9, 10, 11]
low_temp_techs = [24, 25]
no_imput_rows_color = [232, 232, 232]
|
def letter_counter(token, word):
count = 0
for letter in word:
if letter == token:
count = count + 1
else:
continue
return count
|
def letter_counter(token, word):
count = 0
for letter in word:
if letter == token:
count = count + 1
else:
continue
return count
|
class ExceptionBase(Exception):
"""Base exception."""
message: str
def __init__(self, message: str) -> None:
super().__init__(message)
self.message = message
class InvalidPduState(ExceptionBase):
"""Thrown during PDU self-validation."""
def __init__(self, message: str, pdu) -> None:
super().__init__(message=message)
self.pdu = pdu
class InvalidFrame(ExceptionBase):
"""Thrown during framing when a message cannot be extracted from a frame buffer."""
frame: bytes
def __init__(self, message: str, frame: bytes) -> None:
super().__init__(message=message)
self.frame = frame
|
class Exceptionbase(Exception):
"""Base exception."""
message: str
def __init__(self, message: str) -> None:
super().__init__(message)
self.message = message
class Invalidpdustate(ExceptionBase):
"""Thrown during PDU self-validation."""
def __init__(self, message: str, pdu) -> None:
super().__init__(message=message)
self.pdu = pdu
class Invalidframe(ExceptionBase):
"""Thrown during framing when a message cannot be extracted from a frame buffer."""
frame: bytes
def __init__(self, message: str, frame: bytes) -> None:
super().__init__(message=message)
self.frame = frame
|
@React.command()
async def redirect(ctx, *, url):
await ctx.message.delete()
try:
embed = discord.Embed(color=int(json.load(open(f'./Themes/{json.load(open("config.json"))["theme"]}.json'))['embed_color'].replace('#', '0x'), 0), title='Redirect Checker')
embed.set_thumbnail(url=json.load(open(f'./Themes/{json.load(open("config.json"))["theme"]}.json'))['embed_thumbnail_url'])
embed.set_footer(text=json.load(open(f'./Themes/{json.load(open("config.json"))["theme"]}.json'))['embed_footer'], icon_url=json.load(open(f'./Themes/{json.load(open("config.json"))["theme"]}.json'))['embed_footer_url'])
result = json.loads(requests.get(f"https://api.redirect-checker.net/?url={url}&timeout=5&maxhops=10&meta-refresh=1&format=json").text)
for i in range(len(result['data'])):
embed.add_field(name=f"__Redirect #{i + 1}__", value=f"{result['data'][i]['request']['info']['url']}", inline=False)
await ctx.send(embed=embed, delete_after=json.load(open('config.json'))['delete_timeout'])
except Exception as e:
await ctx.send(f"Error: {e}")
|
@React.command()
async def redirect(ctx, *, url):
await ctx.message.delete()
try:
embed = discord.Embed(color=int(json.load(open(f"./Themes/{json.load(open('config.json'))['theme']}.json"))['embed_color'].replace('#', '0x'), 0), title='Redirect Checker')
embed.set_thumbnail(url=json.load(open(f"./Themes/{json.load(open('config.json'))['theme']}.json"))['embed_thumbnail_url'])
embed.set_footer(text=json.load(open(f"./Themes/{json.load(open('config.json'))['theme']}.json"))['embed_footer'], icon_url=json.load(open(f"./Themes/{json.load(open('config.json'))['theme']}.json"))['embed_footer_url'])
result = json.loads(requests.get(f'https://api.redirect-checker.net/?url={url}&timeout=5&maxhops=10&meta-refresh=1&format=json').text)
for i in range(len(result['data'])):
embed.add_field(name=f'__Redirect #{i + 1}__', value=f"{result['data'][i]['request']['info']['url']}", inline=False)
await ctx.send(embed=embed, delete_after=json.load(open('config.json'))['delete_timeout'])
except Exception as e:
await ctx.send(f'Error: {e}')
|
arq_entrada = open("FORMAT.FLC", 'r')
conjunto_entradas = \
{'SISTEMA FUZZY': '',
'CONJUNTO FUZZY': '',
'GRANULARIDADE': 3,
'OPERADOR COMPOSICAO': '',
'OPERADOR AGREGACAO': '',
'INFERENCIA': '',
'REGRA': False,
'DEFAULT': ''}
for linha in arq_entrada.readlines():
#print(linha)
variavel = linha.split(':')[0]
valor = linha.split(':')[1].split('#')[0]
conjunto_entradas[variavel] = valor
print(conjunto_entradas)
|
arq_entrada = open('FORMAT.FLC', 'r')
conjunto_entradas = {'SISTEMA FUZZY': '', 'CONJUNTO FUZZY': '', 'GRANULARIDADE': 3, 'OPERADOR COMPOSICAO': '', 'OPERADOR AGREGACAO': '', 'INFERENCIA': '', 'REGRA': False, 'DEFAULT': ''}
for linha in arq_entrada.readlines():
variavel = linha.split(':')[0]
valor = linha.split(':')[1].split('#')[0]
conjunto_entradas[variavel] = valor
print(conjunto_entradas)
|
num = 1
num = 2
num = 3
num = 4
num = 5
|
num = 1
num = 2
num = 3
num = 4
num = 5
|
# The MIT License (MIT)
#
# Copyright (c) 2016 Adam Schubert
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
class MissingFieldException(Exception):
"""
Exception for cases when something is missing
"""
def __init__(self, message):
"""Initialize MissingFieldException
Args:
message: Message of exception
"""
super(MissingFieldException, self).__init__(
"Field '{}' not found.".format(message))
class FormatException(Exception):
"""
Exception for cases when something has wrong format
"""
pass
class WrongArgumentException(Exception):
"""
Exception for cases when wrong argument is passed
"""
pass
|
class Missingfieldexception(Exception):
"""
Exception for cases when something is missing
"""
def __init__(self, message):
"""Initialize MissingFieldException
Args:
message: Message of exception
"""
super(MissingFieldException, self).__init__("Field '{}' not found.".format(message))
class Formatexception(Exception):
"""
Exception for cases when something has wrong format
"""
pass
class Wrongargumentexception(Exception):
"""
Exception for cases when wrong argument is passed
"""
pass
|
class Parser:
def __init__(self, file_path):
self.dottedproductions = {'S\'': [['.', 'S']]}
file_program = self.read_program(file_path)
self.terminals = file_program[0]
self.nonTerminals = file_program[1]
self.productions = {}
self.transactions = file_program[2:]
for elements in self.transactions:
if elements[0] in self.productions:
self.productions[elements[0]].append(elements[1:])
else:
self.productions[elements[0]] = [elements[1:]]
self.data = [self.terminals, self.nonTerminals, self.productions]
dotted = self.dotMaker()
self.initial_closure = {"S'": [dotted["S'"][0]]}
self.closure(self.initial_closure, dotted, dotted["S'"][0])
def dotMaker(self):
self.dottedproductions = {'S\'': [['.', 'S']]}
for nonTerminal in self.productions:
self.dottedproductions[nonTerminal] = []
for way in self.productions[nonTerminal]:
self.dottedproductions[nonTerminal].append(["."] + way)
return self.dottedproductions
def closure(self, closure_map, transitions_map, transition_value):
dot_index = transition_value.index(".")
if dot_index + 1 == len(transition_value):
return
after_dot = transition_value[dot_index + 1]
if after_dot in self.nonTerminals:
non_terminal = after_dot
if non_terminal not in closure_map:
closure_map[non_terminal] = transitions_map[non_terminal]
else:
closure_map[non_terminal] += transitions_map[non_terminal]
for transition in transitions_map[non_terminal]:
self.closure(closure_map, transitions_map, transition)
@staticmethod
def shiftable(transition):
dot_index = transition.index(".")
if len(transition) > dot_index + 1:
return True
return False
@staticmethod
def shift_dot(transition):
transition = transition[:]
dot_index = transition.index(".")
if not Parser.shiftable(transition):
raise Exception("Should I shift it back ?")
if len(transition) > dot_index + 2:
remainder = transition[dot_index + 2:]
else:
remainder = []
transition = transition[:dot_index] + [transition[dot_index + 1]] + ["."] + remainder
return transition
def canonical_collection(self):
self.idk = {}
self.queue = [{
"state": self.initial_closure,
"initial_dotted": self.dottedproductions,
}]
self.states = []
self.state_parents = {}
while len(self.queue) > 0:
self.goto_all(**self.queue.pop(0))
reduced = self.get_reduced()
for k in reduced:
red_k = list(reduced[k].keys())
if red_k[0] != "S'":
trans = red_k + reduced[k][red_k[0]][0][:-1]
reduce_index = self.transactions.index(trans) + 1
self.idk[k] = {terminal: f"r{reduce_index}" for terminal in self.terminals}
self.idk[k]["$"] = f"r{reduce_index}"
else:
self.idk[k] = {"$": "accept"}
del self.state_parents[0]
for key in self.state_parents:
parent = self.state_parents[key]
if parent["parent_index"] in self.idk:
self.idk[parent["parent_index"]][parent["before_dot"]] = key
else:
self.idk[parent["parent_index"]] = {parent["before_dot"]: key}
table = {f"I{index}": self.idk[index] for index in range(len(self.states))}
self.print_dict(table, "Table:")
def goto_all(self, state, initial_dotted, parent=-1, parent_key="-1"):
if state not in self.states:
self.states.append(state)
index = len(self.states) - 1
self.state_parents[index] = {
"parent_index": parent,
"before_dot": parent_key
}
{}.items()
self.print_dict(state, f"state {index}")
for key in state:
for transition in state[key]:
if self.shiftable(transition):
self.goto_one(initial_dotted, key, transition, index)
else:
if parent in self.idk:
self.idk[parent][parent_key] = self.states.index(state)
else:
self.idk[parent] = {parent_key: self.states.index(state)}
def goto_one(self, initial_dotted, key, state, parent=-1):
shifted_transition = self.shift_dot(state)
closure_map = {key: [shifted_transition]}
self.closure(closure_map, initial_dotted, shifted_transition)
self.queue.append({
"state": closure_map,
"initial_dotted": initial_dotted,
"parent": parent,
"parent_key": shifted_transition[shifted_transition.index(".") - 1]
})
def get_reduced(self):
self.reduced = {}
for state in self.states:
state_key = list(state.keys())[0]
if len(state) == 1 and len(state[state_key]) and len(state[state_key][0]) \
and state[state_key][0][-1] == ".":
self.reduced[self.states.index(state)] = state
return self.reduced
@staticmethod
def read_program(file_path):
file1 = open(file_path, 'r')
lines = file1.readlines()
file1.close()
return [line.replace("\n", "").replace("\t", "").split(" ") for line in lines]
@staticmethod
def print_dict(hashmap, message=None, deepness=""):
if message is not None:
print(deepness + message)
for key in hashmap:
print(f"{deepness}{key} : {hashmap[key]}")
def print_data(self, index=-1):
if index == -1:
exit()
else:
print(self.data[index - 1])
def print_production(self, non_terminal):
data = self.data[2]
if non_terminal in data:
for row in data[non_terminal]:
print(f"{non_terminal} -> {row}")
else:
print("Wrong non terminal!")
|
class Parser:
def __init__(self, file_path):
self.dottedproductions = {"S'": [['.', 'S']]}
file_program = self.read_program(file_path)
self.terminals = file_program[0]
self.nonTerminals = file_program[1]
self.productions = {}
self.transactions = file_program[2:]
for elements in self.transactions:
if elements[0] in self.productions:
self.productions[elements[0]].append(elements[1:])
else:
self.productions[elements[0]] = [elements[1:]]
self.data = [self.terminals, self.nonTerminals, self.productions]
dotted = self.dotMaker()
self.initial_closure = {"S'": [dotted["S'"][0]]}
self.closure(self.initial_closure, dotted, dotted["S'"][0])
def dot_maker(self):
self.dottedproductions = {"S'": [['.', 'S']]}
for non_terminal in self.productions:
self.dottedproductions[nonTerminal] = []
for way in self.productions[nonTerminal]:
self.dottedproductions[nonTerminal].append(['.'] + way)
return self.dottedproductions
def closure(self, closure_map, transitions_map, transition_value):
dot_index = transition_value.index('.')
if dot_index + 1 == len(transition_value):
return
after_dot = transition_value[dot_index + 1]
if after_dot in self.nonTerminals:
non_terminal = after_dot
if non_terminal not in closure_map:
closure_map[non_terminal] = transitions_map[non_terminal]
else:
closure_map[non_terminal] += transitions_map[non_terminal]
for transition in transitions_map[non_terminal]:
self.closure(closure_map, transitions_map, transition)
@staticmethod
def shiftable(transition):
dot_index = transition.index('.')
if len(transition) > dot_index + 1:
return True
return False
@staticmethod
def shift_dot(transition):
transition = transition[:]
dot_index = transition.index('.')
if not Parser.shiftable(transition):
raise exception('Should I shift it back ?')
if len(transition) > dot_index + 2:
remainder = transition[dot_index + 2:]
else:
remainder = []
transition = transition[:dot_index] + [transition[dot_index + 1]] + ['.'] + remainder
return transition
def canonical_collection(self):
self.idk = {}
self.queue = [{'state': self.initial_closure, 'initial_dotted': self.dottedproductions}]
self.states = []
self.state_parents = {}
while len(self.queue) > 0:
self.goto_all(**self.queue.pop(0))
reduced = self.get_reduced()
for k in reduced:
red_k = list(reduced[k].keys())
if red_k[0] != "S'":
trans = red_k + reduced[k][red_k[0]][0][:-1]
reduce_index = self.transactions.index(trans) + 1
self.idk[k] = {terminal: f'r{reduce_index}' for terminal in self.terminals}
self.idk[k]['$'] = f'r{reduce_index}'
else:
self.idk[k] = {'$': 'accept'}
del self.state_parents[0]
for key in self.state_parents:
parent = self.state_parents[key]
if parent['parent_index'] in self.idk:
self.idk[parent['parent_index']][parent['before_dot']] = key
else:
self.idk[parent['parent_index']] = {parent['before_dot']: key}
table = {f'I{index}': self.idk[index] for index in range(len(self.states))}
self.print_dict(table, 'Table:')
def goto_all(self, state, initial_dotted, parent=-1, parent_key='-1'):
if state not in self.states:
self.states.append(state)
index = len(self.states) - 1
self.state_parents[index] = {'parent_index': parent, 'before_dot': parent_key}
{}.items()
self.print_dict(state, f'state {index}')
for key in state:
for transition in state[key]:
if self.shiftable(transition):
self.goto_one(initial_dotted, key, transition, index)
elif parent in self.idk:
self.idk[parent][parent_key] = self.states.index(state)
else:
self.idk[parent] = {parent_key: self.states.index(state)}
def goto_one(self, initial_dotted, key, state, parent=-1):
shifted_transition = self.shift_dot(state)
closure_map = {key: [shifted_transition]}
self.closure(closure_map, initial_dotted, shifted_transition)
self.queue.append({'state': closure_map, 'initial_dotted': initial_dotted, 'parent': parent, 'parent_key': shifted_transition[shifted_transition.index('.') - 1]})
def get_reduced(self):
self.reduced = {}
for state in self.states:
state_key = list(state.keys())[0]
if len(state) == 1 and len(state[state_key]) and len(state[state_key][0]) and (state[state_key][0][-1] == '.'):
self.reduced[self.states.index(state)] = state
return self.reduced
@staticmethod
def read_program(file_path):
file1 = open(file_path, 'r')
lines = file1.readlines()
file1.close()
return [line.replace('\n', '').replace('\t', '').split(' ') for line in lines]
@staticmethod
def print_dict(hashmap, message=None, deepness=''):
if message is not None:
print(deepness + message)
for key in hashmap:
print(f'{deepness}{key} : {hashmap[key]}')
def print_data(self, index=-1):
if index == -1:
exit()
else:
print(self.data[index - 1])
def print_production(self, non_terminal):
data = self.data[2]
if non_terminal in data:
for row in data[non_terminal]:
print(f'{non_terminal} -> {row}')
else:
print('Wrong non terminal!')
|
class instancemethod(object):
def __init__(self, func):
self._func = func
def __get__(self, obj, type_=None):
return lambda *args, **kwargs: self._func(obj, *args, **kwargs)
class Func(object):
def __init__(self):
pass
def __call__(self, *args, **kwargs):
return self, args, kwargs
class A(object):
def __init__(self):
pass
f1 = classmethod(Func())
f2 = instancemethod(Func())
a = A()
print(a.f1(10, 20))
print(a.f2(10, 20))
print(A.f1(10, 20))
|
class Instancemethod(object):
def __init__(self, func):
self._func = func
def __get__(self, obj, type_=None):
return lambda *args, **kwargs: self._func(obj, *args, **kwargs)
class Func(object):
def __init__(self):
pass
def __call__(self, *args, **kwargs):
return (self, args, kwargs)
class A(object):
def __init__(self):
pass
f1 = classmethod(func())
f2 = instancemethod(func())
a = a()
print(a.f1(10, 20))
print(a.f2(10, 20))
print(A.f1(10, 20))
|
#!/usr/bin/env python
# https://adventofcode.com/2020/day/1
# Topic: Report repair
my_list = []
with open("../data/1.puzzle.txt") as fp:
Lines = fp.readlines()
for line in Lines:
my_list.append(int(line))
my_list.sort()
num1 = 0
num2 = 0
for idx, x in enumerate(my_list):
for y in range(0, len(my_list) - idx):
if x + my_list[len(my_list) - 1 - y] == 2020:
num1 = x
num2 = my_list[len(my_list) - 1 - y]
sum = num1 * num2
assert sum == 121396
num3 = 0
for x in my_list:
for y in my_list:
for z in my_list:
if x + y + z == 2020:
num1 = x
num2 = y
num3 = z
sum = num1 * num2 * num3
assert sum == 73616634
|
my_list = []
with open('../data/1.puzzle.txt') as fp:
lines = fp.readlines()
for line in Lines:
my_list.append(int(line))
my_list.sort()
num1 = 0
num2 = 0
for (idx, x) in enumerate(my_list):
for y in range(0, len(my_list) - idx):
if x + my_list[len(my_list) - 1 - y] == 2020:
num1 = x
num2 = my_list[len(my_list) - 1 - y]
sum = num1 * num2
assert sum == 121396
num3 = 0
for x in my_list:
for y in my_list:
for z in my_list:
if x + y + z == 2020:
num1 = x
num2 = y
num3 = z
sum = num1 * num2 * num3
assert sum == 73616634
|
class MasterConfig:
def __init__(self, args):
self.IP = args.ip
self.PORT = args.port
self.PERSISTENCE_DIR = args.persistence_dir
self.SENDER_QUEUE_LENGTH = args.sender_queue_length
self.SENDER_TIMEOUT = args.sender_timeout
self.UI_PORT = args.ui_port
self.CPU_PERCENT_THRESHOLD = 25.0
|
class Masterconfig:
def __init__(self, args):
self.IP = args.ip
self.PORT = args.port
self.PERSISTENCE_DIR = args.persistence_dir
self.SENDER_QUEUE_LENGTH = args.sender_queue_length
self.SENDER_TIMEOUT = args.sender_timeout
self.UI_PORT = args.ui_port
self.CPU_PERCENT_THRESHOLD = 25.0
|
'''knot> pytest tests '''
def test_noting():
assert True
|
"""knot> pytest tests """
def test_noting():
assert True
|
#********************************************************************
# Filename: SingletonPattern_With.Metaclass.py
# Author: Javier Montenegro (https://javiermontenegro.github.io/)
# Copyright:
# Details: This code is the implementation of the singleton pattern.
#*********************************************************************
class MetaSingleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Logger(metaclass=MetaSingleton):
pass
if __name__ == "__main__":
logger1 = Logger()
logger2 = Logger()
# Reffer to same object.
print(logger1, logger2)
|
class Metasingleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Logger(metaclass=MetaSingleton):
pass
if __name__ == '__main__':
logger1 = logger()
logger2 = logger()
print(logger1, logger2)
|
"""
Purpose:
File for holding custom exception types that will be generated by the
kafka_helpers libraries
"""
###
# Consumer Exceptions
###
class TopicNotFound(Exception):
"""
Purpose:
The TopicNotFound will be raised when attempting to consume a topic that
does not exist
"""
pass
###
# Producer Exceptions
###
|
"""
Purpose:
File for holding custom exception types that will be generated by the
kafka_helpers libraries
"""
class Topicnotfound(Exception):
"""
Purpose:
The TopicNotFound will be raised when attempting to consume a topic that
does not exist
"""
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.