content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Time: O(logn) = O(1)
# Space: O(1)
class Solution(object):
# @param {integer} num
# @return {boolean}
def isUgly(self, num):
if num == 0:
return False
for i in [2, 3, 5]:
while num % i == 0:
num /= i
return num == 1
| class Solution(object):
def is_ugly(self, num):
if num == 0:
return False
for i in [2, 3, 5]:
while num % i == 0:
num /= i
return num == 1 |
# Copyright 2019 VMware, Inc.
# SPDX-License-Indentifier: Apache-2.0
class TemplateEngineException(Exception):
"""
Exception class for template engine exceptions.
"""
pass
class InvalidReferenceException(TemplateEngineException):
"""
Exception class for invalid parameter reference.
"""
pass
class UnresolvableParameterException(TemplateEngineException):
"""
Exception class for unresolvable parameters.
"""
pass
| class Templateengineexception(Exception):
"""
Exception class for template engine exceptions.
"""
pass
class Invalidreferenceexception(TemplateEngineException):
"""
Exception class for invalid parameter reference.
"""
pass
class Unresolvableparameterexception(TemplateEngineException):
"""
Exception class for unresolvable parameters.
"""
pass |
def write_xyz(filename, points, verbose=False):
"""
Writes the points as xyz-format file. The xyz-format file can be opened and displayed for instance
in PyMol
:param filename: string
Filename the cartesian coordinates in points are written to as xyz-format file
:param points:
:param verbose:
"""
if verbose:
print("\nwrite_xyz")
print("---------")
print("Filename: %s" % filename)
fp = open(filename, 'w')
npoints = len(points)
fp.write('%i\n' % npoints)
fp.write('Name\n')
for p in points:
fp.write('D %.3f %.3f %.3f\n' % (p[0], p[1], p[2]))
fp.close()
if verbose:
print("-------------------") | def write_xyz(filename, points, verbose=False):
"""
Writes the points as xyz-format file. The xyz-format file can be opened and displayed for instance
in PyMol
:param filename: string
Filename the cartesian coordinates in points are written to as xyz-format file
:param points:
:param verbose:
"""
if verbose:
print('\nwrite_xyz')
print('---------')
print('Filename: %s' % filename)
fp = open(filename, 'w')
npoints = len(points)
fp.write('%i\n' % npoints)
fp.write('Name\n')
for p in points:
fp.write('D %.3f %.3f %.3f\n' % (p[0], p[1], p[2]))
fp.close()
if verbose:
print('-------------------') |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
result = ListNode()
p = result
h = head
if h:
while h.next != None:
if h.val != val:
p.next = ListNode()
p = p.next
p.val = h.val
h = h.next
if h.val != val:
p.next = ListNode()
p = p.next
p.val = h.val
return result.next | class Solution:
def remove_elements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
result = list_node()
p = result
h = head
if h:
while h.next != None:
if h.val != val:
p.next = list_node()
p = p.next
p.val = h.val
h = h.next
if h.val != val:
p.next = list_node()
p = p.next
p.val = h.val
return result.next |
hours = int(input()) * 60
minutes = int(input())
all = hours + minutes + 15
hours = all // 60
minutes = all % 60
if hours > 23:
hours = hours - 24
if minutes < 10:
print (f"{hours}:0{minutes}")
else:
print (f"{hours}:{minutes}")
| hours = int(input()) * 60
minutes = int(input())
all = hours + minutes + 15
hours = all // 60
minutes = all % 60
if hours > 23:
hours = hours - 24
if minutes < 10:
print(f'{hours}:0{minutes}')
else:
print(f'{hours}:{minutes}') |
DEFAULT_PLUGINS = [
"kolibri.plugins.coach",
"kolibri.plugins.default_theme",
"kolibri.plugins.device",
"kolibri.plugins.epub_viewer",
"kolibri.plugins.html5_viewer",
"kolibri.plugins.facility",
"kolibri.plugins.learn",
"kolibri.plugins.media_player",
"kolibri.plugins.pdf_viewer",
"kolibri.plugins.perseus_viewer",
"kolibri.plugins.setup_wizard",
"kolibri.plugins.slideshow_viewer",
"kolibri.plugins.user",
]
| default_plugins = ['kolibri.plugins.coach', 'kolibri.plugins.default_theme', 'kolibri.plugins.device', 'kolibri.plugins.epub_viewer', 'kolibri.plugins.html5_viewer', 'kolibri.plugins.facility', 'kolibri.plugins.learn', 'kolibri.plugins.media_player', 'kolibri.plugins.pdf_viewer', 'kolibri.plugins.perseus_viewer', 'kolibri.plugins.setup_wizard', 'kolibri.plugins.slideshow_viewer', 'kolibri.plugins.user'] |
def pytest_addoption(parser):
parser.addoption("--assays", action="store", default="")
parser.addoption("--test_dir", help='test_dir', action="store", default="/SGRNJ03/randd/user/zhouyiqi/multi_tests/")
def pytest_generate_tests(metafunc):
# This is called for every test. Only get/set command line arguments
# if the argument is specified in the list of test "fixturenames".
assays_value = metafunc.config.option.assays
test_dir_value = metafunc.config.option.test_dir
if 'assays' in metafunc.fixturenames and assays_value is not None:
metafunc.parametrize("assays", [assays_value])
if 'test_dir' in metafunc.fixturenames and test_dir_value is not None:
metafunc.parametrize("test_dir", [test_dir_value]) | def pytest_addoption(parser):
parser.addoption('--assays', action='store', default='')
parser.addoption('--test_dir', help='test_dir', action='store', default='/SGRNJ03/randd/user/zhouyiqi/multi_tests/')
def pytest_generate_tests(metafunc):
assays_value = metafunc.config.option.assays
test_dir_value = metafunc.config.option.test_dir
if 'assays' in metafunc.fixturenames and assays_value is not None:
metafunc.parametrize('assays', [assays_value])
if 'test_dir' in metafunc.fixturenames and test_dir_value is not None:
metafunc.parametrize('test_dir', [test_dir_value]) |
#
# PySNMP MIB module ARTEM-COMPOINT-BLD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARTEM-COMPOINT-BLD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:25:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
TimeTicks, ObjectIdentity, NotificationType, Counter32, MibIdentifier, Gauge32, Counter64, ModuleIdentity, IpAddress, Bits, iso, Unsigned32, Integer32, enterprises, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "ObjectIdentity", "NotificationType", "Counter32", "MibIdentifier", "Gauge32", "Counter64", "ModuleIdentity", "IpAddress", "Bits", "iso", "Unsigned32", "Integer32", "enterprises", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
DisplayString, TextualConvention, RowStatus, MacAddress, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus", "MacAddress", "TruthValue")
artem = ModuleIdentity((1, 3, 6, 1, 4, 1, 4280))
artem.setRevisions(('2005-06-10 12:17', '2005-05-24 13:24', '2005-04-29 12:05',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: artem.setRevisionsDescriptions(('Updated Revision and last-updated.', 'Removed artemBLDIfTableIndex and artemBLDIfIndex from artemBLDIfTable. Index is now ifIndex.', 'Initial version.',))
if mibBuilder.loadTexts: artem.setLastUpdated('200506101217Z')
if mibBuilder.loadTexts: artem.setOrganization('Funkwerk Enterprise Communications.')
if mibBuilder.loadTexts: artem.setContactInfo('juergen.lachmann@funkwerk-ec.com.')
if mibBuilder.loadTexts: artem.setDescription('Funkwerk Enterprise Communications MIB file that provides additional attributes not covered by standard MIBs for Broken Link Detection in artem products.')
artemBLD = ObjectIdentity((1, 3, 6, 1, 4, 1, 4280, 6))
if mibBuilder.loadTexts: artemBLD.setStatus('current')
if mibBuilder.loadTexts: artemBLD.setDescription('Definitions and attributes for Broken Link Detection.')
artemBLDAdminStatus = MibScalar((1, 3, 6, 1, 4, 1, 4280, 6, 1), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: artemBLDAdminStatus.setStatus('current')
if mibBuilder.loadTexts: artemBLDAdminStatus.setDescription('This attribute selects whether periodic BLD link checking is administratively enabled.')
artemBLDLinkState = MibScalar((1, 3, 6, 1, 4, 1, 4280, 6, 2), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: artemBLDLinkState.setStatus('current')
if mibBuilder.loadTexts: artemBLDLinkState.setDescription('This attribute indicates whether the IP target monitored by BLD is currently reachable.')
artemBLDTargetAddress = MibScalar((1, 3, 6, 1, 4, 1, 4280, 6, 3), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: artemBLDTargetAddress.setStatus('current')
if mibBuilder.loadTexts: artemBLDTargetAddress.setDescription('This attribute holds the IP address of the connection target which is periodically checked by BLD.')
artemBLDTargetIf = MibScalar((1, 3, 6, 1, 4, 1, 4280, 6, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: artemBLDTargetIf.setStatus('current')
if mibBuilder.loadTexts: artemBLDTargetIf.setDescription('This attribute hold the ifIndex of the interface that received the most recent reply from the BLD target. The value 0 indicates that no reply has been received.')
artemBLDCheckInterval = MibScalar((1, 3, 6, 1, 4, 1, 4280, 6, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3600)).clone(300)).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: artemBLDCheckInterval.setStatus('current')
if mibBuilder.loadTexts: artemBLDCheckInterval.setDescription('This is the interval between successive checks whether the BLD target is reachable.')
artemBLDTimeout = MibScalar((1, 3, 6, 1, 4, 1, 4280, 6, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 300)).clone(1)).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: artemBLDTimeout.setStatus('current')
if mibBuilder.loadTexts: artemBLDTimeout.setDescription('This attribute defines the timeout for replies from the BLD target.')
artemBLDRetries = MibScalar((1, 3, 6, 1, 4, 1, 4280, 6, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 99)).clone(5)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: artemBLDRetries.setStatus('current')
if mibBuilder.loadTexts: artemBLDRetries.setDescription('This attribute defines the number of timer BLD retries to reach the target after an initial failed attempt until the connection is considered broken.')
artemBLDIfTable = MibTable((1, 3, 6, 1, 4, 1, 4280, 6, 8), )
if mibBuilder.loadTexts: artemBLDIfTable.setStatus('current')
if mibBuilder.loadTexts: artemBLDIfTable.setDescription('This is table of all interfaces which will be modified when BLD detects that its target is unreachable. AP type interfaces are temporarily closed and will not allow any client to associate. Bridge type interfaces are unlocked if their operational status is disabled(2).')
artemBLDIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4280, 6, 8, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: artemBLDIfEntry.setStatus('current')
if mibBuilder.loadTexts: artemBLDIfEntry.setDescription('An entry in artemBLDIfTable.')
artemBLDIfRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4280, 6, 8, 1, 1), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: artemBLDIfRowStatus.setStatus('current')
if mibBuilder.loadTexts: artemBLDIfRowStatus.setDescription('Auxiliary variable for creation of new object instances and/or the deletion of existing object instances.')
artemBLDNotification = MibIdentifier((1, 3, 6, 1, 4, 1, 4280, 6, 9))
artemBLDConnection = NotificationType((1, 3, 6, 1, 4, 1, 4280, 6, 9, 1)).setObjects(("IF-MIB", "ifIndex"), ("ARTEM-COMPOINT-BLD-MIB", "artemBLDLinkState"))
if mibBuilder.loadTexts: artemBLDConnection.setStatus('current')
if mibBuilder.loadTexts: artemBLDConnection.setDescription('This notification is triggered for every interface in artemBLDIfTable whenever BLD detects a change in target link state.')
artemBLDGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4280, 6, 10)).setObjects(("ARTEM-COMPOINT-BLD-MIB", "artemBLDAdminStatus"), ("ARTEM-COMPOINT-BLD-MIB", "artemBLDLinkState"), ("ARTEM-COMPOINT-BLD-MIB", "artemBLDTargetAddress"), ("ARTEM-COMPOINT-BLD-MIB", "artemBLDTargetIf"), ("ARTEM-COMPOINT-BLD-MIB", "artemBLDCheckInterval"), ("ARTEM-COMPOINT-BLD-MIB", "artemBLDTimeout"), ("ARTEM-COMPOINT-BLD-MIB", "artemBLDRetries"), ("ARTEM-COMPOINT-BLD-MIB", "artemBLDIfRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
artemBLDGroup = artemBLDGroup.setStatus('current')
if mibBuilder.loadTexts: artemBLDGroup.setDescription('Attributes for artem Broken Link Detection (BLD).')
artemBLDNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 4280, 6, 11)).setObjects(("ARTEM-COMPOINT-BLD-MIB", "artemBLDConnection"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
artemBLDNotificationGroup = artemBLDNotificationGroup.setStatus('current')
if mibBuilder.loadTexts: artemBLDNotificationGroup.setDescription('Notifications for BLD events')
mibBuilder.exportSymbols("ARTEM-COMPOINT-BLD-MIB", artemBLDCheckInterval=artemBLDCheckInterval, artemBLDGroup=artemBLDGroup, artemBLDIfRowStatus=artemBLDIfRowStatus, artemBLDLinkState=artemBLDLinkState, artem=artem, artemBLDTargetAddress=artemBLDTargetAddress, artemBLD=artemBLD, artemBLDIfEntry=artemBLDIfEntry, artemBLDNotificationGroup=artemBLDNotificationGroup, artemBLDIfTable=artemBLDIfTable, artemBLDAdminStatus=artemBLDAdminStatus, artemBLDNotification=artemBLDNotification, artemBLDTargetIf=artemBLDTargetIf, artemBLDTimeout=artemBLDTimeout, PYSNMP_MODULE_ID=artem, artemBLDConnection=artemBLDConnection, artemBLDRetries=artemBLDRetries)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, constraints_union, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint')
(if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex')
(module_compliance, object_group, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'ObjectGroup', 'NotificationGroup')
(time_ticks, object_identity, notification_type, counter32, mib_identifier, gauge32, counter64, module_identity, ip_address, bits, iso, unsigned32, integer32, enterprises, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'ObjectIdentity', 'NotificationType', 'Counter32', 'MibIdentifier', 'Gauge32', 'Counter64', 'ModuleIdentity', 'IpAddress', 'Bits', 'iso', 'Unsigned32', 'Integer32', 'enterprises', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn')
(display_string, textual_convention, row_status, mac_address, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention', 'RowStatus', 'MacAddress', 'TruthValue')
artem = module_identity((1, 3, 6, 1, 4, 1, 4280))
artem.setRevisions(('2005-06-10 12:17', '2005-05-24 13:24', '2005-04-29 12:05'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
artem.setRevisionsDescriptions(('Updated Revision and last-updated.', 'Removed artemBLDIfTableIndex and artemBLDIfIndex from artemBLDIfTable. Index is now ifIndex.', 'Initial version.'))
if mibBuilder.loadTexts:
artem.setLastUpdated('200506101217Z')
if mibBuilder.loadTexts:
artem.setOrganization('Funkwerk Enterprise Communications.')
if mibBuilder.loadTexts:
artem.setContactInfo('juergen.lachmann@funkwerk-ec.com.')
if mibBuilder.loadTexts:
artem.setDescription('Funkwerk Enterprise Communications MIB file that provides additional attributes not covered by standard MIBs for Broken Link Detection in artem products.')
artem_bld = object_identity((1, 3, 6, 1, 4, 1, 4280, 6))
if mibBuilder.loadTexts:
artemBLD.setStatus('current')
if mibBuilder.loadTexts:
artemBLD.setDescription('Definitions and attributes for Broken Link Detection.')
artem_bld_admin_status = mib_scalar((1, 3, 6, 1, 4, 1, 4280, 6, 1), truth_value().clone('false')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
artemBLDAdminStatus.setStatus('current')
if mibBuilder.loadTexts:
artemBLDAdminStatus.setDescription('This attribute selects whether periodic BLD link checking is administratively enabled.')
artem_bld_link_state = mib_scalar((1, 3, 6, 1, 4, 1, 4280, 6, 2), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
artemBLDLinkState.setStatus('current')
if mibBuilder.loadTexts:
artemBLDLinkState.setDescription('This attribute indicates whether the IP target monitored by BLD is currently reachable.')
artem_bld_target_address = mib_scalar((1, 3, 6, 1, 4, 1, 4280, 6, 3), ip_address().clone(hexValue='00000000')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
artemBLDTargetAddress.setStatus('current')
if mibBuilder.loadTexts:
artemBLDTargetAddress.setDescription('This attribute holds the IP address of the connection target which is periodically checked by BLD.')
artem_bld_target_if = mib_scalar((1, 3, 6, 1, 4, 1, 4280, 6, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
artemBLDTargetIf.setStatus('current')
if mibBuilder.loadTexts:
artemBLDTargetIf.setDescription('This attribute hold the ifIndex of the interface that received the most recent reply from the BLD target. The value 0 indicates that no reply has been received.')
artem_bld_check_interval = mib_scalar((1, 3, 6, 1, 4, 1, 4280, 6, 5), integer32().subtype(subtypeSpec=value_range_constraint(1, 3600)).clone(300)).setUnits('seconds').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
artemBLDCheckInterval.setStatus('current')
if mibBuilder.loadTexts:
artemBLDCheckInterval.setDescription('This is the interval between successive checks whether the BLD target is reachable.')
artem_bld_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 4280, 6, 6), integer32().subtype(subtypeSpec=value_range_constraint(1, 300)).clone(1)).setUnits('seconds').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
artemBLDTimeout.setStatus('current')
if mibBuilder.loadTexts:
artemBLDTimeout.setDescription('This attribute defines the timeout for replies from the BLD target.')
artem_bld_retries = mib_scalar((1, 3, 6, 1, 4, 1, 4280, 6, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 99)).clone(5)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
artemBLDRetries.setStatus('current')
if mibBuilder.loadTexts:
artemBLDRetries.setDescription('This attribute defines the number of timer BLD retries to reach the target after an initial failed attempt until the connection is considered broken.')
artem_bld_if_table = mib_table((1, 3, 6, 1, 4, 1, 4280, 6, 8))
if mibBuilder.loadTexts:
artemBLDIfTable.setStatus('current')
if mibBuilder.loadTexts:
artemBLDIfTable.setDescription('This is table of all interfaces which will be modified when BLD detects that its target is unreachable. AP type interfaces are temporarily closed and will not allow any client to associate. Bridge type interfaces are unlocked if their operational status is disabled(2).')
artem_bld_if_entry = mib_table_row((1, 3, 6, 1, 4, 1, 4280, 6, 8, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'))
if mibBuilder.loadTexts:
artemBLDIfEntry.setStatus('current')
if mibBuilder.loadTexts:
artemBLDIfEntry.setDescription('An entry in artemBLDIfTable.')
artem_bld_if_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 4280, 6, 8, 1, 1), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
artemBLDIfRowStatus.setStatus('current')
if mibBuilder.loadTexts:
artemBLDIfRowStatus.setDescription('Auxiliary variable for creation of new object instances and/or the deletion of existing object instances.')
artem_bld_notification = mib_identifier((1, 3, 6, 1, 4, 1, 4280, 6, 9))
artem_bld_connection = notification_type((1, 3, 6, 1, 4, 1, 4280, 6, 9, 1)).setObjects(('IF-MIB', 'ifIndex'), ('ARTEM-COMPOINT-BLD-MIB', 'artemBLDLinkState'))
if mibBuilder.loadTexts:
artemBLDConnection.setStatus('current')
if mibBuilder.loadTexts:
artemBLDConnection.setDescription('This notification is triggered for every interface in artemBLDIfTable whenever BLD detects a change in target link state.')
artem_bld_group = object_group((1, 3, 6, 1, 4, 1, 4280, 6, 10)).setObjects(('ARTEM-COMPOINT-BLD-MIB', 'artemBLDAdminStatus'), ('ARTEM-COMPOINT-BLD-MIB', 'artemBLDLinkState'), ('ARTEM-COMPOINT-BLD-MIB', 'artemBLDTargetAddress'), ('ARTEM-COMPOINT-BLD-MIB', 'artemBLDTargetIf'), ('ARTEM-COMPOINT-BLD-MIB', 'artemBLDCheckInterval'), ('ARTEM-COMPOINT-BLD-MIB', 'artemBLDTimeout'), ('ARTEM-COMPOINT-BLD-MIB', 'artemBLDRetries'), ('ARTEM-COMPOINT-BLD-MIB', 'artemBLDIfRowStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
artem_bld_group = artemBLDGroup.setStatus('current')
if mibBuilder.loadTexts:
artemBLDGroup.setDescription('Attributes for artem Broken Link Detection (BLD).')
artem_bld_notification_group = notification_group((1, 3, 6, 1, 4, 1, 4280, 6, 11)).setObjects(('ARTEM-COMPOINT-BLD-MIB', 'artemBLDConnection'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
artem_bld_notification_group = artemBLDNotificationGroup.setStatus('current')
if mibBuilder.loadTexts:
artemBLDNotificationGroup.setDescription('Notifications for BLD events')
mibBuilder.exportSymbols('ARTEM-COMPOINT-BLD-MIB', artemBLDCheckInterval=artemBLDCheckInterval, artemBLDGroup=artemBLDGroup, artemBLDIfRowStatus=artemBLDIfRowStatus, artemBLDLinkState=artemBLDLinkState, artem=artem, artemBLDTargetAddress=artemBLDTargetAddress, artemBLD=artemBLD, artemBLDIfEntry=artemBLDIfEntry, artemBLDNotificationGroup=artemBLDNotificationGroup, artemBLDIfTable=artemBLDIfTable, artemBLDAdminStatus=artemBLDAdminStatus, artemBLDNotification=artemBLDNotification, artemBLDTargetIf=artemBLDTargetIf, artemBLDTimeout=artemBLDTimeout, PYSNMP_MODULE_ID=artem, artemBLDConnection=artemBLDConnection, artemBLDRetries=artemBLDRetries) |
def on_chat(num):
pass
def on_chat2(num: number):
pass | def on_chat(num):
pass
def on_chat2(num: number):
pass |
#
# @lc app=leetcode id=17 lang=python3
#
# [17] Letter Combinations of a Phone Number
#
# https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
#
# algorithms
# Medium (48.78%)
# Likes: 5494
# Dislikes: 499
# Total Accepted: 775.5K
# Total Submissions: 1.6M
# Testcase Example: '"23"'
#
# Given a string containing digits from 2-9 inclusive, return all possible
# letter combinations that the number could represent. Return the answer in any
# order.
#
# A mapping of digit to letters (just like on the telephone buttons) is given
# below. Note that 1 does not map to any letters.
#
#
#
#
# Example 1:
#
#
# Input: digits = "23"
# Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
#
#
# Example 2:
#
#
# Input: digits = ""
# Output: []
#
#
# Example 3:
#
#
# Input: digits = "2"
# Output: ["a","b","c"]
#
#
#
# Constraints:
#
#
# 0 <= digits.length <= 4
# digits[i] is a digit in the range ['2', '9'].
#
#
#
# @lc code=start
class Solution:
def __init__(self):
self.int2letter = {
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"]
}
def letterCombinations(self, digits: str) -> List[str]:
if not digits or len(digits) == 0:
return []
res = []
self._dfs(digits, res, "", 0)
return res
def _dfs(self, digits, res, curr, idx):
if len(curr) == len(digits):
res.append(curr[:])
return
if idx >= len(digits):
return
for char in self.int2letter[digits[idx]]:
self._dfs(digits, res, curr + char, idx + 1)
# @lc code=end
| class Solution:
def __init__(self):
self.int2letter = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']}
def letter_combinations(self, digits: str) -> List[str]:
if not digits or len(digits) == 0:
return []
res = []
self._dfs(digits, res, '', 0)
return res
def _dfs(self, digits, res, curr, idx):
if len(curr) == len(digits):
res.append(curr[:])
return
if idx >= len(digits):
return
for char in self.int2letter[digits[idx]]:
self._dfs(digits, res, curr + char, idx + 1) |
# 2 x 2 grid, has 3 choice points at 0,1,2
# At 0, there are 2 choices, at 1 there are 2 choices for both the options of 1 i.e. 0,1 and 1,0
# At level 2, there are no options 0,2 can only move in one way, 1,2 can also move in one way etc
# Therefore the options are a multiple of 2 x array size
# Let's try this
if __name__ == '__main__':
n = 0
for i in range(0,21):
at_this_level = ((i+1) *2)
n = n + at_this_level
print(n)
| if __name__ == '__main__':
n = 0
for i in range(0, 21):
at_this_level = (i + 1) * 2
n = n + at_this_level
print(n) |
def handle_response(response):
if not response.status_code:
raise Exception("Response is not valid")
if response.status_code in range(200, 300):
return response.json()
elif response.status_code < 500:
raise Exception(response.json())
else:
raise Exception("Unknown error") | def handle_response(response):
if not response.status_code:
raise exception('Response is not valid')
if response.status_code in range(200, 300):
return response.json()
elif response.status_code < 500:
raise exception(response.json())
else:
raise exception('Unknown error') |
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2016-Present Datadog, Inc.
API_SURFACE_PATH = "dd-sdk-android/apiSurface"
NIGHTLY_TESTS_DIRECTORY_PATH = "instrumented/nightly-tests/src/androidTest/kotlin"
NIGHTLY_TESTS_PACKAGE = "com/datadog/android/nightly"
IGNORED_TYPES = [
"com.datadog.android.tracing.model.SpanEvent$Span",
"com.datadog.android.rum.model.ActionEvent$Dd",
"com.datadog.android.rum.model.ErrorEvent$Dd",
"com.datadog.android.rum.model.LongTaskEvent$Dd"
]
| api_surface_path = 'dd-sdk-android/apiSurface'
nightly_tests_directory_path = 'instrumented/nightly-tests/src/androidTest/kotlin'
nightly_tests_package = 'com/datadog/android/nightly'
ignored_types = ['com.datadog.android.tracing.model.SpanEvent$Span', 'com.datadog.android.rum.model.ActionEvent$Dd', 'com.datadog.android.rum.model.ErrorEvent$Dd', 'com.datadog.android.rum.model.LongTaskEvent$Dd'] |
# -*- coding:utf-8 -*-
logger = logging.getLogger('M3ARPG')
class User:
pass
| logger = logging.getLogger('M3ARPG')
class User:
pass |
#!/usr/bin/env python3
"""
Sorting List Example 1
"""
# Get a sorted copy of a List
my_list = [9, 1, 8, 2, 7, 6, 3, 5, 4, 0]
sorted_list = sorted(my_list)
print('Original List: ', my_list)
print('Sorted List: ', sorted_list)
# Sort the original List
my_list.sort()
print('Original List (sorted): ', my_list)
# Sort a List in descending order
sorted_list = sorted(my_list, reverse=True)
my_list.sort(reverse=True)
print('Original List (reverse=True): ', my_list)
print('Sorted List (reverse=True): ', sorted_list)
"""
Sorting Tuple Example
"""
my_tuple = (9, 1, 8, 2, 7, 6, 3, 5, 4, 0)
# Tuple is immutable
# Tuple doesn't have sort() method
# The below line throws AttributeError
# my_tuple.sort()
sorted_tuple = tuple(sorted(my_tuple))
print('Sorted Tuple: ', sorted_tuple)
"""
Sorting Dictionary Example
"""
my_dict = {'name': 'Young', 'os': 'Mac', 'job': 'developer', 'gender': 'male'}
# The below line will sort the keys of the dictionary
sorted_dict = sorted(my_dict)
print('Sorted Dictionary Keys: ', type(sorted_dict), sorted_dict)
"""
Sorting with Keys Example 1
- Sorting with Absolute values
"""
nums = [-4, -5, -6, 1, 3, 2]
sorted_nums = sorted(nums)
sorted_abs = sorted(nums, key=abs)
print('Original Numbers: ', nums)
print('Sorted Numbers: ', sorted_nums)
print('Sorted Absolute Values: ', sorted_abs)
"""
Sorting with Keys Example 2
- Sorting with an Attribute of objects
"""
class Employee():
""" Class representing an Employee """
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def __repr__(self):
return '({}, {}, ${})'.format(self.name, self.age, self.salary)
def e_sort(emp):
return emp.name
e1 = Employee('Kim', 28, 50000)
e2 = Employee('Joung', 34, 65000)
e3 = Employee('Young', 39, 60000)
employees = [e1, e2, e3]
# The below line throws TypeError
# sorted_employees = sorted(employees)
# key should be specified to sort objects
sorted_employees = sorted(employees, key=e_sort)
# Using a Lambda function
# sorted_employees = sorted(employees, key=lambda e: e.name)
# Using operator module
# from operator import attrgetter
# sorted_employees = sorted(employees, key=attrgetter('salary'))
# Sorting in descending order
# sorted_employees = sorted(employees, key=e_sort, reverse=True)
print('Sorted Employees List: ', sorted_employees)
| """
Sorting List Example 1
"""
my_list = [9, 1, 8, 2, 7, 6, 3, 5, 4, 0]
sorted_list = sorted(my_list)
print('Original List: ', my_list)
print('Sorted List: ', sorted_list)
my_list.sort()
print('Original List (sorted): ', my_list)
sorted_list = sorted(my_list, reverse=True)
my_list.sort(reverse=True)
print('Original List (reverse=True): ', my_list)
print('Sorted List (reverse=True): ', sorted_list)
'\n Sorting Tuple Example\n'
my_tuple = (9, 1, 8, 2, 7, 6, 3, 5, 4, 0)
sorted_tuple = tuple(sorted(my_tuple))
print('Sorted Tuple: ', sorted_tuple)
'\n Sorting Dictionary Example\n'
my_dict = {'name': 'Young', 'os': 'Mac', 'job': 'developer', 'gender': 'male'}
sorted_dict = sorted(my_dict)
print('Sorted Dictionary Keys: ', type(sorted_dict), sorted_dict)
'\n Sorting with Keys Example 1\n - Sorting with Absolute values\n'
nums = [-4, -5, -6, 1, 3, 2]
sorted_nums = sorted(nums)
sorted_abs = sorted(nums, key=abs)
print('Original Numbers: ', nums)
print('Sorted Numbers: ', sorted_nums)
print('Sorted Absolute Values: ', sorted_abs)
'\n Sorting with Keys Example 2\n - Sorting with an Attribute of objects\n'
class Employee:
""" Class representing an Employee """
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def __repr__(self):
return '({}, {}, ${})'.format(self.name, self.age, self.salary)
def e_sort(emp):
return emp.name
e1 = employee('Kim', 28, 50000)
e2 = employee('Joung', 34, 65000)
e3 = employee('Young', 39, 60000)
employees = [e1, e2, e3]
sorted_employees = sorted(employees, key=e_sort)
print('Sorted Employees List: ', sorted_employees) |
class Solution:
def maxSubArray(self, ls):
if len(ls) == 0:
raise Exception("Array empty") # should be non-empty
runSum = maxSum = ls[0]
i = 0
start = finish = 0
for j in range(1, len(ls)):
if ls[j] > (runSum + ls[j]):
runSum = ls[j]
i = j
else:
runSum += ls[j]
if runSum > maxSum:
maxSum = runSum
start = i
finish = j
print("maxSum =>", maxSum)
print("start =>", start, "; finish =>", finish)
return maxSum
test = Solution()
# print(test.maxSubArray((1,2,3,4)))
A = (-2, 1, -3, 4, -1, 2, 1, -5, 4)
print(test.maxSubArray(A))
| class Solution:
def max_sub_array(self, ls):
if len(ls) == 0:
raise exception('Array empty')
run_sum = max_sum = ls[0]
i = 0
start = finish = 0
for j in range(1, len(ls)):
if ls[j] > runSum + ls[j]:
run_sum = ls[j]
i = j
else:
run_sum += ls[j]
if runSum > maxSum:
max_sum = runSum
start = i
finish = j
print('maxSum =>', maxSum)
print('start =>', start, '; finish =>', finish)
return maxSum
test = solution()
a = (-2, 1, -3, 4, -1, 2, 1, -5, 4)
print(test.maxSubArray(A)) |
COUNTRIES = {
"United States": 5,
"Argentina": 29,
"Australia": 25,
"Austria": 54,
"Bahrain": 145,
"Bangladesh": 47,
"Belgium": 34,
"Bosnia-Herzegovina": 174,
"Botswana": 163,
"Brazil": 32,
"Bulgaria": 70,
"Canada": 6,
"Chile": 27,
"China": 37,
"Colombia": 122,
"Costa Rica": 15,
"Cote D'Ivoire": 78,
"Croatia": 113,
"Cyprus": 107,
"Czech Republic": 55,
"Denmark": 24,
"Egypt": 59,
"Euro Zone": 72,
"Finland": 71,
"France": 22,
"Germany": 17,
"Greece": 51,
"Hong Kong": 39,
"Hungary": 93,
"Iceland": 106,
"India": 14,
"Indonesia": 48,
"Iraq": 66,
"Ireland": 33,
"Israel": 23,
"Italy": 10,
"Jamaica": 119,
"Japan": 35,
"Jordan": 92,
"Kazakhstan": 102,
"Kenya": 57,
"Kuwait": 94,
"Lebanon": 68,
"Luxembourg": 103,
"Malawi": 111,
"Malaysia": 42,
"Malta": 109,
"Mauritius": 188,
"Mexico": 7,
"Mongolia": 139,
"Montenegro": 247,
"Morocco": 105,
"Namibia": 172,
"Netherlands": 21,
"New Zealand": 43,
"Nigeria": 20,
"Norway": 60,
"Oman": 87,
"Pakistan": 44,
"Palestinian Territory": 193,
"Peru": 125,
"Philippines": 45,
"Poland": 53,
"Portugal": 38,
"Qatar": 170,
"Romania": 100,
"Russia": 56,
"Rwanda": 80,
"Saudi Arabia": 52,
"Serbia": 238,
"Singapore": 36,
"Slovakia": 90,
"Slovenia": 112,
"South Africa": 110,
"South Korea": 11,
"Spain": 26,
"Sri Lanka": 162,
"Sweden": 9,
"Switzerland": 12,
"Taiwan": 46,
"Tanzania": 85,
"Thailand": 41,
"Tunisia": 202,
"Turkey": 63,
"Uganda": 123,
"Ukraine": 61,
"United Arab Emirates": 143,
"United Kingdom": 4,
"Venezuela": 138,
"Vietnam": 178,
"Zambia": 84,
"Zimbabwe": 75,
}
SECTORS = {
"Basic Materials": 7,
"Capital Goods": 5,
"Conglomerates": 12,
"Consumer Cyclical": 3,
"Consumer/Non-Cyclical": 8,
"Energy": 9,
"Financial": 1,
"Healthcare": 6,
"Services": 2,
"Technology": 4,
"Transportation": 10,
"Utilities": 11,
}
INDUSTRIES = {
"Advertising ": 81,
"Aerospace & Defense ": 56,
"Air Courier ": 59,
"Airline ": 41,
"Apparel/Accessories ": 68,
"Appliance & Tool ": 67,
"Audio & Video Equipment ": 88,
"Auto & Truck Manufacturers ": 51,
"Auto & Truck Parts ": 72,
"Beverages (Alcoholic) ": 47,
"Beverages (Nonalcoholic) ": 12,
"Biotechnology & Drugs ": 8,
"Broadcasting & Cable TV ": 50,
"Business Services ": 2,
"Casinos & Gaming ": 71,
"Chemical Manufacturing ": 9,
"Chemicals - Plastics & Rubber ": 69,
"Coal ": 45,
"Communications Equipment ": 46,
"Communications Services ": 13,
"Computer Hardware ": 94,
"Computer Networks ": 102,
"Computer Peripherals ": 95,
"Computer Services ": 58,
"Computer Storage Devices ": 100,
"Conglomerates ": 101,
"Constr. & Agric. Machinery ": 87,
"Constr. - Supplies & Fixtures ": 31,
"Construction - Raw Materials ": 6,
"Construction Services ": 38,
"Consumer Financial Services ": 79,
"Containers & Packaging ": 30,
"Crops ": 77,
"Electric Utilities ": 28,
"Electronic Instr. & Controls ": 5,
"Fabricated Plastic & Rubber ": 60,
"Fish/Livestock ": 18,
"Food Processing ": 26,
"Footwear ": 44,
"Forestry & Wood Products ": 35,
"Furniture & Fixtures ": 53,
"Gold & Silver ": 48,
"Healthcare Facilities ": 49,
"Hotels & Motels ": 55,
"Insurance (Accident & Health) ": 78,
"Insurance (Life) ": 7,
"Insurance (Miscellaneous) ": 86,
"Insurance (Prop. & Casualty) ": 10,
"Investment Services ": 1,
"Iron & Steel ": 34,
"Jewelry & Silverware ": 3,
"Major Drugs ": 11,
"Medical Equipment & Supplies ": 62,
"Metal Mining ": 16,
"Misc. Capital Goods ": 24,
"Misc. Fabricated Products ": 20,
"Misc. Financial Services ": 54,
"Misc. Transportation ": 33,
"Mobile Homes & RVs ": 83,
"Money Center Banks ": 29,
"Motion Pictures ": 76,
"Natural Gas Utilities ": 37,
"Non-Metallic Mining ": 90,
"Office Equipment ": 85,
"Office Supplies ": 82,
"Oil & Gas - Integrated ": 22,
"Oil & Gas Operations ": 14,
"Oil Well Services & Equipment ": 17,
"Paper & Paper Products ": 19,
"Personal & Household Prods. ": 43,
"Personal Services ": 89,
"Photography ": 96,
"Printing & Publishing ": 57,
"Printing Services ": 84,
"Railroads ": 93,
"Real Estate Operations ": 27,
"Recreational Activities ": 74,
"Recreational Products ": 97,
"Regional Banks ": 4,
"Rental & Leasing ": 73,
"Restaurants ": 36,
"Retail (Apparel) ": 42,
"Retail (Catalog & Mail Order) ": 98,
"Retail (Department & Discount) ": 65,
"Retail (Drugs) ": 70,
"Retail (Grocery) ": 40,
"Retail (Home Improvement) ": 99,
"Retail (Specialty) ": 39,
"Retail (Technology) ": 92,
"Schools ": 75,
"Scientific & Technical Instr. ": 66,
"Security Systems & Services ": 63,
"Semiconductors ": 21,
"S&Ls/Savings Banks ": 25,
"Software & Programming ": 64,
"Textiles - Non Apparel ": 61,
"Tires ": 32,
"Tobacco ": 91,
"Trucking ": 52,
"Waste Management Services ": 23,
"Water Transportation ": 15,
"Water Utilities ": 80,
}
EQUITY_TYPES = [
"ORD",
"DRC",
"Preferred",
"Unit",
"ClosedEnd",
"REIT",
"ELKS",
"OpenEnd",
"Right",
"ParticipationShare",
"CapitalSecurity",
"PerpetualCapitalSecurity",
"GuaranteeCertificate",
"IGC",
"Warrant",
"SeniorNote",
"Debenture",
"ETF",
"ADR",
"ETC",
"ETN"
]
FILTERS = {
"Dividend": "eq_dividend",
"Dividend Yield": "yield_us",
"Dividend Yield 5YA": "yld5yavg_us",
"Dividend Growth Rate (ANN)": "divgrpct_us",
"Payout Ratio (TTM)": "ttmpayrat_us",
"EPS": "eq_eps",
"P/E Ratio (TTM)": "peexclxor_us",
"Price to Sales (TTM)": "ttmpr2rev_us",
"Price to Cash Flow (MRQ)": "aprfcfps_us",
"Price to Free Cash Flow (TTM)": "ttmprfcfps_us",
"Price to Book (MRQ)": "price2bk_us",
"Price to Tangible Book (MRQ)": "pr2tanbk_us",
"EPS(MRQ) vs Qtr. 1 Yr. Ago": "epschngyr_us",
"EPS(TTM) vs TTM 1 Yr. Ago": "ttmepschg_us",
"5 Year EPS Growth": "epstrendgr_us",
"Sales (MRQ) vs Qtr. 1 Yr. Ago": "revchngyr_us",
"Sales (TTM) vs TTM 1 Yr. Ago (TTM)": "ttmrevchg_us",
"5 Year Sales Growth": "revtrendgr_us",
"5 Year Capital Spending Growth": "csptrendgr_us",
"Asset Turnover (TTM)": "ttmastturn_us",
"Inventory Turnover (TTM)": "ttminvturn_us",
"Revenue/Employee (TTM)": "ttmrevpere_us",
"Net Income/Employee (TTM)": "ttmniperem_us",
"Receivable Turnover (TTM)": "ttmrecturn_us",
"P/E Ratio": "eq_pe_ratio",
"Market Cap": "eq_market_cap",
"1-Year Change": "eq_one_year_return",
"Average Vol. (3m)": "avg_volume",
"Last": "last",
"Daily Change (%)": "pair_change_percent",
"52 wk Range - High": "a52_week_high",
"52 wk Range - Low": "a52_week_low",
"% Change from 52 wk High": "a52_week_high_diff",
"% Change from 52 wk Low": "a52_week_low_diff",
"YTD % Return": "ytd",
"Previous Month % Change": "month_change",
"Volume": "turnover_volume",
"Beta": "eq_beta",
"Revenue": "eq_revenue",
"Gross margin (TTM)": "ttmgrosmgn_us",
"Gross Margin (5YA)": "grosmgn5yr_us",
"Operating margin (TTM)": "ttmopmgn_us",
"Operating margin (5YA)": "opmgn5yr_us",
"Pretax margin (TTM)": "ttmptmgn_us",
"Pretax margin (5YA)": "ptmgn5yr_us",
"Net Profit margin (TTM)": "ttmnpmgn_us",
"Net Profit margin (5YA)": "margin5yr_us",
"Quick Ratio (MRQ)": "qquickrati_us",
"Current Ratio (MRQ)": "qcurratio_us",
"LT Debt to Equity (MRQ)": "qltd2eq_us",
"Total Debt to Equity": "qtotd2eq_us",
"ADX (14 / 1D)": "ADX",
"ATR (14 / 1D)": "ATR",
"Bull/Bear Power (13 / 1D)": "BullBear",
"CCI (14 / 1D)": "CCI",
"Highs/Lows (14 / 1D)": "HL",
"MACD (12,26 / 1D)": "MACD",
"ROC (1D)": "ROC",
"RSI (14 / 1D)": "RSI",
"STOCH (14 / 1D)": "STOCH",
"STOCHRSI (14 / 1D)": "STOCHRSI",
"Ultimate Oscillator (14 /1D)": "UO",
"Williams %R (1D)": "WilliamsR",
}
class ScreenerParams(object):
"""
Return a new screener parameter builder.
You build up the parameters for the stock screener by using the methods in this class.
For example, to get all stocks in Spain with a market cap between EUR 20m and EUR 100m, with a P/E ratio under 20:
```
params = ip.ScreenerParams() \
.with_country("Spain") \
.add_equity_type("ORD") \
.add_filter("P/E Ratio (TTM)", 0, 20)
```
This object can be passed to the `screener()` function to retrieve the results
"""
def __init__(self):
self.country = 'United States'
# The set of valid exchanges depends on the country, so use all exchanges for now
self.exchange = -1
self.sectors = []
self.industries = []
self.equity_types = []
self.filters = {}
"""
Return a list of all valid sectors for the `add_sector` method
"""
def all_sectors(self):
return SECTORS.keys()
"""
Returns a list of all avilable countries
"""
def all_countries(self):
return COUNTRIES.keys()
"""
Returns a list of all valid industry classes for the `add_industry` method
"""
def all_industries(self):
return INDUSTRIES.keys()
"""
Returns a list of all valid equity types for the `add_equity_type` method
"""
def all_equity_types(self):
return EQUITY_TYPES
"""
Returns a list of all valid filters for the `add_filter` method
"""
def all_filters(self):
return FILTERS.keys()
"""
Define the country to use in the screener.
Calling this method twice will overwrite the country filter.
The default value is "United States" if you do not use this method.
To see a list of valid countries, use `all_countries`
"""
def with_country(self, country):
if not country:
raise ValueError("ERR#0039: country can not be None, it should be a str.")
if not country in COUNTRIES.keys():
raise ValueError("ERR#00??: %s is not a valid country")
self.country = country
return self
"""
Add a sector to use in the screener.
Calling this method multiple times will add the sector to the list to retrieve.
The default is to search all sectors.
To see a list of valid sectors, use `all_sectors`
"""
def add_sector(self, sector):
if not sector:
raise ValueError("ERR#00??: sector can not be None, it should be a str.")
if not sector in SECTORS.keys():
raise ValueError("ERR#00??: %s is not a valid sector")
self.sectors.append(sector)
return self
"""
Add an industry to use in the screener.
Calling this method multiple times will add the industry to the list to retrieve.
The default is to search all industries.
To see a list of valid industries, use `all_industries`
"""
def add_industry(self, industry):
if not industry:
raise ValueError("ERR#00??: industry can not be None, it should be a str.")
if not industry in INDUSTRIES.keys():
raise ValueError("ERR#00??: %s is not a valid industry")
self.industries.append(industry)
return self
"""
Add an equity type to use in the screener.
Calling this method multiple times will add the equity type to the list to retrieve.
The default is to search all equity types.
To see a list of valid equity types, use `all_equity_types`
"""
def add_equity_type(self, equity_type):
if not equity_type:
raise ValueError("ERR#00??: equity_type can not be None, it should be a str.")
if not equity_type in EQUITY_TYPES:
raise ValueError("ERR#00??: %s is not a valid equity_type")
self.equity_types.append(equity_type)
return self
"""
Add a filter to use in the screener.
Calling this method multiple times will add the filter to the list to retrieve.
Each filter requires a minimum and a maximum value to use to search the stocks.
To see a list of valid filters, use `all_filters`
"""
def add_filter(self, filter, min=0.0, max=100.0):
if not filter:
raise ValueError("ERR#00??: filter can not be None, it should be a str.")
if not filter in FILTERS.keys():
raise ValueError("ERR#00??: %s is not a valid filter")
self.filters[filter] = {"min": min, "max": max}
return self
"""
Builds the request form object using the values in the builder. You don't have
to call tis method yourself. It is used in the `screener` to build the parameters
for the query to Investing.com's stock screener tool.
"""
def finish(self):
data = {}
data["country[]"] = COUNTRIES[self.country]
data["sector"] = join_arr(self.sectors, SECTORS)
data["industry"] = join_arr(self.industries, INDUSTRIES)
data["equityType"] = join_equities(self.equity_types)
# data["exchange[]"] is omitted for all exchanges
data["order[col]"] = 'name_trans'
data["order[dir]"] = 'a'
data["pn"] = 1
build_filters(data, self.filters)
return data
def join_arr(arr, dict):
if len(arr) == 0:
entries = [str(v) for v in dict.values()]
else:
entries = [str(dict[v]) for v in arr]
return ",".join(entries)
def join_equities(arr):
entries = EQUITY_TYPES if len(arr) == 0 else arr
return ",".join(entries)
def build_filters(data, filters):
for filter in filters:
key = FILTERS[filter]
data["%s[min]" % (key,)] = filters[filter]["min"]
data["%s[max]" % (key,)] = filters[filter]["max"]
| countries = {'United States': 5, 'Argentina': 29, 'Australia': 25, 'Austria': 54, 'Bahrain': 145, 'Bangladesh': 47, 'Belgium': 34, 'Bosnia-Herzegovina': 174, 'Botswana': 163, 'Brazil': 32, 'Bulgaria': 70, 'Canada': 6, 'Chile': 27, 'China': 37, 'Colombia': 122, 'Costa Rica': 15, "Cote D'Ivoire": 78, 'Croatia': 113, 'Cyprus': 107, 'Czech Republic': 55, 'Denmark': 24, 'Egypt': 59, 'Euro Zone': 72, 'Finland': 71, 'France': 22, 'Germany': 17, 'Greece': 51, 'Hong Kong': 39, 'Hungary': 93, 'Iceland': 106, 'India': 14, 'Indonesia': 48, 'Iraq': 66, 'Ireland': 33, 'Israel': 23, 'Italy': 10, 'Jamaica': 119, 'Japan': 35, 'Jordan': 92, 'Kazakhstan': 102, 'Kenya': 57, 'Kuwait': 94, 'Lebanon': 68, 'Luxembourg': 103, 'Malawi': 111, 'Malaysia': 42, 'Malta': 109, 'Mauritius': 188, 'Mexico': 7, 'Mongolia': 139, 'Montenegro': 247, 'Morocco': 105, 'Namibia': 172, 'Netherlands': 21, 'New Zealand': 43, 'Nigeria': 20, 'Norway': 60, 'Oman': 87, 'Pakistan': 44, 'Palestinian Territory': 193, 'Peru': 125, 'Philippines': 45, 'Poland': 53, 'Portugal': 38, 'Qatar': 170, 'Romania': 100, 'Russia': 56, 'Rwanda': 80, 'Saudi Arabia': 52, 'Serbia': 238, 'Singapore': 36, 'Slovakia': 90, 'Slovenia': 112, 'South Africa': 110, 'South Korea': 11, 'Spain': 26, 'Sri Lanka': 162, 'Sweden': 9, 'Switzerland': 12, 'Taiwan': 46, 'Tanzania': 85, 'Thailand': 41, 'Tunisia': 202, 'Turkey': 63, 'Uganda': 123, 'Ukraine': 61, 'United Arab Emirates': 143, 'United Kingdom': 4, 'Venezuela': 138, 'Vietnam': 178, 'Zambia': 84, 'Zimbabwe': 75}
sectors = {'Basic Materials': 7, 'Capital Goods': 5, 'Conglomerates': 12, 'Consumer Cyclical': 3, 'Consumer/Non-Cyclical': 8, 'Energy': 9, 'Financial': 1, 'Healthcare': 6, 'Services': 2, 'Technology': 4, 'Transportation': 10, 'Utilities': 11}
industries = {'Advertising ': 81, 'Aerospace & Defense ': 56, 'Air Courier ': 59, 'Airline ': 41, 'Apparel/Accessories ': 68, 'Appliance & Tool ': 67, 'Audio & Video Equipment ': 88, 'Auto & Truck Manufacturers ': 51, 'Auto & Truck Parts ': 72, 'Beverages (Alcoholic) ': 47, 'Beverages (Nonalcoholic) ': 12, 'Biotechnology & Drugs ': 8, 'Broadcasting & Cable TV ': 50, 'Business Services ': 2, 'Casinos & Gaming ': 71, 'Chemical Manufacturing ': 9, 'Chemicals - Plastics & Rubber ': 69, 'Coal ': 45, 'Communications Equipment ': 46, 'Communications Services ': 13, 'Computer Hardware ': 94, 'Computer Networks ': 102, 'Computer Peripherals ': 95, 'Computer Services ': 58, 'Computer Storage Devices ': 100, 'Conglomerates ': 101, 'Constr. & Agric. Machinery ': 87, 'Constr. - Supplies & Fixtures ': 31, 'Construction - Raw Materials ': 6, 'Construction Services ': 38, 'Consumer Financial Services ': 79, 'Containers & Packaging ': 30, 'Crops ': 77, 'Electric Utilities ': 28, 'Electronic Instr. & Controls ': 5, 'Fabricated Plastic & Rubber ': 60, 'Fish/Livestock ': 18, 'Food Processing ': 26, 'Footwear ': 44, 'Forestry & Wood Products ': 35, 'Furniture & Fixtures ': 53, 'Gold & Silver ': 48, 'Healthcare Facilities ': 49, 'Hotels & Motels ': 55, 'Insurance (Accident & Health) ': 78, 'Insurance (Life) ': 7, 'Insurance (Miscellaneous) ': 86, 'Insurance (Prop. & Casualty) ': 10, 'Investment Services ': 1, 'Iron & Steel ': 34, 'Jewelry & Silverware ': 3, 'Major Drugs ': 11, 'Medical Equipment & Supplies ': 62, 'Metal Mining ': 16, 'Misc. Capital Goods ': 24, 'Misc. Fabricated Products ': 20, 'Misc. Financial Services ': 54, 'Misc. Transportation ': 33, 'Mobile Homes & RVs ': 83, 'Money Center Banks ': 29, 'Motion Pictures ': 76, 'Natural Gas Utilities ': 37, 'Non-Metallic Mining ': 90, 'Office Equipment ': 85, 'Office Supplies ': 82, 'Oil & Gas - Integrated ': 22, 'Oil & Gas Operations ': 14, 'Oil Well Services & Equipment ': 17, 'Paper & Paper Products ': 19, 'Personal & Household Prods. ': 43, 'Personal Services ': 89, 'Photography ': 96, 'Printing & Publishing ': 57, 'Printing Services ': 84, 'Railroads ': 93, 'Real Estate Operations ': 27, 'Recreational Activities ': 74, 'Recreational Products ': 97, 'Regional Banks ': 4, 'Rental & Leasing ': 73, 'Restaurants ': 36, 'Retail (Apparel) ': 42, 'Retail (Catalog & Mail Order) ': 98, 'Retail (Department & Discount) ': 65, 'Retail (Drugs) ': 70, 'Retail (Grocery) ': 40, 'Retail (Home Improvement) ': 99, 'Retail (Specialty) ': 39, 'Retail (Technology) ': 92, 'Schools ': 75, 'Scientific & Technical Instr. ': 66, 'Security Systems & Services ': 63, 'Semiconductors ': 21, 'S&Ls/Savings Banks ': 25, 'Software & Programming ': 64, 'Textiles - Non Apparel ': 61, 'Tires ': 32, 'Tobacco ': 91, 'Trucking ': 52, 'Waste Management Services ': 23, 'Water Transportation ': 15, 'Water Utilities ': 80}
equity_types = ['ORD', 'DRC', 'Preferred', 'Unit', 'ClosedEnd', 'REIT', 'ELKS', 'OpenEnd', 'Right', 'ParticipationShare', 'CapitalSecurity', 'PerpetualCapitalSecurity', 'GuaranteeCertificate', 'IGC', 'Warrant', 'SeniorNote', 'Debenture', 'ETF', 'ADR', 'ETC', 'ETN']
filters = {'Dividend': 'eq_dividend', 'Dividend Yield': 'yield_us', 'Dividend Yield 5YA': 'yld5yavg_us', 'Dividend Growth Rate (ANN)': 'divgrpct_us', 'Payout Ratio (TTM)': 'ttmpayrat_us', 'EPS': 'eq_eps', 'P/E Ratio (TTM)': 'peexclxor_us', 'Price to Sales (TTM)': 'ttmpr2rev_us', 'Price to Cash Flow (MRQ)': 'aprfcfps_us', 'Price to Free Cash Flow (TTM)': 'ttmprfcfps_us', 'Price to Book (MRQ)': 'price2bk_us', 'Price to Tangible Book (MRQ)': 'pr2tanbk_us', 'EPS(MRQ) vs Qtr. 1 Yr. Ago': 'epschngyr_us', 'EPS(TTM) vs TTM 1 Yr. Ago': 'ttmepschg_us', '5 Year EPS Growth': 'epstrendgr_us', 'Sales (MRQ) vs Qtr. 1 Yr. Ago': 'revchngyr_us', 'Sales (TTM) vs TTM 1 Yr. Ago (TTM)': 'ttmrevchg_us', '5 Year Sales Growth': 'revtrendgr_us', '5 Year Capital Spending Growth': 'csptrendgr_us', 'Asset Turnover (TTM)': 'ttmastturn_us', 'Inventory Turnover (TTM)': 'ttminvturn_us', 'Revenue/Employee (TTM)': 'ttmrevpere_us', 'Net Income/Employee (TTM)': 'ttmniperem_us', 'Receivable Turnover (TTM)': 'ttmrecturn_us', 'P/E Ratio': 'eq_pe_ratio', 'Market Cap': 'eq_market_cap', '1-Year Change': 'eq_one_year_return', 'Average Vol. (3m)': 'avg_volume', 'Last': 'last', 'Daily Change (%)': 'pair_change_percent', '52 wk Range - High': 'a52_week_high', '52 wk Range - Low': 'a52_week_low', '% Change from 52 wk High': 'a52_week_high_diff', '% Change from 52 wk Low': 'a52_week_low_diff', 'YTD % Return': 'ytd', 'Previous Month % Change': 'month_change', 'Volume': 'turnover_volume', 'Beta': 'eq_beta', 'Revenue': 'eq_revenue', 'Gross margin (TTM)': 'ttmgrosmgn_us', 'Gross Margin (5YA)': 'grosmgn5yr_us', 'Operating margin (TTM)': 'ttmopmgn_us', 'Operating margin (5YA)': 'opmgn5yr_us', 'Pretax margin (TTM)': 'ttmptmgn_us', 'Pretax margin (5YA)': 'ptmgn5yr_us', 'Net Profit margin (TTM)': 'ttmnpmgn_us', 'Net Profit margin (5YA)': 'margin5yr_us', 'Quick Ratio (MRQ)': 'qquickrati_us', 'Current Ratio (MRQ)': 'qcurratio_us', 'LT Debt to Equity (MRQ)': 'qltd2eq_us', 'Total Debt to Equity': 'qtotd2eq_us', 'ADX (14 / 1D)': 'ADX', 'ATR (14 / 1D)': 'ATR', 'Bull/Bear Power (13 / 1D)': 'BullBear', 'CCI (14 / 1D)': 'CCI', 'Highs/Lows (14 / 1D)': 'HL', 'MACD (12,26 / 1D)': 'MACD', 'ROC (1D)': 'ROC', 'RSI (14 / 1D)': 'RSI', 'STOCH (14 / 1D)': 'STOCH', 'STOCHRSI (14 / 1D)': 'STOCHRSI', 'Ultimate Oscillator (14 /1D)': 'UO', 'Williams %R (1D)': 'WilliamsR'}
class Screenerparams(object):
"""
Return a new screener parameter builder.
You build up the parameters for the stock screener by using the methods in this class.
For example, to get all stocks in Spain with a market cap between EUR 20m and EUR 100m, with a P/E ratio under 20:
```
params = ip.ScreenerParams() .with_country("Spain") .add_equity_type("ORD") .add_filter("P/E Ratio (TTM)", 0, 20)
```
This object can be passed to the `screener()` function to retrieve the results
"""
def __init__(self):
self.country = 'United States'
self.exchange = -1
self.sectors = []
self.industries = []
self.equity_types = []
self.filters = {}
'\n Return a list of all valid sectors for the `add_sector` method \n '
def all_sectors(self):
return SECTORS.keys()
'\n Returns a list of all avilable countries\n '
def all_countries(self):
return COUNTRIES.keys()
'\n Returns a list of all valid industry classes for the `add_industry` method\n '
def all_industries(self):
return INDUSTRIES.keys()
'\n Returns a list of all valid equity types for the `add_equity_type` method\n '
def all_equity_types(self):
return EQUITY_TYPES
'\n Returns a list of all valid filters for the `add_filter` method\n '
def all_filters(self):
return FILTERS.keys()
'\n Define the country to use in the screener. \n \n Calling this method twice will overwrite the country filter.\n \n The default value is "United States" if you do not use this method.\n \n To see a list of valid countries, use `all_countries`\n '
def with_country(self, country):
if not country:
raise value_error('ERR#0039: country can not be None, it should be a str.')
if not country in COUNTRIES.keys():
raise value_error('ERR#00??: %s is not a valid country')
self.country = country
return self
'\n Add a sector to use in the screener. \n \n Calling this method multiple times will add the sector to the list to retrieve.\n The default is to search all sectors.\n \n To see a list of valid sectors, use `all_sectors`\n '
def add_sector(self, sector):
if not sector:
raise value_error('ERR#00??: sector can not be None, it should be a str.')
if not sector in SECTORS.keys():
raise value_error('ERR#00??: %s is not a valid sector')
self.sectors.append(sector)
return self
'\n Add an industry to use in the screener. \n \n Calling this method multiple times will add the industry to the list to retrieve.\n The default is to search all industries.\n \n To see a list of valid industries, use `all_industries`\n '
def add_industry(self, industry):
if not industry:
raise value_error('ERR#00??: industry can not be None, it should be a str.')
if not industry in INDUSTRIES.keys():
raise value_error('ERR#00??: %s is not a valid industry')
self.industries.append(industry)
return self
'\n Add an equity type to use in the screener. \n \n Calling this method multiple times will add the equity type to the list to retrieve.\n The default is to search all equity types.\n \n To see a list of valid equity types, use `all_equity_types`\n '
def add_equity_type(self, equity_type):
if not equity_type:
raise value_error('ERR#00??: equity_type can not be None, it should be a str.')
if not equity_type in EQUITY_TYPES:
raise value_error('ERR#00??: %s is not a valid equity_type')
self.equity_types.append(equity_type)
return self
'\n Add a filter to use in the screener. \n \n Calling this method multiple times will add the filter to the list to retrieve.\n \n Each filter requires a minimum and a maximum value to use to search the stocks.\n \n To see a list of valid filters, use `all_filters`\n '
def add_filter(self, filter, min=0.0, max=100.0):
if not filter:
raise value_error('ERR#00??: filter can not be None, it should be a str.')
if not filter in FILTERS.keys():
raise value_error('ERR#00??: %s is not a valid filter')
self.filters[filter] = {'min': min, 'max': max}
return self
"\n Builds the request form object using the values in the builder. You don't have\n to call tis method yourself. It is used in the `screener` to build the parameters\n for the query to Investing.com's stock screener tool.\n "
def finish(self):
data = {}
data['country[]'] = COUNTRIES[self.country]
data['sector'] = join_arr(self.sectors, SECTORS)
data['industry'] = join_arr(self.industries, INDUSTRIES)
data['equityType'] = join_equities(self.equity_types)
data['order[col]'] = 'name_trans'
data['order[dir]'] = 'a'
data['pn'] = 1
build_filters(data, self.filters)
return data
def join_arr(arr, dict):
if len(arr) == 0:
entries = [str(v) for v in dict.values()]
else:
entries = [str(dict[v]) for v in arr]
return ','.join(entries)
def join_equities(arr):
entries = EQUITY_TYPES if len(arr) == 0 else arr
return ','.join(entries)
def build_filters(data, filters):
for filter in filters:
key = FILTERS[filter]
data['%s[min]' % (key,)] = filters[filter]['min']
data['%s[max]' % (key,)] = filters[filter]['max'] |
# Uses python3
def edit_distance(s, t):
#write your code here
m , n = len(s) , len(t)
dp=[[0 for i in range(n+1)] for j in range(m+1)]
for i in range(m+1): dp[i][0]=i
for j in range(n+1): dp[0][j]=j;
for i in range(1,m+1):
for j in range(1,n+1):
dp[i][j]=min(dp[i-1][j-1] + (0 if s[i-1]==t[j-1] else 1) , \
min(dp[i-1][j]+1,dp[i][j-1]+1) )
return dp[m][n]
if __name__ == "__main__":
print(edit_distance(input(), input()))
| def edit_distance(s, t):
(m, n) = (len(s), len(t))
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = min(dp[i - 1][j - 1] + (0 if s[i - 1] == t[j - 1] else 1), min(dp[i - 1][j] + 1, dp[i][j - 1] + 1))
return dp[m][n]
if __name__ == '__main__':
print(edit_distance(input(), input())) |
c1_list = list(map(int, input().split()))
c2_list = list(map(int, input().split()))
c3_list = list(map(int, input().split()))
for a1 in range(0, 101):
for a2 in range(0, 101):
for a3 in range(0, 101):
b1 = c1_list[0] - a1
b2 = c1_list[1] - a1
b3 = c1_list[2] - a1
if c2_list[0] == a2+b1 and c2_list[1] == a2+b2 \
and c2_list[2] == a2 + b3 and c3_list[0] == a3 + b1 \
and c3_list[1] == a3 + b2 and c3_list[2] == a3 + b3:
print("Yes")
exit()
print("No")
| c1_list = list(map(int, input().split()))
c2_list = list(map(int, input().split()))
c3_list = list(map(int, input().split()))
for a1 in range(0, 101):
for a2 in range(0, 101):
for a3 in range(0, 101):
b1 = c1_list[0] - a1
b2 = c1_list[1] - a1
b3 = c1_list[2] - a1
if c2_list[0] == a2 + b1 and c2_list[1] == a2 + b2 and (c2_list[2] == a2 + b3) and (c3_list[0] == a3 + b1) and (c3_list[1] == a3 + b2) and (c3_list[2] == a3 + b3):
print('Yes')
exit()
print('No') |
class _GTF(object):
def __init__(self, path):
""""""
self.file = open(path, "r")
self.header={}
def read(path):
""""""
... | class _Gtf(object):
def __init__(self, path):
""""""
self.file = open(path, 'r')
self.header = {}
def read(path):
""""""
... |
class ListViewAlignment(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies how items align in the System.Windows.Forms.ListView.
enum ListViewAlignment,values: Default (0),Left (1),SnapToGrid (5),Top (2)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
Default=None
Left=None
SnapToGrid=None
Top=None
value__=None
| class Listviewalignment(Enum, IComparable, IFormattable, IConvertible):
"""
Specifies how items align in the System.Windows.Forms.ListView.
enum ListViewAlignment,values: Default (0),Left (1),SnapToGrid (5),Top (2)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self, *args):
pass
def __gt__(self, *args):
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args):
pass
def __lt__(self, *args):
pass
def __ne__(self, *args):
pass
def __reduce_ex__(self, *args):
pass
def __str__(self, *args):
pass
default = None
left = None
snap_to_grid = None
top = None
value__ = None |
class DrawFromEmptyServer(Exception):
"""Attempted to draw from an empty R&D (corp loses)."""
class ChoiceRequiredError(Exception):
"""A choice is required for."""
class InvalidPaymentChoice(Exception):
"""An invalid payment choice has been made."""
class CostNotSatisfied(Exception):
"""Required costs are not met."""
class InsufficientFunds(Exception):
"""Attempt to draw more out of a resource pool than exists."""
class InvalidResponse(Exception):
"""The response sent by the client is invalid."""
| class Drawfromemptyserver(Exception):
"""Attempted to draw from an empty R&D (corp loses)."""
class Choicerequirederror(Exception):
"""A choice is required for."""
class Invalidpaymentchoice(Exception):
"""An invalid payment choice has been made."""
class Costnotsatisfied(Exception):
"""Required costs are not met."""
class Insufficientfunds(Exception):
"""Attempt to draw more out of a resource pool than exists."""
class Invalidresponse(Exception):
"""The response sent by the client is invalid.""" |
"""
Exceptions are errors
"""
def exceptionHandling():
try:
a = 10
b = 20
c = 0
d = (a + b) / c
print(d)
except:
print("In the except block")
else:
print("Because there was no exception, else is executed")
finally:
print("Finally, always executed")
exceptionHandling() | """
Exceptions are errors
"""
def exception_handling():
try:
a = 10
b = 20
c = 0
d = (a + b) / c
print(d)
except:
print('In the except block')
else:
print('Because there was no exception, else is executed')
finally:
print('Finally, always executed')
exception_handling() |
def linear_truth():
#truth1
tree = Tree(name='N1', size=3)
node2 = tree.create_node('N2',tree.root,2)
node3 = tree.create_node('N3',node2,3)
node4 = tree.create_node('N4',node3,3)
return tree
def linear_branching_truth():
#truth2
tree = Tree(name='N1', size=3)
node2 = tree.create_node('N2',tree.root,2)
node3 = tree.create_node('N3',node2,3)
node4 = tree.create_node('N4',node2,3)
return tree
def branching_to_linear(tree):
#truth1 as a mistake for truth1
tree.switch_parent('N4','N3')
return tree
def split_four(tree, prop_split=0.5):
#corresponds to 2
# print tree.nodes[1].children
if(tree.nodes[1].children.size > 1): #if branching
tree.switch_parent('N4','N3')
tree.split_node('N4','N5',prop_split=prop_split, same=True)
return tree
def collapse_bottom_clusters(tree):
#corresponds to 3
tree.merge_nodes('N3','N4')
return tree
def collapse_all_clusters_and_extra(tree, extra_prop=0.5):
#corresponds to 15
tree.collapse_node('N2')
tree.extra_node(extra_prop, 'N2')
return tree
def extra_two(tree, extra_prop=0.5):
#corresponds to 4
tree.extra_node(extra_prop,'N2')
return tree
def collapse_mid(tree):
#corresponds to 5
tree.merge_nodes('N2','N3')
return(tree)
def extra_four(tree, extra_prop=0.5):
#corresponds to 6
tree.extra_node(extra_prop,'N4')
return tree
def split_four_lin(tree):
#corresponds to 13
if(tree.nodes[1].children.size > 1): #if branching
tree.switch_parent('N4','N3')
tree.split_node('N4','N5',same=False)
return tree
def split_three_from_two(tree):
#corresponds to 13
if(tree.nodes[1].children.size > 1): #if branching
tree.switch_parent('N4','N3')
tree.split_node('N3','N5',same=True)
return tree
def collapse_all_bottom(tree):
tree.collapse_node('N2')
return tree
def extra_one(tree, extra_prop=0.5):
#corresponds to 11
tree.extra_node(extra_prop,'N1', transfer_children=True)
return tree
def extra_root(tree, extra_prop=0.5):
#corresponds to 12
tree.extra_node(extra_prop,None, transfer_children=True)
return tree
def extra_one_switch_three(tree, extra_prop=0.5):
#corresponds to 8
if(tree.nodes[1].children.size > 1): #if branching
tree.switch_parent('N4','N3')
tree.switch_parent('N3', 'N1')
tree.extra_node(extra_prop,'N1', transfer_children=True)
return tree
def three_from_one(tree):
#corresponds to 9
if(tree.nodes[1].children.size > 1): #if branching
tree.switch_parent('N4','N3')
tree.switch_parent('N3','N1')
return(tree)
def three_from_one(tree):
#corresponds to 10
if(tree.nodes[1].children.size == 1): #if branching
tree.switch_parent('N4','N2')
tree.switch_parent('N3','N1')
return(tree)
scenarios ={
'T1' : linear_truth,
'T2' : linear_branching_truth,
'S2' : split_four,
'S3' : collapse_bottom_clusters,
'S4' : extra_two
}
| def linear_truth():
tree = tree(name='N1', size=3)
node2 = tree.create_node('N2', tree.root, 2)
node3 = tree.create_node('N3', node2, 3)
node4 = tree.create_node('N4', node3, 3)
return tree
def linear_branching_truth():
tree = tree(name='N1', size=3)
node2 = tree.create_node('N2', tree.root, 2)
node3 = tree.create_node('N3', node2, 3)
node4 = tree.create_node('N4', node2, 3)
return tree
def branching_to_linear(tree):
tree.switch_parent('N4', 'N3')
return tree
def split_four(tree, prop_split=0.5):
if tree.nodes[1].children.size > 1:
tree.switch_parent('N4', 'N3')
tree.split_node('N4', 'N5', prop_split=prop_split, same=True)
return tree
def collapse_bottom_clusters(tree):
tree.merge_nodes('N3', 'N4')
return tree
def collapse_all_clusters_and_extra(tree, extra_prop=0.5):
tree.collapse_node('N2')
tree.extra_node(extra_prop, 'N2')
return tree
def extra_two(tree, extra_prop=0.5):
tree.extra_node(extra_prop, 'N2')
return tree
def collapse_mid(tree):
tree.merge_nodes('N2', 'N3')
return tree
def extra_four(tree, extra_prop=0.5):
tree.extra_node(extra_prop, 'N4')
return tree
def split_four_lin(tree):
if tree.nodes[1].children.size > 1:
tree.switch_parent('N4', 'N3')
tree.split_node('N4', 'N5', same=False)
return tree
def split_three_from_two(tree):
if tree.nodes[1].children.size > 1:
tree.switch_parent('N4', 'N3')
tree.split_node('N3', 'N5', same=True)
return tree
def collapse_all_bottom(tree):
tree.collapse_node('N2')
return tree
def extra_one(tree, extra_prop=0.5):
tree.extra_node(extra_prop, 'N1', transfer_children=True)
return tree
def extra_root(tree, extra_prop=0.5):
tree.extra_node(extra_prop, None, transfer_children=True)
return tree
def extra_one_switch_three(tree, extra_prop=0.5):
if tree.nodes[1].children.size > 1:
tree.switch_parent('N4', 'N3')
tree.switch_parent('N3', 'N1')
tree.extra_node(extra_prop, 'N1', transfer_children=True)
return tree
def three_from_one(tree):
if tree.nodes[1].children.size > 1:
tree.switch_parent('N4', 'N3')
tree.switch_parent('N3', 'N1')
return tree
def three_from_one(tree):
if tree.nodes[1].children.size == 1:
tree.switch_parent('N4', 'N2')
tree.switch_parent('N3', 'N1')
return tree
scenarios = {'T1': linear_truth, 'T2': linear_branching_truth, 'S2': split_four, 'S3': collapse_bottom_clusters, 'S4': extra_two} |
def map_inputs(user, all_data, data_name, id_list):
text_input = all_data[data_name]
capitalized = text_input.upper()
return {id_list[0]:capitalized}
| def map_inputs(user, all_data, data_name, id_list):
text_input = all_data[data_name]
capitalized = text_input.upper()
return {id_list[0]: capitalized} |
class TSGError(Exception):
pass
class FailedToParse(TSGError):
pass
| class Tsgerror(Exception):
pass
class Failedtoparse(TSGError):
pass |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Events',
'version': '1.1',
'category': 'Marketing/Events',
'sequence': 140,
'summary': 'Publish events, sell tickets',
'website': 'https://www.odoo.com/page/events',
'description': "",
'depends': [
'event',
'website',
'website_partner',
'website_mail',
],
'data': [
'data/event_data.xml',
'views/assets.xml',
'views/res_config_settings_views.xml',
'views/event_snippets.xml',
'views/event_templates_list.xml',
'views/event_templates_page.xml',
'views/event_templates_page_registration.xml',
'views/event_templates_page_misc.xml',
'views/event_templates_widgets.xml',
'views/website_templates.xml',
'views/event_event_views.xml',
'views/event_registration_views.xml',
'views/event_type_views.xml',
'views/website_event_menu_views.xml',
'views/website_visitor_views.xml',
'views/event_menus.xml',
'security/ir.model.access.csv',
'security/event_security.xml',
],
'demo': [
'data/res_partner_demo.xml',
'data/website_visitor_demo.xml',
'data/event_demo.xml',
'data/event_registration_demo.xml',
],
'application': True,
'license': 'LGPL-3',
}
| {'name': 'Events', 'version': '1.1', 'category': 'Marketing/Events', 'sequence': 140, 'summary': 'Publish events, sell tickets', 'website': 'https://www.odoo.com/page/events', 'description': '', 'depends': ['event', 'website', 'website_partner', 'website_mail'], 'data': ['data/event_data.xml', 'views/assets.xml', 'views/res_config_settings_views.xml', 'views/event_snippets.xml', 'views/event_templates_list.xml', 'views/event_templates_page.xml', 'views/event_templates_page_registration.xml', 'views/event_templates_page_misc.xml', 'views/event_templates_widgets.xml', 'views/website_templates.xml', 'views/event_event_views.xml', 'views/event_registration_views.xml', 'views/event_type_views.xml', 'views/website_event_menu_views.xml', 'views/website_visitor_views.xml', 'views/event_menus.xml', 'security/ir.model.access.csv', 'security/event_security.xml'], 'demo': ['data/res_partner_demo.xml', 'data/website_visitor_demo.xml', 'data/event_demo.xml', 'data/event_registration_demo.xml'], 'application': True, 'license': 'LGPL-3'} |
# Certain parameters
R = 8.314 # gas constant
T_F = 25 + 273.15 # feed temperature
E_a = 8500.0 # activation energy
delH_R = 950.0 * 1.00 # sp reaction enthalpy
A_tank = 65.0 # area heat exchanger surface jacket 65
k_0 = 7.0 * 1.00 # sp reaction rate
k_U2 = 32.0 # reaction parameter 1
k_U1 = 4.0 # reaction parameter 2
w_WF = .333 # mass fraction water in feed
w_AF = .667 # mass fraction of A in feed
m_M_KW = 5000.0 # mass of coolant in jacket
fm_M_KW = 300000.0 # coolant flow in jacket 300000;
m_AWT_KW = 1000.0 # mass of coolant in EHE
fm_AWT_KW = 100000.0 # coolant flow in EHE
m_AWT = 200.0 # mass of product in EHE
fm_AWT = 20000.0 # product flow in EHE
m_S = 39000.0 # mass of reactor steel
c_pW = 4.2 # sp heat cap coolant
c_pS = .47 # sp heat cap steel
c_pF = 3.0 # sp heat cap feed
c_pR = 5.0 # sp heat cap reactor contents
k_WS = 17280.0 # heat transfer coeff water-steel
k_AS = 3600.0 # heat transfer coeff monomer-steel
k_PS = 360.0 # heat transfer coeff product-steel
alfa = 5 * 20e4 * 3.6
p_1 = 1.0
| r = 8.314
t_f = 25 + 273.15
e_a = 8500.0
del_h_r = 950.0 * 1.0
a_tank = 65.0
k_0 = 7.0 * 1.0
k_u2 = 32.0
k_u1 = 4.0
w_wf = 0.333
w_af = 0.667
m_m_kw = 5000.0
fm_m_kw = 300000.0
m_awt_kw = 1000.0
fm_awt_kw = 100000.0
m_awt = 200.0
fm_awt = 20000.0
m_s = 39000.0
c_p_w = 4.2
c_p_s = 0.47
c_p_f = 3.0
c_p_r = 5.0
k_ws = 17280.0
k_as = 3600.0
k_ps = 360.0
alfa = 5 * 200000.0 * 3.6
p_1 = 1.0 |
def make_car(manufacturer, model_name, **car_info):
car_info['manufacturer'] = manufacturer
car_info['model_name'] = model_name
return car_info
cars = make_car('suburu', 'outback', color = 'blue', tow_package = True)
print(cars) | def make_car(manufacturer, model_name, **car_info):
car_info['manufacturer'] = manufacturer
car_info['model_name'] = model_name
return car_info
cars = make_car('suburu', 'outback', color='blue', tow_package=True)
print(cars) |
class Solution:
def longestMountain(self, A: List[int]) -> int:
result = base = 0
while base < len(A):
end = base
if end + 1 < len(A) and A[end] < A[end + 1]:
while end + 1 < len(A) and A[end] < A[end + 1]:
end += 1
if end + 1 < len(A) and A[end] > A[end + 1]:
while end + 1 < len(A) and A[end] > A[end + 1]:
end += 1
result = max(result, end - base + 1)
base = max(end, base + 1)
return result | class Solution:
def longest_mountain(self, A: List[int]) -> int:
result = base = 0
while base < len(A):
end = base
if end + 1 < len(A) and A[end] < A[end + 1]:
while end + 1 < len(A) and A[end] < A[end + 1]:
end += 1
if end + 1 < len(A) and A[end] > A[end + 1]:
while end + 1 < len(A) and A[end] > A[end + 1]:
end += 1
result = max(result, end - base + 1)
base = max(end, base + 1)
return result |
class PlatformOutput(object):
# ==========================================================================
# C8200
# ==========================================================================
showVersion = {
'version': {
'chassis': 'C8200-1N-4T',
'chassis_sn': 'FGL2420L6EE',
'compiled_by': 'mcpre',
'compiled_date': 'Fri 16-Oct-20 19:08',
'curr_config_register': '0x2102',
'disks': {
'bootflash:.': {
'disk_size': '7090175',
'type_of_disk': 'flash memory',
},
'harddisk:.': {
'disk_size': '585924608',
'type_of_disk': 'NVMe SSD',
},
'usb0:.': {
'disk_size': '16789568',
'type_of_disk': 'USB flash',
},
},
'hostname': 'cEdge-P2',
'image_id': 'X86_64_LINUX_IOSD-UNIVERSALK9-M',
'image_type': 'developer image',
'last_reload_reason': 'SMU Install',
'main_mem': '3753847',
'mem_size': {
'non-volatile configuration': '32768',
'physical': '8388608',
},
'number_of_intfs': {
'Cellular': '2',
'Gigabit Ethernet': '4',
'Serial': '4',
},
'os': 'IOS-XE',
'platform': 'c8000be',
'processor_board_flash': '7203041280',
'processor_type': '1RU',
'returned_to_rom_by': 'SMU Install',
'rom': 'PROM-20200723',
'rtr_type': 'C8200-1N-4T',
'system_image': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin',
'uptime': '31 minutes',
'uptime_this_cp': '32 minutes',
'version': '17.5.20201016:181710',
'version_short': '17.5',
},
}
showDir = {
'dir': {
'bootflash:/': {
'bytes_free': '2294001664',
'bytes_total': '7203041280',
'files': {
'.PATCH': {
'index': '362881',
'last_modified_date': 'Nov 18 2020 06:39:41 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'.PATCH-backup': {
'index': '225793',
'last_modified_date': 'Nov 18 2020 06:35:08 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'.cdb_backup': {
'index': '282241',
'last_modified_date': 'Jun 9 2020 20:11:42 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'.dbpersist': {
'index': '290305',
'last_modified_date': 'Nov 16 2020 05:11:08 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'.geo': {
'index': '137089',
'last_modified_date': 'Jun 21 2020 19:08:46 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'.iox_dir_list': {
'index': '29',
'last_modified_date': 'Oct 30 2020 18:58:56 +00:00',
'permissions': '-rw-',
'size': '275',
},
'.prst_sync': {
'index': '411265',
'last_modified_date': 'Nov 18 2020 06:36:19 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'.rollback_timer': {
'index': '8065',
'last_modified_date': 'Nov 18 2020 06:39:14 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'.sdwaninstaller': {
'index': '298369',
'last_modified_date': 'Nov 18 2020 06:39:43 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'.sdwaninstallerfs': {
'index': '18',
'last_modified_date': 'Nov 16 2020 05:11:48 +00:00',
'permissions': '-rw-',
'size': '419430400',
},
'.sdwaninternal': {
'index': '96769',
'last_modified_date': 'Jun 9 2020 20:03:48 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'.ssh': {
'index': '403201',
'last_modified_date': 'Jun 9 2020 19:37:47 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'175_yang_kgv.cfg': {
'index': '41',
'last_modified_date': 'Nov 16 2020 22:02:30 +00:00',
'permissions': '-rw-',
'size': '6555',
},
'CSCvW14593_show_audit_log.txt': {
'index': '37',
'last_modified_date': 'Oct 30 2020 19:34:26 +00:00',
'permissions': '-rw-',
'size': '75919',
},
'CSCvv61331_audit_log.txt': {
'index': '31',
'last_modified_date': 'Sep 16 2020 18:09:02 +00:00',
'permissions': '-rw-',
'size': '283402',
},
'CSCvv61331_show_audit_log.txt': {
'index': '36',
'last_modified_date': 'Oct 16 2020 21:46:00 +00:00',
'permissions': '-rw-',
'size': '95734',
},
'CSCvv61331_show_audit_output.txt': {
'index': '35',
'last_modified_date': 'Oct 16 2020 20:48:33 +00:00',
'permissions': '-rw-',
'size': '371048',
},
'CSCvv82742_show_audit_log.txt': {
'index': '33',
'last_modified_date': 'Sep 28 2020 06:40:04 +00:00',
'permissions': '-rw-',
'size': '334666',
},
'HD_destroy_show_audit.txt': {
'index': '30',
'last_modified_date': 'Sep 3 2020 18:49:19 +00:00',
'permissions': '-rw-',
'size': '171680',
},
'PROM-20200723.pkg': {
'index': '25',
'last_modified_date': 'Jul 30 2020 22:00:45 +00:00',
'permissions': '-rw-',
'size': '7222220',
},
'SHARED-IOX': {
'index': '209665',
'last_modified_date': 'Jul 9 2020 06:05:39 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'System_Firmware_Info.txt': {
'index': '42',
'last_modified_date': 'Nov 18 2020 06:37:43 +00:00',
'permissions': '-rw-',
'size': '151',
},
'admin-tech_show_audit.log': {
'index': '27',
'last_modified_date': 'Aug 12 2020 04:39:25 +00:00',
'permissions': '-rw-',
'size': '1322755',
},
'admin-tech_show_audit_log.txt': {
'index': '32',
'last_modified_date': 'Sep 22 2020 22:15:46 +00:00',
'permissions': '-rw-',
'size': '2818976',
},
'c8000be-firmware_dreamliner. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80643',
'last_modified_date': 'Nov 7 2020 02:00:44 +00:00',
'permissions': '-rw-',
'size': '54360',
},
'c8000be-firmware_dreamliner. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314499',
'last_modified_date': 'Nov 6 2020 04:35:15 +00:00',
'permissions': '-rw-',
'size': '54356',
},
'c8000be-firmware_dsp_analogbri. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80644',
'last_modified_date': 'Nov 7 2020 02:00:45 +00:00',
'permissions': '-rw-',
'size': '6677592',
},
'c8000be-firmware_dsp_analogbri. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314500',
'last_modified_date': 'Nov 6 2020 04:35:15 +00:00',
'permissions': '-rw-',
'size': '6677592',
},
'c8000be-firmware_dsp_sp2700. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80645',
'last_modified_date': 'Nov 7 2020 02:00:45 +00:00',
'permissions': '-rw-',
'size': '1762392',
},
'c8000be-firmware_dsp_sp2700. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314501',
'last_modified_date': 'Nov 6 2020 04:35:15 +00:00',
'permissions': '-rw-',
'size': '1762388',
},
'c8000be-firmware_dsp_tilegx. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80646',
'last_modified_date': 'Nov 7 2020 02:00:45 +00:00',
'permissions': '-rw-',
'size': '17933400',
},
'c8000be-firmware_dsp_tilegx. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314502',
'last_modified_date': 'Nov 6 2020 04:35:16 +00:00',
'permissions': '-rw-',
'size': '17933396',
},
'c8000be-firmware_ngwic_t1e1. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80647',
'last_modified_date': 'Nov 7 2020 02:00:45 +00:00',
'permissions': '-rw-',
'size': '11310168',
},
'c8000be-firmware_ngwic_t1e1. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314503',
'last_modified_date': 'Nov 6 2020 04:35:16 +00:00',
'permissions': '-rw-',
'size': '11310164',
},
'c8000be-firmware_nim_async. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80648',
'last_modified_date': 'Nov 7 2020 02:00:46 +00:00',
'permissions': '-rw-',
'size': '12870740',
},
'c8000be-firmware_nim_async. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314504',
'last_modified_date': 'Nov 6 2020 04:35:17 +00:00',
'permissions': '-rw-',
'size': '9344084',
},
'c8000be-firmware_nim_bri_st_fw. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80649',
'last_modified_date': 'Nov 7 2020 02:00:46 +00:00',
'permissions': '-rw-',
'size': '4789336',
},
'c8000be-firmware_nim_bri_st_fw. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314505',
'last_modified_date': 'Nov 6 2020 04:35:17 +00:00',
'permissions': '-rw-',
'size': '4789336',
},
'c8000be-firmware_nim_cwan. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80650',
'last_modified_date': 'Nov 7 2020 02:00:46 +00:00',
'permissions': '-rw-',
'size': '17650772',
},
'c8000be-firmware_nim_cwan. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314506',
'last_modified_date': 'Nov 6 2020 04:35:18 +00:00',
'permissions': '-rw-',
'size': '17650768',
},
'c8000be-firmware_nim_ge. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80651',
'last_modified_date': 'Nov 7 2020 02:00:46 +00:00',
'permissions': '-rw-',
'size': '2933844',
},
'c8000be-firmware_nim_ge. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314507',
'last_modified_date': 'Nov 6 2020 04:35:18 +00:00',
'permissions': '-rw-',
'size': '2933840',
},
'c8000be-firmware_nim_shdsl. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80652',
'last_modified_date': 'Nov 7 2020 02:00:47 +00:00',
'permissions': '-rw-',
'size': '11523156',
},
'c8000be-firmware_nim_shdsl. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314508',
'last_modified_date': 'Nov 6 2020 04:35:18 +00:00',
'permissions': '-rw-',
'size': '11523156',
},
'c8000be-firmware_nim_ssd. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80653',
'last_modified_date': 'Nov 7 2020 02:00:47 +00:00',
'permissions': '-rw-',
'size': '5334100',
},
'c8000be-firmware_nim_ssd. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314509',
'last_modified_date': 'Nov 6 2020 04:35:18 +00:00',
'permissions': '-rw-',
'size': '5334096',
},
'c8000be-firmware_nim_xdsl. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80654',
'last_modified_date': 'Nov 7 2020 02:00:47 +00:00',
'permissions': '-rw-',
'size': '6321236',
},
'c8000be-firmware_nim_xdsl. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314510',
'last_modified_date': 'Nov 6 2020 04:35:18 +00:00',
'permissions': '-rw-',
'size': '6321232',
},
'c8000be-firmware_prince. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80655',
'last_modified_date': 'Nov 7 2020 02:00:48 +00:00',
'permissions': '-rw-',
'size': '10191956',
},
'c8000be-firmware_prince. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314511',
'last_modified_date': 'Nov 6 2020 04:35:18 +00:00',
'permissions': '-rw-',
'size': '10191952',
},
'c8000be-firmware_sm_10g. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80656',
'last_modified_date': 'Nov 7 2020 02:00:48 +00:00',
'permissions': '-rw-',
'size': '2475092',
},
'c8000be-firmware_sm_10g. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314512',
'last_modified_date': 'Nov 6 2020 04:35:19 +00:00',
'permissions': '-rw-',
'size': '2475088',
},
'c8000be-firmware_sm_1t3e3. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80657',
'last_modified_date': 'Nov 7 2020 02:00:48 +00:00',
'permissions': '-rw-',
'size': '11093076',
},
'c8000be-firmware_sm_1t3e3. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314513',
'last_modified_date': 'Nov 6 2020 04:35:19 +00:00',
'permissions': '-rw-',
'size': '11093072',
},
'c8000be-firmware_sm_async. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80658',
'last_modified_date': 'Nov 7 2020 02:00:49 +00:00',
'permissions': '-rw-',
'size': '14259284',
},
'c8000be-firmware_sm_async. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314514',
'last_modified_date': 'Nov 6 2020 04:35:19 +00:00',
'permissions': '-rw-',
'size': '10732624',
},
'c8000be-firmware_sm_dsp_sp2700. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80659',
'last_modified_date': 'Nov 7 2020 02:00:49 +00:00',
'permissions': '-rw-',
'size': '1897560',
},
'c8000be-firmware_sm_dsp_sp2700. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314515',
'last_modified_date': 'Nov 6 2020 04:35:19 +00:00',
'permissions': '-rw-',
'size': '1897560',
},
'c8000be-firmware_sm_nim_adpt. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80660',
'last_modified_date': 'Nov 7 2020 02:00:49 +00:00',
'permissions': '-rw-',
'size': '156760',
},
'c8000be-firmware_sm_nim_adpt. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314516',
'last_modified_date': 'Nov 6 2020 04:35:19 +00:00',
'permissions': '-rw-',
'size': '156756',
},
'c8000be-mono-universalk9. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80661',
'last_modified_date': 'Nov 7 2020 02:01:02 +00:00',
'permissions': '-rw-',
'size': '567600228',
},
'c8000be-mono-universalk9. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314517',
'last_modified_date': 'Nov 6 2020 04:35:30 +00:00',
'permissions': '-rw-',
'size': '555934816',
},
'c8000be-rpboot. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {
'index': '80662',
'last_modified_date': 'Nov 7 2020 02:01:50 +00:00',
'permissions': '-rw-',
'size': '41442704',
},
'c8000be-rpboot. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {
'index': '314518',
'last_modified_date': 'Nov 6 2020 04:36:17 +00:00',
'permissions': '-rw-',
'size': '41515430',
},
'c8000be-universalk9.17.04.01prd9.SPA.bin': {
'index': '40',
'last_modified_date': 'Nov 12 2020 22:50:31 +00:00',
'permissions': '-rw-',
'size': '727336014',
},
'c8000be-universalk9. BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin': {
'index': '39',
'last_modified_date': 'Nov 12 2020 21:41:45 +00:00',
'permissions': '-rw-',
'size': '744614104',
},
'c8000be-universalk9. BLD_POLARIS_DEV_LATEST_20201103_212.conf': {
'index': '80642',
'last_modified_date': 'Nov 7 2020 02:01:50 +00:00',
'permissions': '-rw-',
'size': '11388',
},
'c8000be-universalk9. BLD_V174_THROTTLE_LATEST_20201104_P.conf': {
'index': '314498',
'last_modified_date': 'Nov 6 2020 04:36:17 +00:00',
'permissions': '-rw-',
'size': '11851',
},
'core': {
'index': '177409',
'last_modified_date': 'Jul 27 2020 05:13:21 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'format_audit_log.txt': {
'index': '28',
'last_modified_date': 'Aug 13 2020 21:17:17 +00:00',
'permissions': '-rw-',
'size': '3025023',
},
'fw_upgrade_sysinfo': {
'index': '217729',
'last_modified_date': 'Oct 30 2020 18:05:39 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'gs_script': {
'index': '419329',
'last_modified_date': 'Oct 30 2020 17:59:57 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'guest-share': {
'index': '104833',
'last_modified_date': 'Jun 9 2020 19:39:23 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'ios_core.p7b': {
'index': '14',
'last_modified_date': 'Jun 9 2020 19:38:21 +00:00',
'permissions': '-rw-',
'size': '20109',
},
'iox_host_data_share': {
'index': '193537',
'last_modified_date': 'Jun 9 2020 19:39:43 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'license_evlog': {
'index': '153217',
'last_modified_date': 'Nov 18 2020 06:36:27 +00:00',
'permissions': 'drwx',
'size': '8192',
},
'lost+found': {
'index': '11',
'last_modified_date': 'Jun 9 2020 19:37:10 +00:00',
'permissions': 'drwx',
'size': '16384',
},
'memleak.tcl': {
'index': '13',
'last_modified_date': 'Nov 18 2020 06:36:05 +00:00',
'permissions': '-rw-',
'size': '134808',
},
'mode_event_log': {
'index': '12',
'last_modified_date': 'Nov 18 2020 06:35:46 +00:00',
'permissions': '-rw-',
'size': '27299',
},
'olin_RootCert22.crt': {
'index': '17',
'last_modified_date': 'Jun 10 2020 05:45:44 +00:00',
'permissions': '-rw-',
'size': '1314',
},
'onep': {
'index': '322561',
'last_modified_date': 'Jun 9 2020 19:38:54 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'original-startup-config': {
'index': '24',
'last_modified_date': 'Jul 10 2020 18:32:00 +00:00',
'permissions': '-rw-',
'size': '1471',
},
'original-xe-config': {
'index': '19',
'last_modified_date': 'Nov 5 2020 20:59:12 +00:00',
'permissions': '-rw-',
'size': '6262',
},
'packages.conf': {
'index': '306434',
'last_modified_date': 'Nov 7 2020 02:04:21 +00:00',
'permissions': '-rw-',
'size': '11388',
},
'pki_certificates': {
'index': '22',
'last_modified_date': 'Nov 5 2020 21:03:46 +00:00',
'permissions': '-rw-',
'size': '107',
},
'pnp-info': {
'index': '161281',
'last_modified_date': 'Jun 9 2020 19:38:53 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'pnp-tech': {
'index': '201601',
'last_modified_date': 'Nov 16 2020 05:15:38 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'prev_packages.conf': {
'index': '26',
'last_modified_date': 'Nov 7 2020 02:03:18 +00:00',
'permissions': '-rw-',
'size': '11851',
},
'running-config': {
'index': '21',
'last_modified_date': 'Jun 11 2020 20:35:37 +00:00',
'permissions': '-rw-',
'size': '5222',
},
'sdwan': {
'index': '112897',
'last_modified_date': 'Nov 16 2020 05:13:47 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'show_audit_log.txt': {
'index': '34',
'last_modified_date': 'Nov 7 2020 02:24:28 +00:00',
'permissions': '-rw-',
'size': '371908',
},
'ss_disc': {
'index': '40321',
'last_modified_date': 'Oct 30 2020 17:59:57 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'ssd': {
'index': '38',
'last_modified_date': 'Oct 30 2020 17:59:57 +00:00',
'permissions': '-rw-',
'size': '5242880',
},
'startup-config': {
'index': '23',
'last_modified_date': 'Jun 11 2020 20:44:06 +00:00',
'permissions': '-rw-',
'size': '25',
},
'sysboot': {
'index': '354817',
'last_modified_date': 'Nov 18 2020 06:34:55 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'syslog': {
'index': '387073',
'last_modified_date': 'Nov 16 2020 04:32:19 +00:00',
'permissions': 'drwx',
'size': '12288',
},
'throughput_monitor_params': {
'index': '16',
'last_modified_date': 'Nov 18 2020 06:36:10 +00:00',
'permissions': '-rw-',
'size': '30',
},
'tracelogs': {
'index': '427393',
'last_modified_date': 'Nov 18 2020 07:06:07 +00:00',
'permissions': 'drwx',
'size': '176128',
},
'trustidrootx3_ca.ca': {
'index': '15',
'last_modified_date': 'Jun 9 2020 19:38:21 +00:00',
'permissions': '-rwx',
'size': '1314',
},
'virtual-instance': {
'index': '306433',
'last_modified_date': 'Sep 24 2020 21:31:22 +00:00',
'permissions': 'drwx',
'size': '4096',
},
'vmanage-admin': {
'index': '129025',
'last_modified_date': 'Nov 7 2020 02:21:56 +00:00',
'permissions': 'drwx',
'size': '4096',
},
},
},
'dir': 'bootflash:/',
},
}
showDirEmpty = {}
showPlatform = {
'slot': {
'0': {
'lc': {
'C8200-1N-4T': {
'insert_time': '00:32:26',
'name': 'C8200-1N-4T',
'slot': '0',
'state': 'ok',
'subslot': {
'0': {
'2x1G-2xSFP': {
'insert_time': '00:31:12',
'name': '2x1G-2xSFP',
'state': 'ok',
'subslot': '0',
},
},
'1': {
'NIM-4T': {
'insert_time': '00:31:12',
'name': 'NIM-4T',
'state': 'ok',
'subslot': '1',
},
},
'2': {
'P-LTE-GB': {
'insert_time': '00:31:12',
'name': 'P-LTE-GB',
'state': 'ok',
'subslot': '2',
},
},
'5': {
'SSD-M2NVME-600G': {
'insert_time': '00:31:12',
'name': 'SSD-M2NVME-600G',
'state': 'ok',
'subslot': '5',
},
},
},
},
},
},
'F0': {
'other': {
'C8200-1N-4T': {
'insert_time': '00:32:26',
'name': 'C8200-1N-4T',
'slot': 'F0',
'state': 'ok, active',
},
},
},
'P0': {
'other': {
'PWR-INT-90WAC': {
'insert_time': '00:31:47',
'name': 'PWR-INT-90WAC',
'slot': 'P0',
'state': 'ok',
},
},
},
'P2': {
'other': {
'C8200-FAN-1R': {
'insert_time': '00:31:47',
'name': 'C8200-FAN-1R',
'slot': 'P2',
'state': 'ok',
},
},
},
'R0': {
'rp': {
'C8200-1N-4T': {
'insert_time': '00:32:26',
'name': 'C8200-1N-4T',
'slot': 'R0',
'state': 'ok, active',
},
},
},
},
}
showInventory = {
'main': {
'chassis': {
'C8200-1N-4T': {
'descr': 'Cisco C8200-1N-4T Chassis',
'name': 'Chassis',
'pid': 'C8200-1N-4T',
'sn': 'FGL2420L6EE',
'vid': 'V01',
},
},
},
'slot': {
'0': {
'lc': {
'C8200-1N-4T': {
'descr': 'Cisco C8200-1N-4T Built-In NIM controller',
'name': 'module 0',
'pid': 'C8200-1N-4T',
'sn': '',
'subslot': {
'0': {
'2x1G-2xSFP': {
'descr': 'Front Panel 4 ports Gigabitethernet Module',
'name': 'NIM subslot 0/0',
'pid': '2x1G-2xSFP',
'sn': '',
'vid': 'V01',
},
},
'0 transceiver 3': {
'SFP-GE-S': {
'descr': 'GE SX',
'name': 'subslot 0/0 transceiver 3',
'pid': 'SFP-GE-S',
'sn': 'FNS1047175F',
'vid': 'V01',
},
},
'1': {
'NIM-4T': {
'descr': 'sync serial NIM with 4 ports',
'name': 'NIM subslot 0/1',
'pid': 'NIM-4T',
'sn': 'FOC230369RF',
'vid': 'V01',
},
},
'2': {
'P-LTE-GB': {
'descr': 'P-LTE-GB Module',
'name': 'NIM subslot 0/2',
'pid': 'P-LTE-GB',
'sn': 'FOC22191PWY',
'vid': 'V00',
},
},
'5': {
'SSD-M2NVME-600G': {
'descr': 'NVME SSD Module',
'name': 'NIM subslot 0/5',
'pid': 'SSD-M2NVME-600G',
'sn': 'INTELSSDPELKX010T8',
'vid': 'V01',
},
},
},
'vid': '',
},
},
},
'F0': {
'other': {
'C8200-1N-4T': {
'descr': 'Cisco C8200-1N-4T Forwarding Processor',
'name': 'module F0',
'pid': 'C8200-1N-4T',
'sn': '',
'vid': '',
},
},
},
'Fan_Tray': {
'other': {
'C8200-FAN-1R': {
'descr': 'Cisco C8200 1RU Fan Assembly',
'name': 'Fan Tray',
'pid': 'C8200-FAN-1R',
'sn': '',
'vid': '',
},
},
},
'P0': {
'other': {
'PWR-NOPI': {
'descr': '90W AC Internal Power Supply for Cisco C8200',
'name': 'Power Supply Module 0',
'pid': 'PWR-NOPI',
'sn': '',
'vid': '',
},
},
},
'R0': {
'rp': {
'C8200-1N-4T': {
'descr': 'Cisco C8200-1N-4T Route Processor',
'name': 'module R0',
'pid': 'C8200-1N-4T',
'sn': 'FOC24143XF7',
'vid': 'V01',
},
},
},
},
}
showRedundancy = {
'red_sys_info': {
'available_system_uptime': '31 minutes',
'communications': 'Down',
'communications_reason': 'Failure',
'conf_red_mode': 'Non-redundant',
'hw_mode': 'Simplex',
'last_switchover_reason': 'none',
'maint_mode': 'Disabled',
'oper_red_mode': 'Non-redundant',
'standby_failures': '0',
'switchovers_system_experienced': '0',
},
'slot': {
'slot 6': {
'boot': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin,12;',
'config_register': '0x2102',
'curr_sw_state': 'ACTIVE',
'image_ver': 'Cisco IOS Software [Bengaluru], c8000be Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Experimental Version 17.5.20201016:181710 [S2C-build-polaris_dev-124418-/nobackup/mcpre/BLD-BLD_POLARIS_DEV_LATEST_20201016_180855 217]',
'uptime_in_curr_state': '31 minutes',
},
},
}
ShowIssuStateDetail = {
'slot': {
'R0': {
'issu_in_progress': False,
},
},
}
ShowIssuRollbackTimer = {
'rollback_timer_reason': 'no ISSU operation is in progress',
'rollback_timer_state': 'inactive',
}
platform_all = {
'chassis': 'C8200-1N-4T',
'chassis_sn': 'FGL2420L6EE',
'config_register': '0x2102',
'dir': 'bootflash:/',
'image': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin',
'issu_rollback_timer_reason': 'no ISSU operation is in progress',
'issu_rollback_timer_state': 'inactive',
'main_mem': '3753847',
'os': 'iosxe',
'redundancy_communication': False,
'redundancy_mode': 'Non-redundant',
'rp_uptime': 1860,
'rtr_type': 'C8200-1N-4T',
'slot': {
'lc': {
'0': {
'name': 'C8200-1N-4T',
'sn': '',
'state': 'ok',
'subslot': {
'0': {
'name': '2x1G-2xSFP',
'sn': '',
'state': 'ok',
},
'0 transceiver 3': {
'name': 'SFP-GE-S',
'sn': 'FNS1047175F',
},
'1': {
'name': 'NIM-4T',
'sn': 'FOC230369RF',
'state': 'ok',
},
'2': {
'name': 'P-LTE-GB',
'sn': 'FOC22191PWY',
'state': 'ok',
},
'5': {
'name': 'SSD-M2NVME-600G',
'sn': 'INTELSSDPELKX010T8',
'state': 'ok',
},
},
},
},
'oc': {
'F0': {
'name': 'C8200-1N-4T',
'sn': '',
'state': 'ok, active',
},
'Fan_Tray': {
'sn': '',
},
'P0': {
'name': 'PWR-INT-90WAC',
'sn': '',
'state': 'ok',
},
'P2': {
'name': 'C8200-FAN-1R',
'state': 'ok',
},
},
'rp': {
'R0': {
'boot_image': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin,12;',
'config_register': '0x2102',
'issu': {
'in_progress': False,
},
'name': 'C8200-1N-4T',
'redundancy_state': 'ACTIVE',
'rp_uptime': '31 minutes',
'sn': 'FOC24143XF7',
'state': 'ok, active',
'system_image': 'Cisco IOS Software [Bengaluru], c8000be Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Experimental Version 17.5.20201016:181710 [S2C-build-polaris_dev-124418-/nobackup/mcpre/BLD-BLD_POLARIS_DEV_LATEST_20201016_180855 217]',
},
},
},
'switchover_reason': 'none',
'version': '17.5.20201016:181710',
}
platform_all_empty_dir = {
'chassis': 'C8200-1N-4T',
'chassis_sn': 'FGL2420L6EE',
'config_register': '0x2102',
'dir': 'bootflash:/',
'image': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin',
'issu_rollback_timer_reason': 'no ISSU operation is in progress',
'issu_rollback_timer_state': 'inactive',
'main_mem': '3753847',
'os': 'iosxe',
'redundancy_communication': False,
'redundancy_mode': 'Non-redundant',
'rp_uptime': 1860,
'rtr_type': 'C8200-1N-4T',
'slot': {
'lc': {
'0': {
'name': 'C8200-1N-4T',
'sn': '',
'state': 'ok',
'subslot': {
'0': {
'name': '2x1G-2xSFP',
'sn': '',
'state': 'ok',
},
'0 transceiver 3': {
'name': 'SFP-GE-S',
'sn': 'FNS1047175F',
},
'1': {
'name': 'NIM-4T',
'sn': 'FOC230369RF',
'state': 'ok',
},
'2': {
'name': 'P-LTE-GB',
'sn': 'FOC22191PWY',
'state': 'ok',
},
'5': {
'name': 'SSD-M2NVME-600G',
'sn': 'INTELSSDPELKX010T8',
'state': 'ok',
},
},
},
},
'oc': {
'F0': {
'name': 'C8200-1N-4T',
'sn': '',
'state': 'ok, active',
},
'Fan_Tray': {
'sn': '',
},
'P0': {
'name': 'PWR-INT-90WAC',
'sn': '',
'state': 'ok',
},
'P2': {
'name': 'C8200-FAN-1R',
'state': 'ok',
},
},
'rp': {
'R0': {
'boot_image': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin,12;',
'config_register': '0x2102',
'issu': {
'in_progress': False,
},
'name': 'C8200-1N-4T',
'redundancy_state': 'ACTIVE',
'rp_uptime': '31 minutes',
'sn': 'FOC24143XF7',
'state': 'ok, active',
'system_image': 'Cisco IOS Software [Bengaluru], c8000be Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Experimental Version 17.5.20201016:181710 [S2C-build-polaris_dev-124418-/nobackup/mcpre/BLD-BLD_POLARIS_DEV_LATEST_20201016_180855 217]',
},
},
},
'switchover_reason': 'none',
'version': '17.5.20201016:181710',
}
| class Platformoutput(object):
show_version = {'version': {'chassis': 'C8200-1N-4T', 'chassis_sn': 'FGL2420L6EE', 'compiled_by': 'mcpre', 'compiled_date': 'Fri 16-Oct-20 19:08', 'curr_config_register': '0x2102', 'disks': {'bootflash:.': {'disk_size': '7090175', 'type_of_disk': 'flash memory'}, 'harddisk:.': {'disk_size': '585924608', 'type_of_disk': 'NVMe SSD'}, 'usb0:.': {'disk_size': '16789568', 'type_of_disk': 'USB flash'}}, 'hostname': 'cEdge-P2', 'image_id': 'X86_64_LINUX_IOSD-UNIVERSALK9-M', 'image_type': 'developer image', 'last_reload_reason': 'SMU Install', 'main_mem': '3753847', 'mem_size': {'non-volatile configuration': '32768', 'physical': '8388608'}, 'number_of_intfs': {'Cellular': '2', 'Gigabit Ethernet': '4', 'Serial': '4'}, 'os': 'IOS-XE', 'platform': 'c8000be', 'processor_board_flash': '7203041280', 'processor_type': '1RU', 'returned_to_rom_by': 'SMU Install', 'rom': 'PROM-20200723', 'rtr_type': 'C8200-1N-4T', 'system_image': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin', 'uptime': '31 minutes', 'uptime_this_cp': '32 minutes', 'version': '17.5.20201016:181710', 'version_short': '17.5'}}
show_dir = {'dir': {'bootflash:/': {'bytes_free': '2294001664', 'bytes_total': '7203041280', 'files': {'.PATCH': {'index': '362881', 'last_modified_date': 'Nov 18 2020 06:39:41 +00:00', 'permissions': 'drwx', 'size': '4096'}, '.PATCH-backup': {'index': '225793', 'last_modified_date': 'Nov 18 2020 06:35:08 +00:00', 'permissions': 'drwx', 'size': '4096'}, '.cdb_backup': {'index': '282241', 'last_modified_date': 'Jun 9 2020 20:11:42 +00:00', 'permissions': 'drwx', 'size': '4096'}, '.dbpersist': {'index': '290305', 'last_modified_date': 'Nov 16 2020 05:11:08 +00:00', 'permissions': 'drwx', 'size': '4096'}, '.geo': {'index': '137089', 'last_modified_date': 'Jun 21 2020 19:08:46 +00:00', 'permissions': 'drwx', 'size': '4096'}, '.iox_dir_list': {'index': '29', 'last_modified_date': 'Oct 30 2020 18:58:56 +00:00', 'permissions': '-rw-', 'size': '275'}, '.prst_sync': {'index': '411265', 'last_modified_date': 'Nov 18 2020 06:36:19 +00:00', 'permissions': 'drwx', 'size': '4096'}, '.rollback_timer': {'index': '8065', 'last_modified_date': 'Nov 18 2020 06:39:14 +00:00', 'permissions': 'drwx', 'size': '4096'}, '.sdwaninstaller': {'index': '298369', 'last_modified_date': 'Nov 18 2020 06:39:43 +00:00', 'permissions': 'drwx', 'size': '4096'}, '.sdwaninstallerfs': {'index': '18', 'last_modified_date': 'Nov 16 2020 05:11:48 +00:00', 'permissions': '-rw-', 'size': '419430400'}, '.sdwaninternal': {'index': '96769', 'last_modified_date': 'Jun 9 2020 20:03:48 +00:00', 'permissions': 'drwx', 'size': '4096'}, '.ssh': {'index': '403201', 'last_modified_date': 'Jun 9 2020 19:37:47 +00:00', 'permissions': 'drwx', 'size': '4096'}, '175_yang_kgv.cfg': {'index': '41', 'last_modified_date': 'Nov 16 2020 22:02:30 +00:00', 'permissions': '-rw-', 'size': '6555'}, 'CSCvW14593_show_audit_log.txt': {'index': '37', 'last_modified_date': 'Oct 30 2020 19:34:26 +00:00', 'permissions': '-rw-', 'size': '75919'}, 'CSCvv61331_audit_log.txt': {'index': '31', 'last_modified_date': 'Sep 16 2020 18:09:02 +00:00', 'permissions': '-rw-', 'size': '283402'}, 'CSCvv61331_show_audit_log.txt': {'index': '36', 'last_modified_date': 'Oct 16 2020 21:46:00 +00:00', 'permissions': '-rw-', 'size': '95734'}, 'CSCvv61331_show_audit_output.txt': {'index': '35', 'last_modified_date': 'Oct 16 2020 20:48:33 +00:00', 'permissions': '-rw-', 'size': '371048'}, 'CSCvv82742_show_audit_log.txt': {'index': '33', 'last_modified_date': 'Sep 28 2020 06:40:04 +00:00', 'permissions': '-rw-', 'size': '334666'}, 'HD_destroy_show_audit.txt': {'index': '30', 'last_modified_date': 'Sep 3 2020 18:49:19 +00:00', 'permissions': '-rw-', 'size': '171680'}, 'PROM-20200723.pkg': {'index': '25', 'last_modified_date': 'Jul 30 2020 22:00:45 +00:00', 'permissions': '-rw-', 'size': '7222220'}, 'SHARED-IOX': {'index': '209665', 'last_modified_date': 'Jul 9 2020 06:05:39 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'System_Firmware_Info.txt': {'index': '42', 'last_modified_date': 'Nov 18 2020 06:37:43 +00:00', 'permissions': '-rw-', 'size': '151'}, 'admin-tech_show_audit.log': {'index': '27', 'last_modified_date': 'Aug 12 2020 04:39:25 +00:00', 'permissions': '-rw-', 'size': '1322755'}, 'admin-tech_show_audit_log.txt': {'index': '32', 'last_modified_date': 'Sep 22 2020 22:15:46 +00:00', 'permissions': '-rw-', 'size': '2818976'}, 'c8000be-firmware_dreamliner. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80643', 'last_modified_date': 'Nov 7 2020 02:00:44 +00:00', 'permissions': '-rw-', 'size': '54360'}, 'c8000be-firmware_dreamliner. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314499', 'last_modified_date': 'Nov 6 2020 04:35:15 +00:00', 'permissions': '-rw-', 'size': '54356'}, 'c8000be-firmware_dsp_analogbri. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80644', 'last_modified_date': 'Nov 7 2020 02:00:45 +00:00', 'permissions': '-rw-', 'size': '6677592'}, 'c8000be-firmware_dsp_analogbri. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314500', 'last_modified_date': 'Nov 6 2020 04:35:15 +00:00', 'permissions': '-rw-', 'size': '6677592'}, 'c8000be-firmware_dsp_sp2700. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80645', 'last_modified_date': 'Nov 7 2020 02:00:45 +00:00', 'permissions': '-rw-', 'size': '1762392'}, 'c8000be-firmware_dsp_sp2700. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314501', 'last_modified_date': 'Nov 6 2020 04:35:15 +00:00', 'permissions': '-rw-', 'size': '1762388'}, 'c8000be-firmware_dsp_tilegx. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80646', 'last_modified_date': 'Nov 7 2020 02:00:45 +00:00', 'permissions': '-rw-', 'size': '17933400'}, 'c8000be-firmware_dsp_tilegx. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314502', 'last_modified_date': 'Nov 6 2020 04:35:16 +00:00', 'permissions': '-rw-', 'size': '17933396'}, 'c8000be-firmware_ngwic_t1e1. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80647', 'last_modified_date': 'Nov 7 2020 02:00:45 +00:00', 'permissions': '-rw-', 'size': '11310168'}, 'c8000be-firmware_ngwic_t1e1. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314503', 'last_modified_date': 'Nov 6 2020 04:35:16 +00:00', 'permissions': '-rw-', 'size': '11310164'}, 'c8000be-firmware_nim_async. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80648', 'last_modified_date': 'Nov 7 2020 02:00:46 +00:00', 'permissions': '-rw-', 'size': '12870740'}, 'c8000be-firmware_nim_async. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314504', 'last_modified_date': 'Nov 6 2020 04:35:17 +00:00', 'permissions': '-rw-', 'size': '9344084'}, 'c8000be-firmware_nim_bri_st_fw. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80649', 'last_modified_date': 'Nov 7 2020 02:00:46 +00:00', 'permissions': '-rw-', 'size': '4789336'}, 'c8000be-firmware_nim_bri_st_fw. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314505', 'last_modified_date': 'Nov 6 2020 04:35:17 +00:00', 'permissions': '-rw-', 'size': '4789336'}, 'c8000be-firmware_nim_cwan. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80650', 'last_modified_date': 'Nov 7 2020 02:00:46 +00:00', 'permissions': '-rw-', 'size': '17650772'}, 'c8000be-firmware_nim_cwan. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314506', 'last_modified_date': 'Nov 6 2020 04:35:18 +00:00', 'permissions': '-rw-', 'size': '17650768'}, 'c8000be-firmware_nim_ge. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80651', 'last_modified_date': 'Nov 7 2020 02:00:46 +00:00', 'permissions': '-rw-', 'size': '2933844'}, 'c8000be-firmware_nim_ge. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314507', 'last_modified_date': 'Nov 6 2020 04:35:18 +00:00', 'permissions': '-rw-', 'size': '2933840'}, 'c8000be-firmware_nim_shdsl. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80652', 'last_modified_date': 'Nov 7 2020 02:00:47 +00:00', 'permissions': '-rw-', 'size': '11523156'}, 'c8000be-firmware_nim_shdsl. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314508', 'last_modified_date': 'Nov 6 2020 04:35:18 +00:00', 'permissions': '-rw-', 'size': '11523156'}, 'c8000be-firmware_nim_ssd. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80653', 'last_modified_date': 'Nov 7 2020 02:00:47 +00:00', 'permissions': '-rw-', 'size': '5334100'}, 'c8000be-firmware_nim_ssd. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314509', 'last_modified_date': 'Nov 6 2020 04:35:18 +00:00', 'permissions': '-rw-', 'size': '5334096'}, 'c8000be-firmware_nim_xdsl. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80654', 'last_modified_date': 'Nov 7 2020 02:00:47 +00:00', 'permissions': '-rw-', 'size': '6321236'}, 'c8000be-firmware_nim_xdsl. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314510', 'last_modified_date': 'Nov 6 2020 04:35:18 +00:00', 'permissions': '-rw-', 'size': '6321232'}, 'c8000be-firmware_prince. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80655', 'last_modified_date': 'Nov 7 2020 02:00:48 +00:00', 'permissions': '-rw-', 'size': '10191956'}, 'c8000be-firmware_prince. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314511', 'last_modified_date': 'Nov 6 2020 04:35:18 +00:00', 'permissions': '-rw-', 'size': '10191952'}, 'c8000be-firmware_sm_10g. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80656', 'last_modified_date': 'Nov 7 2020 02:00:48 +00:00', 'permissions': '-rw-', 'size': '2475092'}, 'c8000be-firmware_sm_10g. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314512', 'last_modified_date': 'Nov 6 2020 04:35:19 +00:00', 'permissions': '-rw-', 'size': '2475088'}, 'c8000be-firmware_sm_1t3e3. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80657', 'last_modified_date': 'Nov 7 2020 02:00:48 +00:00', 'permissions': '-rw-', 'size': '11093076'}, 'c8000be-firmware_sm_1t3e3. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314513', 'last_modified_date': 'Nov 6 2020 04:35:19 +00:00', 'permissions': '-rw-', 'size': '11093072'}, 'c8000be-firmware_sm_async. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80658', 'last_modified_date': 'Nov 7 2020 02:00:49 +00:00', 'permissions': '-rw-', 'size': '14259284'}, 'c8000be-firmware_sm_async. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314514', 'last_modified_date': 'Nov 6 2020 04:35:19 +00:00', 'permissions': '-rw-', 'size': '10732624'}, 'c8000be-firmware_sm_dsp_sp2700. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80659', 'last_modified_date': 'Nov 7 2020 02:00:49 +00:00', 'permissions': '-rw-', 'size': '1897560'}, 'c8000be-firmware_sm_dsp_sp2700. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314515', 'last_modified_date': 'Nov 6 2020 04:35:19 +00:00', 'permissions': '-rw-', 'size': '1897560'}, 'c8000be-firmware_sm_nim_adpt. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80660', 'last_modified_date': 'Nov 7 2020 02:00:49 +00:00', 'permissions': '-rw-', 'size': '156760'}, 'c8000be-firmware_sm_nim_adpt. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314516', 'last_modified_date': 'Nov 6 2020 04:35:19 +00:00', 'permissions': '-rw-', 'size': '156756'}, 'c8000be-mono-universalk9. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80661', 'last_modified_date': 'Nov 7 2020 02:01:02 +00:00', 'permissions': '-rw-', 'size': '567600228'}, 'c8000be-mono-universalk9. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314517', 'last_modified_date': 'Nov 6 2020 04:35:30 +00:00', 'permissions': '-rw-', 'size': '555934816'}, 'c8000be-rpboot. BLD_POLARIS_DEV_LATEST_20201103_212701.SSA.pkg': {'index': '80662', 'last_modified_date': 'Nov 7 2020 02:01:50 +00:00', 'permissions': '-rw-', 'size': '41442704'}, 'c8000be-rpboot. BLD_V174_THROTTLE_LATEST_20201104_PRD14.SSA.pkg': {'index': '314518', 'last_modified_date': 'Nov 6 2020 04:36:17 +00:00', 'permissions': '-rw-', 'size': '41515430'}, 'c8000be-universalk9.17.04.01prd9.SPA.bin': {'index': '40', 'last_modified_date': 'Nov 12 2020 22:50:31 +00:00', 'permissions': '-rw-', 'size': '727336014'}, 'c8000be-universalk9. BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin': {'index': '39', 'last_modified_date': 'Nov 12 2020 21:41:45 +00:00', 'permissions': '-rw-', 'size': '744614104'}, 'c8000be-universalk9. BLD_POLARIS_DEV_LATEST_20201103_212.conf': {'index': '80642', 'last_modified_date': 'Nov 7 2020 02:01:50 +00:00', 'permissions': '-rw-', 'size': '11388'}, 'c8000be-universalk9. BLD_V174_THROTTLE_LATEST_20201104_P.conf': {'index': '314498', 'last_modified_date': 'Nov 6 2020 04:36:17 +00:00', 'permissions': '-rw-', 'size': '11851'}, 'core': {'index': '177409', 'last_modified_date': 'Jul 27 2020 05:13:21 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'format_audit_log.txt': {'index': '28', 'last_modified_date': 'Aug 13 2020 21:17:17 +00:00', 'permissions': '-rw-', 'size': '3025023'}, 'fw_upgrade_sysinfo': {'index': '217729', 'last_modified_date': 'Oct 30 2020 18:05:39 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'gs_script': {'index': '419329', 'last_modified_date': 'Oct 30 2020 17:59:57 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'guest-share': {'index': '104833', 'last_modified_date': 'Jun 9 2020 19:39:23 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'ios_core.p7b': {'index': '14', 'last_modified_date': 'Jun 9 2020 19:38:21 +00:00', 'permissions': '-rw-', 'size': '20109'}, 'iox_host_data_share': {'index': '193537', 'last_modified_date': 'Jun 9 2020 19:39:43 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'license_evlog': {'index': '153217', 'last_modified_date': 'Nov 18 2020 06:36:27 +00:00', 'permissions': 'drwx', 'size': '8192'}, 'lost+found': {'index': '11', 'last_modified_date': 'Jun 9 2020 19:37:10 +00:00', 'permissions': 'drwx', 'size': '16384'}, 'memleak.tcl': {'index': '13', 'last_modified_date': 'Nov 18 2020 06:36:05 +00:00', 'permissions': '-rw-', 'size': '134808'}, 'mode_event_log': {'index': '12', 'last_modified_date': 'Nov 18 2020 06:35:46 +00:00', 'permissions': '-rw-', 'size': '27299'}, 'olin_RootCert22.crt': {'index': '17', 'last_modified_date': 'Jun 10 2020 05:45:44 +00:00', 'permissions': '-rw-', 'size': '1314'}, 'onep': {'index': '322561', 'last_modified_date': 'Jun 9 2020 19:38:54 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'original-startup-config': {'index': '24', 'last_modified_date': 'Jul 10 2020 18:32:00 +00:00', 'permissions': '-rw-', 'size': '1471'}, 'original-xe-config': {'index': '19', 'last_modified_date': 'Nov 5 2020 20:59:12 +00:00', 'permissions': '-rw-', 'size': '6262'}, 'packages.conf': {'index': '306434', 'last_modified_date': 'Nov 7 2020 02:04:21 +00:00', 'permissions': '-rw-', 'size': '11388'}, 'pki_certificates': {'index': '22', 'last_modified_date': 'Nov 5 2020 21:03:46 +00:00', 'permissions': '-rw-', 'size': '107'}, 'pnp-info': {'index': '161281', 'last_modified_date': 'Jun 9 2020 19:38:53 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'pnp-tech': {'index': '201601', 'last_modified_date': 'Nov 16 2020 05:15:38 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'prev_packages.conf': {'index': '26', 'last_modified_date': 'Nov 7 2020 02:03:18 +00:00', 'permissions': '-rw-', 'size': '11851'}, 'running-config': {'index': '21', 'last_modified_date': 'Jun 11 2020 20:35:37 +00:00', 'permissions': '-rw-', 'size': '5222'}, 'sdwan': {'index': '112897', 'last_modified_date': 'Nov 16 2020 05:13:47 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'show_audit_log.txt': {'index': '34', 'last_modified_date': 'Nov 7 2020 02:24:28 +00:00', 'permissions': '-rw-', 'size': '371908'}, 'ss_disc': {'index': '40321', 'last_modified_date': 'Oct 30 2020 17:59:57 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'ssd': {'index': '38', 'last_modified_date': 'Oct 30 2020 17:59:57 +00:00', 'permissions': '-rw-', 'size': '5242880'}, 'startup-config': {'index': '23', 'last_modified_date': 'Jun 11 2020 20:44:06 +00:00', 'permissions': '-rw-', 'size': '25'}, 'sysboot': {'index': '354817', 'last_modified_date': 'Nov 18 2020 06:34:55 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'syslog': {'index': '387073', 'last_modified_date': 'Nov 16 2020 04:32:19 +00:00', 'permissions': 'drwx', 'size': '12288'}, 'throughput_monitor_params': {'index': '16', 'last_modified_date': 'Nov 18 2020 06:36:10 +00:00', 'permissions': '-rw-', 'size': '30'}, 'tracelogs': {'index': '427393', 'last_modified_date': 'Nov 18 2020 07:06:07 +00:00', 'permissions': 'drwx', 'size': '176128'}, 'trustidrootx3_ca.ca': {'index': '15', 'last_modified_date': 'Jun 9 2020 19:38:21 +00:00', 'permissions': '-rwx', 'size': '1314'}, 'virtual-instance': {'index': '306433', 'last_modified_date': 'Sep 24 2020 21:31:22 +00:00', 'permissions': 'drwx', 'size': '4096'}, 'vmanage-admin': {'index': '129025', 'last_modified_date': 'Nov 7 2020 02:21:56 +00:00', 'permissions': 'drwx', 'size': '4096'}}}, 'dir': 'bootflash:/'}}
show_dir_empty = {}
show_platform = {'slot': {'0': {'lc': {'C8200-1N-4T': {'insert_time': '00:32:26', 'name': 'C8200-1N-4T', 'slot': '0', 'state': 'ok', 'subslot': {'0': {'2x1G-2xSFP': {'insert_time': '00:31:12', 'name': '2x1G-2xSFP', 'state': 'ok', 'subslot': '0'}}, '1': {'NIM-4T': {'insert_time': '00:31:12', 'name': 'NIM-4T', 'state': 'ok', 'subslot': '1'}}, '2': {'P-LTE-GB': {'insert_time': '00:31:12', 'name': 'P-LTE-GB', 'state': 'ok', 'subslot': '2'}}, '5': {'SSD-M2NVME-600G': {'insert_time': '00:31:12', 'name': 'SSD-M2NVME-600G', 'state': 'ok', 'subslot': '5'}}}}}}, 'F0': {'other': {'C8200-1N-4T': {'insert_time': '00:32:26', 'name': 'C8200-1N-4T', 'slot': 'F0', 'state': 'ok, active'}}}, 'P0': {'other': {'PWR-INT-90WAC': {'insert_time': '00:31:47', 'name': 'PWR-INT-90WAC', 'slot': 'P0', 'state': 'ok'}}}, 'P2': {'other': {'C8200-FAN-1R': {'insert_time': '00:31:47', 'name': 'C8200-FAN-1R', 'slot': 'P2', 'state': 'ok'}}}, 'R0': {'rp': {'C8200-1N-4T': {'insert_time': '00:32:26', 'name': 'C8200-1N-4T', 'slot': 'R0', 'state': 'ok, active'}}}}}
show_inventory = {'main': {'chassis': {'C8200-1N-4T': {'descr': 'Cisco C8200-1N-4T Chassis', 'name': 'Chassis', 'pid': 'C8200-1N-4T', 'sn': 'FGL2420L6EE', 'vid': 'V01'}}}, 'slot': {'0': {'lc': {'C8200-1N-4T': {'descr': 'Cisco C8200-1N-4T Built-In NIM controller', 'name': 'module 0', 'pid': 'C8200-1N-4T', 'sn': '', 'subslot': {'0': {'2x1G-2xSFP': {'descr': 'Front Panel 4 ports Gigabitethernet Module', 'name': 'NIM subslot 0/0', 'pid': '2x1G-2xSFP', 'sn': '', 'vid': 'V01'}}, '0 transceiver 3': {'SFP-GE-S': {'descr': 'GE SX', 'name': 'subslot 0/0 transceiver 3', 'pid': 'SFP-GE-S', 'sn': 'FNS1047175F', 'vid': 'V01'}}, '1': {'NIM-4T': {'descr': 'sync serial NIM with 4 ports', 'name': 'NIM subslot 0/1', 'pid': 'NIM-4T', 'sn': 'FOC230369RF', 'vid': 'V01'}}, '2': {'P-LTE-GB': {'descr': 'P-LTE-GB Module', 'name': 'NIM subslot 0/2', 'pid': 'P-LTE-GB', 'sn': 'FOC22191PWY', 'vid': 'V00'}}, '5': {'SSD-M2NVME-600G': {'descr': 'NVME SSD Module', 'name': 'NIM subslot 0/5', 'pid': 'SSD-M2NVME-600G', 'sn': 'INTELSSDPELKX010T8', 'vid': 'V01'}}}, 'vid': ''}}}, 'F0': {'other': {'C8200-1N-4T': {'descr': 'Cisco C8200-1N-4T Forwarding Processor', 'name': 'module F0', 'pid': 'C8200-1N-4T', 'sn': '', 'vid': ''}}}, 'Fan_Tray': {'other': {'C8200-FAN-1R': {'descr': 'Cisco C8200 1RU Fan Assembly', 'name': 'Fan Tray', 'pid': 'C8200-FAN-1R', 'sn': '', 'vid': ''}}}, 'P0': {'other': {'PWR-NOPI': {'descr': '90W AC Internal Power Supply for Cisco C8200', 'name': 'Power Supply Module 0', 'pid': 'PWR-NOPI', 'sn': '', 'vid': ''}}}, 'R0': {'rp': {'C8200-1N-4T': {'descr': 'Cisco C8200-1N-4T Route Processor', 'name': 'module R0', 'pid': 'C8200-1N-4T', 'sn': 'FOC24143XF7', 'vid': 'V01'}}}}}
show_redundancy = {'red_sys_info': {'available_system_uptime': '31 minutes', 'communications': 'Down', 'communications_reason': 'Failure', 'conf_red_mode': 'Non-redundant', 'hw_mode': 'Simplex', 'last_switchover_reason': 'none', 'maint_mode': 'Disabled', 'oper_red_mode': 'Non-redundant', 'standby_failures': '0', 'switchovers_system_experienced': '0'}, 'slot': {'slot 6': {'boot': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin,12;', 'config_register': '0x2102', 'curr_sw_state': 'ACTIVE', 'image_ver': 'Cisco IOS Software [Bengaluru], c8000be Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Experimental Version 17.5.20201016:181710 [S2C-build-polaris_dev-124418-/nobackup/mcpre/BLD-BLD_POLARIS_DEV_LATEST_20201016_180855 217]', 'uptime_in_curr_state': '31 minutes'}}}
show_issu_state_detail = {'slot': {'R0': {'issu_in_progress': False}}}
show_issu_rollback_timer = {'rollback_timer_reason': 'no ISSU operation is in progress', 'rollback_timer_state': 'inactive'}
platform_all = {'chassis': 'C8200-1N-4T', 'chassis_sn': 'FGL2420L6EE', 'config_register': '0x2102', 'dir': 'bootflash:/', 'image': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin', 'issu_rollback_timer_reason': 'no ISSU operation is in progress', 'issu_rollback_timer_state': 'inactive', 'main_mem': '3753847', 'os': 'iosxe', 'redundancy_communication': False, 'redundancy_mode': 'Non-redundant', 'rp_uptime': 1860, 'rtr_type': 'C8200-1N-4T', 'slot': {'lc': {'0': {'name': 'C8200-1N-4T', 'sn': '', 'state': 'ok', 'subslot': {'0': {'name': '2x1G-2xSFP', 'sn': '', 'state': 'ok'}, '0 transceiver 3': {'name': 'SFP-GE-S', 'sn': 'FNS1047175F'}, '1': {'name': 'NIM-4T', 'sn': 'FOC230369RF', 'state': 'ok'}, '2': {'name': 'P-LTE-GB', 'sn': 'FOC22191PWY', 'state': 'ok'}, '5': {'name': 'SSD-M2NVME-600G', 'sn': 'INTELSSDPELKX010T8', 'state': 'ok'}}}}, 'oc': {'F0': {'name': 'C8200-1N-4T', 'sn': '', 'state': 'ok, active'}, 'Fan_Tray': {'sn': ''}, 'P0': {'name': 'PWR-INT-90WAC', 'sn': '', 'state': 'ok'}, 'P2': {'name': 'C8200-FAN-1R', 'state': 'ok'}}, 'rp': {'R0': {'boot_image': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin,12;', 'config_register': '0x2102', 'issu': {'in_progress': False}, 'name': 'C8200-1N-4T', 'redundancy_state': 'ACTIVE', 'rp_uptime': '31 minutes', 'sn': 'FOC24143XF7', 'state': 'ok, active', 'system_image': 'Cisco IOS Software [Bengaluru], c8000be Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Experimental Version 17.5.20201016:181710 [S2C-build-polaris_dev-124418-/nobackup/mcpre/BLD-BLD_POLARIS_DEV_LATEST_20201016_180855 217]'}}}, 'switchover_reason': 'none', 'version': '17.5.20201016:181710'}
platform_all_empty_dir = {'chassis': 'C8200-1N-4T', 'chassis_sn': 'FGL2420L6EE', 'config_register': '0x2102', 'dir': 'bootflash:/', 'image': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin', 'issu_rollback_timer_reason': 'no ISSU operation is in progress', 'issu_rollback_timer_state': 'inactive', 'main_mem': '3753847', 'os': 'iosxe', 'redundancy_communication': False, 'redundancy_mode': 'Non-redundant', 'rp_uptime': 1860, 'rtr_type': 'C8200-1N-4T', 'slot': {'lc': {'0': {'name': 'C8200-1N-4T', 'sn': '', 'state': 'ok', 'subslot': {'0': {'name': '2x1G-2xSFP', 'sn': '', 'state': 'ok'}, '0 transceiver 3': {'name': 'SFP-GE-S', 'sn': 'FNS1047175F'}, '1': {'name': 'NIM-4T', 'sn': 'FOC230369RF', 'state': 'ok'}, '2': {'name': 'P-LTE-GB', 'sn': 'FOC22191PWY', 'state': 'ok'}, '5': {'name': 'SSD-M2NVME-600G', 'sn': 'INTELSSDPELKX010T8', 'state': 'ok'}}}}, 'oc': {'F0': {'name': 'C8200-1N-4T', 'sn': '', 'state': 'ok, active'}, 'Fan_Tray': {'sn': ''}, 'P0': {'name': 'PWR-INT-90WAC', 'sn': '', 'state': 'ok'}, 'P2': {'name': 'C8200-FAN-1R', 'state': 'ok'}}, 'rp': {'R0': {'boot_image': 'bootflash:c8000be-universalk9.BLD_POLARIS_DEV_LATEST_20201016_180855.SSA.bin,12;', 'config_register': '0x2102', 'issu': {'in_progress': False}, 'name': 'C8200-1N-4T', 'redundancy_state': 'ACTIVE', 'rp_uptime': '31 minutes', 'sn': 'FOC24143XF7', 'state': 'ok, active', 'system_image': 'Cisco IOS Software [Bengaluru], c8000be Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Experimental Version 17.5.20201016:181710 [S2C-build-polaris_dev-124418-/nobackup/mcpre/BLD-BLD_POLARIS_DEV_LATEST_20201016_180855 217]'}}}, 'switchover_reason': 'none', 'version': '17.5.20201016:181710'} |
# This library includes some functions for integrating arrays.
def euler(Tn, dTndt, tStep):
"""
Performs Euler integration to obtain T_{n+1}.
Arguments:
Tn: Array-like representing Temperature at time t_n.
dTndt: Array-like representing dT/dt at time t_n.
tStep: Float determining the time to step over.
Returns T_{n+1} as an array-like.
"""
return Tn + dTndt * tStep
| def euler(Tn, dTndt, tStep):
"""
Performs Euler integration to obtain T_{n+1}.
Arguments:
Tn: Array-like representing Temperature at time t_n.
dTndt: Array-like representing dT/dt at time t_n.
tStep: Float determining the time to step over.
Returns T_{n+1} as an array-like.
"""
return Tn + dTndt * tStep |
class Checkpoints(webapp2.RequestHandler):
def get(self):
self.response.write(json.dumps({"meta": {"code": 400,
"errorType": "paramError",
"errorDetail": "Parameter 'api_key' is missing"
},
"response": {}
}))
| class Checkpoints(webapp2.RequestHandler):
def get(self):
self.response.write(json.dumps({'meta': {'code': 400, 'errorType': 'paramError', 'errorDetail': "Parameter 'api_key' is missing"}, 'response': {}})) |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if(not head or not head.next):
return head
curr = head
tmp = head.next
rest = None
head = tmp
rest = tmp.next
tmp.next = curr
curr.next = self.swapPairs(rest)
return head
| class Solution(object):
def swap_pairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
curr = head
tmp = head.next
rest = None
head = tmp
rest = tmp.next
tmp.next = curr
curr.next = self.swapPairs(rest)
return head |
#U
for row in range(6):
for col in range(10):
if ( col==0 and row!=4 and row!=5) or(col==4 and row!=4 and row!=5)or (row==4 and col==1 ) or (row==4 and col==2)or (row==4 and col==3):
print("*",end=" ")
else:
print(" ",end=" ")
print()
| for row in range(6):
for col in range(10):
if col == 0 and row != 4 and (row != 5) or (col == 4 and row != 4 and (row != 5)) or (row == 4 and col == 1) or (row == 4 and col == 2) or (row == 4 and col == 3):
print('*', end=' ')
else:
print(' ', end=' ')
print() |
# Write paragoo static site project files
def createproject(destinationdir):
"""Writes project files into `destinationdir`"""
return
| def createproject(destinationdir):
"""Writes project files into `destinationdir`"""
return |
#!/usr/bin/env python
class config:
def __init__(self):
self.db_user = 'DBUSERNAME'
self.db_pwd = 'DBPASSWORD'
self.db_name = 'DBNAME'
self.repo_name = "REPOSITORY"
self.user_name = "USERNAME"
self.github_api = u'https://api.github.com/repos/'
self.custom_url = "CUSTOM_URL_TO_FORWARD_PAYLOAD"
self.events_list = ['commit_comment',
'create',
'delete',
'deployment',
'deployment_status',
'download',
'follow',
'fork',
'fork_apply',
'gist',
'gollum',
'issue_comment',
'member',
'membership',
'page_build',
'ping',
'public',
'pull_request',
'pull_request_review_comment',
'push',
'release',
'repository',
'status',
'team_add',
'watch']
| class Config:
def __init__(self):
self.db_user = 'DBUSERNAME'
self.db_pwd = 'DBPASSWORD'
self.db_name = 'DBNAME'
self.repo_name = 'REPOSITORY'
self.user_name = 'USERNAME'
self.github_api = u'https://api.github.com/repos/'
self.custom_url = 'CUSTOM_URL_TO_FORWARD_PAYLOAD'
self.events_list = ['commit_comment', 'create', 'delete', 'deployment', 'deployment_status', 'download', 'follow', 'fork', 'fork_apply', 'gist', 'gollum', 'issue_comment', 'member', 'membership', 'page_build', 'ping', 'public', 'pull_request', 'pull_request_review_comment', 'push', 'release', 'repository', 'status', 'team_add', 'watch'] |
#!python
def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
Running time: O(n)
Memory usage: O(n)"""
if len(items) in [0, 1]:
return True
for i in range(len(items) - 1):
if items[i] > items[i + 1]:
return False
return True
def bubble_sort(items):
"""Sort given items by swapping adjacent items that are out of order, and
repeating until all items are in sorted order.
TODO: Running time: O(n ^ 2)
TODO: Memory usage: O(1)"""
for i in range(len(items) - 1):
for j in range(0, len(items) - i - 1):
if items[j] > items[j + 1]:
items[j], items[j + 1] = items[j + 1], items[j]
def selection_sort(items):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
TODO: Running time: O(n ^ 2)
TODO: Memory usage: O(1)"""
for i in range(len(items)):
min_ind = i
for j in range(i + 1, len(items)):
if items[min_ind] > items[j]:
min_ind = j
items[i], items[min_ind] = items[min_ind], items[i]
def insertion_sort(items):
"""Sort given items by taking first unsorted item, inserting it in sorted
order in front of items, and repeating until all items are in order.
TODO: Running time: O(n ^ 2)
TODO: Memory usage: O(1)"""
for i in range(len(items)):
j = i - 1;
while j >= 0 and items[i] < items[j]:
items[j + 1] = items[j]
j -= 1
items[j + 1] = items[i] | def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
Running time: O(n)
Memory usage: O(n)"""
if len(items) in [0, 1]:
return True
for i in range(len(items) - 1):
if items[i] > items[i + 1]:
return False
return True
def bubble_sort(items):
"""Sort given items by swapping adjacent items that are out of order, and
repeating until all items are in sorted order.
TODO: Running time: O(n ^ 2)
TODO: Memory usage: O(1)"""
for i in range(len(items) - 1):
for j in range(0, len(items) - i - 1):
if items[j] > items[j + 1]:
(items[j], items[j + 1]) = (items[j + 1], items[j])
def selection_sort(items):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
TODO: Running time: O(n ^ 2)
TODO: Memory usage: O(1)"""
for i in range(len(items)):
min_ind = i
for j in range(i + 1, len(items)):
if items[min_ind] > items[j]:
min_ind = j
(items[i], items[min_ind]) = (items[min_ind], items[i])
def insertion_sort(items):
"""Sort given items by taking first unsorted item, inserting it in sorted
order in front of items, and repeating until all items are in order.
TODO: Running time: O(n ^ 2)
TODO: Memory usage: O(1)"""
for i in range(len(items)):
j = i - 1
while j >= 0 and items[i] < items[j]:
items[j + 1] = items[j]
j -= 1
items[j + 1] = items[i] |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
sorted_arr = []
count_zero = 0
for i in input_list:
if i == 0:
sorted_arr = [i] + sorted_arr
count_zero += 1
elif i == 1:
sorted_arr = sorted_arr[:count_zero] + [i] + sorted_arr[count_zero:]
else:
sorted_arr.append(i)
return sorted_arr
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
# All the tests should print Pass
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
test_function([0, 1])
test_function([1, 0])
test_function([0])
test_function([1])
test_function([2]) | def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
sorted_arr = []
count_zero = 0
for i in input_list:
if i == 0:
sorted_arr = [i] + sorted_arr
count_zero += 1
elif i == 1:
sorted_arr = sorted_arr[:count_zero] + [i] + sorted_arr[count_zero:]
else:
sorted_arr.append(i)
return sorted_arr
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print('Pass')
else:
print('Fail')
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
test_function([0, 1])
test_function([1, 0])
test_function([0])
test_function([1])
test_function([2]) |
#!/usr/bin/env python3
#
# Author: Vishwas K Singh
# Email: vishwasks32@gmail.com
num1 = float(input("Enter the First Number: "))
num2 = float(input("Enter the Second Number: "))
print(num1+num2)
| num1 = float(input('Enter the First Number: '))
num2 = float(input('Enter the Second Number: '))
print(num1 + num2) |
'''
Created on Apr 24, 2014
@author: Cory
'''
class Camera:
def __init__(self, location, bounds):
self.location = location
self.bounds = bounds
def set_camera_loc(self, location):
self.location = location
def bound_camera(self, map_bounds):
camx, camy = self.location
camw, camh = self.bounds
if camx - camw/2 < 0:
self.location = (camw/2, camy)
elif camx + camw/2 > map_bounds[0]:
self.location = (map_bounds[0] - camw/2, camy)
if camy - camh/2 < 0:
self.location = (self.location[0], camh/2)
elif camy + camh/2 > map_bounds[1]:
self.location = (self.location[0], map_bounds[1] - camh/2) | """
Created on Apr 24, 2014
@author: Cory
"""
class Camera:
def __init__(self, location, bounds):
self.location = location
self.bounds = bounds
def set_camera_loc(self, location):
self.location = location
def bound_camera(self, map_bounds):
(camx, camy) = self.location
(camw, camh) = self.bounds
if camx - camw / 2 < 0:
self.location = (camw / 2, camy)
elif camx + camw / 2 > map_bounds[0]:
self.location = (map_bounds[0] - camw / 2, camy)
if camy - camh / 2 < 0:
self.location = (self.location[0], camh / 2)
elif camy + camh / 2 > map_bounds[1]:
self.location = (self.location[0], map_bounds[1] - camh / 2) |
def potencia(op1, op2):
print("El resultado de la potencia es: ", op1**op2)
def redondear(op1):
print("El resultado del redondeo es: ", round(op1))
| def potencia(op1, op2):
print('El resultado de la potencia es: ', op1 ** op2)
def redondear(op1):
print('El resultado del redondeo es: ', round(op1)) |
#! /usr/bin/env python3
user_input = input("Please enter some words separated by commas: ")
list_of_words = [word.strip() for word in user_input.split(",")]
unique_words = []
for word in sorted(list_of_words):
if word not in unique_words:
unique_words.append(word)
unique_words = set(sorted(list_of_words))
print(list_of_words)
print(unique_words)
| user_input = input('Please enter some words separated by commas: ')
list_of_words = [word.strip() for word in user_input.split(',')]
unique_words = []
for word in sorted(list_of_words):
if word not in unique_words:
unique_words.append(word)
unique_words = set(sorted(list_of_words))
print(list_of_words)
print(unique_words) |
def spiral(size):
sm = [[0]*size for k in range(size)]
i, j, el = 0, -1, 1
di, dj = [0, 1, 0, -1], [1, 0, -1, 0]
for x in range(2*size - 1):
for y in range((2*size - x) // 2):
i += di[x % 4]
j += dj[x % 4]
sm[i][j] = el
el += 1
return sm
| def spiral(size):
sm = [[0] * size for k in range(size)]
(i, j, el) = (0, -1, 1)
(di, dj) = ([0, 1, 0, -1], [1, 0, -1, 0])
for x in range(2 * size - 1):
for y in range((2 * size - x) // 2):
i += di[x % 4]
j += dj[x % 4]
sm[i][j] = el
el += 1
return sm |
# Time: O(logn) = O(32)
# Space: O(1)
class Solution(object):
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
result = 0
while n:
n &= n - 1
result += 1
return result
| class Solution(object):
def hamming_weight(self, n):
result = 0
while n:
n &= n - 1
result += 1
return result |
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class LinkedList:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = Node(data=nodes.pop(0))
self.head = node
for item in nodes:
node.next = Node(data=item)
node = node.next
def add_first(self,node):
node.next = self.head
self.head = node
def add_last(self,node):
if self.head is None:
self.head = node
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
#Implmenation pending
def add_after(self, target_node_data, new_node):
if not self.head:
raise Exception("List is emppty")
pass
#Implmenation pending
def add_before(self, target_node_data, new_node):
if not self.head:
raise Exception("List is empty")
pass
#Implmenation pending
def remove_node(self, target_node_data):
pass
def __iter__(self):
node = self.head
while node is not None:
yield node
node = node.next
# Debugging repr implementation
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.data)
node = node.next
nodes.append('None')
return " -> ".join(nodes)
if __name__ == '__main__':
ll = LinkedList(['a','b'])
ll.add_first(Node("A"))
print(ll)
ll1 = LinkedList()
print(ll1)
ll1.add_last(Node("c"))
print(ll1) | class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class Linkedlist:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = node(data=nodes.pop(0))
self.head = node
for item in nodes:
node.next = node(data=item)
node = node.next
def add_first(self, node):
node.next = self.head
self.head = node
def add_last(self, node):
if self.head is None:
self.head = node
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
def add_after(self, target_node_data, new_node):
if not self.head:
raise exception('List is emppty')
pass
def add_before(self, target_node_data, new_node):
if not self.head:
raise exception('List is empty')
pass
def remove_node(self, target_node_data):
pass
def __iter__(self):
node = self.head
while node is not None:
yield node
node = node.next
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.data)
node = node.next
nodes.append('None')
return ' -> '.join(nodes)
if __name__ == '__main__':
ll = linked_list(['a', 'b'])
ll.add_first(node('A'))
print(ll)
ll1 = linked_list()
print(ll1)
ll1.add_last(node('c'))
print(ll1) |
def calculateEstimate(data, converted_time, type='impact'):
my_dict= {}
# calculate factor value
factor = 2 ** (converted_time // 3)
# my solution for challenge one
if type == 'impact':
my_dict['currentlyInfected'] = int(my_dict['reportedCases'] * 10)
my_dict['infectionsByRequestedTime'] = my_dict['currentlyInfected'] * factor
elif type == 'severeImpact':
my_dict['currentlyInfected'] = int(data['reportedCases'] * 50)
my_dict['infectionsByRequestedTime'] = int(
my_dict['currentlyInfected'] * factor)
# my solution for challenge two
my_dict['severeCasesByRequestedTime'] = int(
0.15 * my_dict['infectionsByRequestedTime'])
available_beds = 0.35 * data['totalHospitalBeds']
my_dict['hospitalBedsByRequestedTime'] = int(
available_beds - my_dict['severeCasesByRequestedTime'])
# my solution for challenge three
my_dict['casesForICUByRequestedTime'] = int(0.05 * my_dict['infectionsByRequestedTime'])
my_dict['casesForVentilatorsByRequestedTime'] = int(0.02 * my_dict['infectionsByRequestedTime'])
dollars_in_flight = my_dict['infectionsByRequestedTime'] * data['region']['avgDailyIncomePopulation'] * \
data['region']['avgDailyIncomeInUSD']
my_dict['dollarsInFlight'] = int(dollars_in_flight / converted_time)
return my_dict
def estimator(data):
# convert time
converted_time = data['timeToElapse']
if data['periodType'] == 'weeks':
converted_time = converted_time * 7
elif data['periodType'] == 'months':
converted_time = converted_time * 30
impact = calculateEstimate(data, converted_time=converted_time)
severe_impact = calculateEstimate(
data, converted_time=converted_time, type='severeImpact')
result = {
'data': data,
'impact': impact,
'severeImpact': severe_impact
}
return result | def calculate_estimate(data, converted_time, type='impact'):
my_dict = {}
factor = 2 ** (converted_time // 3)
if type == 'impact':
my_dict['currentlyInfected'] = int(my_dict['reportedCases'] * 10)
my_dict['infectionsByRequestedTime'] = my_dict['currentlyInfected'] * factor
elif type == 'severeImpact':
my_dict['currentlyInfected'] = int(data['reportedCases'] * 50)
my_dict['infectionsByRequestedTime'] = int(my_dict['currentlyInfected'] * factor)
my_dict['severeCasesByRequestedTime'] = int(0.15 * my_dict['infectionsByRequestedTime'])
available_beds = 0.35 * data['totalHospitalBeds']
my_dict['hospitalBedsByRequestedTime'] = int(available_beds - my_dict['severeCasesByRequestedTime'])
my_dict['casesForICUByRequestedTime'] = int(0.05 * my_dict['infectionsByRequestedTime'])
my_dict['casesForVentilatorsByRequestedTime'] = int(0.02 * my_dict['infectionsByRequestedTime'])
dollars_in_flight = my_dict['infectionsByRequestedTime'] * data['region']['avgDailyIncomePopulation'] * data['region']['avgDailyIncomeInUSD']
my_dict['dollarsInFlight'] = int(dollars_in_flight / converted_time)
return my_dict
def estimator(data):
converted_time = data['timeToElapse']
if data['periodType'] == 'weeks':
converted_time = converted_time * 7
elif data['periodType'] == 'months':
converted_time = converted_time * 30
impact = calculate_estimate(data, converted_time=converted_time)
severe_impact = calculate_estimate(data, converted_time=converted_time, type='severeImpact')
result = {'data': data, 'impact': impact, 'severeImpact': severe_impact}
return result |
class data():
def media(self,x):
totalx=len(x)
somatorio=0;
for x_i in x:
somatorio+=x_i
pass
return somatorio/totalx
def Quantil(self,porcent,x):
return porcent*len(x)
pass
def Correlacao(self,x,y):
for x_i in x:
x_i+=x_i
for y_i in y:
y_i+=y_i
return x_i+y_i/len(x)-1
pass
def derivada(self,x,ponto):
return x+ponto+1
pass
def Aoquadrado(x):
return x*2
pass
def Acurracia(self,x,y):
return x-y
pass
pass
| class Data:
def media(self, x):
totalx = len(x)
somatorio = 0
for x_i in x:
somatorio += x_i
pass
return somatorio / totalx
def quantil(self, porcent, x):
return porcent * len(x)
pass
def correlacao(self, x, y):
for x_i in x:
x_i += x_i
for y_i in y:
y_i += y_i
return x_i + y_i / len(x) - 1
pass
def derivada(self, x, ponto):
return x + ponto + 1
pass
def aoquadrado(x):
return x * 2
pass
def acurracia(self, x, y):
return x - y
pass
pass |
""" Checking the height, weight and age of students in two classes (A and B) of two schools. """
class school():
def __init__(self, age, height, weight):
self.age = age
self.height = height
self.weight = weight
# Calculating the average age of students
def age_average(self, age):
age_avg = sum(age) / len(age)
return age_avg
# Calculating the average height of students
def height_average(self, height):
height_avg = sum(height) / len(height)
return height_avg
# Calculating the average weight of students
def weight_average(self, weight):
weight_avg = sum(weight) / len(weight)
return weight_avg
# Prints a class with an average height
def max_average():
if A.height_average(heightA) > B.height_average(heightB):
print('A')
elif A.height_average(heightA) == B.height_average(heightB):
Aw = A.weight_average(weightA)
Bw = B.weight_average(weightB)
if Aw < Bw :
print('A')
if Aw > Bw :
print('B')
if Aw == Bw :
print('Same')
elif A.height_average(heightA) < B.height_average(heightB):
print('B')
numA = int(input("enter the number of students:"))
ageA = list(map(int,input("enter the age of the students: ").split()))
heightA = list(map(int,input("enter the height of the students:").split()))
weightA = list(map(int,input("enter the weight of the students:").split()))
numB = int(input("enter the number of students:"))
ageB = list(map(int,input("enter the age of the students: ").split()))
heightB = list(map(int,input("enter the height of the students:").split()))
weightB = list(map(int,input("enter the weight of the students:").split()))
A = school(ageA, heightA, weightA)
B = school(ageB, heightB, weightB)
print(float(A.age_average(ageA)))
print(float(A.height_average(heightA)))
print(float(A.weight_average(weightA)))
print(float(B.age_average(ageB)))
print(float(B.height_average(heightB)))
print(float(B.weight_average(weightB)))
max_average() | """ Checking the height, weight and age of students in two classes (A and B) of two schools. """
class School:
def __init__(self, age, height, weight):
self.age = age
self.height = height
self.weight = weight
def age_average(self, age):
age_avg = sum(age) / len(age)
return age_avg
def height_average(self, height):
height_avg = sum(height) / len(height)
return height_avg
def weight_average(self, weight):
weight_avg = sum(weight) / len(weight)
return weight_avg
def max_average():
if A.height_average(heightA) > B.height_average(heightB):
print('A')
elif A.height_average(heightA) == B.height_average(heightB):
aw = A.weight_average(weightA)
bw = B.weight_average(weightB)
if Aw < Bw:
print('A')
if Aw > Bw:
print('B')
if Aw == Bw:
print('Same')
elif A.height_average(heightA) < B.height_average(heightB):
print('B')
num_a = int(input('enter the number of students:'))
age_a = list(map(int, input('enter the age of the students: ').split()))
height_a = list(map(int, input('enter the height of the students:').split()))
weight_a = list(map(int, input('enter the weight of the students:').split()))
num_b = int(input('enter the number of students:'))
age_b = list(map(int, input('enter the age of the students: ').split()))
height_b = list(map(int, input('enter the height of the students:').split()))
weight_b = list(map(int, input('enter the weight of the students:').split()))
a = school(ageA, heightA, weightA)
b = school(ageB, heightB, weightB)
print(float(A.age_average(ageA)))
print(float(A.height_average(heightA)))
print(float(A.weight_average(weightA)))
print(float(B.age_average(ageB)))
print(float(B.height_average(heightB)))
print(float(B.weight_average(weightB)))
max_average() |
"""
https://www.hackerrank.com/challenges/one-week-preparation-kit-lonely-integer/problem
"""
def _solve_method_2(a):
"""Use a dictionary."""
d = dict()
for item in a:
if not item in d:
d[item] = 1
else:
d[item] += 1
for k, v in d.items():
if v == 1:
return k
def _solve_method_1(a):
"""First sort them, and then count by two's, until a 'problem' is found."""
a = sorted(a)
found_it = a[0]
def lonely_integer(a):
return _solve_method_2(a)
if __name__ == '__main__':
assert lonely_integer([1, 2, 3, 4, 3, 2, 1]) == 4
| """
https://www.hackerrank.com/challenges/one-week-preparation-kit-lonely-integer/problem
"""
def _solve_method_2(a):
"""Use a dictionary."""
d = dict()
for item in a:
if not item in d:
d[item] = 1
else:
d[item] += 1
for (k, v) in d.items():
if v == 1:
return k
def _solve_method_1(a):
"""First sort them, and then count by two's, until a 'problem' is found."""
a = sorted(a)
found_it = a[0]
def lonely_integer(a):
return _solve_method_2(a)
if __name__ == '__main__':
assert lonely_integer([1, 2, 3, 4, 3, 2, 1]) == 4 |
# Link: https://leetcode.com/problems/palindrome-number/
class Solution:
# @param {integer} x
# @return {boolean}
def isPalindrome(self, x):
x = str(x)
for i in range(0, len(x) / 2):
if x[i] != x[len(x) - i - 1]:
return False
return True
| class Solution:
def is_palindrome(self, x):
x = str(x)
for i in range(0, len(x) / 2):
if x[i] != x[len(x) - i - 1]:
return False
return True |
# Python Tuples (a,b)
# Immutable
# Use - passing data that does not need changing
# Faster than list
# "safer" than list
# Can be key in dict unlike list
# For Heterogeneous data - meaning mixing different data types(int,str,list et al) inside
# https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences
# https://realpython.com/python-lists-tuples/
my_tuple = ("Valdis", "programmer", 45, 200, [1, 2, 3])
print(my_tuple)
type(my_tuple)
print(my_tuple[0])
len(my_tuple)
my_tuple[-1]
my_tuple[-1][1]
mini_3 = my_tuple[:3]
print(mini_3, type(mini_3))
my_tuple[::2]
my_tuple[::-1]
reverse_inner = tuple(el * 2 for el in my_tuple)
my_list = []
for el in my_tuple:
if type(el) == int:
my_list.append(1/el)
else:
my_list.append(el[::-1])
my_rev_tuple = tuple(my_list)
my_rev_tuple
print(my_tuple)
# my_tuple[1] = "scientist"
my_list = list(my_tuple)
print(my_list)
my_list[1] = "scientist"
new_tuple = tuple(my_list)
print(new_tuple)
t = () # empty tuple only question where would you use it?
print(t, type(t))
t = (1, 2, 55) # 2 or more elements
print(t, type(t))
t = (5,) # if you really need a tuple of one element
my_tuple.count("programmer")
new_tuple.count("programmer")
new_tuple.index("scientist")
my_tuple.index(45)
a = 10
b = 20
print(a, b)
# how to change them
temp = a
a = b
b = temp
print(a, b)
# in Python the above is simpler!
print(a, b)
a, b = b, a # we can even change a,b,c,d = d,c,b,a and more
print(a, b)
(name, job, age, top_speed, favorite_list) = my_tuple # tuple unpacking
print(name, job, age, top_speed, favorite_list)
name is my_tuple[0]
# tuple unpacking and using _ for values that we do need
(name, job, _, top_speed, _) = my_tuple
print(name, _) # so _ will have value of last unpacking
def getMinMax(my_num_list):
# so tuple will be created when returning multiple values
return min(my_num_list), max(my_num_list)
res = getMinMax([3, 6, 1, 2])
print(res, type(res))
| my_tuple = ('Valdis', 'programmer', 45, 200, [1, 2, 3])
print(my_tuple)
type(my_tuple)
print(my_tuple[0])
len(my_tuple)
my_tuple[-1]
my_tuple[-1][1]
mini_3 = my_tuple[:3]
print(mini_3, type(mini_3))
my_tuple[::2]
my_tuple[::-1]
reverse_inner = tuple((el * 2 for el in my_tuple))
my_list = []
for el in my_tuple:
if type(el) == int:
my_list.append(1 / el)
else:
my_list.append(el[::-1])
my_rev_tuple = tuple(my_list)
my_rev_tuple
print(my_tuple)
my_list = list(my_tuple)
print(my_list)
my_list[1] = 'scientist'
new_tuple = tuple(my_list)
print(new_tuple)
t = ()
print(t, type(t))
t = (1, 2, 55)
print(t, type(t))
t = (5,)
my_tuple.count('programmer')
new_tuple.count('programmer')
new_tuple.index('scientist')
my_tuple.index(45)
a = 10
b = 20
print(a, b)
temp = a
a = b
b = temp
print(a, b)
print(a, b)
(a, b) = (b, a)
print(a, b)
(name, job, age, top_speed, favorite_list) = my_tuple
print(name, job, age, top_speed, favorite_list)
name is my_tuple[0]
(name, job, _, top_speed, _) = my_tuple
print(name, _)
def get_min_max(my_num_list):
return (min(my_num_list), max(my_num_list))
res = get_min_max([3, 6, 1, 2])
print(res, type(res)) |
# TABUADA DE UM NUMERO
num = int(input('Tabuada do: '))
print('{} X 1 = {}'.format(num, (num*1)))
print('{} X 2 = {}'.format(num, (num*2)))
print('{} X 3 = {}'.format(num, (num*3)))
print('{} X 4 = {}'.format(num, (num*4)))
print('{} X 5 = {}'.format(num, (num*5)))
print('{} X 6 = {}'.format(num, (num*6)))
print('{} X 7 = {}'.format(num, (num*7)))
print('{} X 8 = {}'.format(num, (num*8)))
print('{} X 9 = {}'.format(num, (num*9)))
print('{} X 10 = {}'.format(num, (num*10))) | num = int(input('Tabuada do: '))
print('{} X 1 = {}'.format(num, num * 1))
print('{} X 2 = {}'.format(num, num * 2))
print('{} X 3 = {}'.format(num, num * 3))
print('{} X 4 = {}'.format(num, num * 4))
print('{} X 5 = {}'.format(num, num * 5))
print('{} X 6 = {}'.format(num, num * 6))
print('{} X 7 = {}'.format(num, num * 7))
print('{} X 8 = {}'.format(num, num * 8))
print('{} X 9 = {}'.format(num, num * 9))
print('{} X 10 = {}'.format(num, num * 10)) |
def filter_variance(data, lower, upper):
"""
:param data: abundance data frame
:param lower: lower percentile filter
:param upper: upper percentile filter
:return: filtered abundance data frame
"""
data['row_variance'] = data.var(axis=1)
lower_quantile = data['row_variance'].quantile(round(lower/100, 1))
upper_quantile = data['row_variance'].quantile(round(upper/100, 1))
quantile_filtered = data[data['row_variance'].gt(lower_quantile) & data['row_variance'].lt(upper_quantile)]
quantile_filtered.drop(columns=['row_variance'], inplace=True)
return quantile_filtered
| def filter_variance(data, lower, upper):
"""
:param data: abundance data frame
:param lower: lower percentile filter
:param upper: upper percentile filter
:return: filtered abundance data frame
"""
data['row_variance'] = data.var(axis=1)
lower_quantile = data['row_variance'].quantile(round(lower / 100, 1))
upper_quantile = data['row_variance'].quantile(round(upper / 100, 1))
quantile_filtered = data[data['row_variance'].gt(lower_quantile) & data['row_variance'].lt(upper_quantile)]
quantile_filtered.drop(columns=['row_variance'], inplace=True)
return quantile_filtered |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class Openvslam(CMakePackage):
"""OpenVSLAM is a monocular, stereo, and RGBD visual SLAM system."""
homepage = "https://openvslam.readthedocs.io/"
git = "https://github.com/xdspacelab/openvslam.git"
version('master', branch='master')
# https://openvslam.readthedocs.io/en/master/installation.html
depends_on('cmake@3.1:', type='build')
depends_on('eigen@3.3.0:')
depends_on('g2o')
depends_on('dbow2@shinsumicco')
depends_on('yaml-cpp@0.6.0:')
depends_on('opencv@3.3.1:+core+imgcodecs+videoio+features2d+calib3d+highgui')
depends_on('pangolin')
patch('https://github.com/xdspacelab/openvslam/commit/eeb58880443700fd79688d9646fd633c42fa60eb.patch',
sha256='131159b0042300614d039ceb3538defe4d302b59dc748b02287fc8ff895e6bbd')
@run_after('install')
def post_install(self):
# https://github.com/xdspacelab/openvslam/issues/501
mkdir(self.prefix.bin)
with working_dir(self.build_directory):
install('run_*', self.prefix.bin)
install(join_path('lib*', 'libpangolin_viewer.*'), self.prefix.lib)
| class Openvslam(CMakePackage):
"""OpenVSLAM is a monocular, stereo, and RGBD visual SLAM system."""
homepage = 'https://openvslam.readthedocs.io/'
git = 'https://github.com/xdspacelab/openvslam.git'
version('master', branch='master')
depends_on('cmake@3.1:', type='build')
depends_on('eigen@3.3.0:')
depends_on('g2o')
depends_on('dbow2@shinsumicco')
depends_on('yaml-cpp@0.6.0:')
depends_on('opencv@3.3.1:+core+imgcodecs+videoio+features2d+calib3d+highgui')
depends_on('pangolin')
patch('https://github.com/xdspacelab/openvslam/commit/eeb58880443700fd79688d9646fd633c42fa60eb.patch', sha256='131159b0042300614d039ceb3538defe4d302b59dc748b02287fc8ff895e6bbd')
@run_after('install')
def post_install(self):
mkdir(self.prefix.bin)
with working_dir(self.build_directory):
install('run_*', self.prefix.bin)
install(join_path('lib*', 'libpangolin_viewer.*'), self.prefix.lib) |
# import datetime
# from functools import wraps
# from app import datetime, Share, desc, Mail, Message, Cache, SQLAlchemy, session, request, flash, render_template, redirect, url_for, Markup
# ------------------------------------------------------------------
# helper functions to clean up app.py / view file
def get_datetime_today():
now = datetime.datetime.now()
today = datetime.date(now.year, now.month, now.day)
return today
# Converts numbers to $---,---,---.-- format and returns as string.
def pretty_numbers(value):
return '${:,.2f}'.format(value)
def pretty_ints(value):
return '{:,}'.format(value)
def pretty_percent(value):
return '{:,.2f}%'.format(value)
def pretty_leaders(leaders):
for l in leaders:
l.prettyvalue = pretty_numbers(l.value)
return leaders
# Determines the color for gains/loses by passing a boolean value
# to the html template
def set_color(change):
if float(change) < 0.000000:
return True
else:
return False
# cache
def get_leaderboard(user):
allplayers = Portfolio.query.order_by(desc(Portfolio.value)).all()
leaders = Portfolio.query.order_by(desc(Portfolio.value)).limit(5).all()
leaders = pretty_leaders(leaders)
allplayers = pretty_leaders(allplayers)
if user != None:
user = User.query.filter_by(name=session['username']).first()
# finding player's position in leaderboard
for idx, val in enumerate(allplayers):
if user.portfolio == val:
user.rank = idx+1
else:
loggedin_user = None # needed?
user = None
return user, allplayers, leaders
def get_user():
if 'username' in session:
loggedin_user = session['username']
user = session['username']
else:
loggedin_user = None
user = None
return user
# bypass? or cache?
def get_account_details(portfolio, positions):
value = portfolio.cash
total_gain_loss = float(0.00)
total_cost = float(0.00)
for p in positions:
stock_lookup_and_write(p.symbol)
p.value = Stock.query.filter_by(symbol=p.symbol).first().price*p.sharecount
p.prettyvalue = pretty_numbers(p.value)
p.prettycost = pretty_numbers(p.cost)
value += p.value
p.gain_loss = p.value - p.cost
p.gain_loss_percent = p.gain_loss/p.cost*100
if p.gain_loss <= 0.0000:
p.loss = True
p.prettygain_loss = pretty_numbers(p.gain_loss)
total_gain_loss = float(p.gain_loss) + total_gain_loss
total_cost = float(p.cost) + total_cost
p.prettygain_loss_percent = pretty_percent(p.gain_loss_percent)
portfolio.total_cost = total_cost
portfolio.prettytotal_cost = pretty_numbers(total_cost)
portfolio.value = value
portfolio.prettyvalue = pretty_numbers(portfolio.value)
portfolio.prettycash = pretty_numbers(portfolio.cash)
portfolio.total_stock_value = portfolio.value - portfolio.cash
portfolio.prettytotal_stock_value = pretty_numbers(portfolio.total_stock_value)
portfolio.total_gain_loss = total_gain_loss
portfolio.prettytotal_gain_loss = pretty_numbers(portfolio.total_gain_loss)
if portfolio.total_cost != 0.00:
portfolio.total_gain_loss_percent = portfolio.total_gain_loss/portfolio.total_cost*100
portfolio.prettytotal_gain_loss_percent = pretty_percent(portfolio.total_gain_loss_percent)
else:
portfolio.total_gain_loss_percent = 0
portfolio.prettytotal_gain_loss_percent = "0%"
if portfolio.total_gain_loss < 0.00:
portfolio.loss = True
db.session.commit() # not necessary?
return portfolio, positions
# This is to take out punctuation and white spaces from the stock search string.
def clean_stock_search(symbol):
punctuation = '''!()-[]{ };:'"\,<>./?@#$%^&*_~0123456789'''
no_punct = ""
for char in symbol:
if char not in punctuation:
no_punct = no_punct + char
if len(no_punct) == 0:
no_punct = 'RETRY'
return no_punct
# bypass?
# @db_if_yahoo_fail
def get_Share(symbol):
stock = Share(clean_stock_search(symbol))
return stock
# Puts various attributes into 'stock' via different Share methods.
def set_stock_data(stock):
stock.name = stock.data_set["Name"]
stock.symbol = stock.data_set["Symbol"].upper()
stock.exchange = stock.get_stock_exchange()
stock.price = float(stock.get_price())
stock.prettyprice = pretty_numbers(stock.price)
stock.change = stock.get_change()
stock.percent_change = stock.data_set["PercentChange"]
stock.afterhours = stock.data_set['AfterHoursChangeRealtime']
stock.last_traded = stock.get_trade_datetime()
stock.prev_close = stock.get_prev_close()
stock.open = stock.get_open()
stock.bid = stock.data_set['Bid']
stock.ask = stock.data_set['Ask']
stock.yr_target = stock.data_set['OneyrTargetPrice']
stock.volume = stock.get_volume()
stock.av_volume = stock.get_avg_daily_volume()
stock.day_low = stock.get_days_low()
stock.day_high = stock.get_days_high()
stock.day_range = str(stock.day_high)+" - "+str(stock.day_low)
stock.year_high = stock.get_year_high()
stock.year_low = stock.get_year_low()
stock.year_range = str(stock.year_high)+" - "+str(stock.year_low)
stock.market_cap = stock.data_set["MarketCapitalization"]
stock.peratio = stock.data_set["PERatio"]
if stock.peratio != None:
stock.prettyperatio = pretty_numbers(float(stock.peratio))
else:
stock.prettyperatio = None
stock.div = stock.data_set["DividendYield"]
# not sure why this is causing problems, commenting for now
# stock.div = float(stock.div)
stock.prettyex_div = stock.data_set['ExDividendDate']
stock.ex_div = convert_yhoo_date(stock.data_set['ExDividendDate'])
stock.prettydiv_pay = stock.data_set['DividendPayDate']
stock.div_pay = convert_yhoo_date(stock.data_set['DividendPayDate'])
stock.view_count = 1
stock.loss = set_color(stock.change)
return stock
def write_stock_to_db(stock):
# Here, the input 'stock' argument is a stock object
# which has been passed through the set_stock_data function.
# it might be worth taking the commit()s outside of the function
if Stock.query.filter_by(symbol=stock.symbol).first() == None:
db.session.add(Stock(stock.symbol, stock.name, stock.exchange, stock.price, \
stock.div, stock.ex_div, stock.div_pay, stock.market_cap, stock.view_count))
db.session.commit()
else:
write_stock = Stock.query.filter_by(symbol=stock.symbol).first()
write_stock.view_count += 1
write_stock.price = stock.price
write_stock.div_yield = stock.div
write_stock.ex_div = stock.ex_div
write_stock.div_pay = stock.div_pay
write_stock.market_cap = stock.market_cap
db.session.commit()
# Look up a stock based on a 'cleaned' input string
def stock_lookup_and_write(symbol):
stock = set_stock_data(Share(symbol))
write_stock_to_db(stock)
return stock
# I don't think I've implemented this everywhere yet, need to review.
def search_company(symbol):
symbol = "%"+symbol+"%"
# results = Stock.query.filter(Stock.name.ilike(symbol)).first()
results = Stock.query.filter(Stock.name.ilike(symbol)).all()
return results
# Yahoo dates are strings that look like "8/12/2015"; we need to
# convert this into a python datetime format for the db.
def convert_yhoo_date(yhoo_date):
# argument yhoo_date should look like "8/6/2015" or None.
if yhoo_date != None:
# split and unpack month, day, year variables
month, day, year = yhoo_date.split('/')
# convert from strings to integers, for datetime.date function below
month = int(month)
day = int(day)
year = int(year)
# create datetime object
return datetime.date(year, month, day)
else:
return None
def trade(stock, share_amount, buy_or_sell, user, portfolio, positions):
stock = set_stock_data(stock)
write_stock_to_db(stock) # NOW?
# get actual stock in db ## WHY?
stock = Stock.query.filter_by(symbol=stock.symbol).first()
# price and total_cost should be float
price = (stock.price) #I don't think this is strictly necessary.
total_cost = float(share_amount*price)
today = get_datetime_today()
# 1 or -1 multiplier against share_amount
if buy_or_sell == 'buy':
# wants to buy
bs_mult = 1
total_cost = total_cost*bs_mult
# check to see if user has enough cash available
cash = float(portfolio.cash)
if cash > total_cost:
new_cash = cash - total_cost
# for new positions in a given stock
if portfolio.positions.filter_by(symbol=stock.symbol).first() == None:
# create & write the new position
position = Position(user.portfolio.id, stock.symbol, total_cost, total_cost, share_amount, None)
db.session.add(position)
db.session.commit()
flash(" Opened position in " + stock.name + ".")
# now create trade (need datetime object)
trade = Trade(stock.symbol, position.id, user.portfolio.id, total_cost, share_amount, today, stock.div_yield, stock.ex_div, stock.div_pay)
db.session.add(trade)
# db.session.commit()
flash("You bought " + str(share_amount) + " shares of " + stock.name + " at " + pretty_numbers(price) + " per share.")
# adjusting user.portfolio.cash
user.portfolio.cash = new_cash
db.session.commit()
flash("Cash adjusted: -" + pretty_numbers(total_cost))
# for already existing positions
elif user.portfolio.positions.filter_by(symbol=stock.symbol).all() != None:
position = user.portfolio.positions.filter_by(symbol=stock.symbol).first()
# found the position, now adjust share count.
trade = Trade(stock.symbol, position.id, user.portfolio.id, total_cost, share_amount, today, stock.div_yield, stock.ex_div, stock.div_pay)
db.session.add(trade)
flash("You bought " + str(share_amount) + " shares of " + stock.name + " at " + pretty_numbers(price) + " per share.")
user.portfolio.cash = new_cash
position.cost = float(position.cost) + total_cost
position.value = float(position.value) + total_cost
position.sharecount += share_amount
db.session.commit()
else:
deficit = total_cost - cash
flash("Sorry, that costs "+ pretty_numbers(total_cost) + ", which is " + pretty_numbers(deficit) + " more than you have available. Try buying fewer shares.")
else:
# wants to sell
bs_mult = -1
total_cost = total_cost*bs_mult
# check to see if there are enough stocks in the user's position
position = user.portfolio.positions.filter_by(symbol=stock.symbol).first()
if position != None:
if position.sharecount >= share_amount:
trade = Trade(stock.symbol, position.id, user.portfolio.id, total_cost, -1*share_amount, today, stock.div_yield, stock.ex_div, stock.div_pay)
db.session.add(trade)
flash("You sold " + str(share_amount) + " shares of " + stock.name + " at " + pretty_numbers(stock.price) + " per share. Adding " + pretty_numbers(total_cost*-1) + " to your cash balance.")
# update position
user.portfolio.cash = float(user.portfolio.cash) - total_cost
position.cost = float(position.cost) + total_cost
position.value = float(position.value) + total_cost
position.sharecount = position.sharecount + share_amount*bs_mult
# I'll remove this one if I can figure out the bug with Heroku's db.
db.session.commit()
# close position if no more shares
if position.sharecount == 0:
try:
db.session.delete(position)
db.session.commit()
flash("Your position in " + stock.name + " has been closed.")
except:
flash("Your position in " + stock.name + " is now empty. I'm working on a way to remove it from the database.")
else:
flash("You only have " + str(position.sharecount) + " shares of " + str(stock.symbol) + ". Try selling fewer shares.")
else:
flash("You don't have any shares of " + stock.symbol + " to sell.")
def new_user_email(user):
msg = Message('Welcome to StockHawk, {}!'.format(user.name), sender=('Adam', config.BaseConfig.MAIL_USERNAME), recipients=[user.email])
msg.html = "<h3>Hi %s,</h3><p>Thanks for registering an account with StockHawk. We've added $1,000,000 of play money to your account. <a href='http://stockhawk.herokuapp.com/login'>Sign in</a> and start trading!<br><br>Good luck!<br> - Adam</p>" % user.name
mail.send(msg)
def reset_password_email(user):
pass
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('You need to log in first.')
return redirect(url_for('login'))
return wrap
def login_reminder(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
message = Markup("<a href='/login'>Sign in</a> or <a href='/register'>register</a> to play.")
flash(message)
return f(*args, **kwargs)
return wrap
# Started, but not finished this decorator. I need to think about if it makes sense to implement this. There might be use cases for a similar decorator to limit trading times/days, but again, that might not serve a purpose.
# def after_hours_mode(f):
# @wraps(f)
# def wrap(*args, **kwargs):
# now = datetime.datetime.utcnow()
# if now.weekday() >= 5:
# #don't allow queries UNLESS the stock is NOT in db
# pass
# else:
# return f(*args, **kwargs)
# return wrap
# If there's no connectivity to yahoo-finance api, bypass and query db instead, but also indicate this to user
# def db_if_yahoo_fail(f):
# @wraps(f)
# def wrap(*args, **kwargs):
# try:
# f(*args, **kwargs)
# return flash('hi')
# except:
# flash("Couldn't connect to yahoo-finance API, getting quotes from database.")
# # return search_company(*args)
# return redirect(url_for('news'))
# return wrap
# -------------------------------------------------------
| def get_datetime_today():
now = datetime.datetime.now()
today = datetime.date(now.year, now.month, now.day)
return today
def pretty_numbers(value):
return '${:,.2f}'.format(value)
def pretty_ints(value):
return '{:,}'.format(value)
def pretty_percent(value):
return '{:,.2f}%'.format(value)
def pretty_leaders(leaders):
for l in leaders:
l.prettyvalue = pretty_numbers(l.value)
return leaders
def set_color(change):
if float(change) < 0.0:
return True
else:
return False
def get_leaderboard(user):
allplayers = Portfolio.query.order_by(desc(Portfolio.value)).all()
leaders = Portfolio.query.order_by(desc(Portfolio.value)).limit(5).all()
leaders = pretty_leaders(leaders)
allplayers = pretty_leaders(allplayers)
if user != None:
user = User.query.filter_by(name=session['username']).first()
for (idx, val) in enumerate(allplayers):
if user.portfolio == val:
user.rank = idx + 1
else:
loggedin_user = None
user = None
return (user, allplayers, leaders)
def get_user():
if 'username' in session:
loggedin_user = session['username']
user = session['username']
else:
loggedin_user = None
user = None
return user
def get_account_details(portfolio, positions):
value = portfolio.cash
total_gain_loss = float(0.0)
total_cost = float(0.0)
for p in positions:
stock_lookup_and_write(p.symbol)
p.value = Stock.query.filter_by(symbol=p.symbol).first().price * p.sharecount
p.prettyvalue = pretty_numbers(p.value)
p.prettycost = pretty_numbers(p.cost)
value += p.value
p.gain_loss = p.value - p.cost
p.gain_loss_percent = p.gain_loss / p.cost * 100
if p.gain_loss <= 0.0:
p.loss = True
p.prettygain_loss = pretty_numbers(p.gain_loss)
total_gain_loss = float(p.gain_loss) + total_gain_loss
total_cost = float(p.cost) + total_cost
p.prettygain_loss_percent = pretty_percent(p.gain_loss_percent)
portfolio.total_cost = total_cost
portfolio.prettytotal_cost = pretty_numbers(total_cost)
portfolio.value = value
portfolio.prettyvalue = pretty_numbers(portfolio.value)
portfolio.prettycash = pretty_numbers(portfolio.cash)
portfolio.total_stock_value = portfolio.value - portfolio.cash
portfolio.prettytotal_stock_value = pretty_numbers(portfolio.total_stock_value)
portfolio.total_gain_loss = total_gain_loss
portfolio.prettytotal_gain_loss = pretty_numbers(portfolio.total_gain_loss)
if portfolio.total_cost != 0.0:
portfolio.total_gain_loss_percent = portfolio.total_gain_loss / portfolio.total_cost * 100
portfolio.prettytotal_gain_loss_percent = pretty_percent(portfolio.total_gain_loss_percent)
else:
portfolio.total_gain_loss_percent = 0
portfolio.prettytotal_gain_loss_percent = '0%'
if portfolio.total_gain_loss < 0.0:
portfolio.loss = True
db.session.commit()
return (portfolio, positions)
def clean_stock_search(symbol):
punctuation = '!()-[]{ };:\'"\\,<>./?@#$%^&*_~0123456789'
no_punct = ''
for char in symbol:
if char not in punctuation:
no_punct = no_punct + char
if len(no_punct) == 0:
no_punct = 'RETRY'
return no_punct
def get__share(symbol):
stock = share(clean_stock_search(symbol))
return stock
def set_stock_data(stock):
stock.name = stock.data_set['Name']
stock.symbol = stock.data_set['Symbol'].upper()
stock.exchange = stock.get_stock_exchange()
stock.price = float(stock.get_price())
stock.prettyprice = pretty_numbers(stock.price)
stock.change = stock.get_change()
stock.percent_change = stock.data_set['PercentChange']
stock.afterhours = stock.data_set['AfterHoursChangeRealtime']
stock.last_traded = stock.get_trade_datetime()
stock.prev_close = stock.get_prev_close()
stock.open = stock.get_open()
stock.bid = stock.data_set['Bid']
stock.ask = stock.data_set['Ask']
stock.yr_target = stock.data_set['OneyrTargetPrice']
stock.volume = stock.get_volume()
stock.av_volume = stock.get_avg_daily_volume()
stock.day_low = stock.get_days_low()
stock.day_high = stock.get_days_high()
stock.day_range = str(stock.day_high) + ' - ' + str(stock.day_low)
stock.year_high = stock.get_year_high()
stock.year_low = stock.get_year_low()
stock.year_range = str(stock.year_high) + ' - ' + str(stock.year_low)
stock.market_cap = stock.data_set['MarketCapitalization']
stock.peratio = stock.data_set['PERatio']
if stock.peratio != None:
stock.prettyperatio = pretty_numbers(float(stock.peratio))
else:
stock.prettyperatio = None
stock.div = stock.data_set['DividendYield']
stock.prettyex_div = stock.data_set['ExDividendDate']
stock.ex_div = convert_yhoo_date(stock.data_set['ExDividendDate'])
stock.prettydiv_pay = stock.data_set['DividendPayDate']
stock.div_pay = convert_yhoo_date(stock.data_set['DividendPayDate'])
stock.view_count = 1
stock.loss = set_color(stock.change)
return stock
def write_stock_to_db(stock):
if Stock.query.filter_by(symbol=stock.symbol).first() == None:
db.session.add(stock(stock.symbol, stock.name, stock.exchange, stock.price, stock.div, stock.ex_div, stock.div_pay, stock.market_cap, stock.view_count))
db.session.commit()
else:
write_stock = Stock.query.filter_by(symbol=stock.symbol).first()
write_stock.view_count += 1
write_stock.price = stock.price
write_stock.div_yield = stock.div
write_stock.ex_div = stock.ex_div
write_stock.div_pay = stock.div_pay
write_stock.market_cap = stock.market_cap
db.session.commit()
def stock_lookup_and_write(symbol):
stock = set_stock_data(share(symbol))
write_stock_to_db(stock)
return stock
def search_company(symbol):
symbol = '%' + symbol + '%'
results = Stock.query.filter(Stock.name.ilike(symbol)).all()
return results
def convert_yhoo_date(yhoo_date):
if yhoo_date != None:
(month, day, year) = yhoo_date.split('/')
month = int(month)
day = int(day)
year = int(year)
return datetime.date(year, month, day)
else:
return None
def trade(stock, share_amount, buy_or_sell, user, portfolio, positions):
stock = set_stock_data(stock)
write_stock_to_db(stock)
stock = Stock.query.filter_by(symbol=stock.symbol).first()
price = stock.price
total_cost = float(share_amount * price)
today = get_datetime_today()
if buy_or_sell == 'buy':
bs_mult = 1
total_cost = total_cost * bs_mult
cash = float(portfolio.cash)
if cash > total_cost:
new_cash = cash - total_cost
if portfolio.positions.filter_by(symbol=stock.symbol).first() == None:
position = position(user.portfolio.id, stock.symbol, total_cost, total_cost, share_amount, None)
db.session.add(position)
db.session.commit()
flash(' Opened position in ' + stock.name + '.')
trade = trade(stock.symbol, position.id, user.portfolio.id, total_cost, share_amount, today, stock.div_yield, stock.ex_div, stock.div_pay)
db.session.add(trade)
flash('You bought ' + str(share_amount) + ' shares of ' + stock.name + ' at ' + pretty_numbers(price) + ' per share.')
user.portfolio.cash = new_cash
db.session.commit()
flash('Cash adjusted: -' + pretty_numbers(total_cost))
elif user.portfolio.positions.filter_by(symbol=stock.symbol).all() != None:
position = user.portfolio.positions.filter_by(symbol=stock.symbol).first()
trade = trade(stock.symbol, position.id, user.portfolio.id, total_cost, share_amount, today, stock.div_yield, stock.ex_div, stock.div_pay)
db.session.add(trade)
flash('You bought ' + str(share_amount) + ' shares of ' + stock.name + ' at ' + pretty_numbers(price) + ' per share.')
user.portfolio.cash = new_cash
position.cost = float(position.cost) + total_cost
position.value = float(position.value) + total_cost
position.sharecount += share_amount
db.session.commit()
else:
deficit = total_cost - cash
flash('Sorry, that costs ' + pretty_numbers(total_cost) + ', which is ' + pretty_numbers(deficit) + ' more than you have available. Try buying fewer shares.')
else:
bs_mult = -1
total_cost = total_cost * bs_mult
position = user.portfolio.positions.filter_by(symbol=stock.symbol).first()
if position != None:
if position.sharecount >= share_amount:
trade = trade(stock.symbol, position.id, user.portfolio.id, total_cost, -1 * share_amount, today, stock.div_yield, stock.ex_div, stock.div_pay)
db.session.add(trade)
flash('You sold ' + str(share_amount) + ' shares of ' + stock.name + ' at ' + pretty_numbers(stock.price) + ' per share. Adding ' + pretty_numbers(total_cost * -1) + ' to your cash balance.')
user.portfolio.cash = float(user.portfolio.cash) - total_cost
position.cost = float(position.cost) + total_cost
position.value = float(position.value) + total_cost
position.sharecount = position.sharecount + share_amount * bs_mult
db.session.commit()
if position.sharecount == 0:
try:
db.session.delete(position)
db.session.commit()
flash('Your position in ' + stock.name + ' has been closed.')
except:
flash('Your position in ' + stock.name + " is now empty. I'm working on a way to remove it from the database.")
else:
flash('You only have ' + str(position.sharecount) + ' shares of ' + str(stock.symbol) + '. Try selling fewer shares.')
else:
flash("You don't have any shares of " + stock.symbol + ' to sell.')
def new_user_email(user):
msg = message('Welcome to StockHawk, {}!'.format(user.name), sender=('Adam', config.BaseConfig.MAIL_USERNAME), recipients=[user.email])
msg.html = "<h3>Hi %s,</h3><p>Thanks for registering an account with StockHawk. We've added $1,000,000 of play money to your account. <a href='http://stockhawk.herokuapp.com/login'>Sign in</a> and start trading!<br><br>Good luck!<br> - Adam</p>" % user.name
mail.send(msg)
def reset_password_email(user):
pass
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('You need to log in first.')
return redirect(url_for('login'))
return wrap
def login_reminder(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
message = markup("<a href='/login'>Sign in</a> or <a href='/register'>register</a> to play.")
flash(message)
return f(*args, **kwargs)
return wrap |
"""
A complex MDP, illustrating multiple possible transitions (from different
actions) as well as a non-constant discount parameter.
"""
| """
A complex MDP, illustrating multiple possible transitions (from different
actions) as well as a non-constant discount parameter.
""" |
del_items(0x80139B6C)
SetType(0x80139B6C, "unsigned char map_buf[61440]")
del_items(0x80148B6C)
SetType(0x80148B6C, "unsigned short *imgbuf[21]")
del_items(0x80148BC0)
SetType(0x80148BC0, "struct POLY_FT4 br[10][2][2]")
del_items(0x80149200)
SetType(0x80149200, "struct POLY_FT4 tmdc_pol[10][2][2]")
del_items(0x80149840)
SetType(0x80149840, "struct RECT mdc_buf[2]")
del_items(0x80149850)
SetType(0x80149850, "struct SVECTOR tmdc_pol_offs[10][10][2]")
del_items(0x80149E90)
SetType(0x80149E90, "struct mdc_header *mdc_idx[10]")
del_items(0x80149EB8)
SetType(0x80149EB8, "struct _mdecanim mdec_queue[16]")
del_items(0x80149FF8)
SetType(0x80149FF8, "struct DR_ENV mdec_drenv[2]")
del_items(0x8014A078)
SetType(0x8014A078, "int (*stream_buf[504])[33]")
del_items(0x8014A0FC)
SetType(0x8014A0FC, "struct strheader *stream_bufh[33]")
| del_items(2148768620)
set_type(2148768620, 'unsigned char map_buf[61440]')
del_items(2148830060)
set_type(2148830060, 'unsigned short *imgbuf[21]')
del_items(2148830144)
set_type(2148830144, 'struct POLY_FT4 br[10][2][2]')
del_items(2148831744)
set_type(2148831744, 'struct POLY_FT4 tmdc_pol[10][2][2]')
del_items(2148833344)
set_type(2148833344, 'struct RECT mdc_buf[2]')
del_items(2148833360)
set_type(2148833360, 'struct SVECTOR tmdc_pol_offs[10][10][2]')
del_items(2148834960)
set_type(2148834960, 'struct mdc_header *mdc_idx[10]')
del_items(2148835000)
set_type(2148835000, 'struct _mdecanim mdec_queue[16]')
del_items(2148835320)
set_type(2148835320, 'struct DR_ENV mdec_drenv[2]')
del_items(2148835448)
set_type(2148835448, 'int (*stream_buf[504])[33]')
del_items(2148835580)
set_type(2148835580, 'struct strheader *stream_bufh[33]') |
pessoas = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22}
print(pessoas)
del pessoas['sexo']
print(pessoas)
pessoas['nome'] = 'Rafael'
print(pessoas)
pessoas['peso'] = 98.5
print(pessoas) | pessoas = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22}
print(pessoas)
del pessoas['sexo']
print(pessoas)
pessoas['nome'] = 'Rafael'
print(pessoas)
pessoas['peso'] = 98.5
print(pessoas) |
"""
Exceptions.
"""
class AlreadyAllocated(Exception):
pass
class NotAllocated(Exception):
pass
class BufferAlreadyAllocated(AlreadyAllocated):
pass
class BufferNotAllocated(NotAllocated):
pass
class BusAlreadyAllocated(AlreadyAllocated):
pass
class BusNotAllocated(NotAllocated):
pass
class IncompatibleRate(Exception):
pass
class NodeAlreadyAllocated(AlreadyAllocated):
pass
class NodeNotAllocated(NotAllocated):
pass
class NonrealtimeOutputMissing(Exception):
pass
class NonrealtimeRenderError(Exception):
pass
class RequestTimeout(Exception):
pass
class ServerCannotBoot(Exception):
pass
class ServerOnline(Exception):
pass
class ServerOffline(Exception):
pass
class OwnedServerShutdown(Exception):
pass
class UnownedServerShutdown(Exception):
pass
class TooManyClients(Exception):
pass
| """
Exceptions.
"""
class Alreadyallocated(Exception):
pass
class Notallocated(Exception):
pass
class Bufferalreadyallocated(AlreadyAllocated):
pass
class Buffernotallocated(NotAllocated):
pass
class Busalreadyallocated(AlreadyAllocated):
pass
class Busnotallocated(NotAllocated):
pass
class Incompatiblerate(Exception):
pass
class Nodealreadyallocated(AlreadyAllocated):
pass
class Nodenotallocated(NotAllocated):
pass
class Nonrealtimeoutputmissing(Exception):
pass
class Nonrealtimerendererror(Exception):
pass
class Requesttimeout(Exception):
pass
class Servercannotboot(Exception):
pass
class Serveronline(Exception):
pass
class Serveroffline(Exception):
pass
class Ownedservershutdown(Exception):
pass
class Unownedservershutdown(Exception):
pass
class Toomanyclients(Exception):
pass |
# The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
# Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
sumSeries = 0
for x in range(1, 1001):
sumSeries += pow(x, x)
print(str(sumSeries)[-10:])
| sum_series = 0
for x in range(1, 1001):
sum_series += pow(x, x)
print(str(sumSeries)[-10:]) |
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
| class Queue:
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue) |
#Task 2.1
my_list=[]
i=11
k=1
for i in range(1,i):
my_list.append(k)
k+=3
print("Task 2.1 ",my_list)
#Task 2.2
my_listnew = my_list
my_listnew.extend([1, 5, 13, 20])
print ("Task 2.2 ",my_listnew)
#Task2.3
my_set = set(my_list)
print("Task 2.3 ",my_set)
#Task 2.4
def compare_elements(a:list, b:set):
if len(a) > len(b):
return "List is bigger"
else:
return "Set is bigger"
print("Task 2.4 ",compare_elements(my_listnew, my_set))
#Task 3
def get_value_from_list(data:list, index:int):
try:
return data[index]
except:
return "None"
print("Task 3 ",get_value_from_list([1,2,3], 1))
print("Task 3 ",get_value_from_list([1,2,3], 16))
#Task 4
dict = {"Name": "", "Age": "", "Hobby": ""}
def create_dict(name:str, age:int, hobby:str):
dict["Name"] = name
dict["Age"] = age
dict["Hobby"] = hobby
return dict
print("Task 4",create_dict("Denis", 26, "Books"))
#Task 5
def calculate_fibo(n:int):
fibo = [0]
a, b = 0, 1
for i in range(1,n,1):
fibo.append(b)
a, b = b, a + b
return fibo
print(calculate_fibo(10))
| my_list = []
i = 11
k = 1
for i in range(1, i):
my_list.append(k)
k += 3
print('Task 2.1 ', my_list)
my_listnew = my_list
my_listnew.extend([1, 5, 13, 20])
print('Task 2.2 ', my_listnew)
my_set = set(my_list)
print('Task 2.3 ', my_set)
def compare_elements(a: list, b: set):
if len(a) > len(b):
return 'List is bigger'
else:
return 'Set is bigger'
print('Task 2.4 ', compare_elements(my_listnew, my_set))
def get_value_from_list(data: list, index: int):
try:
return data[index]
except:
return 'None'
print('Task 3 ', get_value_from_list([1, 2, 3], 1))
print('Task 3 ', get_value_from_list([1, 2, 3], 16))
dict = {'Name': '', 'Age': '', 'Hobby': ''}
def create_dict(name: str, age: int, hobby: str):
dict['Name'] = name
dict['Age'] = age
dict['Hobby'] = hobby
return dict
print('Task 4', create_dict('Denis', 26, 'Books'))
def calculate_fibo(n: int):
fibo = [0]
(a, b) = (0, 1)
for i in range(1, n, 1):
fibo.append(b)
(a, b) = (b, a + b)
return fibo
print(calculate_fibo(10)) |
class BinaryMaxHeap:
def __init__(self):
self.elements = []
def __str__(self):
return self.elements
def __repr__(self):
return self.elements
def max_heapify(self, unordered_list, i):
left = (2 * i) + 1
right = (2 * i) + 2
# If the element has no left child, then it won't have a right child either,
# because in heaps we insert elements from left to right.
if left >= len(unordered_list):
return unordered_list
# If the element has no right child, check if the max heap property is satisfied with the left child.
if right >= len(unordered_list):
if unordered_list[i] < unordered_list[left]:
unordered_list[i], unordered_list[left] = (
unordered_list[left],
unordered_list[i],
)
return unordered_list
# Check if the max heap property is satisfied if the element has both left and right children.
# If not, replace the root element with the child with the greater priority.
if (
unordered_list[i] < unordered_list[left]
or unordered_list[i] < unordered_list[right]
):
if unordered_list[left] < unordered_list[right]:
unordered_list[i], unordered_list[right] = (
unordered_list[right],
unordered_list[i],
)
# repeat the process of max heapify on the child with whom the element was exchanged.
return self.max_heapify(unordered_list, right)
else:
unordered_list[i], unordered_list[left] = (
unordered_list[left],
unordered_list[i],
)
return self.max_heapify(unordered_list, left)
return unordered_list
def build_max_heap(self, unordered_list):
# To build a max heap from an unordered list,
# start performing the max_heapify routine on elements with index n/2 -> 0,
# as elements with an index greater than n/2 will be leaf nodes.
for i in reversed(range((len(unordered_list) // 2))):
self.max_heapify(unordered_list, i)
self.elements = unordered_list
return unordered_list
def get_max_element(self):
return self.elements[0]
def remove_max_element(self):
# exchange the max element with the last element.
self.elements[0], self.elements[-1] = self.elements[-1], self.elements[0]
element = self.elements.pop(-1)
# perform max heapify on the 0th index to maintain the max heap property.
self.max_heapify(self.elements, 0)
return element
def insert_element(self, element):
# insert the element at the last.
self.elements.append(element)
element_index = len(self.elements) - 1
# keep exchanging the inserted element with its parent if its value is greater.
while element_index > 0:
parent_index = (element_index - 1) // 2
if self.elements[element_index] > self.elements[parent_index]:
self.elements[element_index], self.elements[parent_index] = (
self.elements[parent_index],
self.elements[element_index],
)
element_index = parent_index
else:
break
def main():
h = BinaryMaxHeap()
unordered_list = [16, 4, 10, 14, 7, 9, 3, 2, 8, 1]
print(h.build_max_heap(unordered_list))
print(h.get_max_element())
print(h.remove_max_element())
h.insert_element(40)
print(h.elements)
if __name__ == "__main__":
main()
| class Binarymaxheap:
def __init__(self):
self.elements = []
def __str__(self):
return self.elements
def __repr__(self):
return self.elements
def max_heapify(self, unordered_list, i):
left = 2 * i + 1
right = 2 * i + 2
if left >= len(unordered_list):
return unordered_list
if right >= len(unordered_list):
if unordered_list[i] < unordered_list[left]:
(unordered_list[i], unordered_list[left]) = (unordered_list[left], unordered_list[i])
return unordered_list
if unordered_list[i] < unordered_list[left] or unordered_list[i] < unordered_list[right]:
if unordered_list[left] < unordered_list[right]:
(unordered_list[i], unordered_list[right]) = (unordered_list[right], unordered_list[i])
return self.max_heapify(unordered_list, right)
else:
(unordered_list[i], unordered_list[left]) = (unordered_list[left], unordered_list[i])
return self.max_heapify(unordered_list, left)
return unordered_list
def build_max_heap(self, unordered_list):
for i in reversed(range(len(unordered_list) // 2)):
self.max_heapify(unordered_list, i)
self.elements = unordered_list
return unordered_list
def get_max_element(self):
return self.elements[0]
def remove_max_element(self):
(self.elements[0], self.elements[-1]) = (self.elements[-1], self.elements[0])
element = self.elements.pop(-1)
self.max_heapify(self.elements, 0)
return element
def insert_element(self, element):
self.elements.append(element)
element_index = len(self.elements) - 1
while element_index > 0:
parent_index = (element_index - 1) // 2
if self.elements[element_index] > self.elements[parent_index]:
(self.elements[element_index], self.elements[parent_index]) = (self.elements[parent_index], self.elements[element_index])
element_index = parent_index
else:
break
def main():
h = binary_max_heap()
unordered_list = [16, 4, 10, 14, 7, 9, 3, 2, 8, 1]
print(h.build_max_heap(unordered_list))
print(h.get_max_element())
print(h.remove_max_element())
h.insert_element(40)
print(h.elements)
if __name__ == '__main__':
main() |
expected_output = {
'vrf':
{'default':
{'address_family':
{'ipv4':
{'default_rpf_table': 'IPv4-Unicast-default',
'isis_mcast_topology': False,
'mo_frr_flow_based': False,
'mo_frr_rib': False,
'multipath': True,
'pim_rpfs_registered': 'Unicast RIB table',
'rib_convergence_time_left': '00:00:00',
'rib_convergence_timeout': '00:30:00',
'rump_mu_rib': False,
'table':
{'IPv4-Unicast-default':
{'pim_rpf_registrations': 1,
'rib_table_converged': True}}}}}}}
| expected_output = {'vrf': {'default': {'address_family': {'ipv4': {'default_rpf_table': 'IPv4-Unicast-default', 'isis_mcast_topology': False, 'mo_frr_flow_based': False, 'mo_frr_rib': False, 'multipath': True, 'pim_rpfs_registered': 'Unicast RIB table', 'rib_convergence_time_left': '00:00:00', 'rib_convergence_timeout': '00:30:00', 'rump_mu_rib': False, 'table': {'IPv4-Unicast-default': {'pim_rpf_registrations': 1, 'rib_table_converged': True}}}}}}} |
class AllBrowsersBusy(RuntimeError):
pass
class BrowserStackTunnelClosed(RuntimeError):
pass
class TooManyElements(RuntimeError):
pass
class UnknownSelector(RuntimeError):
pass
class UnsupportedBrowser(RuntimeError):
pass
| class Allbrowsersbusy(RuntimeError):
pass
class Browserstacktunnelclosed(RuntimeError):
pass
class Toomanyelements(RuntimeError):
pass
class Unknownselector(RuntimeError):
pass
class Unsupportedbrowser(RuntimeError):
pass |
"""Houston client exceptions"""
class HoustonException(Exception):
"""Base Houston client exception"""
pass
class HoustonServerBusy(HoustonException):
"""Raised due to too many requests to process"""
pass
class HoustonClientError(HoustonException):
"""Error raised when the client has made an invalid request"""
pass
class HoustonServerError(HoustonException):
"""Error raised when Houston server has issues"""
pass
| """Houston client exceptions"""
class Houstonexception(Exception):
"""Base Houston client exception"""
pass
class Houstonserverbusy(HoustonException):
"""Raised due to too many requests to process"""
pass
class Houstonclienterror(HoustonException):
"""Error raised when the client has made an invalid request"""
pass
class Houstonservererror(HoustonException):
"""Error raised when Houston server has issues"""
pass |
# robin-0 ( Nabil Ibtehaz)
'''
This code implements the Bellman-Ford Algorithm
to solve the single source shortest path problem.
'''
class Edge:
'''
This is the class to model graph edges
it has 3 attributes startingNode ,
endingNode and weight
'''
# constructor
def __init__(self,startingNode,endingNode,weight):
self.startingNode=startingNode
self.endingNode=endingNode
self.weight=weight
def BellmanFord(source):
'''
This function implements the Bellman Ford algorithm
to find the single source shortest path problem
It takes the source vertex as input and returns a
list containing the lengths of shortest paths to
other vertices
'''
shortestPaths = [ None ] * nVertices
shortestPaths[source]=0 # path from source to source is 0 :p
for i in range(nVertices-1):
for j in edgeList:
if( shortestPaths [ j.startingNode ] !=None ):
if(shortestPaths [j.endingNode] ==None):
shortestPaths [j.endingNode] = shortestPaths [ j.startingNode ] + j.weight
else :
# Relaxation
shortestPaths [j.endingNode] = min( shortestPaths [j.endingNode] , shortestPaths [ j.startingNode ] + j.weight )
# check for negative cycle
for j in edgeList:
if( shortestPaths [ j.startingNode ] !=None and shortestPaths [ j.endingNode ] !=None ):
if ( shortestPaths [j.endingNode] > ( shortestPaths [ j.startingNode ] + j.weight ) ):
print("Not Possible Negative Cycle Exists")
return None
return shortestPaths
if __name__ == "__main__":
'''
This is the main function.
A simple UI is provided
'''
print('Vertices are 0-indexed')
nVertices = int(input('Number of Vertices: '))
edgeList = []
nEdges = int(input('Number of Edges: '))
for i in range(nEdges):
print('Enter Edge ' +str(i+1) )
startingNode = int(input('Starting Node: '))
endingNode = int(input('Ending Node: '))
weight = int(input('Weight: '))
edgeList.append(Edge(startingNode,endingNode,weight))
print("****************************************\n")
print("Please select one of the following\n")
choice = int(input('1. Find Shortest Path From Sources\n2. End\n'))
while(choice==1):
sourceNode=int(input('Source Node(0-indexed) : '))
print(BellmanFord(sourceNode))
print("****************************************\n")
print("Please select one of the following\n")
choice = int(input('1. Find Shortest Path From Sources\n2. End\n'))
| """
This code implements the Bellman-Ford Algorithm
to solve the single source shortest path problem.
"""
class Edge:
"""
This is the class to model graph edges
it has 3 attributes startingNode ,
endingNode and weight
"""
def __init__(self, startingNode, endingNode, weight):
self.startingNode = startingNode
self.endingNode = endingNode
self.weight = weight
def bellman_ford(source):
"""
This function implements the Bellman Ford algorithm
to find the single source shortest path problem
It takes the source vertex as input and returns a
list containing the lengths of shortest paths to
other vertices
"""
shortest_paths = [None] * nVertices
shortestPaths[source] = 0
for i in range(nVertices - 1):
for j in edgeList:
if shortestPaths[j.startingNode] != None:
if shortestPaths[j.endingNode] == None:
shortestPaths[j.endingNode] = shortestPaths[j.startingNode] + j.weight
else:
shortestPaths[j.endingNode] = min(shortestPaths[j.endingNode], shortestPaths[j.startingNode] + j.weight)
for j in edgeList:
if shortestPaths[j.startingNode] != None and shortestPaths[j.endingNode] != None:
if shortestPaths[j.endingNode] > shortestPaths[j.startingNode] + j.weight:
print('Not Possible Negative Cycle Exists')
return None
return shortestPaths
if __name__ == '__main__':
'\n\t\tThis is the main function.\n\n\t\tA simple UI is provided\n\t'
print('Vertices are 0-indexed')
n_vertices = int(input('Number of Vertices: '))
edge_list = []
n_edges = int(input('Number of Edges: '))
for i in range(nEdges):
print('Enter Edge ' + str(i + 1))
starting_node = int(input('Starting Node: '))
ending_node = int(input('Ending Node: '))
weight = int(input('Weight: '))
edgeList.append(edge(startingNode, endingNode, weight))
print('****************************************\n')
print('Please select one of the following\n')
choice = int(input('1. Find Shortest Path From Sources\n2. End\n'))
while choice == 1:
source_node = int(input('Source Node(0-indexed) : '))
print(bellman_ford(sourceNode))
print('****************************************\n')
print('Please select one of the following\n')
choice = int(input('1. Find Shortest Path From Sources\n2. End\n')) |
heif_chroma_undefined = 99
heif_chroma_monochrome = 0
heif_chroma_420 = 1
heif_chroma_422 = 2
heif_chroma_444 = 3
heif_chroma_interleaved_RGB = 10
heif_chroma_interleaved_RGBA = 11
heif_chroma_interleaved_RRGGBB_BE = 12
heif_chroma_interleaved_RRGGBBAA_BE = 13
heif_colorspace_undefined = 99
heif_colorspace_YCbCr = 0
heif_colorspace_RGB = 1
heif_colorspace_monochrome = 2
heif_channel_Y = 0
heif_channel_Cb = 1
heif_channel_Cr = 2
heif_channel_R = 3
heif_channel_G = 4
heif_channel_B = 5
heif_channel_Alpha = 6
heif_channel_interleaved = 10
def encode_fourcc(fourcc):
encoded = (
ord(fourcc[0]) << 24
| ord(fourcc[1]) << 16
| ord(fourcc[2]) << 8
| ord(fourcc[3])
)
return encoded
heif_color_profile_type_not_present = 0
heif_color_profile_type_nclx = encode_fourcc("nclx")
heif_color_profile_type_rICC = encode_fourcc("rICCC")
heif_color_profile_type_prof = encode_fourcc("prof")
heif_filetype_no = 0
heif_filetype_yes_supported = 1
heif_filetype_yes_unsupported = 2
heif_filetype_maybe = 3
| heif_chroma_undefined = 99
heif_chroma_monochrome = 0
heif_chroma_420 = 1
heif_chroma_422 = 2
heif_chroma_444 = 3
heif_chroma_interleaved_rgb = 10
heif_chroma_interleaved_rgba = 11
heif_chroma_interleaved_rrggbb_be = 12
heif_chroma_interleaved_rrggbbaa_be = 13
heif_colorspace_undefined = 99
heif_colorspace_y_cb_cr = 0
heif_colorspace_rgb = 1
heif_colorspace_monochrome = 2
heif_channel_y = 0
heif_channel__cb = 1
heif_channel__cr = 2
heif_channel_r = 3
heif_channel_g = 4
heif_channel_b = 5
heif_channel__alpha = 6
heif_channel_interleaved = 10
def encode_fourcc(fourcc):
encoded = ord(fourcc[0]) << 24 | ord(fourcc[1]) << 16 | ord(fourcc[2]) << 8 | ord(fourcc[3])
return encoded
heif_color_profile_type_not_present = 0
heif_color_profile_type_nclx = encode_fourcc('nclx')
heif_color_profile_type_r_icc = encode_fourcc('rICCC')
heif_color_profile_type_prof = encode_fourcc('prof')
heif_filetype_no = 0
heif_filetype_yes_supported = 1
heif_filetype_yes_unsupported = 2
heif_filetype_maybe = 3 |
'''
Problem Statement: Given two sorted arrays, A and B,
determine their intersection. What elements are common to A and B?
'''
A = [2, 3, 3, 5, 7, 11]
B = [3, 3, 7, 15, 31]
# One line solution
#print(set(A).intersection(B))
def intersection_arrays(A, B):
i = 0
j = 0
intersection = list()
while i < len(A) and j < len(B):
if A[i] == B[j]:
if i == 0 or A[i] != A[i-1]:
intersection.append(A[i])
i += 1
j += 1
elif A[i] < B[j]:
i += 1
else:
j += 1
return intersection
print(intersection_arrays(A, B)) | """
Problem Statement: Given two sorted arrays, A and B,
determine their intersection. What elements are common to A and B?
"""
a = [2, 3, 3, 5, 7, 11]
b = [3, 3, 7, 15, 31]
def intersection_arrays(A, B):
i = 0
j = 0
intersection = list()
while i < len(A) and j < len(B):
if A[i] == B[j]:
if i == 0 or A[i] != A[i - 1]:
intersection.append(A[i])
i += 1
j += 1
elif A[i] < B[j]:
i += 1
else:
j += 1
return intersection
print(intersection_arrays(A, B)) |
## Duplicate Encoder
## 6 kyu
## https://www.codewars.com/kata/54b42f9314d9229fd6000d9c
def duplicate_encode(word):
new = ''
for character in word:
if word.lower().count(character.lower()) == 1:
new += ("(")
else:
new += (')')
return new | def duplicate_encode(word):
new = ''
for character in word:
if word.lower().count(character.lower()) == 1:
new += '('
else:
new += ')'
return new |
print("Welcome to the tip calculator.")
total = float(input("What was the total bill? $"))
percent = int(input("What percentage tip would you like to give? 10%, 12%, or 15%? "))
people = int(input("How many people to split the bill? "))
total += ((percent * total) / 100)
per_person = round(total / people, 2)
print(f"Each person should pay: ${per_person}") | print('Welcome to the tip calculator.')
total = float(input('What was the total bill? $'))
percent = int(input('What percentage tip would you like to give? 10%, 12%, or 15%? '))
people = int(input('How many people to split the bill? '))
total += percent * total / 100
per_person = round(total / people, 2)
print(f'Each person should pay: ${per_person}') |
class Solution:
def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
"""
The original Dijkstra algorithm is to find the shorting distances
between a starting node and each of the rest nodes.
This problem can be considered as a variant of Dijkstra problem.
"""
graph = defaultdict(list)
for entry in times:
source, target, weight = entry
graph[source].append((weight, target))
queue = graph[K]
heapq.heapify(queue)
clocks = 0
visited = [False for i in range(N+1)]
visited[K] = True
visit_cnt = 1
while queue:
timestamp, target = heapq.heappop(queue)
clocks = timestamp
if not visited[target]:
visit_cnt += 1
if visit_cnt == N:
break
visited[target] = True
for next_weight, next_target in graph[target]:
heapq.heappush(queue, (clocks+next_weight, next_target))
return clocks if visit_cnt == N else -1
class SolutionDijkstra:
def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
"""
Dijkstra with heap
"""
graph = defaultdict(list)
for entry in times:
source, target, weight = entry
graph[source].append((weight, target))
queue = graph[K]
heapq.heapify(queue)
min_elapse = {K:0}
while queue:
# one of the cases is that there might be several edges between two nodes.
# the most optimal one would be picked,
# therefore we should ignore the rest of the edges.
clocks, target = heapq.heappop(queue)
if target in min_elapse:
continue
min_elapse[target] = clocks
for next_weight, next_target in graph[target]:
if next_target not in min_elapse:
heapq.heappush(queue, (clocks + next_weight, next_target))
return max(min_elapse.values()) if len(min_elapse) == N else -1
| class Solution:
def network_delay_time(self, times: List[List[int]], N: int, K: int) -> int:
"""
The original Dijkstra algorithm is to find the shorting distances
between a starting node and each of the rest nodes.
This problem can be considered as a variant of Dijkstra problem.
"""
graph = defaultdict(list)
for entry in times:
(source, target, weight) = entry
graph[source].append((weight, target))
queue = graph[K]
heapq.heapify(queue)
clocks = 0
visited = [False for i in range(N + 1)]
visited[K] = True
visit_cnt = 1
while queue:
(timestamp, target) = heapq.heappop(queue)
clocks = timestamp
if not visited[target]:
visit_cnt += 1
if visit_cnt == N:
break
visited[target] = True
for (next_weight, next_target) in graph[target]:
heapq.heappush(queue, (clocks + next_weight, next_target))
return clocks if visit_cnt == N else -1
class Solutiondijkstra:
def network_delay_time(self, times: List[List[int]], N: int, K: int) -> int:
"""
Dijkstra with heap
"""
graph = defaultdict(list)
for entry in times:
(source, target, weight) = entry
graph[source].append((weight, target))
queue = graph[K]
heapq.heapify(queue)
min_elapse = {K: 0}
while queue:
(clocks, target) = heapq.heappop(queue)
if target in min_elapse:
continue
min_elapse[target] = clocks
for (next_weight, next_target) in graph[target]:
if next_target not in min_elapse:
heapq.heappush(queue, (clocks + next_weight, next_target))
return max(min_elapse.values()) if len(min_elapse) == N else -1 |
class Manager:
place = ""
number = 0
def __init__(self, place, number):
self.place = place
self.number = number
def toString(self):
print("Place: " + self.place + ". Number: " + self.number + ".")
print(" ") | class Manager:
place = ''
number = 0
def __init__(self, place, number):
self.place = place
self.number = number
def to_string(self):
print('Place: ' + self.place + '. Number: ' + self.number + '.')
print(' ') |
class Solution:
@staticmethod
def naive(m,n):
dp = [[0 for i in range(n+1)] for j in range(m+1)]
dp[m-1][n-1]=1
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
dp[i][j] = max(dp[i][j],dp[i+1][j]+dp[i][j+1])
return dp[0][0] | class Solution:
@staticmethod
def naive(m, n):
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
dp[m - 1][n - 1] = 1
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
dp[i][j] = max(dp[i][j], dp[i + 1][j] + dp[i][j + 1])
return dp[0][0] |
"""
bmh_search.py
This module implements bmh search to find a substring in a string
BMH Search Overview:
--------------------
Uses a bad-character shift of the rightmost character of the window to
compute shifts.
The trick to this algorithm is `bmbc`, a lookup table with a default
value equal to the length of the pattern to be searched, so that
the algorithm can skip `len(pattern)` indices through the string
for efficiency's sake. For example, if we're searching through the
string "cotton milled paper" for the pattern "grumble", we look at
the last letter "r" (BMH goes backwards through a string) and notices
that it is not equal to "e". Thus, we can afford to jump our search
index back a whole seven characters.
However, not all the entries in `bmbc` are equal to `len(pattern)`.
If we searched the string "adventure time" for "grumble", we'd find
the "e" to match but mismatch the "m" and "l" in the string and
pattern, respectively. In this case, we can only jump back six
characters safely, which is why `bmbc` contains values that are not
simply `len(pattern)`.
Pre: a string > substring.
Post: returns a list of indices where the substring was found.
Time: Complexity: O(m + n), where m is the substring to be found.
Space: Complexity: O(m), where m is the substring to be found.
Psuedo Code: https://github.com/FooBarWidget/boyer-moore-horspool
(converted from C++)
bmh_search.search(string, substring) -> list[integers]
bmh_search.search(string, substring) -> list[empty]
"""
def search(text, pattern):
pattern_length = len(pattern)
text_length = len(text)
offsets = []
if pattern_length > text_length:
return offsets
bmbc = [pattern_length] * 256
for index, char in enumerate(pattern[:-1]):
bmbc[ord(char)] = pattern_length - index - 1
bmbc = tuple(bmbc)
search_index = pattern_length - 1
while search_index < text_length:
pattern_index = pattern_length - 1
text_index = search_index
while text_index >= 0 and \
text[text_index] == pattern[pattern_index]:
pattern_index -= 1
text_index -= 1
if pattern_index == -1:
offsets.append(text_index + 1)
search_index += bmbc[ord(text[search_index])]
return offsets | """
bmh_search.py
This module implements bmh search to find a substring in a string
BMH Search Overview:
--------------------
Uses a bad-character shift of the rightmost character of the window to
compute shifts.
The trick to this algorithm is `bmbc`, a lookup table with a default
value equal to the length of the pattern to be searched, so that
the algorithm can skip `len(pattern)` indices through the string
for efficiency's sake. For example, if we're searching through the
string "cotton milled paper" for the pattern "grumble", we look at
the last letter "r" (BMH goes backwards through a string) and notices
that it is not equal to "e". Thus, we can afford to jump our search
index back a whole seven characters.
However, not all the entries in `bmbc` are equal to `len(pattern)`.
If we searched the string "adventure time" for "grumble", we'd find
the "e" to match but mismatch the "m" and "l" in the string and
pattern, respectively. In this case, we can only jump back six
characters safely, which is why `bmbc` contains values that are not
simply `len(pattern)`.
Pre: a string > substring.
Post: returns a list of indices where the substring was found.
Time: Complexity: O(m + n), where m is the substring to be found.
Space: Complexity: O(m), where m is the substring to be found.
Psuedo Code: https://github.com/FooBarWidget/boyer-moore-horspool
(converted from C++)
bmh_search.search(string, substring) -> list[integers]
bmh_search.search(string, substring) -> list[empty]
"""
def search(text, pattern):
pattern_length = len(pattern)
text_length = len(text)
offsets = []
if pattern_length > text_length:
return offsets
bmbc = [pattern_length] * 256
for (index, char) in enumerate(pattern[:-1]):
bmbc[ord(char)] = pattern_length - index - 1
bmbc = tuple(bmbc)
search_index = pattern_length - 1
while search_index < text_length:
pattern_index = pattern_length - 1
text_index = search_index
while text_index >= 0 and text[text_index] == pattern[pattern_index]:
pattern_index -= 1
text_index -= 1
if pattern_index == -1:
offsets.append(text_index + 1)
search_index += bmbc[ord(text[search_index])]
return offsets |
# The sequence we want to analyze
seq = 'GACAGACUCCAUGCACGUGGGUAUCUGUC'
# Initialize GC counter
n_gc = 0
# Initialize sequence length
len_seq = 0
# Loop through sequence and count G's and C's
for base in seq:
len_seq += 1
if base in 'GCgc':
n_gc += 1
# Divide to get GC content
print(n_gc / len_seq)
# We'll do one through 5
my_integers = [1,2,3,4,5]
# Double each one
for n in my_integers:
n *= 2
# Check out the result
print(my_integers)
# Does not work quite right
# We have to use iterators
# Range function gives an iterable that enables counting.
for i in range(10):
print(i, end=' ')
# Range function gives an iterable that enables counting.
for i in range(2,10):
print(i, end=' ')
# Print a newline
print()
# Print even numbers, 2 through 9
for i in range(2,10,2):
print(i, end=' ')
# Type conversion from range to list
list = list(range(10))
print()
print(list)
print()
# Make the previous function working
my_integers = [1,2,3,4,5]
print(my_integers)
print()
for i in range(len(my_integers)):
my_integers[i] *= 2
print(my_integers)
print()
print(seq)
# Initialize GC counter
n_gc = 0
# Initialized sequence length
len_seq = 0
# Loop through sequence and print index of G's
for base in seq:
if base in 'Gg':
print(len_seq, end=' ')
len_seq += 1
print()
# We can use enumerate ()
# Loop through sequence and print index of G's
for i, base in enumerate(seq):
if base in 'Gg':
print(i, end=' ')
print()
for i, base in enumerate(seq):
print(i,base)
print()
for i in range(len(seq)):
print(i,seq[i])
print()
my_integers = [1,2,3,4,5]
# Double each one
for i, _ in enumerate(my_integers):
my_integers[i] *= 2
# Check out the result
my_integers
# The zip() function
names = ('Lloyd','Holiday','Heath')
positions = ('MF','MF','F')
numbers = (10,12,17)
for num, pos, name in zip(numbers,positions, names):
print(num,name,pos)
# reversed() function
count_up = ('ignition', 1,2,3,4,5,6,7,8,9,10)
for count in reversed(count_up):
print(count)
# 'while' Loop
# Define start codon
start_codon = 'AUG'
# Initialize sequence index
i = 0
# Scan sequence until we hit start codon
while seq[i:i+3] != start_codon:
i += 1
# Show the result
print('The start codon starts at index',i)
print()
# Define codon of interest
codon = 'GCC'
# Initialize sequence index
i = 0
# Scan sequence until we hit the start codon or end of the sequence
while seq[i:i+3] != codon and i < len(seq):
i += 1
# Show the result
if i == len(seq):
print('Codon not found in sequence.')
else:
print('The codon starts at index',i)
# Use 'for' loop with break instead of 'while'
start_codon = 'AUG'
# Scan sequence until we hit the start codon
for i in range(len(seq)):
if seq[i:i+3] == start_codon:
print('The start codon starts at index',i,'as expected')
break
else:
print('Codon not found in sequence.')
| seq = 'GACAGACUCCAUGCACGUGGGUAUCUGUC'
n_gc = 0
len_seq = 0
for base in seq:
len_seq += 1
if base in 'GCgc':
n_gc += 1
print(n_gc / len_seq)
my_integers = [1, 2, 3, 4, 5]
for n in my_integers:
n *= 2
print(my_integers)
for i in range(10):
print(i, end=' ')
for i in range(2, 10):
print(i, end=' ')
print()
for i in range(2, 10, 2):
print(i, end=' ')
list = list(range(10))
print()
print(list)
print()
my_integers = [1, 2, 3, 4, 5]
print(my_integers)
print()
for i in range(len(my_integers)):
my_integers[i] *= 2
print(my_integers)
print()
print(seq)
n_gc = 0
len_seq = 0
for base in seq:
if base in 'Gg':
print(len_seq, end=' ')
len_seq += 1
print()
for (i, base) in enumerate(seq):
if base in 'Gg':
print(i, end=' ')
print()
for (i, base) in enumerate(seq):
print(i, base)
print()
for i in range(len(seq)):
print(i, seq[i])
print()
my_integers = [1, 2, 3, 4, 5]
for (i, _) in enumerate(my_integers):
my_integers[i] *= 2
my_integers
names = ('Lloyd', 'Holiday', 'Heath')
positions = ('MF', 'MF', 'F')
numbers = (10, 12, 17)
for (num, pos, name) in zip(numbers, positions, names):
print(num, name, pos)
count_up = ('ignition', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
for count in reversed(count_up):
print(count)
start_codon = 'AUG'
i = 0
while seq[i:i + 3] != start_codon:
i += 1
print('The start codon starts at index', i)
print()
codon = 'GCC'
i = 0
while seq[i:i + 3] != codon and i < len(seq):
i += 1
if i == len(seq):
print('Codon not found in sequence.')
else:
print('The codon starts at index', i)
start_codon = 'AUG'
for i in range(len(seq)):
if seq[i:i + 3] == start_codon:
print('The start codon starts at index', i, 'as expected')
break
else:
print('Codon not found in sequence.') |
def search(l, x):
return searchInRange(l, x, 0, len(l)-1)
def searchInRange(l, x, min, max):
if min>max:
return False
else:
middle = min+(max-min)/2
if x > l[middle]:
# Search in right half
return searchInRange(l, x, middle+1, max)
elif x < l[middle]:
# Search in left half
return searchInRange(l, x, min, middle-1)
else:
# Found in the middle
return True
| def search(l, x):
return search_in_range(l, x, 0, len(l) - 1)
def search_in_range(l, x, min, max):
if min > max:
return False
else:
middle = min + (max - min) / 2
if x > l[middle]:
return search_in_range(l, x, middle + 1, max)
elif x < l[middle]:
return search_in_range(l, x, min, middle - 1)
else:
return True |
"""This file was adapted from Appium sample code found at
https://github.com/appium/appium/tree/master/sample-code
as of November 15, 2021.
For fixtures and imports, see ./conftest.py"""
class TestFirst():
def test_first(self, driver):
"""Simply checks test discovery and setup.
Should be successfully collected and pass."""
print("I am first test! I ran!")
assert True
| """This file was adapted from Appium sample code found at
https://github.com/appium/appium/tree/master/sample-code
as of November 15, 2021.
For fixtures and imports, see ./conftest.py"""
class Testfirst:
def test_first(self, driver):
"""Simply checks test discovery and setup.
Should be successfully collected and pass."""
print('I am first test! I ran!')
assert True |
#
# @lc app=leetcode id=1372 lang=python3
#
# [1372] Longest ZigZag Path in a Binary Tree
#
# @lc code=start
# 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 longestZigZag(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
nodes = [root]
cache = {}
max_len = 0
while nodes:
node = nodes.pop()
if node.left:
nodes.append(node.left)
if node.right:
nodes.append(node.right)
length = max(self._longestZigZag(node,True,cache),self._longestZigZag(node,False,cache))
if length>max_len:
max_len = length
return max_len
def _longestZigZag(self, root,is_left, cache):
if (root,is_left) in cache:
return cache[(root,is_left)]
if is_left:
result = self._longestZigZag(root.left,False,cache)+1 if root.left else 0
cache[(root,is_left)] = result
return result
else:
result = self._longestZigZag(root.right,True,cache)+1 if root.right else 0
cache[(root,is_left)] = result
return result
# @lc code=end
| class Solution:
def longest_zig_zag(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
nodes = [root]
cache = {}
max_len = 0
while nodes:
node = nodes.pop()
if node.left:
nodes.append(node.left)
if node.right:
nodes.append(node.right)
length = max(self._longestZigZag(node, True, cache), self._longestZigZag(node, False, cache))
if length > max_len:
max_len = length
return max_len
def _longest_zig_zag(self, root, is_left, cache):
if (root, is_left) in cache:
return cache[root, is_left]
if is_left:
result = self._longestZigZag(root.left, False, cache) + 1 if root.left else 0
cache[root, is_left] = result
return result
else:
result = self._longestZigZag(root.right, True, cache) + 1 if root.right else 0
cache[root, is_left] = result
return result |
CONTACT_FIELDS = {
"preferred_call_time": "STRING",
"quiz_complete_date": "STRING",
"q6": "STRING",
"q5": "STRING",
"q4_other": "STRING",
"q4": "STRING",
"q3": "STRING",
"q2_explained": "STRING",
"q2": "STRING",
"q1_explained": "STRING",
"q1": "STRING",
"preferred_response_time": "STRING",
"response_time_satisfaction": "STRING",
"topic_expectations": "STRING",
"expectation": "STRING",
"close_case": "TIMESTAMP",
"open_case": "TIMESTAMP",
"question_count": "INTEGER",
"main_menu_count": "INTEGER",
"first_choice": "STRING",
"last_call_duration": "STRING",
"uncaught_message": "STRING",
"error_count": "INTEGER",
"love_option": "STRING",
"first_interaction": "TIMESTAMP",
"urnsmerge": "STRING",
"handover_timestamp": "TIMESTAMP",
"gender": "STRING",
"county": "STRING",
"counsellor_request": "STRING",
"urn": "STRING",
"age": "STRING",
"uuid": "STRING",
"name": "STRING",
"modified_on": "TIMESTAMP",
}
GROUP_CONTACT_FIELDS = {"group_uuid": "STRING", "contact_uuid": "STRING"}
GROUP_FIELDS = {"name": "STRING", "uuid": "STRING"}
FLOWS_FIELDS = {"labels": "STRING", "name": "STRING", "uuid": "STRING"}
FLOW_RUNS_FIELDS = {
"modified_on": "TIMESTAMP",
"responded": "BOOLEAN",
"contact_uuid": "STRING",
"flow_uuid": "STRING",
"exit_type": "STRING",
"created_at": "TIMESTAMP",
"exited_on": "TIMESTAMP",
"id": "INTEGER",
}
PAGEVIEW_FIELDS = {
"timestamp": "TIMESTAMP",
"page": "INTEGER",
"revision": "INTEGER",
"id": "INTEGER",
"run_uuid": "STRING",
"contact_uuid": "STRING",
}
FLOW_RUN_VALUES_FIELDS = {
"input": "STRING",
"time": "TIMESTAMP",
"category": "STRING",
"name": "STRING",
"value": "STRING",
"run_id": "INTEGER",
}
| contact_fields = {'preferred_call_time': 'STRING', 'quiz_complete_date': 'STRING', 'q6': 'STRING', 'q5': 'STRING', 'q4_other': 'STRING', 'q4': 'STRING', 'q3': 'STRING', 'q2_explained': 'STRING', 'q2': 'STRING', 'q1_explained': 'STRING', 'q1': 'STRING', 'preferred_response_time': 'STRING', 'response_time_satisfaction': 'STRING', 'topic_expectations': 'STRING', 'expectation': 'STRING', 'close_case': 'TIMESTAMP', 'open_case': 'TIMESTAMP', 'question_count': 'INTEGER', 'main_menu_count': 'INTEGER', 'first_choice': 'STRING', 'last_call_duration': 'STRING', 'uncaught_message': 'STRING', 'error_count': 'INTEGER', 'love_option': 'STRING', 'first_interaction': 'TIMESTAMP', 'urnsmerge': 'STRING', 'handover_timestamp': 'TIMESTAMP', 'gender': 'STRING', 'county': 'STRING', 'counsellor_request': 'STRING', 'urn': 'STRING', 'age': 'STRING', 'uuid': 'STRING', 'name': 'STRING', 'modified_on': 'TIMESTAMP'}
group_contact_fields = {'group_uuid': 'STRING', 'contact_uuid': 'STRING'}
group_fields = {'name': 'STRING', 'uuid': 'STRING'}
flows_fields = {'labels': 'STRING', 'name': 'STRING', 'uuid': 'STRING'}
flow_runs_fields = {'modified_on': 'TIMESTAMP', 'responded': 'BOOLEAN', 'contact_uuid': 'STRING', 'flow_uuid': 'STRING', 'exit_type': 'STRING', 'created_at': 'TIMESTAMP', 'exited_on': 'TIMESTAMP', 'id': 'INTEGER'}
pageview_fields = {'timestamp': 'TIMESTAMP', 'page': 'INTEGER', 'revision': 'INTEGER', 'id': 'INTEGER', 'run_uuid': 'STRING', 'contact_uuid': 'STRING'}
flow_run_values_fields = {'input': 'STRING', 'time': 'TIMESTAMP', 'category': 'STRING', 'name': 'STRING', 'value': 'STRING', 'run_id': 'INTEGER'} |
class Handler:
"""
Cloud provider API handler base class. Defines
common API between inherited handler classes.
"""
def __init__(self, app):
self.app = app
self.compute_client = None
self.storage_client = None
def fetch_available_ip_address(self):
return ""
"""
you'll need more methods, probably one for
each kubernetes object that you need to launch
also -- i subclassed and pushed all this code into
here so that every build() method in the compute_party
class doesnt have like
if my_provider == "AWS":
# some boto3 code
elif my_provider == "GCP":
# some gcloud code
etc.
""" | class Handler:
"""
Cloud provider API handler base class. Defines
common API between inherited handler classes.
"""
def __init__(self, app):
self.app = app
self.compute_client = None
self.storage_client = None
def fetch_available_ip_address(self):
return ''
'\n you\'ll need more methods, probably one for \n each kubernetes object that you need to launch\n \n also -- i subclassed and pushed all this code into\n here so that every build() method in the compute_party\n class doesnt have like\n \n if my_provider == "AWS":\n # some boto3 code\n elif my_provider == "GCP":\n # some gcloud code\n etc.\n ' |
"""
Should emit:
B018 - on lines 16-25, 29, 32
"""
def foo1():
"""my docstring"""
def foo2():
"""my docstring"""
a = 2
"str" # Str (no raise)
f"{int}" # JoinedStr (no raise)
1j # Number (complex)
1 # Number (int)
1.0 # Number (float)
b"foo" # Binary
True # NameConstant (True)
False # NameConstant (False)
None # NameConstant (None)
[1, 2] # list
{1, 2} # set
{"foo": "bar"} # dict
def foo3():
123
a = 2
"str"
3
| """
Should emit:
B018 - on lines 16-25, 29, 32
"""
def foo1():
"""my docstring"""
def foo2():
"""my docstring"""
a = 2
'str'
f'{int}'
1j
1
1.0
b'foo'
True
False
None
[1, 2]
{1, 2}
{'foo': 'bar'}
def foo3():
123
a = 2
'str'
3 |
# This module contains the shaders used to render snap point coordinates.
# The shaders for snapping to a vertex.
VERT_SHADER_V = """
#version 330
uniform mat4 p3d_ModelMatrix;
in vec4 p3d_Vertex;
void main() {
gl_Position = p3d_ModelMatrix * p3d_Vertex;
}
"""
GEOM_SHADER_V = """
#version 330
layout(triangles) in;
// Three points will be generated: 3 vertices
layout(points, max_vertices=3) out;
uniform mat4 p3d_ViewProjectionMatrix;
uniform mat4 p3d_ViewMatrixInverse;
uniform mat4 p3d_ProjectionMatrix;
uniform bool inverted;
uniform bool two_sided;
out vec3 snap_coords;
void main()
{
vec3 P0 = gl_in[0].gl_Position.xyz;
vec3 P1 = gl_in[1].gl_Position.xyz;
vec3 P2 = gl_in[2].gl_Position.xyz;
vec3 positions[3] = vec3[] (P0, P1, P2);
vec3 V0 = P1 - P0;
vec3 V1 = P2 - P1;
vec3 face_normal = inverted ? cross(V1, V0) : cross(V0, V1);
vec3 vec;
if (p3d_ProjectionMatrix[3].w == 1.)
// orthographic lens;
// use inverted camera direction vector
vec = p3d_ViewMatrixInverse[2].xyz;
else
// perspective lens;
// compute vector pointing from any point of triangle to camera origin
vec = p3d_ViewMatrixInverse[3].xyz - P0;
if (two_sided || dot(vec, face_normal) >= 0.) {
// generate points
for (int i = 0; i < 3; ++i)
{
gl_Position = p3d_ViewProjectionMatrix * vec4(positions[i], 1.0);
snap_coords = positions[i];
EmitVertex();
EndPrimitive();
}
}
}
"""
# The shaders for snapping to an edge midpoint.
VERT_SHADER_E = """
#version 330
uniform mat4 p3d_ModelMatrix;
in vec4 p3d_Vertex;
in int sides;
out Vertex
{
int side_gen;
} vertex;
void main() {
gl_Position = p3d_ModelMatrix * p3d_Vertex;
vertex.side_gen = sides;
}
"""
GEOM_SHADER_E = """
#version 330
layout(triangles) in;
// Three lines will be generated: 6 vertices
layout(line_strip, max_vertices=6) out;
uniform mat4 p3d_ViewProjectionMatrix;
uniform mat4 p3d_ViewMatrixInverse;
uniform mat4 p3d_ProjectionMatrix;
uniform bool inverted;
uniform bool two_sided;
in Vertex
{
int side_gen;
} vertex[];
out vec3 snap_coords;
void main()
{
int side_generation, S0, S1, S2;
int sides[3];
// determine which sides should be generated (1) or not (0)
side_generation = vertex[0].side_gen;
S0 = side_generation >> 2;
S1 = (side_generation ^ (S0 << 2)) >> 1;
S2 = side_generation ^ (S0 << 2) ^ (S1 << 1);
sides = int[] (S0, S1, S2);
vec3 P0 = gl_in[0].gl_Position.xyz;
vec3 P1 = gl_in[1].gl_Position.xyz;
vec3 P2 = gl_in[2].gl_Position.xyz;
vec3 positions[4] = vec3[] (P0, P1, P2, P0);
vec3 V0 = P1 - P0;
vec3 V1 = P2 - P1;
vec3 face_normal = inverted ? cross(V1, V0) : cross(V0, V1);
vec3 vec;
if (p3d_ProjectionMatrix[3].w == 1.)
// orthographic lens;
// use inverted camera direction vector
vec = p3d_ViewMatrixInverse[2].xyz;
else
// perspective lens;
// compute vector pointing from any point of triangle to camera origin
vec = p3d_ViewMatrixInverse[3].xyz - P0;
if (two_sided || dot(vec, face_normal) >= 0.) {
// generate sides
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < sides[i]; ++j)
{
snap_coords = (positions[i] + positions[i + 1]) * .5;
gl_Position = p3d_ViewProjectionMatrix * vec4(positions[i], 1.0);
EmitVertex();
gl_Position = p3d_ViewProjectionMatrix * vec4(positions[i + 1], 1.0);
EmitVertex();
EndPrimitive();
}
}
}
}
"""
# The shaders for snapping to a polygon center.
VERT_SHADER_P = """
#version 330
uniform mat4 p3d_ModelMatrix;
in vec4 p3d_Vertex;
in vec3 snap_pos;
out Vertex
{
vec3 snap_pos;
} vertex;
void main() {
gl_Position = p3d_ModelMatrix * p3d_Vertex;
vertex.snap_pos = (p3d_ModelMatrix * vec4(snap_pos, 1.)).xyz;
}
"""
GEOM_SHADER_P = """
#version 330
layout(triangles) in;
// One triangles will be generated: 3 vertices
layout(triangle_strip, max_vertices=3) out;
uniform mat4 p3d_ViewProjectionMatrix;
uniform mat4 p3d_ViewMatrixInverse;
uniform mat4 p3d_ProjectionMatrix;
uniform bool inverted;
uniform bool two_sided;
in Vertex
{
vec3 snap_pos;
} vertex[];
out vec3 snap_coords;
void main()
{
vec3 P0, P1, P2;
snap_coords = vertex[0].snap_pos;
if (inverted) {
P0 = gl_in[2].gl_Position.xyz;
P1 = gl_in[1].gl_Position.xyz;
P2 = gl_in[0].gl_Position.xyz;
}
else {
P0 = gl_in[0].gl_Position.xyz;
P1 = gl_in[1].gl_Position.xyz;
P2 = gl_in[2].gl_Position.xyz;
}
vec3 positions[3] = vec3[] (P0, P1, P2);
vec3 V0 = P1 - P0;
vec3 V1 = P2 - P1;
vec3 face_normal = cross(V0, V1);
vec3 vec;
if (p3d_ProjectionMatrix[3].w == 1.)
// orthographic lens;
// use inverted camera direction vector
vec = p3d_ViewMatrixInverse[2].xyz;
else
// perspective lens;
// compute vector pointing from any point of triangle to camera origin
vec = p3d_ViewMatrixInverse[3].xyz - P0;
if (two_sided || dot(vec, face_normal) >= 0.) {
for (int i = 0; i < 3; ++i)
{
gl_Position = p3d_ViewProjectionMatrix * vec4(positions[i], 1.0);
EmitVertex();
}
EndPrimitive();
}
}
"""
FRAG_SHADER = """
#version 330
uniform float snap_type_id;
in vec3 snap_coords;
layout(location = 0) out vec4 out_color;
void main() {
// output the snap point coordinates as a color value
out_color = vec4(snap_coords, snap_type_id);
}
"""
| vert_shader_v = '\n #version 330\n\n uniform mat4 p3d_ModelMatrix;\n in vec4 p3d_Vertex;\n\n void main() {\n gl_Position = p3d_ModelMatrix * p3d_Vertex;\n }\n'
geom_shader_v = '\n #version 330\n\n layout(triangles) in;\n\n // Three points will be generated: 3 vertices\n layout(points, max_vertices=3) out;\n\n uniform mat4 p3d_ViewProjectionMatrix;\n uniform mat4 p3d_ViewMatrixInverse;\n uniform mat4 p3d_ProjectionMatrix;\n uniform bool inverted;\n uniform bool two_sided;\n\n out vec3 snap_coords;\n\n void main()\n {\n\n vec3 P0 = gl_in[0].gl_Position.xyz;\n vec3 P1 = gl_in[1].gl_Position.xyz;\n vec3 P2 = gl_in[2].gl_Position.xyz;\n vec3 positions[3] = vec3[] (P0, P1, P2);\n vec3 V0 = P1 - P0;\n vec3 V1 = P2 - P1;\n vec3 face_normal = inverted ? cross(V1, V0) : cross(V0, V1);\n vec3 vec;\n\n if (p3d_ProjectionMatrix[3].w == 1.)\n // orthographic lens;\n // use inverted camera direction vector\n vec = p3d_ViewMatrixInverse[2].xyz;\n else\n // perspective lens;\n // compute vector pointing from any point of triangle to camera origin\n vec = p3d_ViewMatrixInverse[3].xyz - P0;\n\n if (two_sided || dot(vec, face_normal) >= 0.) {\n // generate points\n for (int i = 0; i < 3; ++i)\n {\n gl_Position = p3d_ViewProjectionMatrix * vec4(positions[i], 1.0);\n snap_coords = positions[i];\n EmitVertex();\n EndPrimitive();\n }\n }\n\n }\n'
vert_shader_e = '\n #version 330\n\n uniform mat4 p3d_ModelMatrix;\n in vec4 p3d_Vertex;\n in int sides;\n\n out Vertex\n {\n int side_gen;\n } vertex;\n\n void main() {\n gl_Position = p3d_ModelMatrix * p3d_Vertex;\n vertex.side_gen = sides;\n }\n'
geom_shader_e = '\n #version 330\n\n layout(triangles) in;\n\n // Three lines will be generated: 6 vertices\n layout(line_strip, max_vertices=6) out;\n\n uniform mat4 p3d_ViewProjectionMatrix;\n uniform mat4 p3d_ViewMatrixInverse;\n uniform mat4 p3d_ProjectionMatrix;\n uniform bool inverted;\n uniform bool two_sided;\n\n in Vertex\n {\n int side_gen;\n } vertex[];\n\n out vec3 snap_coords;\n\n void main()\n {\n\n int side_generation, S0, S1, S2;\n int sides[3];\n\n // determine which sides should be generated (1) or not (0)\n side_generation = vertex[0].side_gen;\n S0 = side_generation >> 2;\n S1 = (side_generation ^ (S0 << 2)) >> 1;\n S2 = side_generation ^ (S0 << 2) ^ (S1 << 1);\n sides = int[] (S0, S1, S2);\n\n vec3 P0 = gl_in[0].gl_Position.xyz;\n vec3 P1 = gl_in[1].gl_Position.xyz;\n vec3 P2 = gl_in[2].gl_Position.xyz;\n vec3 positions[4] = vec3[] (P0, P1, P2, P0);\n vec3 V0 = P1 - P0;\n vec3 V1 = P2 - P1;\n vec3 face_normal = inverted ? cross(V1, V0) : cross(V0, V1);\n vec3 vec;\n\n if (p3d_ProjectionMatrix[3].w == 1.)\n // orthographic lens;\n // use inverted camera direction vector\n vec = p3d_ViewMatrixInverse[2].xyz;\n else\n // perspective lens;\n // compute vector pointing from any point of triangle to camera origin\n vec = p3d_ViewMatrixInverse[3].xyz - P0;\n\n if (two_sided || dot(vec, face_normal) >= 0.) {\n // generate sides\n for (int i = 0; i < 3; ++i)\n {\n for (int j = 0; j < sides[i]; ++j)\n {\n\n snap_coords = (positions[i] + positions[i + 1]) * .5;\n\n gl_Position = p3d_ViewProjectionMatrix * vec4(positions[i], 1.0);\n EmitVertex();\n\n gl_Position = p3d_ViewProjectionMatrix * vec4(positions[i + 1], 1.0);\n EmitVertex();\n\n EndPrimitive();\n\n }\n }\n }\n\n }\n'
vert_shader_p = '\n #version 330\n\n uniform mat4 p3d_ModelMatrix;\n in vec4 p3d_Vertex;\n in vec3 snap_pos;\n\n out Vertex\n {\n vec3 snap_pos;\n } vertex;\n\n void main() {\n gl_Position = p3d_ModelMatrix * p3d_Vertex;\n vertex.snap_pos = (p3d_ModelMatrix * vec4(snap_pos, 1.)).xyz;\n }\n'
geom_shader_p = '\n #version 330\n\n layout(triangles) in;\n\n // One triangles will be generated: 3 vertices\n layout(triangle_strip, max_vertices=3) out;\n\n uniform mat4 p3d_ViewProjectionMatrix;\n uniform mat4 p3d_ViewMatrixInverse;\n uniform mat4 p3d_ProjectionMatrix;\n uniform bool inverted;\n uniform bool two_sided;\n\n in Vertex\n {\n vec3 snap_pos;\n } vertex[];\n\n out vec3 snap_coords;\n\n void main()\n {\n\n vec3 P0, P1, P2;\n snap_coords = vertex[0].snap_pos;\n\n if (inverted) {\n P0 = gl_in[2].gl_Position.xyz;\n P1 = gl_in[1].gl_Position.xyz;\n P2 = gl_in[0].gl_Position.xyz;\n }\n else {\n P0 = gl_in[0].gl_Position.xyz;\n P1 = gl_in[1].gl_Position.xyz;\n P2 = gl_in[2].gl_Position.xyz;\n }\n vec3 positions[3] = vec3[] (P0, P1, P2);\n vec3 V0 = P1 - P0;\n vec3 V1 = P2 - P1;\n vec3 face_normal = cross(V0, V1);\n vec3 vec;\n\n if (p3d_ProjectionMatrix[3].w == 1.)\n // orthographic lens;\n // use inverted camera direction vector\n vec = p3d_ViewMatrixInverse[2].xyz;\n else\n // perspective lens;\n // compute vector pointing from any point of triangle to camera origin\n vec = p3d_ViewMatrixInverse[3].xyz - P0;\n\n if (two_sided || dot(vec, face_normal) >= 0.) {\n for (int i = 0; i < 3; ++i)\n {\n gl_Position = p3d_ViewProjectionMatrix * vec4(positions[i], 1.0);\n EmitVertex();\n }\n EndPrimitive();\n }\n\n }\n'
frag_shader = '\n #version 330\n\n uniform float snap_type_id;\n in vec3 snap_coords;\n\n layout(location = 0) out vec4 out_color;\n\n void main() {\n // output the snap point coordinates as a color value\n out_color = vec4(snap_coords, snap_type_id);\n }\n' |
# -*- coding: utf-8 -*-
class OutputFormatterStyle(object):
FOREGROUND_COLORS = {
'black': 30,
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'magenta': 35,
'cyan': 36,
'white': 37
}
BACKGROUND_COLORS = {
'black': 40,
'red': 41,
'green': 42,
'yellow': 43,
'blue': 44,
'magenta': 45,
'cyan': 46,
'white': 47
}
OPTIONS = {
'bold': 1,
'underscore': 4,
'blink': 5,
'reverse': 7,
'conceal': 8,
}
def __init__(self, foreground=None, background=None, options=None):
self.foreground = None
self.background = None
if foreground:
self.set_foreground(foreground)
if background:
self.set_background(background)
options = options or []
if not isinstance(options, list):
options = [options]
self.set_options(options)
def set_foreground(self, foreground):
self.foreground = self.__class__.FOREGROUND_COLORS[foreground]
def set_background(self, background):
self.background = self.__class__.BACKGROUND_COLORS[background]
def set_option(self, option):
if option not in self.OPTIONS:
raise Exception('Invalid option specified: "%s". Expected one of (%s)'
% (option, ', '.join(self.OPTIONS.keys())))
if option not in self.options:
self.options.append(self.OPTIONS[option])
def set_options(self, options):
self.options = []
for option in options:
self.set_option(option)
def apply(self, text):
codes = []
if self.foreground:
codes.append(self.foreground)
if self.background:
codes.append(self.background)
if len(self.options):
codes += self.options
if not len(codes):
return text
return '\033[%sm%s\033[0m' % (';'.join(map(str, codes)), text) | class Outputformatterstyle(object):
foreground_colors = {'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37}
background_colors = {'black': 40, 'red': 41, 'green': 42, 'yellow': 43, 'blue': 44, 'magenta': 45, 'cyan': 46, 'white': 47}
options = {'bold': 1, 'underscore': 4, 'blink': 5, 'reverse': 7, 'conceal': 8}
def __init__(self, foreground=None, background=None, options=None):
self.foreground = None
self.background = None
if foreground:
self.set_foreground(foreground)
if background:
self.set_background(background)
options = options or []
if not isinstance(options, list):
options = [options]
self.set_options(options)
def set_foreground(self, foreground):
self.foreground = self.__class__.FOREGROUND_COLORS[foreground]
def set_background(self, background):
self.background = self.__class__.BACKGROUND_COLORS[background]
def set_option(self, option):
if option not in self.OPTIONS:
raise exception('Invalid option specified: "%s". Expected one of (%s)' % (option, ', '.join(self.OPTIONS.keys())))
if option not in self.options:
self.options.append(self.OPTIONS[option])
def set_options(self, options):
self.options = []
for option in options:
self.set_option(option)
def apply(self, text):
codes = []
if self.foreground:
codes.append(self.foreground)
if self.background:
codes.append(self.background)
if len(self.options):
codes += self.options
if not len(codes):
return text
return '\x1b[%sm%s\x1b[0m' % (';'.join(map(str, codes)), text) |
def get_vars(conta) -> list:
vars = list()
for c in conta:
# print(c)
if c.isalpha() or c == '=':
vars.append(c)
# print(c, vars)
# print(vars)
return vars
cores = ['blue',
'green',
'yellow',
'red',
'cyan',
'gray',
'light green',
'white']
def mostrar(n):
for nn in n:
print(nn)
def formatar(line, conta) -> list:
line += 1
line = str(line)
print(conta)
formatado = list()
contador = 0
for i, c in enumerate(conta):
if c.isalpha() and c != '=':
p1 = i
p2 = p1 + 1
p1 = str(p1)
p2 = str(p2)
# print('p1:', type(p1), p1)
nome = c+line+p1
print(nome)
if contador == len(cores):
contador = 0
d = {
'nome': nome,
'p1': line+'.'+p1,
'p2': line +'.'+p2,
'fg': cores[contador]
}
formatado.append(d)
contador += 1
# mostrar
# print()
# mostrar(formatado)
return formatado
if __name__ == '__main__':
formatar(line=0, conta='33xcx8x=safsafsfasfasfsf')
| def get_vars(conta) -> list:
vars = list()
for c in conta:
if c.isalpha() or c == '=':
vars.append(c)
return vars
cores = ['blue', 'green', 'yellow', 'red', 'cyan', 'gray', 'light green', 'white']
def mostrar(n):
for nn in n:
print(nn)
def formatar(line, conta) -> list:
line += 1
line = str(line)
print(conta)
formatado = list()
contador = 0
for (i, c) in enumerate(conta):
if c.isalpha() and c != '=':
p1 = i
p2 = p1 + 1
p1 = str(p1)
p2 = str(p2)
nome = c + line + p1
print(nome)
if contador == len(cores):
contador = 0
d = {'nome': nome, 'p1': line + '.' + p1, 'p2': line + '.' + p2, 'fg': cores[contador]}
formatado.append(d)
contador += 1
return formatado
if __name__ == '__main__':
formatar(line=0, conta='33xcx8x=safsafsfasfasfsf') |
def getHammingDistance(a, b):
aLen = len(a)
bLen = len(b)
if aLen == 0 or bLen == 0:
return 0
diff = 0
if aLen != bLen:
diff = abs(aLen - bLen)
if aLen < bLen:
a = a + ' ' * diff
elif bLen < aLen:
b = b + ' ' * diff
result = 0
length = max(aLen, bLen)
for i in range(length):
if a[i] != b[i]:
result += 1
return result
if __name__ == '__main__':
ans = getHammingDistance('12345','abcde')
print(ans) | def get_hamming_distance(a, b):
a_len = len(a)
b_len = len(b)
if aLen == 0 or bLen == 0:
return 0
diff = 0
if aLen != bLen:
diff = abs(aLen - bLen)
if aLen < bLen:
a = a + ' ' * diff
elif bLen < aLen:
b = b + ' ' * diff
result = 0
length = max(aLen, bLen)
for i in range(length):
if a[i] != b[i]:
result += 1
return result
if __name__ == '__main__':
ans = get_hamming_distance('12345', 'abcde')
print(ans) |
printlevel = 0
singlemargin = ' '
marginflag = False
class nextlevel():
def __enter__(self):
global printlevel
printlevel+=1
def __exit__(self, *args, **kwargs):
global printlevel
printlevel-=1
def current_level():
return printlevel
def printmargin(kwargs):
global marginflag
prefix = kwargs.pop('prefix', None)
postfix = kwargs.pop('postfix', None)
prefixopts = kwargs.pop('prefixopts', dict(end=''))
postfixopts = kwargs.pop('postfixopts', dict(end=' '))
if marginflag:
return
if prefix:
print(*prefix, **prefixopts)
print(singlemargin*printlevel, sep='', end='')
if postfix:
print(*postfix, **postfixopts)
marginflag=True
def resetmarginflag(*args, **kwargs):
global marginflag
for arg in args+(kwargs.pop('sep', ''), kwargs.pop('end', '\n')):
if not isinstance(arg, str):
arg = str(arg)
if '\n' in arg:
marginflag=False
return
def printl(*args, **kwargs):
printmargin(kwargs)
print(*args, **kwargs)
resetmarginflag(*args, **kwargs)
| printlevel = 0
singlemargin = ' '
marginflag = False
class Nextlevel:
def __enter__(self):
global printlevel
printlevel += 1
def __exit__(self, *args, **kwargs):
global printlevel
printlevel -= 1
def current_level():
return printlevel
def printmargin(kwargs):
global marginflag
prefix = kwargs.pop('prefix', None)
postfix = kwargs.pop('postfix', None)
prefixopts = kwargs.pop('prefixopts', dict(end=''))
postfixopts = kwargs.pop('postfixopts', dict(end=' '))
if marginflag:
return
if prefix:
print(*prefix, **prefixopts)
print(singlemargin * printlevel, sep='', end='')
if postfix:
print(*postfix, **postfixopts)
marginflag = True
def resetmarginflag(*args, **kwargs):
global marginflag
for arg in args + (kwargs.pop('sep', ''), kwargs.pop('end', '\n')):
if not isinstance(arg, str):
arg = str(arg)
if '\n' in arg:
marginflag = False
return
def printl(*args, **kwargs):
printmargin(kwargs)
print(*args, **kwargs)
resetmarginflag(*args, **kwargs) |
elementos_eletro = {'F':3.98,"O":3.44,"Cl":3.16,'N':3.04,'Br':2.96,'I':2.66,'S':2.58,'Ac':0.7,"La":0.79,'Sr':0.82,'Ce':0.89,'Th':0.89,'Na':0.93,'Y':0.95,
'Li':0.98,'K':0.82,'Pr':1.1,'Pa':1.1,'Nd':1.12,'Pm':1.13,'Sm':1.14,
'Gd':1.17,"Dy":1.2,'Zr':1.22,'Er':1.22,'Tm':1.23,'Yb':1.24,'Lu':1.25,
'Ta':1.27,'Cm':1.28,'W':1.3,'U':1.3,'Bk':1.3,'Cf':1.3,'Es':1.3,
'Fm':1.3,'Md':1.3,'No':1.3,'Lr':1.3,'Rf':1.3,'Db':1.3,'Mg':1.31,
'Nb':1.31,'Ca':1.36,'Am':1.36,'Pu':1.38,'Re':1.5,'Np':1.5,'Sc':1.54,
'Cr':1.55,'Be':1.57,'Mo':1.6,'Al':1.61,'Bi':1.62,'Ti':1.63,'Cu':1.65,
'V':1.66,'ln':1.69,'Sn':1.78,'Zn':1.81,'Mn':1.83,'Fe':1.88 ,'Si':1.9,
'Ni':1.9,'Ru':1.9,'Ir':1.9,'Co':1.91,'Cd':1.93,'Sb':1.96 ,'Pb':2,
'Rn':2,'Ga':2.01,'At':2.02,'B':2.04,'I':2.05,'Xe':2.1,'Tc':2.16,
'As':2.18,'P':2.19,'H':2.2,'Rh':2.26,'Ag':2.2,'Pt':2.2,'Au':2.2,
'Fr':2.24,'Pd':2.28,'Hg':2.28,'Po':2.33,'Os':2.36,'TI':2.54,'C':2.55,
'Se':2.55,'S':2.58,'Ba':2.6,'Cs':2.66,'Kr':2.96,'Rb':0.8}
| elementos_eletro = {'F': 3.98, 'O': 3.44, 'Cl': 3.16, 'N': 3.04, 'Br': 2.96, 'I': 2.66, 'S': 2.58, 'Ac': 0.7, 'La': 0.79, 'Sr': 0.82, 'Ce': 0.89, 'Th': 0.89, 'Na': 0.93, 'Y': 0.95, 'Li': 0.98, 'K': 0.82, 'Pr': 1.1, 'Pa': 1.1, 'Nd': 1.12, 'Pm': 1.13, 'Sm': 1.14, 'Gd': 1.17, 'Dy': 1.2, 'Zr': 1.22, 'Er': 1.22, 'Tm': 1.23, 'Yb': 1.24, 'Lu': 1.25, 'Ta': 1.27, 'Cm': 1.28, 'W': 1.3, 'U': 1.3, 'Bk': 1.3, 'Cf': 1.3, 'Es': 1.3, 'Fm': 1.3, 'Md': 1.3, 'No': 1.3, 'Lr': 1.3, 'Rf': 1.3, 'Db': 1.3, 'Mg': 1.31, 'Nb': 1.31, 'Ca': 1.36, 'Am': 1.36, 'Pu': 1.38, 'Re': 1.5, 'Np': 1.5, 'Sc': 1.54, 'Cr': 1.55, 'Be': 1.57, 'Mo': 1.6, 'Al': 1.61, 'Bi': 1.62, 'Ti': 1.63, 'Cu': 1.65, 'V': 1.66, 'ln': 1.69, 'Sn': 1.78, 'Zn': 1.81, 'Mn': 1.83, 'Fe': 1.88, 'Si': 1.9, 'Ni': 1.9, 'Ru': 1.9, 'Ir': 1.9, 'Co': 1.91, 'Cd': 1.93, 'Sb': 1.96, 'Pb': 2, 'Rn': 2, 'Ga': 2.01, 'At': 2.02, 'B': 2.04, 'I': 2.05, 'Xe': 2.1, 'Tc': 2.16, 'As': 2.18, 'P': 2.19, 'H': 2.2, 'Rh': 2.26, 'Ag': 2.2, 'Pt': 2.2, 'Au': 2.2, 'Fr': 2.24, 'Pd': 2.28, 'Hg': 2.28, 'Po': 2.33, 'Os': 2.36, 'TI': 2.54, 'C': 2.55, 'Se': 2.55, 'S': 2.58, 'Ba': 2.6, 'Cs': 2.66, 'Kr': 2.96, 'Rb': 0.8} |
# [Silent Crusade] Starling's Proposal
BASTILLE = 9073003
sm.setSpeakerID(BASTILLE)
sm.sendNext("I've been expecting you! Come, let's go somewhere where we can speak in private.")
sm.warp(931050500)
sm.completeQuest(parentID) | bastille = 9073003
sm.setSpeakerID(BASTILLE)
sm.sendNext("I've been expecting you! Come, let's go somewhere where we can speak in private.")
sm.warp(931050500)
sm.completeQuest(parentID) |
def tryInt(inp):
try: return int(inp)
except: return inp
def findNameIndex(name, fileContent):
for i, entry in list(enumerate(fileContent)):
if name == entry and (i%2) == 0:
return i
return False
def getFile():
with open("scores.txt") as f :
return [ tryInt(x) for x in f.read().splitlines() ]
def saveFile(obj):
with open("scores.txt", "w") as f:
for entry in obj: print(entry, file=f)
def addPerson(name, score) :
content = getFile()
content += [ name, int(score) ]
saveFile(content)
def updateScore(name, score):
content = getFile()
ind = findNameIndex( name, content )
content[ ind + 1 ] = int(score)
saveFile( content )
def getScore(name):
content = getFile()
return content[ findNameIndex(name, content) + 1 ]
| def try_int(inp):
try:
return int(inp)
except:
return inp
def find_name_index(name, fileContent):
for (i, entry) in list(enumerate(fileContent)):
if name == entry and i % 2 == 0:
return i
return False
def get_file():
with open('scores.txt') as f:
return [try_int(x) for x in f.read().splitlines()]
def save_file(obj):
with open('scores.txt', 'w') as f:
for entry in obj:
print(entry, file=f)
def add_person(name, score):
content = get_file()
content += [name, int(score)]
save_file(content)
def update_score(name, score):
content = get_file()
ind = find_name_index(name, content)
content[ind + 1] = int(score)
save_file(content)
def get_score(name):
content = get_file()
return content[find_name_index(name, content) + 1] |
# Target for including SkFlate.
{
'targets': [
{
'target_name': 'skflate',
'type': 'static_library',
'dependencies': [
'skia_lib.gyp:skia_lib',
],
'conditions': [
# When zlib is not availible on a system,
# SK_NO_FLATE will be defined.
[ 'skia_os != "win"',
{
'dependencies': [
'zlib.gyp:zlib',
],
}
],
],
'sources': [
'../src/core/SkFlate.cpp',
],
},
],
}
| {'targets': [{'target_name': 'skflate', 'type': 'static_library', 'dependencies': ['skia_lib.gyp:skia_lib'], 'conditions': [['skia_os != "win"', {'dependencies': ['zlib.gyp:zlib']}]], 'sources': ['../src/core/SkFlate.cpp']}]} |
s = []
dir = [[0,1],[1,0],[1,1],[-1,1]]
for i in range(20):
s.append(list(map(int, input().split())))
print(s)
ans = 0
def f(x, y, dx, dy):
global ans
ret = 1
for i in range(4):
if x >= 20 or y >= 20: return
ret *= s[x][y]
x += dx
y += dy
if ret > ans: ans = ret
for i in range(20):
for j in range(20):
for l in range(len(dir)):
f(i, j, dir[l][0], dir[l][1])
print("ans = ", ans)
| s = []
dir = [[0, 1], [1, 0], [1, 1], [-1, 1]]
for i in range(20):
s.append(list(map(int, input().split())))
print(s)
ans = 0
def f(x, y, dx, dy):
global ans
ret = 1
for i in range(4):
if x >= 20 or y >= 20:
return
ret *= s[x][y]
x += dx
y += dy
if ret > ans:
ans = ret
for i in range(20):
for j in range(20):
for l in range(len(dir)):
f(i, j, dir[l][0], dir[l][1])
print('ans = ', ans) |
class Invoice:
"""This class contains basic information about an invoice
:param title: Product name
:type title: str
:param description: Product description
:type description: str
:param start_parameter: Unique bot deep.linking parameter that can be used to generate this invoice
:type start_parameter: str
:param currency: Three letter ISO 4217 currency code
:type currency: str
:param total_amount: Total amount in the smallest units of the currency (int, not float/double)
:type total_amount: int
"""
def __init__(self, *, title, description, start_parameter, currency, total_amount):
self.title = title
self.description = description
self.start_parameter = start_parameter
self.currency = currency
self.total_amount = total_amount
| class Invoice:
"""This class contains basic information about an invoice
:param title: Product name
:type title: str
:param description: Product description
:type description: str
:param start_parameter: Unique bot deep.linking parameter that can be used to generate this invoice
:type start_parameter: str
:param currency: Three letter ISO 4217 currency code
:type currency: str
:param total_amount: Total amount in the smallest units of the currency (int, not float/double)
:type total_amount: int
"""
def __init__(self, *, title, description, start_parameter, currency, total_amount):
self.title = title
self.description = description
self.start_parameter = start_parameter
self.currency = currency
self.total_amount = total_amount |
def check_exam(arr1,arr2):
def points(corr,stud):
if stud == corr:
return 4
elif stud:
return -1
else:
return 0
return max(0, sum(points(*it) for it in zip(arr1,arr2)))
| def check_exam(arr1, arr2):
def points(corr, stud):
if stud == corr:
return 4
elif stud:
return -1
else:
return 0
return max(0, sum((points(*it) for it in zip(arr1, arr2)))) |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1358/B
t = int(input())
for _ in range(t):
n,m = list(map(int,input().split()))
print((n*m+1)//2)
| t = int(input())
for _ in range(t):
(n, m) = list(map(int, input().split()))
print((n * m + 1) // 2) |
MAJOR = 0
MINOR = 1
PATCH = ''
SUFFIX = '' # eg.rc0
__version__ = f"{MAJOR}.{MINOR}.{PATCH}{SUFFIX}" | major = 0
minor = 1
patch = ''
suffix = ''
__version__ = f'{MAJOR}.{MINOR}.{PATCH}{SUFFIX}' |
###############################################################################################
# This module is used to check if a process is already running
# I don't think this is being used anymore. I may delete it, but I suspect it is very useful.
# I may move it to a utility module.
# I'll comment it out later and see what breaks.
# I need to create automated tests first using assert statements.
# Then if I break something, I'll know right away.
def checkIfProcessRunning(processName):
'''
Check if there is any running process that contains the given name processName.
'''
# Iterate over the all the running process
for proc in psutil.process_iter():
try:
# Check if process name contains the given name string.
if processName.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False
###############################################################################################
# End Check if a process is already running | def check_if_process_running(processName):
"""
Check if there is any running process that contains the given name processName.
"""
for proc in psutil.process_iter():
try:
if processName.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False |
class Solution:
def shiftingLetters(self, S, shifts):
"""
:type S: str
:type shifts: List[int]
:rtype: str
"""
s = sum(shifts)
lst = list(S)
for i, shift in enumerate(shifts):
ch = ord(lst[i]) - 97
ch = (ch + s) % 26
lst[i] = chr(ch + 97)
s -= shift
return ''.join(lst)
| class Solution:
def shifting_letters(self, S, shifts):
"""
:type S: str
:type shifts: List[int]
:rtype: str
"""
s = sum(shifts)
lst = list(S)
for (i, shift) in enumerate(shifts):
ch = ord(lst[i]) - 97
ch = (ch + s) % 26
lst[i] = chr(ch + 97)
s -= shift
return ''.join(lst) |
lista=[]
soma=0
for cont in range(10):
nota=int(input("Digite a nota: "))
lista.append(nota)
print(lista)
| lista = []
soma = 0
for cont in range(10):
nota = int(input('Digite a nota: '))
lista.append(nota)
print(lista) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.