content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
self.description = "Try to upgrade two packages which would break deps"
lp1 = pmpkg("pkg1")
lp1.depends = ["pkg2=1.0"]
self.addpkg2db("local", lp1)
lp2 = pmpkg("pkg2", "1.0-1")
self.addpkg2db("local", lp2)
p1 = pmpkg("pkg1", "1.1-1")
p1.depends = ["pkg2=1.0-1"]
self.addpkg(p1)
p2 = pmpkg("pkg2", "1.1-1")
self.addpkg(p2)
self.args = "-U %s" % " ".join([p.filename() for p in (p1, p2)])
self.addrule("PACMAN_RETCODE=1")
self.addrule("PKG_VERSION=pkg1|1.0-1")
self.addrule("PKG_VERSION=pkg2|1.0-1")
| self.description = 'Try to upgrade two packages which would break deps'
lp1 = pmpkg('pkg1')
lp1.depends = ['pkg2=1.0']
self.addpkg2db('local', lp1)
lp2 = pmpkg('pkg2', '1.0-1')
self.addpkg2db('local', lp2)
p1 = pmpkg('pkg1', '1.1-1')
p1.depends = ['pkg2=1.0-1']
self.addpkg(p1)
p2 = pmpkg('pkg2', '1.1-1')
self.addpkg(p2)
self.args = '-U %s' % ' '.join([p.filename() for p in (p1, p2)])
self.addrule('PACMAN_RETCODE=1')
self.addrule('PKG_VERSION=pkg1|1.0-1')
self.addrule('PKG_VERSION=pkg2|1.0-1') |
def intersection_of(lhs, rhs):
"""
Intersects two posting lists.
"""
i = 0
j = 0
intersection = []
while (i < len(lhs) and j < len(rhs)):
if (lhs[i] == rhs[j]):
intersection.append(lhs[i])
i += 1
j += 1
elif (lhs[i] < rhs[j]):
i += 1
else:
j += 1
return intersection
def intersection_of_all(posting_lists):
"""
Intersects multiple posting lists.
"""
posting_lists = _to_list(posting_lists)
if (posting_lists):
posting_lists.sort(key=len)
answer = posting_lists[0]
for list in posting_lists[1:]:
answer = intersection_of(answer, list)
return answer
else:
return []
def _to_list(iterable):
return (list(iterable)
if (not isinstance(iterable, list))
else iterable)
def union_of(lhs, rhs):
"""
Computes the union of two posting lists.
"""
i = 0
j = 0
answer = []
while (i < len(lhs) or j < len(rhs)):
if (j == len(rhs) or
(i < len(lhs) and lhs[i] < rhs[j])):
answer.append(lhs[i])
i += 1
elif (i == len(lhs) or rhs[j] < lhs[i]):
answer.append(rhs[j])
j += 1
else:
answer.append(lhs[i])
i += 1
j += 1
return answer
def union_of_all(posting_lists):
"""
Computes the union of multiple posting lists.
"""
answer = []
for p in posting_lists:
answer = union_of(answer, p)
return answer
def difference_of(lhs, rhs):
"""
Computes the difference of two posting lists, that is, the elements
in the first list which are not elements in the second list.
"""
i = 0
j = 0
answer = []
while (i < len(lhs)):
if (j == len(rhs) or lhs[i] < rhs[j]):
answer.append(lhs[i])
i += 1
elif (rhs[j] < lhs[i]):
j += 1
else:
i += 1
return answer
| def intersection_of(lhs, rhs):
"""
Intersects two posting lists.
"""
i = 0
j = 0
intersection = []
while i < len(lhs) and j < len(rhs):
if lhs[i] == rhs[j]:
intersection.append(lhs[i])
i += 1
j += 1
elif lhs[i] < rhs[j]:
i += 1
else:
j += 1
return intersection
def intersection_of_all(posting_lists):
"""
Intersects multiple posting lists.
"""
posting_lists = _to_list(posting_lists)
if posting_lists:
posting_lists.sort(key=len)
answer = posting_lists[0]
for list in posting_lists[1:]:
answer = intersection_of(answer, list)
return answer
else:
return []
def _to_list(iterable):
return list(iterable) if not isinstance(iterable, list) else iterable
def union_of(lhs, rhs):
"""
Computes the union of two posting lists.
"""
i = 0
j = 0
answer = []
while i < len(lhs) or j < len(rhs):
if j == len(rhs) or (i < len(lhs) and lhs[i] < rhs[j]):
answer.append(lhs[i])
i += 1
elif i == len(lhs) or rhs[j] < lhs[i]:
answer.append(rhs[j])
j += 1
else:
answer.append(lhs[i])
i += 1
j += 1
return answer
def union_of_all(posting_lists):
"""
Computes the union of multiple posting lists.
"""
answer = []
for p in posting_lists:
answer = union_of(answer, p)
return answer
def difference_of(lhs, rhs):
"""
Computes the difference of two posting lists, that is, the elements
in the first list which are not elements in the second list.
"""
i = 0
j = 0
answer = []
while i < len(lhs):
if j == len(rhs) or lhs[i] < rhs[j]:
answer.append(lhs[i])
i += 1
elif rhs[j] < lhs[i]:
j += 1
else:
i += 1
return answer |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def insert(self, head, data):
p = Node(data)
if head == None:
head = p
elif head.next == None:
head.next = p
else:
start = head
while (start.next != None):
start = start.next
start.next = p
return head
def display(self, head):
current = head
while current:
print(current.data, end=' ')
current = current.next
def removeDuplicates(self, head):
node = head
while node.next:
if node.data == node.next.data:
node.next = node.next.next
else:
node = node.next
return head
mylist = Solution()
T = [1, 2, 2, 3, 3, 4]
head = None
for i in T:
data = i
head = mylist.insert(head, data)
head = mylist.removeDuplicates(head)
mylist.display(head)
| class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def insert(self, head, data):
p = node(data)
if head == None:
head = p
elif head.next == None:
head.next = p
else:
start = head
while start.next != None:
start = start.next
start.next = p
return head
def display(self, head):
current = head
while current:
print(current.data, end=' ')
current = current.next
def remove_duplicates(self, head):
node = head
while node.next:
if node.data == node.next.data:
node.next = node.next.next
else:
node = node.next
return head
mylist = solution()
t = [1, 2, 2, 3, 3, 4]
head = None
for i in T:
data = i
head = mylist.insert(head, data)
head = mylist.removeDuplicates(head)
mylist.display(head) |
__version__ = "1.1.0"
'''
1.1.0
- Base demo module with version info
''' | __version__ = '1.1.0'
'\n1.1.0\n - Base demo module with version info \n' |
#
# PySNMP MIB module CISCOSB-EVENTS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-EVENTS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:06:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection")
switch001, = mibBuilder.importSymbols("CISCOSB-MIB", "switch001")
RlSmartPortsMacroNameOrZero, = mibBuilder.importSymbols("CISCOSB-SMARTPORTS-MIB", "RlSmartPortsMacroNameOrZero")
InterfaceIndex, InterfaceIndexOrZero = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "InterfaceIndexOrZero")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Counter32, NotificationType, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Counter64, TimeTicks, Unsigned32, Gauge32, MibIdentifier, Integer32, Bits, ObjectIdentity, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "NotificationType", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Counter64", "TimeTicks", "Unsigned32", "Gauge32", "MibIdentifier", "Integer32", "Bits", "ObjectIdentity", "IpAddress")
RowStatus, TruthValue, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TruthValue", "DisplayString", "TextualConvention")
rlEventsMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150))
rlEventsMib.setRevisions(('2010-09-11 00:00',))
if mibBuilder.loadTexts: rlEventsMib.setLastUpdated('201009110000Z')
if mibBuilder.loadTexts: rlEventsMib.setOrganization('Cisco Small Business')
class SmartPortType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
namedValues = NamedValues(("unknown", 1), ("default", 2), ("printer", 3), ("desktop", 4), ("guest", 5), ("server", 6), ("host", 7), ("ip-camera", 8), ("ip-phone", 9), ("ip-phone-desktop", 10), ("switch", 11), ("router", 12), ("ap", 13))
class SmartPortMacroParameterName(DisplayString):
status = 'current'
subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(1, 32)
class SmartPortMacroParameterValue(DisplayString):
status = 'current'
subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(1, 80)
class SmartPortMacroType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("built-in", 1), ("user-defined", 2))
class SmartPortMacroParameterOrder(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))
namedValues = NamedValues(("single", 1), ("first", 2), ("middle", 3), ("last", 4))
rlPortEvents = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1))
rlAutoSmartPortAdminStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2), ("controlled", 3))).clone('controlled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortAdminStatus.setStatus('current')
rlAutoSmartPortOperStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlAutoSmartPortOperStatus.setStatus('current')
rlAutoSmartPortLastVoiceVlanStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlAutoSmartPortLastVoiceVlanStatus.setStatus('current')
rlAutoSmartPortLastVoiceVlanId = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlAutoSmartPortLastVoiceVlanId.setStatus('current')
rlAutoSmartPortLearningProtocols = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 5), Bits().clone(namedValues=NamedValues(("cdp", 0), ("lldp", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortLearningProtocols.setStatus('current')
rlAutoSmartPortTypesTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6), )
if mibBuilder.loadTexts: rlAutoSmartPortTypesTable.setStatus('current')
rlAutoSmartPortTypesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1), ).setIndexNames((0, "CISCOSB-EVENTS-MIB", "rlAutoSmartPortTypesType"))
if mibBuilder.loadTexts: rlAutoSmartPortTypesEntry.setStatus('current')
rlAutoSmartPortTypesType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 1), SmartPortType())
if mibBuilder.loadTexts: rlAutoSmartPortTypesType.setStatus('current')
rlAutoSmartPortTypeStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2), ("default", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortTypeStatus.setStatus('current')
rlAutoSmartPortMacro = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 3), RlSmartPortsMacroNameOrZero()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortMacro.setStatus('current')
rlAutoSmartPortTypesRevertToDefaultMacro = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 4), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortTypesRevertToDefaultMacro.setStatus('current')
rlAutoSmartPortTypesRevertToDefaultParams = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 5), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortTypesRevertToDefaultParams.setStatus('current')
rlAutoSmartPortTypesBuiltinMacro = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 6), SmartPortMacroType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlAutoSmartPortTypesBuiltinMacro.setStatus('current')
rlAutoSmartPortMacrosParamTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7), )
if mibBuilder.loadTexts: rlAutoSmartPortMacrosParamTable.setStatus('current')
rlAutoSmartPortMacrosParamEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7, 1), ).setIndexNames((0, "CISCOSB-EVENTS-MIB", "rlAutoSmartPortTypesType"), (0, "CISCOSB-EVENTS-MIB", "rlAutoSmartPortMacroType"), (1, "CISCOSB-EVENTS-MIB", "rlAutoSmartPortMacrosParamName"))
if mibBuilder.loadTexts: rlAutoSmartPortMacrosParamEntry.setStatus('current')
rlAutoSmartPortMacroType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7, 1, 1), SmartPortMacroType())
if mibBuilder.loadTexts: rlAutoSmartPortMacroType.setStatus('current')
rlAutoSmartPortMacrosParamName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7, 1, 2), SmartPortMacroParameterName())
if mibBuilder.loadTexts: rlAutoSmartPortMacrosParamName.setStatus('current')
rlAutoSmartPortMacrosParamOrder = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7, 1, 3), SmartPortMacroParameterOrder()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortMacrosParamOrder.setStatus('current')
rlAutoSmartPortMacrosParamValue = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7, 1, 4), SmartPortMacroParameterValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortMacrosParamValue.setStatus('current')
rlAutoSmartPortPortsTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8), )
if mibBuilder.loadTexts: rlAutoSmartPortPortsTable.setStatus('current')
rlAutoSmartPortPortsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1), ).setIndexNames((0, "CISCOSB-EVENTS-MIB", "rlAutoSmartPortPort"))
if mibBuilder.loadTexts: rlAutoSmartPortPortsEntry.setStatus('current')
rlAutoSmartPortPort = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: rlAutoSmartPortPort.setStatus('current')
rlAutoSmartPortPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortPortStatus.setStatus('current')
rlAutoSmartPortPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 3), SmartPortType().clone('default')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortPortType.setStatus('current')
rlAutoSmartPortPersistency = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("persistent", 1), ("not-persistent", 2))).clone('not-persistent')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortPersistency.setStatus('current')
rlAutoSmartPortLearntPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 5), SmartPortType().clone('default')).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlAutoSmartPortLearntPortType.setStatus('current')
rlAutoSmartPortPortAcquiringType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("default", 1), ("configuration", 2), ("persistency", 3), ("learning", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortPortAcquiringType.setStatus('current')
rlAutoSmartPortLastActivatedMacro = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 7), RlSmartPortsMacroNameOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlAutoSmartPortLastActivatedMacro.setStatus('current')
rlAutoSmartPortFailedCommandNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlAutoSmartPortFailedCommandNumber.setStatus('current')
rlAutoSmartPortSetLearntPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 9), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortSetLearntPortType.setStatus('current')
rlAutoSmartPortParamsTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9), )
if mibBuilder.loadTexts: rlAutoSmartPortParamsTable.setStatus('current')
rlAutoSmartPortParamsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9, 1), ).setIndexNames((0, "CISCOSB-EVENTS-MIB", "rlAutoSmartPortIfIndex"), (1, "CISCOSB-EVENTS-MIB", "rlAutoSmartPortParamName"))
if mibBuilder.loadTexts: rlAutoSmartPortParamsEntry.setStatus('current')
rlAutoSmartPortIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: rlAutoSmartPortIfIndex.setStatus('current')
rlAutoSmartPortParamName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9, 1, 2), SmartPortMacroParameterName())
if mibBuilder.loadTexts: rlAutoSmartPortParamName.setStatus('current')
rlAutoSmartPortParamOrder = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9, 1, 3), SmartPortMacroParameterOrder()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAutoSmartPortParamOrder.setStatus('current')
rlAutoSmartPortParamValue = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9, 1, 4), SmartPortMacroParameterValue())
if mibBuilder.loadTexts: rlAutoSmartPortParamValue.setStatus('current')
rlAutoSmartTrunkRefreshTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 10), )
if mibBuilder.loadTexts: rlAutoSmartTrunkRefreshTable.setStatus('current')
rlAutoSmartTrunkRefreshEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 10, 1), ).setIndexNames((0, "CISCOSB-EVENTS-MIB", "rlAutoSmartTrunkRefreshSmartPortType"), (0, "CISCOSB-EVENTS-MIB", "rlAutoSmartTrunkRefreshIfIndex"))
if mibBuilder.loadTexts: rlAutoSmartTrunkRefreshEntry.setStatus('current')
rlAutoSmartTrunkRefreshSmartPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 10, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 11, 12, 13))).clone(namedValues=NamedValues(("default", 1), ("switch", 11), ("router", 12), ("ap", 13))))
if mibBuilder.loadTexts: rlAutoSmartTrunkRefreshSmartPortType.setStatus('current')
rlAutoSmartTrunkRefreshIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 10, 1, 2), InterfaceIndexOrZero())
if mibBuilder.loadTexts: rlAutoSmartTrunkRefreshIfIndex.setStatus('current')
rlAutoSmartTrunkRefreshRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 10, 1, 3), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlAutoSmartTrunkRefreshRowStatus.setStatus('current')
rlAutoSmartBusy = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 11), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlAutoSmartBusy.setStatus('current')
mibBuilder.exportSymbols("CISCOSB-EVENTS-MIB", rlAutoSmartPortPort=rlAutoSmartPortPort, rlAutoSmartPortLastVoiceVlanStatus=rlAutoSmartPortLastVoiceVlanStatus, rlAutoSmartPortTypesRevertToDefaultMacro=rlAutoSmartPortTypesRevertToDefaultMacro, rlAutoSmartPortTypesBuiltinMacro=rlAutoSmartPortTypesBuiltinMacro, rlAutoSmartPortMacrosParamTable=rlAutoSmartPortMacrosParamTable, rlAutoSmartPortFailedCommandNumber=rlAutoSmartPortFailedCommandNumber, rlAutoSmartTrunkRefreshIfIndex=rlAutoSmartTrunkRefreshIfIndex, rlPortEvents=rlPortEvents, rlAutoSmartPortLearningProtocols=rlAutoSmartPortLearningProtocols, rlAutoSmartPortParamName=rlAutoSmartPortParamName, SmartPortMacroType=SmartPortMacroType, rlAutoSmartBusy=rlAutoSmartBusy, rlAutoSmartPortMacrosParamName=rlAutoSmartPortMacrosParamName, rlAutoSmartPortOperStatus=rlAutoSmartPortOperStatus, rlAutoSmartPortTypesTable=rlAutoSmartPortTypesTable, rlAutoSmartPortPortsEntry=rlAutoSmartPortPortsEntry, rlAutoSmartPortTypesEntry=rlAutoSmartPortTypesEntry, rlAutoSmartPortTypeStatus=rlAutoSmartPortTypeStatus, rlAutoSmartPortPortAcquiringType=rlAutoSmartPortPortAcquiringType, SmartPortMacroParameterValue=SmartPortMacroParameterValue, rlAutoSmartPortPortStatus=rlAutoSmartPortPortStatus, SmartPortType=SmartPortType, rlAutoSmartPortTypesRevertToDefaultParams=rlAutoSmartPortTypesRevertToDefaultParams, rlAutoSmartPortLastActivatedMacro=rlAutoSmartPortLastActivatedMacro, rlAutoSmartPortMacrosParamOrder=rlAutoSmartPortMacrosParamOrder, rlAutoSmartTrunkRefreshSmartPortType=rlAutoSmartTrunkRefreshSmartPortType, rlAutoSmartPortLearntPortType=rlAutoSmartPortLearntPortType, rlAutoSmartTrunkRefreshRowStatus=rlAutoSmartTrunkRefreshRowStatus, rlAutoSmartPortAdminStatus=rlAutoSmartPortAdminStatus, rlAutoSmartPortParamsEntry=rlAutoSmartPortParamsEntry, rlAutoSmartPortMacroType=rlAutoSmartPortMacroType, rlAutoSmartPortParamsTable=rlAutoSmartPortParamsTable, rlAutoSmartPortPortType=rlAutoSmartPortPortType, rlAutoSmartPortTypesType=rlAutoSmartPortTypesType, rlAutoSmartPortMacro=rlAutoSmartPortMacro, rlAutoSmartPortPersistency=rlAutoSmartPortPersistency, PYSNMP_MODULE_ID=rlEventsMib, rlAutoSmartTrunkRefreshTable=rlAutoSmartTrunkRefreshTable, rlAutoSmartPortLastVoiceVlanId=rlAutoSmartPortLastVoiceVlanId, rlAutoSmartPortPortsTable=rlAutoSmartPortPortsTable, rlAutoSmartPortParamOrder=rlAutoSmartPortParamOrder, rlEventsMib=rlEventsMib, rlAutoSmartPortIfIndex=rlAutoSmartPortIfIndex, SmartPortMacroParameterName=SmartPortMacroParameterName, rlAutoSmartPortParamValue=rlAutoSmartPortParamValue, rlAutoSmartTrunkRefreshEntry=rlAutoSmartTrunkRefreshEntry, SmartPortMacroParameterOrder=SmartPortMacroParameterOrder, rlAutoSmartPortMacrosParamEntry=rlAutoSmartPortMacrosParamEntry, rlAutoSmartPortMacrosParamValue=rlAutoSmartPortMacrosParamValue, rlAutoSmartPortSetLearntPortType=rlAutoSmartPortSetLearntPortType)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection')
(switch001,) = mibBuilder.importSymbols('CISCOSB-MIB', 'switch001')
(rl_smart_ports_macro_name_or_zero,) = mibBuilder.importSymbols('CISCOSB-SMARTPORTS-MIB', 'RlSmartPortsMacroNameOrZero')
(interface_index, interface_index_or_zero) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex', 'InterfaceIndexOrZero')
(snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(counter32, notification_type, iso, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, counter64, time_ticks, unsigned32, gauge32, mib_identifier, integer32, bits, object_identity, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'NotificationType', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Counter64', 'TimeTicks', 'Unsigned32', 'Gauge32', 'MibIdentifier', 'Integer32', 'Bits', 'ObjectIdentity', 'IpAddress')
(row_status, truth_value, display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'TruthValue', 'DisplayString', 'TextualConvention')
rl_events_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150))
rlEventsMib.setRevisions(('2010-09-11 00:00',))
if mibBuilder.loadTexts:
rlEventsMib.setLastUpdated('201009110000Z')
if mibBuilder.loadTexts:
rlEventsMib.setOrganization('Cisco Small Business')
class Smartporttype(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
named_values = named_values(('unknown', 1), ('default', 2), ('printer', 3), ('desktop', 4), ('guest', 5), ('server', 6), ('host', 7), ('ip-camera', 8), ('ip-phone', 9), ('ip-phone-desktop', 10), ('switch', 11), ('router', 12), ('ap', 13))
class Smartportmacroparametername(DisplayString):
status = 'current'
subtype_spec = DisplayString.subtypeSpec + value_size_constraint(1, 32)
class Smartportmacroparametervalue(DisplayString):
status = 'current'
subtype_spec = DisplayString.subtypeSpec + value_size_constraint(1, 80)
class Smartportmacrotype(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2))
named_values = named_values(('built-in', 1), ('user-defined', 2))
class Smartportmacroparameterorder(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4))
named_values = named_values(('single', 1), ('first', 2), ('middle', 3), ('last', 4))
rl_port_events = mib_identifier((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1))
rl_auto_smart_port_admin_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2), ('controlled', 3))).clone('controlled')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortAdminStatus.setStatus('current')
rl_auto_smart_port_oper_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('disabled')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlAutoSmartPortOperStatus.setStatus('current')
rl_auto_smart_port_last_voice_vlan_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('disabled')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlAutoSmartPortLastVoiceVlanStatus.setStatus('current')
rl_auto_smart_port_last_voice_vlan_id = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 4), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlAutoSmartPortLastVoiceVlanId.setStatus('current')
rl_auto_smart_port_learning_protocols = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 5), bits().clone(namedValues=named_values(('cdp', 0), ('lldp', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortLearningProtocols.setStatus('current')
rl_auto_smart_port_types_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6))
if mibBuilder.loadTexts:
rlAutoSmartPortTypesTable.setStatus('current')
rl_auto_smart_port_types_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1)).setIndexNames((0, 'CISCOSB-EVENTS-MIB', 'rlAutoSmartPortTypesType'))
if mibBuilder.loadTexts:
rlAutoSmartPortTypesEntry.setStatus('current')
rl_auto_smart_port_types_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 1), smart_port_type())
if mibBuilder.loadTexts:
rlAutoSmartPortTypesType.setStatus('current')
rl_auto_smart_port_type_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2), ('default', 3)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortTypeStatus.setStatus('current')
rl_auto_smart_port_macro = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 3), rl_smart_ports_macro_name_or_zero()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortMacro.setStatus('current')
rl_auto_smart_port_types_revert_to_default_macro = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 4), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortTypesRevertToDefaultMacro.setStatus('current')
rl_auto_smart_port_types_revert_to_default_params = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 5), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortTypesRevertToDefaultParams.setStatus('current')
rl_auto_smart_port_types_builtin_macro = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 6, 1, 6), smart_port_macro_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlAutoSmartPortTypesBuiltinMacro.setStatus('current')
rl_auto_smart_port_macros_param_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7))
if mibBuilder.loadTexts:
rlAutoSmartPortMacrosParamTable.setStatus('current')
rl_auto_smart_port_macros_param_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7, 1)).setIndexNames((0, 'CISCOSB-EVENTS-MIB', 'rlAutoSmartPortTypesType'), (0, 'CISCOSB-EVENTS-MIB', 'rlAutoSmartPortMacroType'), (1, 'CISCOSB-EVENTS-MIB', 'rlAutoSmartPortMacrosParamName'))
if mibBuilder.loadTexts:
rlAutoSmartPortMacrosParamEntry.setStatus('current')
rl_auto_smart_port_macro_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7, 1, 1), smart_port_macro_type())
if mibBuilder.loadTexts:
rlAutoSmartPortMacroType.setStatus('current')
rl_auto_smart_port_macros_param_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7, 1, 2), smart_port_macro_parameter_name())
if mibBuilder.loadTexts:
rlAutoSmartPortMacrosParamName.setStatus('current')
rl_auto_smart_port_macros_param_order = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7, 1, 3), smart_port_macro_parameter_order()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortMacrosParamOrder.setStatus('current')
rl_auto_smart_port_macros_param_value = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 7, 1, 4), smart_port_macro_parameter_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortMacrosParamValue.setStatus('current')
rl_auto_smart_port_ports_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8))
if mibBuilder.loadTexts:
rlAutoSmartPortPortsTable.setStatus('current')
rl_auto_smart_port_ports_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1)).setIndexNames((0, 'CISCOSB-EVENTS-MIB', 'rlAutoSmartPortPort'))
if mibBuilder.loadTexts:
rlAutoSmartPortPortsEntry.setStatus('current')
rl_auto_smart_port_port = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 1), interface_index())
if mibBuilder.loadTexts:
rlAutoSmartPortPort.setStatus('current')
rl_auto_smart_port_port_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('enabled')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortPortStatus.setStatus('current')
rl_auto_smart_port_port_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 3), smart_port_type().clone('default')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortPortType.setStatus('current')
rl_auto_smart_port_persistency = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('persistent', 1), ('not-persistent', 2))).clone('not-persistent')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortPersistency.setStatus('current')
rl_auto_smart_port_learnt_port_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 5), smart_port_type().clone('default')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlAutoSmartPortLearntPortType.setStatus('current')
rl_auto_smart_port_port_acquiring_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('default', 1), ('configuration', 2), ('persistency', 3), ('learning', 4)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortPortAcquiringType.setStatus('current')
rl_auto_smart_port_last_activated_macro = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 7), rl_smart_ports_macro_name_or_zero()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlAutoSmartPortLastActivatedMacro.setStatus('current')
rl_auto_smart_port_failed_command_number = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 8), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlAutoSmartPortFailedCommandNumber.setStatus('current')
rl_auto_smart_port_set_learnt_port_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 8, 1, 9), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortSetLearntPortType.setStatus('current')
rl_auto_smart_port_params_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9))
if mibBuilder.loadTexts:
rlAutoSmartPortParamsTable.setStatus('current')
rl_auto_smart_port_params_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9, 1)).setIndexNames((0, 'CISCOSB-EVENTS-MIB', 'rlAutoSmartPortIfIndex'), (1, 'CISCOSB-EVENTS-MIB', 'rlAutoSmartPortParamName'))
if mibBuilder.loadTexts:
rlAutoSmartPortParamsEntry.setStatus('current')
rl_auto_smart_port_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9, 1, 1), interface_index())
if mibBuilder.loadTexts:
rlAutoSmartPortIfIndex.setStatus('current')
rl_auto_smart_port_param_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9, 1, 2), smart_port_macro_parameter_name())
if mibBuilder.loadTexts:
rlAutoSmartPortParamName.setStatus('current')
rl_auto_smart_port_param_order = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9, 1, 3), smart_port_macro_parameter_order()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlAutoSmartPortParamOrder.setStatus('current')
rl_auto_smart_port_param_value = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 9, 1, 4), smart_port_macro_parameter_value())
if mibBuilder.loadTexts:
rlAutoSmartPortParamValue.setStatus('current')
rl_auto_smart_trunk_refresh_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 10))
if mibBuilder.loadTexts:
rlAutoSmartTrunkRefreshTable.setStatus('current')
rl_auto_smart_trunk_refresh_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 10, 1)).setIndexNames((0, 'CISCOSB-EVENTS-MIB', 'rlAutoSmartTrunkRefreshSmartPortType'), (0, 'CISCOSB-EVENTS-MIB', 'rlAutoSmartTrunkRefreshIfIndex'))
if mibBuilder.loadTexts:
rlAutoSmartTrunkRefreshEntry.setStatus('current')
rl_auto_smart_trunk_refresh_smart_port_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 10, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 11, 12, 13))).clone(namedValues=named_values(('default', 1), ('switch', 11), ('router', 12), ('ap', 13))))
if mibBuilder.loadTexts:
rlAutoSmartTrunkRefreshSmartPortType.setStatus('current')
rl_auto_smart_trunk_refresh_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 10, 1, 2), interface_index_or_zero())
if mibBuilder.loadTexts:
rlAutoSmartTrunkRefreshIfIndex.setStatus('current')
rl_auto_smart_trunk_refresh_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 10, 1, 3), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
rlAutoSmartTrunkRefreshRowStatus.setStatus('current')
rl_auto_smart_busy = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 150, 1, 11), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlAutoSmartBusy.setStatus('current')
mibBuilder.exportSymbols('CISCOSB-EVENTS-MIB', rlAutoSmartPortPort=rlAutoSmartPortPort, rlAutoSmartPortLastVoiceVlanStatus=rlAutoSmartPortLastVoiceVlanStatus, rlAutoSmartPortTypesRevertToDefaultMacro=rlAutoSmartPortTypesRevertToDefaultMacro, rlAutoSmartPortTypesBuiltinMacro=rlAutoSmartPortTypesBuiltinMacro, rlAutoSmartPortMacrosParamTable=rlAutoSmartPortMacrosParamTable, rlAutoSmartPortFailedCommandNumber=rlAutoSmartPortFailedCommandNumber, rlAutoSmartTrunkRefreshIfIndex=rlAutoSmartTrunkRefreshIfIndex, rlPortEvents=rlPortEvents, rlAutoSmartPortLearningProtocols=rlAutoSmartPortLearningProtocols, rlAutoSmartPortParamName=rlAutoSmartPortParamName, SmartPortMacroType=SmartPortMacroType, rlAutoSmartBusy=rlAutoSmartBusy, rlAutoSmartPortMacrosParamName=rlAutoSmartPortMacrosParamName, rlAutoSmartPortOperStatus=rlAutoSmartPortOperStatus, rlAutoSmartPortTypesTable=rlAutoSmartPortTypesTable, rlAutoSmartPortPortsEntry=rlAutoSmartPortPortsEntry, rlAutoSmartPortTypesEntry=rlAutoSmartPortTypesEntry, rlAutoSmartPortTypeStatus=rlAutoSmartPortTypeStatus, rlAutoSmartPortPortAcquiringType=rlAutoSmartPortPortAcquiringType, SmartPortMacroParameterValue=SmartPortMacroParameterValue, rlAutoSmartPortPortStatus=rlAutoSmartPortPortStatus, SmartPortType=SmartPortType, rlAutoSmartPortTypesRevertToDefaultParams=rlAutoSmartPortTypesRevertToDefaultParams, rlAutoSmartPortLastActivatedMacro=rlAutoSmartPortLastActivatedMacro, rlAutoSmartPortMacrosParamOrder=rlAutoSmartPortMacrosParamOrder, rlAutoSmartTrunkRefreshSmartPortType=rlAutoSmartTrunkRefreshSmartPortType, rlAutoSmartPortLearntPortType=rlAutoSmartPortLearntPortType, rlAutoSmartTrunkRefreshRowStatus=rlAutoSmartTrunkRefreshRowStatus, rlAutoSmartPortAdminStatus=rlAutoSmartPortAdminStatus, rlAutoSmartPortParamsEntry=rlAutoSmartPortParamsEntry, rlAutoSmartPortMacroType=rlAutoSmartPortMacroType, rlAutoSmartPortParamsTable=rlAutoSmartPortParamsTable, rlAutoSmartPortPortType=rlAutoSmartPortPortType, rlAutoSmartPortTypesType=rlAutoSmartPortTypesType, rlAutoSmartPortMacro=rlAutoSmartPortMacro, rlAutoSmartPortPersistency=rlAutoSmartPortPersistency, PYSNMP_MODULE_ID=rlEventsMib, rlAutoSmartTrunkRefreshTable=rlAutoSmartTrunkRefreshTable, rlAutoSmartPortLastVoiceVlanId=rlAutoSmartPortLastVoiceVlanId, rlAutoSmartPortPortsTable=rlAutoSmartPortPortsTable, rlAutoSmartPortParamOrder=rlAutoSmartPortParamOrder, rlEventsMib=rlEventsMib, rlAutoSmartPortIfIndex=rlAutoSmartPortIfIndex, SmartPortMacroParameterName=SmartPortMacroParameterName, rlAutoSmartPortParamValue=rlAutoSmartPortParamValue, rlAutoSmartTrunkRefreshEntry=rlAutoSmartTrunkRefreshEntry, SmartPortMacroParameterOrder=SmartPortMacroParameterOrder, rlAutoSmartPortMacrosParamEntry=rlAutoSmartPortMacrosParamEntry, rlAutoSmartPortMacrosParamValue=rlAutoSmartPortMacrosParamValue, rlAutoSmartPortSetLearntPortType=rlAutoSmartPortSetLearntPortType) |
# https://leetcode.com/problems/lru-cache/
class Node:
def __init__(self, key, value, nxt=None, prev=None):
self.key = key
self.value = value
self.next = nxt
self.prev = prev
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.map = dict()
# Setup doubly linked list
self.linked_list_head = Node(None, None)
self.linked_list_tail = Node(None, None, None, self.linked_list_head)
self.linked_list_head.next = self.linked_list_tail
def get(self, key: int) -> int:
if key not in self.map:
return -1
curNode = self.map[key]
# Remove from list
curNode.prev.next = curNode.next
curNode.next.prev = curNode.prev
# Add to front
curNode.next = self.linked_list_head.next
curNode.next.prev = curNode
self.linked_list_head.next = curNode
curNode.prev = self.linked_list_head
return curNode.value
def put(self, key: int, value: int) -> None:
if key in self.map:
self.map[key].value = value
self.get(key)
return
if len(self.map) >= self.capacity:
nodeToEvict = self.linked_list_tail.prev
# Remove the node from list
self.linked_list_tail.prev = nodeToEvict.prev
nodeToEvict.prev.next = self.linked_list_tail
# Remove from map
del self.map[nodeToEvict.key]
# Add to front
curNode = Node(key, value, self.linked_list_head.next, self.linked_list_head)
self.linked_list_head.next = curNode
curNode.next.prev = curNode
# Add to map
self.map[key] = curNode
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
| class Node:
def __init__(self, key, value, nxt=None, prev=None):
self.key = key
self.value = value
self.next = nxt
self.prev = prev
class Lrucache:
def __init__(self, capacity: int):
self.capacity = capacity
self.map = dict()
self.linked_list_head = node(None, None)
self.linked_list_tail = node(None, None, None, self.linked_list_head)
self.linked_list_head.next = self.linked_list_tail
def get(self, key: int) -> int:
if key not in self.map:
return -1
cur_node = self.map[key]
curNode.prev.next = curNode.next
curNode.next.prev = curNode.prev
curNode.next = self.linked_list_head.next
curNode.next.prev = curNode
self.linked_list_head.next = curNode
curNode.prev = self.linked_list_head
return curNode.value
def put(self, key: int, value: int) -> None:
if key in self.map:
self.map[key].value = value
self.get(key)
return
if len(self.map) >= self.capacity:
node_to_evict = self.linked_list_tail.prev
self.linked_list_tail.prev = nodeToEvict.prev
nodeToEvict.prev.next = self.linked_list_tail
del self.map[nodeToEvict.key]
cur_node = node(key, value, self.linked_list_head.next, self.linked_list_head)
self.linked_list_head.next = curNode
curNode.next.prev = curNode
self.map[key] = curNode |
#memocate.py: The Trivial Memory Allocator in Python
#Disclaimer: Use this at your own discretion. I am not responsible for anything that happens.
#Author: TD
#initialization
a = "a"
mode = input("(0) Intensive or (1) Safe: ")
#Storing string to memory until overflow.
#Concatenating Runtime: O(n)
if(mode):
print("Safe Mode O(n)")
while(1):
a = a + "a"
#Concatenating Runtime O(n^2)
else:
print("Intensive Mode O(n^2)")
while(1):
a = a + a
| a = 'a'
mode = input('(0) Intensive or (1) Safe: ')
if mode:
print('Safe Mode O(n)')
while 1:
a = a + 'a'
else:
print('Intensive Mode O(n^2)')
while 1:
a = a + a |
#
# @lc app=leetcode id=1275 lang=python3
#
# [1275] Find Winner on a Tic Tac Toe Game
#
# @lc code=start
class Solution:
def tictactoe(self, moves: list[list[int]]) -> str:
rows, cols, hill, dale, mark = [0, 0, 0], [0, 0, 0], 0, 0, 1
for i, j in moves:
rows[i] += mark
cols[j] += mark
hill += mark * (i == 2 - j)
dale += mark * (i == j)
if abs(rows[i]) == 3:
return "A" if rows[i] == 3 else "B"
elif abs(cols[j]) == 3:
return "A" if cols[j] == 3 else "B"
elif abs(hill) == 3:
return "A" if hill == 3 else "B"
elif abs(dale) == 3:
return "A" if dale == 3 else "B"
mark = -mark
return "Pending" if len(moves) < 9 else "Draw"
# @lc code=end
| class Solution:
def tictactoe(self, moves: list[list[int]]) -> str:
(rows, cols, hill, dale, mark) = ([0, 0, 0], [0, 0, 0], 0, 0, 1)
for (i, j) in moves:
rows[i] += mark
cols[j] += mark
hill += mark * (i == 2 - j)
dale += mark * (i == j)
if abs(rows[i]) == 3:
return 'A' if rows[i] == 3 else 'B'
elif abs(cols[j]) == 3:
return 'A' if cols[j] == 3 else 'B'
elif abs(hill) == 3:
return 'A' if hill == 3 else 'B'
elif abs(dale) == 3:
return 'A' if dale == 3 else 'B'
mark = -mark
return 'Pending' if len(moves) < 9 else 'Draw' |
'''
File: imports.py
Project: src
File Created: Sunday, 28th February 2021 3:10:35 am
Author: Sparsh Dutta (sparsh.dtt@gmail.com)
-----
Last Modified: Sunday, 28th February 2021 3:10:35 am
Modified By: Sparsh Dutta (sparsh.dtt@gmail.com>)
-----
Copyright 2021 Sparsh Dutta
'''
| """
File: imports.py
Project: src
File Created: Sunday, 28th February 2021 3:10:35 am
Author: Sparsh Dutta (sparsh.dtt@gmail.com)
-----
Last Modified: Sunday, 28th February 2021 3:10:35 am
Modified By: Sparsh Dutta (sparsh.dtt@gmail.com>)
-----
Copyright 2021 Sparsh Dutta
""" |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def geometric_mid(*args):
if args:
ans = 1
for item in args:
ans *= item
return pow(ans, 1/len(args))
else:
return None
if __name__ == "__main__":
print(geometric_mid())
print(geometric_mid(5, 4, 2, 8, 9))
print(geometric_mid(3, 7, 4, 9, 4, 5))
| def geometric_mid(*args):
if args:
ans = 1
for item in args:
ans *= item
return pow(ans, 1 / len(args))
else:
return None
if __name__ == '__main__':
print(geometric_mid())
print(geometric_mid(5, 4, 2, 8, 9))
print(geometric_mid(3, 7, 4, 9, 4, 5)) |
"""
Clothing is a class that represents pieces of clothing in a closet. It tracks the color, category, and clean/dirty state.
"""
class Clothing:
"""
>>> blue_shirt = Clothing("shirt", "blue")
>>> blue_shirt.category
'shirt'
>>> blue_shirt.color
'blue'
>>> blue_shirt.is_clean
True
>>> blue_shirt.wear()
>>> blue_shirt.is_clean
False
>>> blue_shirt.clean()
>>> blue_shirt.is_clean
True
"""
# Write an __init__ method
def __init__(self, category, color):
self.category = category
self.color = color
self.is_clean = True
# Write the wear() method
def wear(self):
self.is_clean = False
# Write the clean() method
def clean(self):
self.is_clean = True | """
Clothing is a class that represents pieces of clothing in a closet. It tracks the color, category, and clean/dirty state.
"""
class Clothing:
"""
>>> blue_shirt = Clothing("shirt", "blue")
>>> blue_shirt.category
'shirt'
>>> blue_shirt.color
'blue'
>>> blue_shirt.is_clean
True
>>> blue_shirt.wear()
>>> blue_shirt.is_clean
False
>>> blue_shirt.clean()
>>> blue_shirt.is_clean
True
"""
def __init__(self, category, color):
self.category = category
self.color = color
self.is_clean = True
def wear(self):
self.is_clean = False
def clean(self):
self.is_clean = True |
# Compute mean of combined data set: combined_mean
combined_mean = np.mean(np.concatenate((bd_1975, bd_2012)))
# Shift the samples
bd_1975_shifted = bd_1975 - np.mean(bd_1975) + combined_mean
bd_2012_shifted = bd_2012 - np.mean(bd_2012) + combined_mean
# Get bootstrap replicates of shifted data sets
bs_replicates_1975 = draw_bs_reps(bd_1975_shifted, np.mean, 10000)
bs_replicates_2012 = draw_bs_reps(bd_2012_shifted, np.mean, 10000)
# Compute replicates of difference of means: bs_diff_replicates
bs_diff_replicates = bs_replicates_2012 - bs_replicates_1975
# Compute the p-value: p
p = np.sum(bs_diff_replicates >= mean_diff) / len(bs_diff_replicates)
# Print p-value
print('p =', p)
| combined_mean = np.mean(np.concatenate((bd_1975, bd_2012)))
bd_1975_shifted = bd_1975 - np.mean(bd_1975) + combined_mean
bd_2012_shifted = bd_2012 - np.mean(bd_2012) + combined_mean
bs_replicates_1975 = draw_bs_reps(bd_1975_shifted, np.mean, 10000)
bs_replicates_2012 = draw_bs_reps(bd_2012_shifted, np.mean, 10000)
bs_diff_replicates = bs_replicates_2012 - bs_replicates_1975
p = np.sum(bs_diff_replicates >= mean_diff) / len(bs_diff_replicates)
print('p =', p) |
class Solution(object):
def convert_phone(self, phone):
phone = phone.strip().replace(' ', '').replace('(', '').replace(')', '').replace('-', '').replace('+', '')
if len(phone) == 10:
return "***-***-" + phone[-4:]
else:
return "+" + '*' * (len(phone) - 10) + "-***-***-" + phone[-4:]
def convert_email(self, email):
email = email.lower()
first_name, host = email.split('@')
return first_name[0] + '*****' + first_name[-1] + '@' + host
def maskPII(self, S):
"""
:type S: str
:rtype: str
"""
return self.convert_email(S) if '@' in S else self.convert_phone(S) | class Solution(object):
def convert_phone(self, phone):
phone = phone.strip().replace(' ', '').replace('(', '').replace(')', '').replace('-', '').replace('+', '')
if len(phone) == 10:
return '***-***-' + phone[-4:]
else:
return '+' + '*' * (len(phone) - 10) + '-***-***-' + phone[-4:]
def convert_email(self, email):
email = email.lower()
(first_name, host) = email.split('@')
return first_name[0] + '*****' + first_name[-1] + '@' + host
def mask_pii(self, S):
"""
:type S: str
:rtype: str
"""
return self.convert_email(S) if '@' in S else self.convert_phone(S) |
"""
Given only a reference to a specific node in a linked list, delete that node from a singly-linked list.
Example:
The code below should first construct a linked list (x -> y -> z) and then delete `y`
from the linked list by calling the function `delete_node`. It is your job to write the `delete_node` function.
"""
class LinkedListNode():
def __init__(self, value):
self.value = value
self.next = None
def delete_node(delete_this_node):
# Your code here
next_node = delete_this_node.next
# copy all of next node into the current node we are "deleting"
# start with the value
if next_node is not None:
delete_this_node.value = next_node.value
# skip over the next_node in our linked list
delete_this_node.next = next_node.next
else:
print("Sorry we cannot delete the last node using this technique")
x = LinkedListNode('X')
y = LinkedListNode('Y')
z = LinkedListNode('Z')
x.next = y
y.next = z
delete_node(y)
"""
Linked Lists Core Operations:
- access
- search
- insert
- delete
""" | """
Given only a reference to a specific node in a linked list, delete that node from a singly-linked list.
Example:
The code below should first construct a linked list (x -> y -> z) and then delete `y`
from the linked list by calling the function `delete_node`. It is your job to write the `delete_node` function.
"""
class Linkedlistnode:
def __init__(self, value):
self.value = value
self.next = None
def delete_node(delete_this_node):
next_node = delete_this_node.next
if next_node is not None:
delete_this_node.value = next_node.value
delete_this_node.next = next_node.next
else:
print('Sorry we cannot delete the last node using this technique')
x = linked_list_node('X')
y = linked_list_node('Y')
z = linked_list_node('Z')
x.next = y
y.next = z
delete_node(y)
' \nLinked Lists Core Operations:\n - access\n - search\n - insert\n - delete\n' |
__author__ = "Max Dippel, Michael Burkart and Matthias Urban"
__version__ = "0.0.1"
__license__ = "BSD"
CSConfig = dict()
# SchedulerStepLR
step_lr = dict()
step_lr['step_size'] = (1, 10)
step_lr['gamma'] = (0.001, 0.9)
CSConfig['step_lr'] = step_lr
# SchedulerExponentialLR
exponential_lr = dict()
exponential_lr['gamma'] = (0.8, 0.9999)
CSConfig['exponential_lr'] = exponential_lr
# SchedulerReduceLROnPlateau
reduce_on_plateau = dict()
reduce_on_plateau['factor'] = (0.05, 0.5)
reduce_on_plateau['patience'] = (3, 10)
CSConfig['reduce_on_plateau'] = reduce_on_plateau
# SchedulerCyclicLR
cyclic_lr = dict()
cyclic_lr['max_factor'] = (1.0, 2)
cyclic_lr['min_factor'] = (0.001, 1.0)
cyclic_lr['cycle_length'] = (3, 10)
CSConfig['cyclic_lr'] = cyclic_lr
# SchedulerCosineAnnealingWithRestartsLR
cosine_annealing_lr = dict()
cosine_annealing_lr['T_max'] = (1, 20)
cosine_annealing_lr['T_mult'] = (1.0, 2.0)
CSConfig['cosine_annealing_lr'] = cosine_annealing_lr
| __author__ = 'Max Dippel, Michael Burkart and Matthias Urban'
__version__ = '0.0.1'
__license__ = 'BSD'
cs_config = dict()
step_lr = dict()
step_lr['step_size'] = (1, 10)
step_lr['gamma'] = (0.001, 0.9)
CSConfig['step_lr'] = step_lr
exponential_lr = dict()
exponential_lr['gamma'] = (0.8, 0.9999)
CSConfig['exponential_lr'] = exponential_lr
reduce_on_plateau = dict()
reduce_on_plateau['factor'] = (0.05, 0.5)
reduce_on_plateau['patience'] = (3, 10)
CSConfig['reduce_on_plateau'] = reduce_on_plateau
cyclic_lr = dict()
cyclic_lr['max_factor'] = (1.0, 2)
cyclic_lr['min_factor'] = (0.001, 1.0)
cyclic_lr['cycle_length'] = (3, 10)
CSConfig['cyclic_lr'] = cyclic_lr
cosine_annealing_lr = dict()
cosine_annealing_lr['T_max'] = (1, 20)
cosine_annealing_lr['T_mult'] = (1.0, 2.0)
CSConfig['cosine_annealing_lr'] = cosine_annealing_lr |
# [8 kyu] Double Char
#
# Author: Hsins
# Date: 2019/11/28
def two_sort(array):
word = sorted(array)[0]
return "".join(c + '***' for c in word)[0:-3]
| def two_sort(array):
word = sorted(array)[0]
return ''.join((c + '***' for c in word))[0:-3] |
def func(x,y):
if(y == 0):
return 0
else:
print(x,y)
return x + func(x,y-1)
func(10,10)
| def func(x, y):
if y == 0:
return 0
else:
print(x, y)
return x + func(x, y - 1)
func(10, 10) |
"""
Factorial of a number
e.g. 4! = 4*3*2*1
"""
def factorial_of_number(num):
if num > 0:
return num * factorial_of_number(num - 1)
else:
return 1
if __name__ == "__main__":
print(factorial_of_number(5))
| """
Factorial of a number
e.g. 4! = 4*3*2*1
"""
def factorial_of_number(num):
if num > 0:
return num * factorial_of_number(num - 1)
else:
return 1
if __name__ == '__main__':
print(factorial_of_number(5)) |
class Person(Thing):
"""A person (alive, dead, undead, or fictional)."""
address: Optional[str] = None
affiliations: Optional[Array["Organization"]] = None
emails: Optional[Array[str]] = None
familyNames: Optional[Array[str]] = None
funders: Optional[Array[Union["Organization", "Person"]]] = None
givenNames: Optional[Array[str]] = None
honorificPrefix: Optional[str] = None
honorificSuffix: Optional[str] = None
jobTitle: Optional[str] = None
memberOf: Optional[Array["Organization"]] = None
telephoneNumbers: Optional[Array[str]] = None
def __init__(
self,
address: Optional[str] = None,
affiliations: Optional[Array["Organization"]] = None,
alternateNames: Optional[Array[str]] = None,
description: Optional[Union[str, Array["Node"]]] = None,
emails: Optional[Array[str]] = None,
familyNames: Optional[Array[str]] = None,
funders: Optional[Array[Union["Organization", "Person"]]] = None,
givenNames: Optional[Array[str]] = None,
honorificPrefix: Optional[str] = None,
honorificSuffix: Optional[str] = None,
id: Optional[str] = None,
jobTitle: Optional[str] = None,
memberOf: Optional[Array["Organization"]] = None,
meta: Optional[Dict[str, Any]] = None,
name: Optional[str] = None,
telephoneNumbers: Optional[Array[str]] = None,
url: Optional[str] = None
) -> None:
super().__init__(
alternateNames=alternateNames,
description=description,
id=id,
meta=meta,
name=name,
url=url
)
if address is not None:
self.address = address
if affiliations is not None:
self.affiliations = affiliations
if emails is not None:
self.emails = emails
if familyNames is not None:
self.familyNames = familyNames
if funders is not None:
self.funders = funders
if givenNames is not None:
self.givenNames = givenNames
if honorificPrefix is not None:
self.honorificPrefix = honorificPrefix
if honorificSuffix is not None:
self.honorificSuffix = honorificSuffix
if jobTitle is not None:
self.jobTitle = jobTitle
if memberOf is not None:
self.memberOf = memberOf
if telephoneNumbers is not None:
self.telephoneNumbers = telephoneNumbers
| class Person(Thing):
"""A person (alive, dead, undead, or fictional)."""
address: Optional[str] = None
affiliations: Optional[Array['Organization']] = None
emails: Optional[Array[str]] = None
family_names: Optional[Array[str]] = None
funders: Optional[Array[Union['Organization', 'Person']]] = None
given_names: Optional[Array[str]] = None
honorific_prefix: Optional[str] = None
honorific_suffix: Optional[str] = None
job_title: Optional[str] = None
member_of: Optional[Array['Organization']] = None
telephone_numbers: Optional[Array[str]] = None
def __init__(self, address: Optional[str]=None, affiliations: Optional[Array['Organization']]=None, alternateNames: Optional[Array[str]]=None, description: Optional[Union[str, Array['Node']]]=None, emails: Optional[Array[str]]=None, familyNames: Optional[Array[str]]=None, funders: Optional[Array[Union['Organization', 'Person']]]=None, givenNames: Optional[Array[str]]=None, honorificPrefix: Optional[str]=None, honorificSuffix: Optional[str]=None, id: Optional[str]=None, jobTitle: Optional[str]=None, memberOf: Optional[Array['Organization']]=None, meta: Optional[Dict[str, Any]]=None, name: Optional[str]=None, telephoneNumbers: Optional[Array[str]]=None, url: Optional[str]=None) -> None:
super().__init__(alternateNames=alternateNames, description=description, id=id, meta=meta, name=name, url=url)
if address is not None:
self.address = address
if affiliations is not None:
self.affiliations = affiliations
if emails is not None:
self.emails = emails
if familyNames is not None:
self.familyNames = familyNames
if funders is not None:
self.funders = funders
if givenNames is not None:
self.givenNames = givenNames
if honorificPrefix is not None:
self.honorificPrefix = honorificPrefix
if honorificSuffix is not None:
self.honorificSuffix = honorificSuffix
if jobTitle is not None:
self.jobTitle = jobTitle
if memberOf is not None:
self.memberOf = memberOf
if telephoneNumbers is not None:
self.telephoneNumbers = telephoneNumbers |
class Solution:
"""
@param nums: a list of integers
@param lower: a integer
@param upper: a integer
@return: return a integer
"""
def countRangeSum(self, nums, lower, upper):
prefixSumCnt = {0: 1}
presum = 0
result = 0
for num in nums:
presum += num
for j in range(lower, upper + 1):
if presum - j in prefixSumCnt:
result += prefixSumCnt[presum - j]
prefixSumCnt[presum] = prefixSumCnt.get(presum, 0) + 1
return result
| class Solution:
"""
@param nums: a list of integers
@param lower: a integer
@param upper: a integer
@return: return a integer
"""
def count_range_sum(self, nums, lower, upper):
prefix_sum_cnt = {0: 1}
presum = 0
result = 0
for num in nums:
presum += num
for j in range(lower, upper + 1):
if presum - j in prefixSumCnt:
result += prefixSumCnt[presum - j]
prefixSumCnt[presum] = prefixSumCnt.get(presum, 0) + 1
return result |
class Params:
# the most important parameter
random_seed = 224422
# system params
verbose = True
device = None # to be set on runtime
num_workers = 2
# dataset params
datasets_dir = 'datasets'
dataset = 'churches'
train_suffix = 'train'
valid_suffix = 'val'
flip = True
normalize = True
# images params
image_size = (512, 1024)
input_left = True
in_channels = 3
out_channels = 3
# experimenter params
runs_dir = 'runs'
save_checkpoints = True
load_checkpoint = None
checkpoints_subdir = 'checkpoints'
checkpoints_template = 'pix2pix{}.pt'
checkpoints_freq = 10
examples_subdir = 'examples'
metadata_file = 'metadata.json'
metrics_file = 'metrics.json'
examples_ids = [6, 9, 11, 16, 45]
# generator params
generator_channels = 64
generator_layers = 4
generator_kernel = 5
generator_dropout = 0.5
generator_norm = 'instance'
# discriminator params
adversarial = True
discriminator_channels = 64
discriminator_layers = 3
discriminator_norm = 'instance'
# train params
batch_size = 4
num_epochs = 50
lr = 3e-4
loss = 'L2'
loss_lambda = 100.0
def set_params():
return Params()
| class Params:
random_seed = 224422
verbose = True
device = None
num_workers = 2
datasets_dir = 'datasets'
dataset = 'churches'
train_suffix = 'train'
valid_suffix = 'val'
flip = True
normalize = True
image_size = (512, 1024)
input_left = True
in_channels = 3
out_channels = 3
runs_dir = 'runs'
save_checkpoints = True
load_checkpoint = None
checkpoints_subdir = 'checkpoints'
checkpoints_template = 'pix2pix{}.pt'
checkpoints_freq = 10
examples_subdir = 'examples'
metadata_file = 'metadata.json'
metrics_file = 'metrics.json'
examples_ids = [6, 9, 11, 16, 45]
generator_channels = 64
generator_layers = 4
generator_kernel = 5
generator_dropout = 0.5
generator_norm = 'instance'
adversarial = True
discriminator_channels = 64
discriminator_layers = 3
discriminator_norm = 'instance'
batch_size = 4
num_epochs = 50
lr = 0.0003
loss = 'L2'
loss_lambda = 100.0
def set_params():
return params() |
#
# Example file for working with functions
#
# define a basic function
def func1():
print ("I am a function")
# function that takes arguments
def func2(arg1, arg2):
print (arg1, " ", arg2)
# function that returns a value
def cube(x):
return x*x*x
# function with default value for an argument
def power(num, x=1):
result = 1;
for i in range(x):
result = result * num
return result
#function with variable number of arguments
def multi_add(*args):
result = 0;
for x in args:
result = result + x
return result
#func1()
#print (func1())
#print (func1)
#func2(10,20)
#print (func2(10,20))
#print (func2)
#print (cube(3))
#print (power(2))
#print (power(2,3))
print (power(x=10, num=10))
#print (multi_add(4,5,10,4))
| def func1():
print('I am a function')
def func2(arg1, arg2):
print(arg1, ' ', arg2)
def cube(x):
return x * x * x
def power(num, x=1):
result = 1
for i in range(x):
result = result * num
return result
def multi_add(*args):
result = 0
for x in args:
result = result + x
return result
print(power(x=10, num=10)) |
name = input("Enter lenght of name: ")
if len(name) < 3:
print("name must be at least 3 characters")
elif len(name) > 50:
print("name can be a maximum of 50 characters")
else:
print("name looks good!")
| name = input('Enter lenght of name: ')
if len(name) < 3:
print('name must be at least 3 characters')
elif len(name) > 50:
print('name can be a maximum of 50 characters')
else:
print('name looks good!') |
# File: Lists_inside_Dictionary_in_Python.py
# Description: Calculating the scores of sports team by using Lists inside Dictionary
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 Valentyn N Sichkar
# github.com/sichkar-valentyn
# Reference to:
# [1] Valentyn N Sichkar. Lists inside Dictionary in Python // GitHub platform [Electronic resource]. URL: https://github.com/sichkar-valentyn/Lists_inside_Dictionary_in_Python (date of access: XX.XX.XXXX)
# Implementing the task
# Lists inside dictionary
# Calculating the scores of sports team
n = int(input()) # number of games
string = ''
d = {}
# Format of input is following:
# Team;score;Team;score
for i in range(n):
string = input().split(';')
# If there is no yet teams in the dictionary
if string[0] not in d:
d[string[0]] = [1, 0, 0, 0, 0]
else:
d[string[0]][0] += 1
if string[2] not in d:
d[string[2]] = [1, 0, 0, 0, 0]
else:
d[string[2]][0] += 1
# Calculating data
if int(string[1]) > int(string[3]): # Who wins
d[string[0]][1] += 1
d[string[0]][4] += 3
d[string[2]][3] += 1
elif int(string[1]) == int(string[3]): # If draw
d[string[0]][2] += 1
d[string[2]][2] += 1
d[string[0]][4] += 1
d[string[2]][4] += 1
elif int(string[1]) < int(string[3]): # Who loses
d[string[2]][1] += 1
d[string[2]][4] += 3
d[string[0]][3] += 1
# Showing the table with results
# Format of output is following:
# Team: number_of_games number_of_wins number_of_draw_games number_of_lost_games score_of_win_games
for x, y in d.items():
print(x, end=':')
for z in y:
print(z, end=' ')
print()
| n = int(input())
string = ''
d = {}
for i in range(n):
string = input().split(';')
if string[0] not in d:
d[string[0]] = [1, 0, 0, 0, 0]
else:
d[string[0]][0] += 1
if string[2] not in d:
d[string[2]] = [1, 0, 0, 0, 0]
else:
d[string[2]][0] += 1
if int(string[1]) > int(string[3]):
d[string[0]][1] += 1
d[string[0]][4] += 3
d[string[2]][3] += 1
elif int(string[1]) == int(string[3]):
d[string[0]][2] += 1
d[string[2]][2] += 1
d[string[0]][4] += 1
d[string[2]][4] += 1
elif int(string[1]) < int(string[3]):
d[string[2]][1] += 1
d[string[2]][4] += 3
d[string[0]][3] += 1
for (x, y) in d.items():
print(x, end=':')
for z in y:
print(z, end=' ')
print() |
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
def filter_iter(list, pred):
filtered = []
for i in list:
if pred(i):
filtered.append(i)
return filtered
def filter_beautiful(list, pred):
return [x for x in list if pred(x)]
def even(x):
return x % 2 == 0
print(filter_iter(my_list, even))
print(filter_beautiful(my_list, even)) | my_list = [1, 2, 3, 4, 5, 6, 7, 8]
def filter_iter(list, pred):
filtered = []
for i in list:
if pred(i):
filtered.append(i)
return filtered
def filter_beautiful(list, pred):
return [x for x in list if pred(x)]
def even(x):
return x % 2 == 0
print(filter_iter(my_list, even))
print(filter_beautiful(my_list, even)) |
"""
986. Interval List Intersections
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].)
Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Reminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists.
"""
# SWEEP line method
# Runtime: 172 ms, faster than 22.99% of Python3 online submissions for Interval List Intersections.
# Memory Usage: 14 MB, less than 6.06% of Python3 online submissions for Interval List Intersections.
class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
indices = []
for start, end in A:
indices.append([start, 1])
indices.append([end, -1])
for start, end in B:
indices.append([start, 1])
indices.append([end, -1])
indices = sorted(indices, key=lambda x:(x[0], -x[1]))
start = -1
res = []
num_interval = 0
for index, is_start in indices:
if is_start == 1:
start = max(index, start)
num_interval += 1
else:
if start != -1 and num_interval > 1:
res.append([start, index])
start = -1
num_interval -= 1
return res | """
986. Interval List Intersections
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].)
Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Reminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists.
"""
class Solution:
def interval_intersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
indices = []
for (start, end) in A:
indices.append([start, 1])
indices.append([end, -1])
for (start, end) in B:
indices.append([start, 1])
indices.append([end, -1])
indices = sorted(indices, key=lambda x: (x[0], -x[1]))
start = -1
res = []
num_interval = 0
for (index, is_start) in indices:
if is_start == 1:
start = max(index, start)
num_interval += 1
else:
if start != -1 and num_interval > 1:
res.append([start, index])
start = -1
num_interval -= 1
return res |
title=xpath("div[@class=BlogTitle]")
urls="http://my\\.oschina\\.net/flashsword/blog/\\d+"
result={"title":title,"urls":urls}
| title = xpath('div[@class=BlogTitle]')
urls = 'http://my\\.oschina\\.net/flashsword/blog/\\d+'
result = {'title': title, 'urls': urls} |
print("nihao,shijie")
print("lalalalal")
print("ninniiiinnij")
| print('nihao,shijie')
print('lalalalal')
print('ninniiiinnij') |
# -*- coding: utf-8 -*-
"""Top-level package for condastats."""
__author__ = """Sophia Man Yang"""
__version__ = '0.1.0'
| """Top-level package for condastats."""
__author__ = 'Sophia Man Yang'
__version__ = '0.1.0' |
for _ in range(int(input())):
n=int(input())
nums=list(map(int, input().split()))
ini=10**5
for i in range(n):
if ini>nums[i]:
ini=nums[i]
res=i
print(res+1)
| for _ in range(int(input())):
n = int(input())
nums = list(map(int, input().split()))
ini = 10 ** 5
for i in range(n):
if ini > nums[i]:
ini = nums[i]
res = i
print(res + 1) |
#
# Copyright (C) 2018 SecurityCentral Contributors see LICENSE for license
#
'''
This base platform module exports platform dependant constants.
'''
class SecurityCentralPlatformBaseConstants(object):
pass
| """
This base platform module exports platform dependant constants.
"""
class Securitycentralplatformbaseconstants(object):
pass |
expected_output = {
'Et0/2:12': {
'type': 'BD_PORT',
'is_path_list': False,
'port': 'Et0/2:12'
},
'[IR]20012:2.2.2.2': {
'type':'VXLAN_REP',
'is_path_list': True,
'path_list': {
'id': 1191,
'path_count': 1,
'type': 'VXLAN_REP',
'description': '[IR]20012:2.2.2.2'
}
},
'[IR]20012:3.3.3.2': {
'type':'VXLAN_REP',
'is_path_list': True,
'path_list': {
'id': 1184,
'path_count': 1,
'type': 'VXLAN_REP',
'description': '[IR]20012:3.3.3.2'
}
}
} | expected_output = {'Et0/2:12': {'type': 'BD_PORT', 'is_path_list': False, 'port': 'Et0/2:12'}, '[IR]20012:2.2.2.2': {'type': 'VXLAN_REP', 'is_path_list': True, 'path_list': {'id': 1191, 'path_count': 1, 'type': 'VXLAN_REP', 'description': '[IR]20012:2.2.2.2'}}, '[IR]20012:3.3.3.2': {'type': 'VXLAN_REP', 'is_path_list': True, 'path_list': {'id': 1184, 'path_count': 1, 'type': 'VXLAN_REP', 'description': '[IR]20012:3.3.3.2'}}} |
#!/usr/bin/env python
# -*- coding: utf-8; -*-
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
class Timeseries:
def __init__(self, col_name, df, date_range=None, min=None, max=None):
self.col_name = col_name
self.df = df
self.date_range = date_range
self.min = min
self.max = max
def plot(self, **kwargs):
# this could be improved :)
pass
| class Timeseries:
def __init__(self, col_name, df, date_range=None, min=None, max=None):
self.col_name = col_name
self.df = df
self.date_range = date_range
self.min = min
self.max = max
def plot(self, **kwargs):
pass |
nums = input('Please enter 5 numbers, separated by commas:\n')
nums1 = nums.split(',')
#print('You entered ' + nums1[0] + ', ' + nums1[1] + ', ' + nums1[2] + ', ' + nums1[3] + ', ' + nums1[4] + ', ' )
print('You entered ' + nums1[0] + ', ' + nums1[1] + ', ' + nums1[2] + ', ' + nums1[3] + ', ' + nums1[4] +'.')
nums1[0] = int(nums1[0])
nums1[1] = int(nums1[1])
nums1[2] = int(nums1[2])
nums1[3] = int(nums1[3])
nums1[4] = int(nums1[4])
total = (nums1[0] + nums1[1] + nums1[2] + nums1[3] + nums1[4])
total = str(total)
print('The sum is: ' + total) | nums = input('Please enter 5 numbers, separated by commas:\n')
nums1 = nums.split(',')
print('You entered ' + nums1[0] + ', ' + nums1[1] + ', ' + nums1[2] + ', ' + nums1[3] + ', ' + nums1[4] + '.')
nums1[0] = int(nums1[0])
nums1[1] = int(nums1[1])
nums1[2] = int(nums1[2])
nums1[3] = int(nums1[3])
nums1[4] = int(nums1[4])
total = nums1[0] + nums1[1] + nums1[2] + nums1[3] + nums1[4]
total = str(total)
print('The sum is: ' + total) |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class VmwareTagActions(object):
# vSphere Automation API (6.5)
# API Reference: https://code.vmware.com/web/dp/explorer-apis?id=191
def __init__(self, session, url_base):
self.session = session
self.url_base = url_base
############################################################################
# Request Actions
def make_url(self, endpoint):
return self.url_base + endpoint
def get(self, endpoint):
url = self.make_url(endpoint)
response = self.session.get(url)
response.raise_for_status()
return response.json()
def post(self, endpoint, payload=None):
url = self.make_url(endpoint)
response = self.session.post(url, json=payload)
response.raise_for_status()
if response.text:
return response.json()
return None
def delete(self, endpoint, payload=None):
url = self.make_url(endpoint)
response = self.session.delete(url, json=payload)
response.raise_for_status()
if response.text:
return response.json()
return None
############################################################################
# Category Functions
def category_list(self):
response = self.get("/rest/com/vmware/cis/tagging/category")
return response['value']
def category_get(self, category_id):
response = self.get("/rest/com/vmware/cis/tagging/category/id:{}".format(category_id))
return response['value']
def category_delete(self, category_id):
response = self.delete("/rest/com/vmware/cis/tagging/category/id:{}".format(category_id))
return response
def category_find_by_name(self, name):
category_id_list = self.category_list()
for category_id in category_id_list:
category = self.category_get(category_id)
if category["name"] == name:
return category
return None
def category_create_spec(self):
return {"name": "",
"description": "",
"cardinality": "SINGLE", # "SINGLE", "MULTIPLE"
"associable_types": ["VirtualMachine"]} # One or more VMWARE_OBJECT_TYPES
def category_create(self, name, description=None, cardinality=None,
associable_types=None):
create_spec = self.category_create_spec()
create_spec['name'] = name
if description:
create_spec['description'] = description
if cardinality:
create_spec['cardinality'] = cardinality
if associable_types is not None:
create_spec['associable_types'] = associable_types
response = self.post("/rest/com/vmware/cis/tagging/category",
payload={'create_spec': create_spec})
return response['value']
def category_get_or_create(self, name, description=None, cardinality=None,
associable_types=None):
category = self.category_find_by_name(name)
if not category:
# on success this returns the new category's id
category_id = self.category_create(name, description, cardinality, associable_types)
category = self.category_get(category_id)
return category
############################################################################
# Tag Functions
def tag_list(self, category_id=None):
# Return all tags from the given category, or all tags from all categories
if category_id:
response = self.post("/rest/com/vmware/cis/tagging/tag/id:{}?~action="
"list-tags-for-category".format(category_id))
else:
response = self.get("/rest/com/vmware/cis/tagging/tag")
return response["value"]
def tag_get(self, tag_id):
response = self.get("/rest/com/vmware/cis/tagging/tag/id:{}".format(tag_id))
return response['value']
def tag_delete(self, tag_id):
response = self.delete("/rest/com/vmware/cis/tagging/tag/id:{}".format(tag_id))
return response
# If a category ID is not given then this will return the first tag it finds with the given name
def tag_find_by_name(self, name, category_id=None):
tag_id_list = self.tag_list(category_id)
for tag_id in tag_id_list:
tag = self.tag_get(tag_id)
if tag['name'] == name:
return tag
return None
def tag_create_spec(self):
return {"name": "",
"description": "",
"category_id": ""}
def tag_create(self, name, category_id, description=None):
create_spec = self.tag_create_spec()
create_spec["name"] = name
create_spec["category_id"] = category_id
if description:
create_spec["description"] = description
response = self.post("/rest/com/vmware/cis/tagging/tag",
payload={"create_spec": create_spec})
return response["value"]
# This does not create a new category, it will fail if the given category ID doesn't exist
def tag_get_or_create(self, name, category_id, description=None):
tag = self.tag_find_by_name(name, category_id)
if not tag:
# on success this returns the new tag's id
created_tag_id = self.tag_create(name, category_id, description)
tag = self.tag_get(created_tag_id)
return tag
############################################################################
# Tag Association Functions
def tag_association_endpoint(self, action, tag_id=None):
if tag_id:
return "/rest/com/vmware/cis/tagging/tag-association/id:{}?~action={}".format(tag_id,
action)
else:
return "/rest/com/vmware/cis/tagging/tag-association?~action={}".format(action)
def tag_association_attach(self, tag_id, obj_type, obj_id):
return self.post(self.tag_association_endpoint("attach", tag_id),
payload={"object_id": {"id": obj_id,
"type": obj_type}})
def tag_association_attach_multiple(self, tag_ids, obj_type, obj_id):
return self.post(self.tag_association_endpoint("attach-multiple-tags-to-object"),
payload={"tag_ids": tag_ids,
"object_id": {"id": obj_id,
"type": obj_type}})
def tag_association_detach(self, tag_id, obj_type, obj_id):
return self.post(self.tag_association_endpoint("detach", tag_id),
payload={"object_id": {"id": obj_id,
"type": obj_type}})
def tag_association_list_attached_tags(self, obj_type, obj_id):
response = self.post(self.tag_association_endpoint("list-attached-tags"),
payload={"object_id": {"id": obj_id,
"type": obj_type}})
return response['value']
def tag_association_list_attached_objects(self, tag_id):
response = self.post(self.tag_association_endpoint("list-attached-objects",
tag_id))
return response['value']
def tag_association_detach_category(self, category_id, obj_type, obj_id):
# get all tags for this object
tag_id_list = self.tag_association_list_attached_tags(obj_type, obj_id)
# if the tag's category matches category_id then detach the tag
results = []
for tag_id in tag_id_list:
tag = self.tag_get(tag_id)
if tag['category_id'] == category_id:
self.tag_association_detach(tag_id, obj_type, obj_id)
results.append(tag)
return results
def tag_association_replace(self, tag_id, obj_type, obj_id):
# remove all tags
tag = self.tag_get(tag_id)
self.tag_association_detach_category(tag['category_id'], obj_type, obj_id)
# attach the provided tag in this category to the object
return self.tag_association_attach(tag_id, obj_type, obj_id)
| class Vmwaretagactions(object):
def __init__(self, session, url_base):
self.session = session
self.url_base = url_base
def make_url(self, endpoint):
return self.url_base + endpoint
def get(self, endpoint):
url = self.make_url(endpoint)
response = self.session.get(url)
response.raise_for_status()
return response.json()
def post(self, endpoint, payload=None):
url = self.make_url(endpoint)
response = self.session.post(url, json=payload)
response.raise_for_status()
if response.text:
return response.json()
return None
def delete(self, endpoint, payload=None):
url = self.make_url(endpoint)
response = self.session.delete(url, json=payload)
response.raise_for_status()
if response.text:
return response.json()
return None
def category_list(self):
response = self.get('/rest/com/vmware/cis/tagging/category')
return response['value']
def category_get(self, category_id):
response = self.get('/rest/com/vmware/cis/tagging/category/id:{}'.format(category_id))
return response['value']
def category_delete(self, category_id):
response = self.delete('/rest/com/vmware/cis/tagging/category/id:{}'.format(category_id))
return response
def category_find_by_name(self, name):
category_id_list = self.category_list()
for category_id in category_id_list:
category = self.category_get(category_id)
if category['name'] == name:
return category
return None
def category_create_spec(self):
return {'name': '', 'description': '', 'cardinality': 'SINGLE', 'associable_types': ['VirtualMachine']}
def category_create(self, name, description=None, cardinality=None, associable_types=None):
create_spec = self.category_create_spec()
create_spec['name'] = name
if description:
create_spec['description'] = description
if cardinality:
create_spec['cardinality'] = cardinality
if associable_types is not None:
create_spec['associable_types'] = associable_types
response = self.post('/rest/com/vmware/cis/tagging/category', payload={'create_spec': create_spec})
return response['value']
def category_get_or_create(self, name, description=None, cardinality=None, associable_types=None):
category = self.category_find_by_name(name)
if not category:
category_id = self.category_create(name, description, cardinality, associable_types)
category = self.category_get(category_id)
return category
def tag_list(self, category_id=None):
if category_id:
response = self.post('/rest/com/vmware/cis/tagging/tag/id:{}?~action=list-tags-for-category'.format(category_id))
else:
response = self.get('/rest/com/vmware/cis/tagging/tag')
return response['value']
def tag_get(self, tag_id):
response = self.get('/rest/com/vmware/cis/tagging/tag/id:{}'.format(tag_id))
return response['value']
def tag_delete(self, tag_id):
response = self.delete('/rest/com/vmware/cis/tagging/tag/id:{}'.format(tag_id))
return response
def tag_find_by_name(self, name, category_id=None):
tag_id_list = self.tag_list(category_id)
for tag_id in tag_id_list:
tag = self.tag_get(tag_id)
if tag['name'] == name:
return tag
return None
def tag_create_spec(self):
return {'name': '', 'description': '', 'category_id': ''}
def tag_create(self, name, category_id, description=None):
create_spec = self.tag_create_spec()
create_spec['name'] = name
create_spec['category_id'] = category_id
if description:
create_spec['description'] = description
response = self.post('/rest/com/vmware/cis/tagging/tag', payload={'create_spec': create_spec})
return response['value']
def tag_get_or_create(self, name, category_id, description=None):
tag = self.tag_find_by_name(name, category_id)
if not tag:
created_tag_id = self.tag_create(name, category_id, description)
tag = self.tag_get(created_tag_id)
return tag
def tag_association_endpoint(self, action, tag_id=None):
if tag_id:
return '/rest/com/vmware/cis/tagging/tag-association/id:{}?~action={}'.format(tag_id, action)
else:
return '/rest/com/vmware/cis/tagging/tag-association?~action={}'.format(action)
def tag_association_attach(self, tag_id, obj_type, obj_id):
return self.post(self.tag_association_endpoint('attach', tag_id), payload={'object_id': {'id': obj_id, 'type': obj_type}})
def tag_association_attach_multiple(self, tag_ids, obj_type, obj_id):
return self.post(self.tag_association_endpoint('attach-multiple-tags-to-object'), payload={'tag_ids': tag_ids, 'object_id': {'id': obj_id, 'type': obj_type}})
def tag_association_detach(self, tag_id, obj_type, obj_id):
return self.post(self.tag_association_endpoint('detach', tag_id), payload={'object_id': {'id': obj_id, 'type': obj_type}})
def tag_association_list_attached_tags(self, obj_type, obj_id):
response = self.post(self.tag_association_endpoint('list-attached-tags'), payload={'object_id': {'id': obj_id, 'type': obj_type}})
return response['value']
def tag_association_list_attached_objects(self, tag_id):
response = self.post(self.tag_association_endpoint('list-attached-objects', tag_id))
return response['value']
def tag_association_detach_category(self, category_id, obj_type, obj_id):
tag_id_list = self.tag_association_list_attached_tags(obj_type, obj_id)
results = []
for tag_id in tag_id_list:
tag = self.tag_get(tag_id)
if tag['category_id'] == category_id:
self.tag_association_detach(tag_id, obj_type, obj_id)
results.append(tag)
return results
def tag_association_replace(self, tag_id, obj_type, obj_id):
tag = self.tag_get(tag_id)
self.tag_association_detach_category(tag['category_id'], obj_type, obj_id)
return self.tag_association_attach(tag_id, obj_type, obj_id) |
class Solution:
def countBits(self, n: int) -> list[int]:
res = []
for i in range(n + 1):
res.append(bin(i).count("1"))
return res
class Solution:
def countBits(self, n: int) -> list[int]:
res = [0] * (n + 1)
for x in range(1, n + 1):
res[x] = res[x & (x - 1)] + 1
return res
| class Solution:
def count_bits(self, n: int) -> list[int]:
res = []
for i in range(n + 1):
res.append(bin(i).count('1'))
return res
class Solution:
def count_bits(self, n: int) -> list[int]:
res = [0] * (n + 1)
for x in range(1, n + 1):
res[x] = res[x & x - 1] + 1
return res |
R1_info = {
'device_type': 'cisco_ios',
'ip': '192.168.1.1',
'username': 'user',
'password': 'pass',
}
R2_info = {
'device_type': 'cisco_ios',
'ip': '192.168.1.2',
'username': 'user',
'password': 'pass',
}
R3_info = {
'device_type': 'cisco_ios',
'ip': '192.168.1.3',
'username': 'user',
'password': 'pass',
}
R4_info = {
'device_type': 'cisco_ios',
'ip': '192.168.1.4',
'username': 'user',
'password': 'pass',
}
R5_info = {
'device_type': 'cisco_ios',
'ip': '192.168.1.5',
'username': 'user',
'password': 'pass',
}
R1_connections = {
'2': 's2/0',
'3': 's2/1',
'4': 's2/2',
}
R2_connections = {
'1': 's2/0',
'3': 'e0/0',
'5': 's3/0',
}
R3_connections = {
'1': 's2/1',
'2': 'e0/0',
'4': 'e0/1',
'5': 's3/1',
}
R4_connections = {
'1': 's2/2',
'3': 'e0/1',
'5': 's3/2',
}
R5_connections = {
'2': 's3/0',
'3': 's3/1',
'4': 's3/2',
}
R1 = (R1_info, R1_connections)
R2 = (R2_info, R2_connections)
R3 = (R3_info, R3_connections)
R4 = (R4_info, R4_connections)
R5 = (R5_info, R5_connections) | r1_info = {'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': 'user', 'password': 'pass'}
r2_info = {'device_type': 'cisco_ios', 'ip': '192.168.1.2', 'username': 'user', 'password': 'pass'}
r3_info = {'device_type': 'cisco_ios', 'ip': '192.168.1.3', 'username': 'user', 'password': 'pass'}
r4_info = {'device_type': 'cisco_ios', 'ip': '192.168.1.4', 'username': 'user', 'password': 'pass'}
r5_info = {'device_type': 'cisco_ios', 'ip': '192.168.1.5', 'username': 'user', 'password': 'pass'}
r1_connections = {'2': 's2/0', '3': 's2/1', '4': 's2/2'}
r2_connections = {'1': 's2/0', '3': 'e0/0', '5': 's3/0'}
r3_connections = {'1': 's2/1', '2': 'e0/0', '4': 'e0/1', '5': 's3/1'}
r4_connections = {'1': 's2/2', '3': 'e0/1', '5': 's3/2'}
r5_connections = {'2': 's3/0', '3': 's3/1', '4': 's3/2'}
r1 = (R1_info, R1_connections)
r2 = (R2_info, R2_connections)
r3 = (R3_info, R3_connections)
r4 = (R4_info, R4_connections)
r5 = (R5_info, R5_connections) |
# -*- coding: utf-8 -*-
"""
webelementspy.jsscripts
~~~~~~~~~~~~
This file contain JS scripts to be injected to webdriver
:copyright: (c) 2019 by Yasser.
:license: MIT, see LICENSE for more details.
"""
__all__ = ['js_init', 'js_listner_capture', 'js_raw_html']
js_init = {}
js_init['js_init_init_check'] = r'''
if(document.pyspy_html_elem) return;
'''
js_init['js_init_html_elem'] = r'''
document.pyspy_html_elem = function(name) {
if (document.contentType == 'application/xhtml+xml') {
return 'x:' + name
} else {
return name
}
}
'''
js_init['js_init_xp_attr_val'] = r'''
document.pyspy_xp_attr_val = function(value) {
if (value.indexOf("'") < 0) {
return "'" + value + "'"
} else if (value.indexOf('"') < 0) {
return '"' + value + '"'
} else {
let result = 'concat('
let part = ''
let didReachEndOfValue = false
while (!didReachEndOfValue) {
let apos = value.indexOf("'")
let quot = value.indexOf('"')
if (apos < 0) {
result += "'" + value + "'"
didReachEndOfValue = true
break
} else if (quot < 0) {
result += '"' + value + '"'
didReachEndOfValue = true
break
} else if (quot < apos) {
part = value.substring(0, apos)
result += "'" + part + "'"
value = value.substring(part.length)
} else {
part = value.substring(0, quot)
result += '"' + part + '"'
value = value.substring(part.length)
}
result += ','
}
result += ')'
return result
}
}
'''
js_init['js_init_find_elem'] = r'''
document.pyspy_find_elem = function(loc) {
try {
const locator = parse_locator(loc, true)
return document.pyspy_find_elem({ [locator.type]: locator.string }, document)
} catch (error) {
return null
}
}
'''
js_init['js_init_xp_precise'] = r'''
document.pyspy_xp_precise = function(xpath, e) {
if (document.pyspy_find_elem(xpath) != e) {
let result = e.ownerDocument.evaluate(
xpath,
e.ownerDocument,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
)
for (let i = 0, len = result.snapshotLength; i < len; i++) {
let newPath = 'xpath=(' + xpath + ')[' + (i + 1) + ']'
if (document.pyspy_find_elem(newPath) == e) {
return newPath
}
}
}
return xpath
}
'''
js_init['js_init_generate_ids'] = r'''
document.pyspy_generate_ids = function(e){
document.IDs_builder = new Object()
document.IDs_builder.EVENT = e.type
document.IDs_builder.PATHS = {}
document.IDs_builder.add = function(name, finder) {
if (finder){
this.PATHS[name] = finder
}
}
var jsonParser
if(Object.toJSON){
jsonParser = Object.toJSON;
}
else{
jsonParser = JSON.stringify;
}
document.IDs_builder.add('id', document.pyspy_find_by_id(e.target))
document.IDs_builder.add('name', document.pyspy_find_by_name(e.target))
document.IDs_builder.add('css', document.pyspy_find_by_css(e.target))
document.IDs_builder.add('xpath:link', document.pyspy_find_by_xpath_link(e.target))
document.IDs_builder.add('xpath:innerText', document.pyspy_find_by_xpath_innerText(e.target))
document.IDs_builder.add('xpath:img', document.pyspy_find_by_xpath_img(e.target))
return jsonParser(document.IDs_builder);
}
'''
js_init['js_init_find_by_id'] = r'''
document.pyspy_find_by_id = function id(elem) {
if (elem.id) {
return elem.id
}
return null
}
'''
js_init['js_init_find_by_name'] = r'''
document.pyspy_find_by_name = function name(elem) {
if (elem.name) {
return elem.name
}
return null
}
'''
js_init['js_init_find_by_xpath_innerText'] = r'''
document.pyspy_find_by_xpath_innerText = function xpath_innerText(elem) {
if (elem.innerText) {
return `//${elem.nodeName.toLowerCase()}[contains(.,'${elem.innerText}')]`
}
return null
}
'''
js_init['js_init_find_by_xpath_link'] = r'''
document.pyspy_find_by_xpath_link = function xpath_link(elem) {
if (elem.nodeName == 'A') {
let text = elem.textContent
if (!text.match(/^\s*$/)) {
return document.pyspy_xp_precise(
'//' +
document.pyspy_html_elem('a') +
"[contains(text(),'" +
text.replace(/^\s+/, '').replace(/\s+$/, '') +
"')]",
elem
)
}
}
return null
}
'''
js_init['js_init_find_by_xpath_img'] = r'''
document.pyspy_find_by_xpath_img = function xpath_img(elem) {
if (elem.nodeName == 'IMG') {
if (elem.alt != '') {
return document.pyspy_xp_precise(
'//' +
document.pyspy_html_elem('img') +
'[@alt=' +
document.pyspy_xp_attr_val(elem.alt) +
']',
elem
)
} else if (elem.title != '') {
return document.pyspy_xp_precise(
'//' +
document.pyspy_html_elem('img') +
'[@title=' +
document.pyspy_xp_attr_val(elem.title) +
']',
elem
)
} else if (elem.src != '') {
return document.pyspy_xp_precise(
'//' +
document.pyspy_html_elem('img') +
'[contains(@src,' +
document.pyspy_xp_attr_val(elem.src) +
')]',
elem
)
}
}
return null
}
'''
js_init['js_init_find_by_css'] = r'''
document.pyspy_find_by_css = function css_attr(elem) {
const dataAttributes = ['data-test', 'data-test-id']
for (let i = 0; i < dataAttributes.length; i++) {
const attr = dataAttributes[i]
const value = elem.getAttribute(attr)
if (value) {
return `*[${attr}="${value}"]`
}
}
return null
}
'''
js_init['js_init_mouse_over'] = r'''
document.pyspy_mouse_over = function(e){
if(e.target == document.documentElement) return
document.pyspy_last_elem = e.target;
document.pyspy_border_color = e.target.style.outline;
document.pyspy_highlight_color = e.target.style.backgroundColor;
e.target.style.backgroundColor = "#FDFF47";
document.pyspy_spy_listener = document.pyspy_generate_ids(e);
}
'''
js_init['js_init_onmouseout'] = r'''
document.onmouseout = function(ev){
if(document.pyspy_last_elem){
ev.target.style.outline = document.pyspy_border_color;
ev.target.style.backgroundColor = document.pyspy_highlight_color;
}
}
'''
js_init['js_init_onclick'] = r'''
document.pyspy_click = function(e){
if(e.target == document.documentElement) return
document.pyspy_last_elem = e.target;
document.pyspy_border_color = e.target.style.outline;
document.pyspy_highlight_color = e.target.style.backgroundColor;
e.target.style.backgroundColor = "#7CFC00";
document.pyspy_spy_listener = document.pyspy_generate_ids(e);
}
'''
js_init['js_init_onmouseup'] = r'''
document.onmouseup = function(ev){
if(document.pyspy_last_elem){
ev.target.style.outline = document.pyspy_border_color;
ev.target.style.backgroundColor = document.pyspy_highlight_color;
}
}
'''
js_init['js_init_cursor'] = r'''
document.pyspy_cursor = document.body.style.cursor;
'''
js_init['js_init_start_listner'] = r'''
document.body.style.cursor = "pointer";
document.pyspy_spy_listener = null;
document.addEventListener('click', document.pyspy_click,false);
document.addEventListener('mouseover', document.pyspy_mouse_over, false);
'''
js_listner_capture = r'''
var callback = arguments[arguments.length - 1];
if(!document.pyspy_mouse_over){
callback('{"pyspy_error":"*** spy listner not running ***"}');
return;
}
var waitForActions = function(){
if(document.pyspy_spy_listener){
var response = document.pyspy_spy_listener
document.pyspy_spy_listener = null;
callback(response);
}
else{
setTimeout(waitForActions, 50);
}
}
waitForActions();
'''
js_raw_html = r'''
var callback = arguments[arguments.length - 1];
callback(document.documentElement.innerHTML);
'''
| """
webelementspy.jsscripts
~~~~~~~~~~~~
This file contain JS scripts to be injected to webdriver
:copyright: (c) 2019 by Yasser.
:license: MIT, see LICENSE for more details.
"""
__all__ = ['js_init', 'js_listner_capture', 'js_raw_html']
js_init = {}
js_init['js_init_init_check'] = '\nif(document.pyspy_html_elem) return;\n'
js_init['js_init_html_elem'] = "\ndocument.pyspy_html_elem = function(name) {\n if (document.contentType == 'application/xhtml+xml') {\n return 'x:' + name\n } else {\n return name\n }\n}\n"
js_init['js_init_xp_attr_val'] = '\ndocument.pyspy_xp_attr_val = function(value) {\n if (value.indexOf("\'") < 0) {\n return "\'" + value + "\'"\n } else if (value.indexOf(\'"\') < 0) {\n return \'"\' + value + \'"\'\n } else {\n let result = \'concat(\'\n let part = \'\'\n let didReachEndOfValue = false\n while (!didReachEndOfValue) {\n let apos = value.indexOf("\'")\n let quot = value.indexOf(\'"\')\n if (apos < 0) {\n result += "\'" + value + "\'"\n didReachEndOfValue = true\n break\n } else if (quot < 0) {\n result += \'"\' + value + \'"\'\n didReachEndOfValue = true\n break\n } else if (quot < apos) {\n part = value.substring(0, apos)\n result += "\'" + part + "\'"\n value = value.substring(part.length)\n } else {\n part = value.substring(0, quot)\n result += \'"\' + part + \'"\'\n value = value.substring(part.length)\n }\n result += \',\'\n }\n result += \')\'\n return result\n }\n}\n'
js_init['js_init_find_elem'] = '\ndocument.pyspy_find_elem = function(loc) {\n try {\n const locator = parse_locator(loc, true)\n return document.pyspy_find_elem({ [locator.type]: locator.string }, document)\n } catch (error) {\n return null\n }\n}\n'
js_init['js_init_xp_precise'] = "\ndocument.pyspy_xp_precise = function(xpath, e) {\n if (document.pyspy_find_elem(xpath) != e) {\n let result = e.ownerDocument.evaluate(\n xpath,\n e.ownerDocument,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null\n )\n for (let i = 0, len = result.snapshotLength; i < len; i++) {\n let newPath = 'xpath=(' + xpath + ')[' + (i + 1) + ']'\n if (document.pyspy_find_elem(newPath) == e) {\n return newPath\n }\n }\n }\n return xpath\n}\n"
js_init['js_init_generate_ids'] = "\ndocument.pyspy_generate_ids = function(e){\n document.IDs_builder = new Object()\n document.IDs_builder.EVENT = e.type\n document.IDs_builder.PATHS = {}\n\n document.IDs_builder.add = function(name, finder) {\n if (finder){\n this.PATHS[name] = finder\n }\n }\n var jsonParser\n if(Object.toJSON){\n jsonParser = Object.toJSON;\n }\n else{\n jsonParser = JSON.stringify;\n }\n document.IDs_builder.add('id', document.pyspy_find_by_id(e.target))\n document.IDs_builder.add('name', document.pyspy_find_by_name(e.target))\n document.IDs_builder.add('css', document.pyspy_find_by_css(e.target))\n document.IDs_builder.add('xpath:link', document.pyspy_find_by_xpath_link(e.target))\n document.IDs_builder.add('xpath:innerText', document.pyspy_find_by_xpath_innerText(e.target))\n document.IDs_builder.add('xpath:img', document.pyspy_find_by_xpath_img(e.target))\n \n return jsonParser(document.IDs_builder);\n}\n"
js_init['js_init_find_by_id'] = '\ndocument.pyspy_find_by_id = function id(elem) {\n if (elem.id) {\n return elem.id\n }\n return null\n}\n'
js_init['js_init_find_by_name'] = '\ndocument.pyspy_find_by_name = function name(elem) {\n if (elem.name) {\n return elem.name\n }\n return null\n}\n'
js_init['js_init_find_by_xpath_innerText'] = "\ndocument.pyspy_find_by_xpath_innerText = function xpath_innerText(elem) {\n if (elem.innerText) {\n return `//${elem.nodeName.toLowerCase()}[contains(.,'${elem.innerText}')]`\n }\n return null\n}\n"
js_init['js_init_find_by_xpath_link'] = '\ndocument.pyspy_find_by_xpath_link = function xpath_link(elem) {\n if (elem.nodeName == \'A\') {\n let text = elem.textContent\n if (!text.match(/^\\s*$/)) {\n return document.pyspy_xp_precise(\n \'//\' +\n document.pyspy_html_elem(\'a\') +\n "[contains(text(),\'" +\n text.replace(/^\\s+/, \'\').replace(/\\s+$/, \'\') +\n "\')]",\n elem\n )\n }\n }\n return null\n}\n'
js_init['js_init_find_by_xpath_img'] = "\ndocument.pyspy_find_by_xpath_img = function xpath_img(elem) {\n if (elem.nodeName == 'IMG') {\n if (elem.alt != '') {\n return document.pyspy_xp_precise(\n '//' +\n document.pyspy_html_elem('img') +\n '[@alt=' +\n document.pyspy_xp_attr_val(elem.alt) +\n ']',\n elem\n )\n } else if (elem.title != '') {\n return document.pyspy_xp_precise(\n '//' +\n document.pyspy_html_elem('img') +\n '[@title=' +\n document.pyspy_xp_attr_val(elem.title) +\n ']',\n elem\n )\n } else if (elem.src != '') {\n return document.pyspy_xp_precise(\n '//' +\n document.pyspy_html_elem('img') +\n '[contains(@src,' +\n document.pyspy_xp_attr_val(elem.src) +\n ')]',\n elem\n )\n }\n }\n return null\n}\n"
js_init['js_init_find_by_css'] = '\ndocument.pyspy_find_by_css = function css_attr(elem) {\n const dataAttributes = [\'data-test\', \'data-test-id\']\n for (let i = 0; i < dataAttributes.length; i++) {\n const attr = dataAttributes[i]\n const value = elem.getAttribute(attr)\n if (value) {\n return `*[${attr}="${value}"]`\n }\n }\n return null\n}\n'
js_init['js_init_mouse_over'] = '\ndocument.pyspy_mouse_over = function(e){\n if(e.target == document.documentElement) return\n document.pyspy_last_elem = e.target;\n document.pyspy_border_color = e.target.style.outline;\n document.pyspy_highlight_color = e.target.style.backgroundColor;\n e.target.style.backgroundColor = "#FDFF47";\n document.pyspy_spy_listener = document.pyspy_generate_ids(e);\n}\n'
js_init['js_init_onmouseout'] = '\n document.onmouseout = function(ev){\n if(document.pyspy_last_elem){\n ev.target.style.outline = document.pyspy_border_color;\n ev.target.style.backgroundColor = document.pyspy_highlight_color;\n }\n}\n'
js_init['js_init_onclick'] = '\n document.pyspy_click = function(e){\n if(e.target == document.documentElement) return\n document.pyspy_last_elem = e.target;\n document.pyspy_border_color = e.target.style.outline;\n document.pyspy_highlight_color = e.target.style.backgroundColor;\n e.target.style.backgroundColor = "#7CFC00";\n document.pyspy_spy_listener = document.pyspy_generate_ids(e);\n}\n'
js_init['js_init_onmouseup'] = '\n document.onmouseup = function(ev){\n if(document.pyspy_last_elem){\n ev.target.style.outline = document.pyspy_border_color;\n ev.target.style.backgroundColor = document.pyspy_highlight_color;\n }\n}\n'
js_init['js_init_cursor'] = '\ndocument.pyspy_cursor = document.body.style.cursor;\n'
js_init['js_init_start_listner'] = '\ndocument.body.style.cursor = "pointer";\ndocument.pyspy_spy_listener = null;\ndocument.addEventListener(\'click\', document.pyspy_click,false);\ndocument.addEventListener(\'mouseover\', document.pyspy_mouse_over, false);\n'
js_listner_capture = '\n var callback = arguments[arguments.length - 1];\n if(!document.pyspy_mouse_over){\n callback(\'{"pyspy_error":"*** spy listner not running ***"}\');\n return;\n }\n var waitForActions = function(){\n if(document.pyspy_spy_listener){\n var response = document.pyspy_spy_listener\n document.pyspy_spy_listener = null;\n callback(response);\n }\n else{\n setTimeout(waitForActions, 50);\n }\n }\n waitForActions();\n'
js_raw_html = '\n var callback = arguments[arguments.length - 1];\n callback(document.documentElement.innerHTML);\n' |
'''
Created on 10/02/2012
@author: Alumno
'''
def suma(x, y):
return x+y
def multiplica(x, y):
return x*y
def cuadrado(x):
return x*x | """
Created on 10/02/2012
@author: Alumno
"""
def suma(x, y):
return x + y
def multiplica(x, y):
return x * y
def cuadrado(x):
return x * x |
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/1029/B
n = int(input())
al = list(map(int,input().split()))
cnt = 1
mxc = 0
for i in range(n-1):
if al[i+1]-al[i] <= al[i]:
cnt += 1
else:
if cnt>mxc:
mxc = cnt
cnt = 1
print(max(mxc,cnt))
| n = int(input())
al = list(map(int, input().split()))
cnt = 1
mxc = 0
for i in range(n - 1):
if al[i + 1] - al[i] <= al[i]:
cnt += 1
else:
if cnt > mxc:
mxc = cnt
cnt = 1
print(max(mxc, cnt)) |
def solve_knapsack(profits, weights, capacity):
if profits is None \
or weights is None \
or len(profits) == 0 \
or len(profits) != len(weights):
return 0
return unbounded_knapsack(profits, weights, capacity, 0)
# We are trying to find the maximum profit
def unbounded_knapsack(profits, weights, capacity, curr_index):
n = len(profits) # or len(weights)
if capacity <= 0 or curr_index >= n: # base checks
return 0
# recursive call after choosing the items at the curr_index,
# Note that we recursive call on all items as we did not increment curr_index
profit_by_inclusion = 0
if weights[curr_index] <= capacity:
profit_by_inclusion = profits[curr_index] + \
unbounded_knapsack(profits, weights, capacity - weights[curr_index], curr_index)
# recursive call after excluding the element at the currentIndex
profit_by_exclusion = unbounded_knapsack(profits, weights, capacity, curr_index + 1)
return max(profit_by_inclusion, profit_by_exclusion)
def main():
print(solve_knapsack([15, 50, 60, 90], [1, 3, 4, 5], 8))
print(solve_knapsack([15, 50, 60, 90], [1, 3, 4, 5], 6))
main()
| def solve_knapsack(profits, weights, capacity):
if profits is None or weights is None or len(profits) == 0 or (len(profits) != len(weights)):
return 0
return unbounded_knapsack(profits, weights, capacity, 0)
def unbounded_knapsack(profits, weights, capacity, curr_index):
n = len(profits)
if capacity <= 0 or curr_index >= n:
return 0
profit_by_inclusion = 0
if weights[curr_index] <= capacity:
profit_by_inclusion = profits[curr_index] + unbounded_knapsack(profits, weights, capacity - weights[curr_index], curr_index)
profit_by_exclusion = unbounded_knapsack(profits, weights, capacity, curr_index + 1)
return max(profit_by_inclusion, profit_by_exclusion)
def main():
print(solve_knapsack([15, 50, 60, 90], [1, 3, 4, 5], 8))
print(solve_knapsack([15, 50, 60, 90], [1, 3, 4, 5], 6))
main() |
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
paths = [[1] * n for _ in range(m)]
for row in range(1, m):
for col in range(1, n):
paths[row][col] = paths[row-1][col] + paths[row][col-1]
return paths[m-1][n-1] | class Solution:
def unique_paths(self, m: int, n: int) -> int:
paths = [[1] * n for _ in range(m)]
for row in range(1, m):
for col in range(1, n):
paths[row][col] = paths[row - 1][col] + paths[row][col - 1]
return paths[m - 1][n - 1] |
# The search the 2D array for the target element where array is sorted from
# left to right and top to bottom
def search_2D_array(arr,x):
row = 0
col = len(arr[0]) - 1
while row < len(arr) and col >= 0:
if arr[col][row] == x:
return True
elif arr[row][col] < x:
row += 1
else:
col -= 1
return False
if __name__ == "__main__":
arr = [[10, 20, 30, 40],
[15, 25, 35, 45],
[27, 29, 37, 48],
[32, 33, 39, 50]
]
if search_2D_array(arr,37):
print("Present in array")
else:
print("Not present.")
| def search_2_d_array(arr, x):
row = 0
col = len(arr[0]) - 1
while row < len(arr) and col >= 0:
if arr[col][row] == x:
return True
elif arr[row][col] < x:
row += 1
else:
col -= 1
return False
if __name__ == '__main__':
arr = [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]]
if search_2_d_array(arr, 37):
print('Present in array')
else:
print('Not present.') |
n, k = map(int, input().split())
a = list(map(int, input().split()))
fre = [0] * (10 ** 5 + 5)
unique = 0
j = 0
for i in range(n):
if fre[a[i]] == 0:
unique += 1
fre[a[i]] += 1
while unique == k:
fre[a[j]] -= 1
if fre[a[j]] == 0:
print(j + 1, i + 1)
exit()
j += 1
print('-1 -1')
| (n, k) = map(int, input().split())
a = list(map(int, input().split()))
fre = [0] * (10 ** 5 + 5)
unique = 0
j = 0
for i in range(n):
if fre[a[i]] == 0:
unique += 1
fre[a[i]] += 1
while unique == k:
fre[a[j]] -= 1
if fre[a[j]] == 0:
print(j + 1, i + 1)
exit()
j += 1
print('-1 -1') |
"""The pyang library for parsing, validating, and converting YANG modules"""
__version__ = '2.5.3'
__date__ = '2022-03-30'
| """The pyang library for parsing, validating, and converting YANG modules"""
__version__ = '2.5.3'
__date__ = '2022-03-30' |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of the `swift_import` rule."""
load(":api.bzl", "swift_common")
load(":attrs.bzl", "SWIFT_COMMON_RULE_ATTRS")
load(":providers.bzl", "SwiftClangModuleInfo", "merge_swift_clang_module_infos")
load("@bazel_skylib//lib:dicts.bzl", "dicts")
def _swift_import_impl(ctx):
archives = ctx.files.archives
deps = ctx.attr.deps
swiftdocs = ctx.files.swiftdocs
swiftmodules = ctx.files.swiftmodules
providers = [
DefaultInfo(
files = depset(direct = archives + swiftdocs + swiftmodules),
runfiles = ctx.runfiles(
collect_data = True,
collect_default = True,
files = ctx.files.data,
),
),
swift_common.build_swift_info(
deps = deps,
direct_libraries = archives,
direct_swiftdocs = swiftdocs,
direct_swiftmodules = swiftmodules,
),
]
# Only propagate `SwiftClangModuleInfo` if any of our deps does.
if any([SwiftClangModuleInfo in dep for dep in deps]):
clang_module = merge_swift_clang_module_infos(deps)
providers.append(clang_module)
return providers
swift_import = rule(
attrs = dicts.add(
SWIFT_COMMON_RULE_ATTRS,
{
"archives": attr.label_list(
allow_empty = False,
allow_files = ["a"],
doc = """
The list of `.a` files provided to Swift targets that depend on this target.
""",
mandatory = True,
),
"swiftdocs": attr.label_list(
allow_empty = True,
allow_files = ["swiftdoc"],
doc = """
The list of `.swiftdoc` files provided to Swift targets that depend on this target.
""",
default = [],
mandatory = False,
),
"swiftmodules": attr.label_list(
allow_empty = False,
allow_files = ["swiftmodule"],
doc = """
The list of `.swiftmodule` files provided to Swift targets that depend on this target.
""",
mandatory = True,
),
},
),
doc = """
Allows for the use of precompiled Swift modules as dependencies in other `swift_library` and
`swift_binary` targets.
""",
implementation = _swift_import_impl,
)
| """Implementation of the `swift_import` rule."""
load(':api.bzl', 'swift_common')
load(':attrs.bzl', 'SWIFT_COMMON_RULE_ATTRS')
load(':providers.bzl', 'SwiftClangModuleInfo', 'merge_swift_clang_module_infos')
load('@bazel_skylib//lib:dicts.bzl', 'dicts')
def _swift_import_impl(ctx):
archives = ctx.files.archives
deps = ctx.attr.deps
swiftdocs = ctx.files.swiftdocs
swiftmodules = ctx.files.swiftmodules
providers = [default_info(files=depset(direct=archives + swiftdocs + swiftmodules), runfiles=ctx.runfiles(collect_data=True, collect_default=True, files=ctx.files.data)), swift_common.build_swift_info(deps=deps, direct_libraries=archives, direct_swiftdocs=swiftdocs, direct_swiftmodules=swiftmodules)]
if any([SwiftClangModuleInfo in dep for dep in deps]):
clang_module = merge_swift_clang_module_infos(deps)
providers.append(clang_module)
return providers
swift_import = rule(attrs=dicts.add(SWIFT_COMMON_RULE_ATTRS, {'archives': attr.label_list(allow_empty=False, allow_files=['a'], doc='\nThe list of `.a` files provided to Swift targets that depend on this target.\n', mandatory=True), 'swiftdocs': attr.label_list(allow_empty=True, allow_files=['swiftdoc'], doc='\nThe list of `.swiftdoc` files provided to Swift targets that depend on this target.\n', default=[], mandatory=False), 'swiftmodules': attr.label_list(allow_empty=False, allow_files=['swiftmodule'], doc='\nThe list of `.swiftmodule` files provided to Swift targets that depend on this target.\n', mandatory=True)}), doc='\nAllows for the use of precompiled Swift modules as dependencies in other `swift_library` and\n`swift_binary` targets.\n', implementation=_swift_import_impl) |
n = int(input())
spaces = 2*(n-1)
for i in range(1, n+1):
print(" "*spaces, end="")
if i == 1:
print("1")
else:
for j in range(i, 2*i):
print(str(j) + " ", end="")
for j in range(2*i-2, i-1, -1 ):
print(str(j) + " ", end="")
print()
spaces -= 2 | n = int(input())
spaces = 2 * (n - 1)
for i in range(1, n + 1):
print(' ' * spaces, end='')
if i == 1:
print('1')
else:
for j in range(i, 2 * i):
print(str(j) + ' ', end='')
for j in range(2 * i - 2, i - 1, -1):
print(str(j) + ' ', end='')
print()
spaces -= 2 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-12-22 10:42:23
# @Author : Jan Yang
# @Software : Sublime Text
class Email:
def __init__(self):
pass
| class Email:
def __init__(self):
pass |
# Perulangan pada string
print('=====Perulangan Pada String=====')
teks = 'helloworld'
print('teks =',teks)
hitung = 0
for i in range(len(teks)):
if 'l' == teks[i]:
hitung = hitung + 1
print('jumlah l pada teks',teks,'adalah',hitung) | print('=====Perulangan Pada String=====')
teks = 'helloworld'
print('teks =', teks)
hitung = 0
for i in range(len(teks)):
if 'l' == teks[i]:
hitung = hitung + 1
print('jumlah l pada teks', teks, 'adalah', hitung) |
"""
APCS 106/10
Logic Operator
20220127
by Kevin Hsu
"""
iTmp = input("input three number:\n").split()
x = int(iTmp[0])
y = int(iTmp[1])
z = int(iTmp[2])
answer = [0] * 3
if x > 0:
x = 1
if y > 0:
y = 1
if ((x & y) == z):
answer[0] = 1
else:
answer[0] = 0
if ((x | y) == z):
answer[1] = 1
else:
answer[1] = 0
if ((x ^ y) == z):
answer[2] = 1
else:
answer[2] = 0
if answer[0] == 1:
print("AND")
if answer[1] == 1:
print("OR")
if answer[2] == 1:
print("XOR")
if answer[0] == 0 and answer[1] == 0 and answer[2] == 0:
print("IMPOSSIBLE") | """
APCS 106/10
Logic Operator
20220127
by Kevin Hsu
"""
i_tmp = input('input three number:\n').split()
x = int(iTmp[0])
y = int(iTmp[1])
z = int(iTmp[2])
answer = [0] * 3
if x > 0:
x = 1
if y > 0:
y = 1
if x & y == z:
answer[0] = 1
else:
answer[0] = 0
if x | y == z:
answer[1] = 1
else:
answer[1] = 0
if x ^ y == z:
answer[2] = 1
else:
answer[2] = 0
if answer[0] == 1:
print('AND')
if answer[1] == 1:
print('OR')
if answer[2] == 1:
print('XOR')
if answer[0] == 0 and answer[1] == 0 and (answer[2] == 0):
print('IMPOSSIBLE') |
h, m = 100, 200
h_deg, m_deg = h//2, m//3
# In Python3, // rounds down to the nearest whole number
angle = abs(h_deg - m_deg)
if angle > 180:
angle = 360 - angle
print(int(angle))
| (h, m) = (100, 200)
(h_deg, m_deg) = (h // 2, m // 3)
angle = abs(h_deg - m_deg)
if angle > 180:
angle = 360 - angle
print(int(angle)) |
# Gregary C. Zweigle
# 2020
MAX_PIANO_NOTE = 88
# TODO - Should this move elsewhere?
class FileName:
def __init__(self):
self.note_number = 0
self.file_name_l = 'EMPTY_L'
self.file_name_r = 'EMPTY_R'
def initialize_file_name(self, record_start_note):
self.note_number = int(float(record_start_note))
self.file_name_l = 'noteL' + str(self.note_number) + '.dat'
self.file_name_r = 'noteR' + str(self.note_number) + '.dat'
def advance_file_name(self):
self.note_number = self.note_number + 1
self.file_name_l = 'noteL' + str(self.note_number) + '.dat'
self.file_name_r = 'noteR' + str(self.note_number) + '.dat'
def get_file_name(self):
return (self.file_name_l, self.file_name_r)
def check_if_finished_all_notes(self):
if self.note_number > MAX_PIANO_NOTE:
return True
else:
return False
# TODO - Originally it seemed like a good idea to track
# notes in this class, but its too unrelated, need to move out.
def get_note_number(self):
return self.note_number | max_piano_note = 88
class Filename:
def __init__(self):
self.note_number = 0
self.file_name_l = 'EMPTY_L'
self.file_name_r = 'EMPTY_R'
def initialize_file_name(self, record_start_note):
self.note_number = int(float(record_start_note))
self.file_name_l = 'noteL' + str(self.note_number) + '.dat'
self.file_name_r = 'noteR' + str(self.note_number) + '.dat'
def advance_file_name(self):
self.note_number = self.note_number + 1
self.file_name_l = 'noteL' + str(self.note_number) + '.dat'
self.file_name_r = 'noteR' + str(self.note_number) + '.dat'
def get_file_name(self):
return (self.file_name_l, self.file_name_r)
def check_if_finished_all_notes(self):
if self.note_number > MAX_PIANO_NOTE:
return True
else:
return False
def get_note_number(self):
return self.note_number |
n = int(input())
s = list(map(int, input().split()))
c = [0] * 10010
res, count = 0, 0
for i in s:
c[i] += 1
if c[i] > count:
res = i
count = c[i]
elif c[i] == count:
res = min(res, i)
print(res)
| n = int(input())
s = list(map(int, input().split()))
c = [0] * 10010
(res, count) = (0, 0)
for i in s:
c[i] += 1
if c[i] > count:
res = i
count = c[i]
elif c[i] == count:
res = min(res, i)
print(res) |
INPUT= """2
0
0
-2
0
1
-2
-1
-6
2
-1
2
0
2
-13
0
-2
-15
-15
-3
-10
-11
1
-5
-20
-21
-14
-21
-4
-9
-29
2
-10
-5
-33
-33
-9
0
2
-24
0
-26
-24
-38
-28
-42
-14
-42
2
-2
-48
-48
-17
-19
-26
-39
0
-15
-42
-3
-19
-19
-7
-1
-11
-5
-17
-46
-15
-43
-22
-31
-60
-59
-71
-58
-39
-66
-74
-11
-18
-68
1
-70
-79
-18
-56
-17
0
-52
-79
-86
-90
-74
-89
-20
-30
-65
-2
-47
-42
-33
-35
-61
-4
-101
-38
-8
-26
-37
-56
-30
-36
-55
-87
-85
-58
-22
-9
-81
-119
-94
-81
-83
-24
-105
-21
-69
-11
-7
-114
-60
-74
-19
-126
-66
-106
-5
-112
0
-58
-18
-122
-50
-72
-83
-15
-93
-60
-17
-37
-55
-119
-118
-12
-101
-65
-35
-122
-149
-97
-140
-62
-101
-85
-23
-43
-141
-158
-37
-103
-142
1
-112
-55
-139
-90
-5
-75
-73
-171
-4
-39
-4
-135
-126
-40
-74
-161
-125
-174
-90
-129
-126
-166
-106
-16
-51
-54
-135
-37
-21
-103
-73
-64
-59
-88
-153
-196
-123
-98
-36
-193
-164
-111
-81
-49
-87
-91
-191
-219
-103
-217
-107
-87
-82
-23
-157
-56
-20
-149
-133
-53
-37
-199
-85
-133
-12
-228
-15
-217
-106
-52
-179
-118
-54
-70
-99
-160
-24
-71
-55
-7
-105
-174
-187
-226
-210
-55
-130
-137
-255
-259
-117
-10
-162
-61
-19
-54
-225
-23
-84
-183
-262
-44
-215
-268
-201
-89
-3
-241
-277
-8
-177
-31
-269
-35
-132
-175
-253
-85
-286
-265
-292
-196
-132
-212
-131
-117
-196
-245
-294
-32
-20
-184
-246
-171
-64
-220
-3
-179
-186
-51
-276
-203
-191
-205
-141
-304
-186
-273
-299
-17
-46
-254
-126
-268
-163
-69
-326
-192
-279
-293
-220
-20
-137
-330
-8
-53
-49
2
-149
-181
-298
-297
-66
-136
-166
-146
-28
-146
-226
-270
-349
-216
-348
-184
-298
-348
-323
-244
-207
-22
-172
-359
-188
-1
-278
-76
-216
-343
-29
-37
-257
-357
-226
-19
-246
-76
-105
-312
-219
-268
0
-230
-379
-357
-69
-1
-30
-321
-212
-262
-297
-86
-102
-390
-384
-98
-294
-359
-326
-58
-296
-104
-309
-244
-308
-116
-148
-134
-307
-307
-207
-391
-312
-209
-334
-225
-193
-345
-224
-299
-110
-414
-252
-302
-142
-239
-376
-54
-227
-126
-154
-263
-18
-387
-214
-129
-163
-151
-325
-401
-382
-329
-288
-283
-376
-211
-221
-448
-292
-187
-76
-84
-342
-162
-251
-110
-66
-349
-435
-380
-82
-281
-29
-61
-402
-287
-118
-428
-429
-403
-324
-391
-203
-374
-397
-352
-462
-440
-89
-209
-133
-436
-187
-142
-299
-402
-210
-217
-50
-456
-177
-335
-204
-338
-146
-82
-379
-332
-148
-370
-188
-42
-351
-219
-89
-129
-388
-42
-338
-169
-104
-508
-43
-432
-99
-484
2
-461
-469
-151
-279
-309
-121
-306
-210
-302
-100
-415
-307
2
-111
-432
-457
-299
-95
-327
-508
-327
-211
-319
-83
-340
-474
-160
-494
-351
-177
-514
-198
-177
-45
-364
-232
-432
-137
-467
-11
-253
-237
-367
-42
-442
-14
-323
-489
-466
-389
-362
-195
-110
-170
-394
-234
-296
-296
-469
-275
-2
-413
-149
-477
-543
-435
-255
-259
-152
-73
-47
-72
-252
-499
-305
-169
-406
-280
-287
-43
-20
-242
-271
-336
-500
-341
-354
-559
-364
-126
-173
-444
-555
-532
-532
-369
-468
-315
-469
-506
-151
-202
-459
-139
-434
-383
-353
-13
-272
-517
-629
-573
-502
-337
-454
-376
-288
-430
-503
-482
-327
-418
-623
-576
-412
-416
-457
-84
-251
-466
-520
-262
-642
-329
-308
-145
-391
-189
-226
-48
-167
-626
-325
-288
-432
-615
-149
-414
-387
-622
-260
-200
-483
-531
-22
-82
-308
-593
-271
-134
-431
-190
-460
-434
-558
-166
-136
-404
-10
-225
-397
-375
-371
-654
-374
-137
-659
-413
-117
-602
-585
-601
-451
-171
-296
-437
-505
-675
-153
-286
-28
-515
-221
-124
-662
-516
-119
-390
-78
-372
-490
-403
-341
-623
-264
-672
-94
-238
-250
-382
-526
-360
-170
-109
-228
-226
-70
-519
-481
-174
-471
-9
-497
-488
-337
-729
-72
-489
-717
-426
-159
-436
-600
-84
-1
-742
-258
-346
-205
-427
-479
-243
-358
-90
-482
-471
-234
-131
-108
-670
-740
-748
-427
-563
-691
-354
-427
-755
-708
-389
-741
-125
-723
-274
-464
-223
-497
-182
-167
-83
-387
-464
-195
-131
-161
-213
-671
-491
-66
-138
-121
-498
-408
-429
-643
-803
-118
-561
-217
-282
-400
-396
-434
-501
-134
-409
-162
-696
-14
-269
-663
-531
-620
-208
-71
-511
-421
-371
-797
-454
-273
-167
-261
-618
-769
-738
-71
-239
-117
-204
-149
-820
-222
-337
-383
-181
-433
-765
-367
-286
-152
-59
-673
-333
-238
-121
-16
-614
-630
-196
-306
-703
-363
-296
-366
-515
-673
-90
-421
-474
-794
-522
-842
-185
-732
-642
-830
-19
-735
-153
-814
-654
-550
-175
-626
-148
-661
-876
-601
-822
-692
-784
-761
-738
-144
-672
-16
-572
-484
-851
-849
-41
-59
-700
-586
-323
-504
-156
-755
-408
-10
-228
-116
-174
-860
-837
-796
-392
-380
-403
-886
-360
-200
-38
-544
-448
-281
-218
-132
-571
-650
-666
-332
-130
-618
-306
-272
-95
-110
-804
-25
-61
-114
-369
-675
-58
-341
-543
-477
-936
-617
-684
-803
-40
-285
-919
-72
-685
-318
-107
-210
-926
-600
-130
-707
-355
-221
-951
-687
-599
-745
-889
-10
-188
-687
-191
-789
-44
-774
-53
-738
-889
-332
-575
-838
-975
-224
-720
-910
-478
-35
-740
-549
-911
-624
-596
-865
-485
-476
-348
-664
-674
-597
-839
-698
-746
-527
-95
-623
-662
-795
-287
-969
-21
-730
-191
-866"""
jump_list = [int(x) for x in INPUT.split("\n")]
current_index = 0
steps_taken = 0
while 0 <= current_index < len(jump_list):
current_jump = jump_list[current_index]
jump_list[current_index] += 1
current_index += current_jump
steps_taken += 1
print("V1 Final index: %d, steps taken: %d" % (current_index, steps_taken))
jump_list = [int(x) for x in INPUT.split("\n")]
current_index = 0
steps_taken = 0
while 0 <= current_index < len(jump_list):
current_jump = jump_list[current_index]
if current_jump >= 3:
jump_list[current_index] -= 1
else:
jump_list[current_index] += 1
current_index += current_jump
steps_taken += 1
print("V2 Final index: %d, steps taken: %d" % (current_index, steps_taken))
| input = '2\n0\n0\n-2\n0\n1\n-2\n-1\n-6\n2\n-1\n2\n0\n2\n-13\n0\n-2\n-15\n-15\n-3\n-10\n-11\n1\n-5\n-20\n-21\n-14\n-21\n-4\n-9\n-29\n2\n-10\n-5\n-33\n-33\n-9\n0\n2\n-24\n0\n-26\n-24\n-38\n-28\n-42\n-14\n-42\n2\n-2\n-48\n-48\n-17\n-19\n-26\n-39\n0\n-15\n-42\n-3\n-19\n-19\n-7\n-1\n-11\n-5\n-17\n-46\n-15\n-43\n-22\n-31\n-60\n-59\n-71\n-58\n-39\n-66\n-74\n-11\n-18\n-68\n1\n-70\n-79\n-18\n-56\n-17\n0\n-52\n-79\n-86\n-90\n-74\n-89\n-20\n-30\n-65\n-2\n-47\n-42\n-33\n-35\n-61\n-4\n-101\n-38\n-8\n-26\n-37\n-56\n-30\n-36\n-55\n-87\n-85\n-58\n-22\n-9\n-81\n-119\n-94\n-81\n-83\n-24\n-105\n-21\n-69\n-11\n-7\n-114\n-60\n-74\n-19\n-126\n-66\n-106\n-5\n-112\n0\n-58\n-18\n-122\n-50\n-72\n-83\n-15\n-93\n-60\n-17\n-37\n-55\n-119\n-118\n-12\n-101\n-65\n-35\n-122\n-149\n-97\n-140\n-62\n-101\n-85\n-23\n-43\n-141\n-158\n-37\n-103\n-142\n1\n-112\n-55\n-139\n-90\n-5\n-75\n-73\n-171\n-4\n-39\n-4\n-135\n-126\n-40\n-74\n-161\n-125\n-174\n-90\n-129\n-126\n-166\n-106\n-16\n-51\n-54\n-135\n-37\n-21\n-103\n-73\n-64\n-59\n-88\n-153\n-196\n-123\n-98\n-36\n-193\n-164\n-111\n-81\n-49\n-87\n-91\n-191\n-219\n-103\n-217\n-107\n-87\n-82\n-23\n-157\n-56\n-20\n-149\n-133\n-53\n-37\n-199\n-85\n-133\n-12\n-228\n-15\n-217\n-106\n-52\n-179\n-118\n-54\n-70\n-99\n-160\n-24\n-71\n-55\n-7\n-105\n-174\n-187\n-226\n-210\n-55\n-130\n-137\n-255\n-259\n-117\n-10\n-162\n-61\n-19\n-54\n-225\n-23\n-84\n-183\n-262\n-44\n-215\n-268\n-201\n-89\n-3\n-241\n-277\n-8\n-177\n-31\n-269\n-35\n-132\n-175\n-253\n-85\n-286\n-265\n-292\n-196\n-132\n-212\n-131\n-117\n-196\n-245\n-294\n-32\n-20\n-184\n-246\n-171\n-64\n-220\n-3\n-179\n-186\n-51\n-276\n-203\n-191\n-205\n-141\n-304\n-186\n-273\n-299\n-17\n-46\n-254\n-126\n-268\n-163\n-69\n-326\n-192\n-279\n-293\n-220\n-20\n-137\n-330\n-8\n-53\n-49\n2\n-149\n-181\n-298\n-297\n-66\n-136\n-166\n-146\n-28\n-146\n-226\n-270\n-349\n-216\n-348\n-184\n-298\n-348\n-323\n-244\n-207\n-22\n-172\n-359\n-188\n-1\n-278\n-76\n-216\n-343\n-29\n-37\n-257\n-357\n-226\n-19\n-246\n-76\n-105\n-312\n-219\n-268\n0\n-230\n-379\n-357\n-69\n-1\n-30\n-321\n-212\n-262\n-297\n-86\n-102\n-390\n-384\n-98\n-294\n-359\n-326\n-58\n-296\n-104\n-309\n-244\n-308\n-116\n-148\n-134\n-307\n-307\n-207\n-391\n-312\n-209\n-334\n-225\n-193\n-345\n-224\n-299\n-110\n-414\n-252\n-302\n-142\n-239\n-376\n-54\n-227\n-126\n-154\n-263\n-18\n-387\n-214\n-129\n-163\n-151\n-325\n-401\n-382\n-329\n-288\n-283\n-376\n-211\n-221\n-448\n-292\n-187\n-76\n-84\n-342\n-162\n-251\n-110\n-66\n-349\n-435\n-380\n-82\n-281\n-29\n-61\n-402\n-287\n-118\n-428\n-429\n-403\n-324\n-391\n-203\n-374\n-397\n-352\n-462\n-440\n-89\n-209\n-133\n-436\n-187\n-142\n-299\n-402\n-210\n-217\n-50\n-456\n-177\n-335\n-204\n-338\n-146\n-82\n-379\n-332\n-148\n-370\n-188\n-42\n-351\n-219\n-89\n-129\n-388\n-42\n-338\n-169\n-104\n-508\n-43\n-432\n-99\n-484\n2\n-461\n-469\n-151\n-279\n-309\n-121\n-306\n-210\n-302\n-100\n-415\n-307\n2\n-111\n-432\n-457\n-299\n-95\n-327\n-508\n-327\n-211\n-319\n-83\n-340\n-474\n-160\n-494\n-351\n-177\n-514\n-198\n-177\n-45\n-364\n-232\n-432\n-137\n-467\n-11\n-253\n-237\n-367\n-42\n-442\n-14\n-323\n-489\n-466\n-389\n-362\n-195\n-110\n-170\n-394\n-234\n-296\n-296\n-469\n-275\n-2\n-413\n-149\n-477\n-543\n-435\n-255\n-259\n-152\n-73\n-47\n-72\n-252\n-499\n-305\n-169\n-406\n-280\n-287\n-43\n-20\n-242\n-271\n-336\n-500\n-341\n-354\n-559\n-364\n-126\n-173\n-444\n-555\n-532\n-532\n-369\n-468\n-315\n-469\n-506\n-151\n-202\n-459\n-139\n-434\n-383\n-353\n-13\n-272\n-517\n-629\n-573\n-502\n-337\n-454\n-376\n-288\n-430\n-503\n-482\n-327\n-418\n-623\n-576\n-412\n-416\n-457\n-84\n-251\n-466\n-520\n-262\n-642\n-329\n-308\n-145\n-391\n-189\n-226\n-48\n-167\n-626\n-325\n-288\n-432\n-615\n-149\n-414\n-387\n-622\n-260\n-200\n-483\n-531\n-22\n-82\n-308\n-593\n-271\n-134\n-431\n-190\n-460\n-434\n-558\n-166\n-136\n-404\n-10\n-225\n-397\n-375\n-371\n-654\n-374\n-137\n-659\n-413\n-117\n-602\n-585\n-601\n-451\n-171\n-296\n-437\n-505\n-675\n-153\n-286\n-28\n-515\n-221\n-124\n-662\n-516\n-119\n-390\n-78\n-372\n-490\n-403\n-341\n-623\n-264\n-672\n-94\n-238\n-250\n-382\n-526\n-360\n-170\n-109\n-228\n-226\n-70\n-519\n-481\n-174\n-471\n-9\n-497\n-488\n-337\n-729\n-72\n-489\n-717\n-426\n-159\n-436\n-600\n-84\n-1\n-742\n-258\n-346\n-205\n-427\n-479\n-243\n-358\n-90\n-482\n-471\n-234\n-131\n-108\n-670\n-740\n-748\n-427\n-563\n-691\n-354\n-427\n-755\n-708\n-389\n-741\n-125\n-723\n-274\n-464\n-223\n-497\n-182\n-167\n-83\n-387\n-464\n-195\n-131\n-161\n-213\n-671\n-491\n-66\n-138\n-121\n-498\n-408\n-429\n-643\n-803\n-118\n-561\n-217\n-282\n-400\n-396\n-434\n-501\n-134\n-409\n-162\n-696\n-14\n-269\n-663\n-531\n-620\n-208\n-71\n-511\n-421\n-371\n-797\n-454\n-273\n-167\n-261\n-618\n-769\n-738\n-71\n-239\n-117\n-204\n-149\n-820\n-222\n-337\n-383\n-181\n-433\n-765\n-367\n-286\n-152\n-59\n-673\n-333\n-238\n-121\n-16\n-614\n-630\n-196\n-306\n-703\n-363\n-296\n-366\n-515\n-673\n-90\n-421\n-474\n-794\n-522\n-842\n-185\n-732\n-642\n-830\n-19\n-735\n-153\n-814\n-654\n-550\n-175\n-626\n-148\n-661\n-876\n-601\n-822\n-692\n-784\n-761\n-738\n-144\n-672\n-16\n-572\n-484\n-851\n-849\n-41\n-59\n-700\n-586\n-323\n-504\n-156\n-755\n-408\n-10\n-228\n-116\n-174\n-860\n-837\n-796\n-392\n-380\n-403\n-886\n-360\n-200\n-38\n-544\n-448\n-281\n-218\n-132\n-571\n-650\n-666\n-332\n-130\n-618\n-306\n-272\n-95\n-110\n-804\n-25\n-61\n-114\n-369\n-675\n-58\n-341\n-543\n-477\n-936\n-617\n-684\n-803\n-40\n-285\n-919\n-72\n-685\n-318\n-107\n-210\n-926\n-600\n-130\n-707\n-355\n-221\n-951\n-687\n-599\n-745\n-889\n-10\n-188\n-687\n-191\n-789\n-44\n-774\n-53\n-738\n-889\n-332\n-575\n-838\n-975\n-224\n-720\n-910\n-478\n-35\n-740\n-549\n-911\n-624\n-596\n-865\n-485\n-476\n-348\n-664\n-674\n-597\n-839\n-698\n-746\n-527\n-95\n-623\n-662\n-795\n-287\n-969\n-21\n-730\n-191\n-866'
jump_list = [int(x) for x in INPUT.split('\n')]
current_index = 0
steps_taken = 0
while 0 <= current_index < len(jump_list):
current_jump = jump_list[current_index]
jump_list[current_index] += 1
current_index += current_jump
steps_taken += 1
print('V1 Final index: %d, steps taken: %d' % (current_index, steps_taken))
jump_list = [int(x) for x in INPUT.split('\n')]
current_index = 0
steps_taken = 0
while 0 <= current_index < len(jump_list):
current_jump = jump_list[current_index]
if current_jump >= 3:
jump_list[current_index] -= 1
else:
jump_list[current_index] += 1
current_index += current_jump
steps_taken += 1
print('V2 Final index: %d, steps taken: %d' % (current_index, steps_taken)) |
class ApiError(Exception):
pass
class AuthorizationFailed(Exception):
pass
| class Apierror(Exception):
pass
class Authorizationfailed(Exception):
pass |
s = 'one two one two one'
print(s.replace('one', 'two').replace('two', 'one'))
# one one one one one
print(s.replace('one', 'X').replace('two', 'one').replace('X', 'two'))
# two one two one two
def swap_str(s_org, s1, s2, temp='*q@w-e~r^'):
return s_org.replace(s1, temp).replace(s2, s1).replace(temp, s2)
print(swap_str(s, 'one', 'two'))
# two one two one two
print(s.replace('o', 't').replace('t', 'o'))
# one owo one owo one
print(s.translate(str.maketrans({'o': 't', 't': 'o'})))
# tne owt tne owt tne
print(s.translate(str.maketrans('ot', 'to')))
# tne owt tne owt tne
| s = 'one two one two one'
print(s.replace('one', 'two').replace('two', 'one'))
print(s.replace('one', 'X').replace('two', 'one').replace('X', 'two'))
def swap_str(s_org, s1, s2, temp='*q@w-e~r^'):
return s_org.replace(s1, temp).replace(s2, s1).replace(temp, s2)
print(swap_str(s, 'one', 'two'))
print(s.replace('o', 't').replace('t', 'o'))
print(s.translate(str.maketrans({'o': 't', 't': 'o'})))
print(s.translate(str.maketrans('ot', 'to'))) |
# TODO: create functions for data sending
async def send_data(event, buttons):
pass
| async def send_data(event, buttons):
pass |
n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
c = input().split()
if c[0] == "update":
s.update(set(map(int, input().split())))
elif c[0] == "intersection_update":
s.intersection_update(set(map(int, input().split())))
elif c[0] == "difference_update":
s.difference_update(set(map(int, input().split())))
else:
s.symmetric_difference_update(set(map(int, input().split())))
print(sum(s)) | n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
c = input().split()
if c[0] == 'update':
s.update(set(map(int, input().split())))
elif c[0] == 'intersection_update':
s.intersection_update(set(map(int, input().split())))
elif c[0] == 'difference_update':
s.difference_update(set(map(int, input().split())))
else:
s.symmetric_difference_update(set(map(int, input().split())))
print(sum(s)) |
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def right_view_util(root, max_level, level):
if not root:
return
if max_level[0] < level:
print(root.val)
max_level[0] = level
right_view_util(root.right, max_level, level+1)
right_view_util(root.left, max_level, level+1)
def right_view(root):
max_level = [0]
right_view_util(root, max_level, 1)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
right_view(root)
| class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def right_view_util(root, max_level, level):
if not root:
return
if max_level[0] < level:
print(root.val)
max_level[0] = level
right_view_util(root.right, max_level, level + 1)
right_view_util(root.left, max_level, level + 1)
def right_view(root):
max_level = [0]
right_view_util(root, max_level, 1)
root = node(1)
root.left = node(2)
root.right = node(3)
root.left.left = node(4)
root.left.right = node(5)
root.right.left = node(6)
root.right.right = node(7)
root.right.left.right = node(8)
right_view(root) |
def removeDuplicates(nums):
"""
:type nums: List[int] - sorted
:rtype: List[int]
"""
i = 0
for j in range(len(nums)):
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
return nums[0: i + 1]
print(removeDuplicates([1, 1, 2, 3, 3, 3, 5]))
print(removeDuplicates([])) | def remove_duplicates(nums):
"""
:type nums: List[int] - sorted
:rtype: List[int]
"""
i = 0
for j in range(len(nums)):
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
return nums[0:i + 1]
print(remove_duplicates([1, 1, 2, 3, 3, 3, 5]))
print(remove_duplicates([])) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# # https://oj.leetcode.com/problems/symmetric-tree
# Given a binary tree, check whether it is a mirror of itself
# (ie, symmetric around its center).
# For example, this binary tree is symmetric:
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
#
# But the following is not:
# 1
# / \
# 2 2
# \ \
# 3 3
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
def isSym(L, R):
if not L and not R:
return True
if L and R and L.val == R.val:
return isSym(L.left, R.right) and isSym(L.right, R.left)
return False
return isSym(root, root)
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
tree = \
TreeNode(1,
TreeNode(2,
TreeNode(3),
TreeNode(4) \
),
TreeNode(2,
TreeNode(4),
TreeNode(3)
)
)
s = Solution()
r = s.isSymmetric(tree)
print(r)
| class Solution(object):
def is_symmetric(self, root):
def is_sym(L, R):
if not L and (not R):
return True
if L and R and (L.val == R.val):
return is_sym(L.left, R.right) and is_sym(L.right, R.left)
return False
return is_sym(root, root)
class Treenode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
tree = tree_node(1, tree_node(2, tree_node(3), tree_node(4)), tree_node(2, tree_node(4), tree_node(3)))
s = solution()
r = s.isSymmetric(tree)
print(r) |
# These regexes must not include line anchors ('^', '$'). Those will be added by the
# ValidateRegex library function and anybody else who needs them.
NAME_VALIDATION = r"(?P<name>[@\-\w\.]+)"
# This regex needs to exactly match the above, EXCEPT that the name should be "name2". So if the
# above regex changes, change this one. This is kind of gross. :\
NAME2_VALIDATION = r"(?P<name2>[@\-\w\.]+)"
# Regexes for validating permission/argument names
PERMISSION_VALIDATION = r"(?P<name>(?:[a-z0-9]+[_\-\.])*[a-z0-9]+)"
PERMISSION_WILDCARD_VALIDATION = r"(?P<name>(?:[a-z0-9]+[_\-\.])*[a-z0-9]+(?:\.\*)?)"
ARGUMENT_VALIDATION = r"(?P<argument>|\*|[\w=+/.:-]+\*?)"
# Global permission names to prevent stringly typed things
PERMISSION_GRANT = "grouper.permission.grant"
PERMISSION_CREATE = "grouper.permission.create"
PERMISSION_AUDITOR = "grouper.permission.auditor"
AUDIT_MANAGER = "grouper.audit.manage"
AUDIT_VIEWER = "grouper.audit.view"
# Permissions that are always created and are reserved.
SYSTEM_PERMISSIONS = [
(PERMISSION_CREATE, "Ability to create permissions within Grouper."),
(PERMISSION_GRANT, "Ability to grant a permission to a group."),
(PERMISSION_AUDITOR, "Ability to own or manage groups with audited permissions."),
(AUDIT_MANAGER, "Ability to start global audits and view audit status."),
(AUDIT_VIEWER, "Ability to view audit results and status."),
]
# Used to construct name tuples in notification engine.
ILLEGAL_NAME_CHARACTER = '|'
# A list of regular expressions that are reserved anywhere names are created. I.e., if a regex
# in this list is matched, a permission cannot be created in the UI. Same with group names.
# These are case insensitive.
RESERVED_NAMES = [
r"^grouper",
r"^admin",
r"^test",
r"^[^.]*$",
r"^[0-9]+$", # Reserved in order to select user or group by id.
r".*\|.*",
]
# Maximum length a name can be. This applies to user names and permission arguments.
MAX_NAME_LENGTH = 128
| name_validation = '(?P<name>[@\\-\\w\\.]+)'
name2_validation = '(?P<name2>[@\\-\\w\\.]+)'
permission_validation = '(?P<name>(?:[a-z0-9]+[_\\-\\.])*[a-z0-9]+)'
permission_wildcard_validation = '(?P<name>(?:[a-z0-9]+[_\\-\\.])*[a-z0-9]+(?:\\.\\*)?)'
argument_validation = '(?P<argument>|\\*|[\\w=+/.:-]+\\*?)'
permission_grant = 'grouper.permission.grant'
permission_create = 'grouper.permission.create'
permission_auditor = 'grouper.permission.auditor'
audit_manager = 'grouper.audit.manage'
audit_viewer = 'grouper.audit.view'
system_permissions = [(PERMISSION_CREATE, 'Ability to create permissions within Grouper.'), (PERMISSION_GRANT, 'Ability to grant a permission to a group.'), (PERMISSION_AUDITOR, 'Ability to own or manage groups with audited permissions.'), (AUDIT_MANAGER, 'Ability to start global audits and view audit status.'), (AUDIT_VIEWER, 'Ability to view audit results and status.')]
illegal_name_character = '|'
reserved_names = ['^grouper', '^admin', '^test', '^[^.]*$', '^[0-9]+$', '.*\\|.*']
max_name_length = 128 |
def check(n):
sqlist = str(n**2)# list(map(int,str(n**2)))
l = len(sqlist)
if l%2 == 0: #if even
rsq = int(sqlist[l//2:])
lsq = int(sqlist[:l//2])
else:
rsq = int(sqlist[(l-1)//2:])
if l!= 1:
lsq = int(sqlist[:(l-1)//2])
else:
lsq = 0 #only lsq can have an empty list
if rsq + lsq == n:
return True
p = int(input())
q = int(input())
ans = []
for i in range(p, q+1):
if check(i) == True:
ans.append(i)
if len(ans)!= 0:
for i in ans:
print(i, end =' ')
else:
print('INVALID RANGE')
#for i in [1,9,45,55,99]:
#print(check(i))
| def check(n):
sqlist = str(n ** 2)
l = len(sqlist)
if l % 2 == 0:
rsq = int(sqlist[l // 2:])
lsq = int(sqlist[:l // 2])
else:
rsq = int(sqlist[(l - 1) // 2:])
if l != 1:
lsq = int(sqlist[:(l - 1) // 2])
else:
lsq = 0
if rsq + lsq == n:
return True
p = int(input())
q = int(input())
ans = []
for i in range(p, q + 1):
if check(i) == True:
ans.append(i)
if len(ans) != 0:
for i in ans:
print(i, end=' ')
else:
print('INVALID RANGE') |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
AUTHOR = 'Ben Poile'
SITENAME = 'blog'
SITEURL = 'https://poiley.github.io'
# GITHUB_URL = 'https://github.com/poiley/poiley.github.io'
PATH = 'content'
OUTPUT_PATH = 'output'
STATIC_PATHS = ['articles', 'downloads']
ARTICLE_PATHS = ['articles',]
ARTICLE_URL = 'articles/{date:%Y}/{date:%m}/{slug}.html'
ARTICLE_SAVE_AS = 'articles/{date:%Y}/{date:%m}/{slug}.html'
TIMEZONE = 'America/Los_Angeles'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blog Roll
LINKS = (('Home', 'https://poile.dev/'),
('All Posts', 'https://www.python.org/'),
('Resume', 'https://docs.google.com/document/d/1T2MaWT8CHgR9t5hDoQqLDpXZYJ5eKKwgfJBa2nVceo0/edit?usp=sharing'))
# Social widget
SOCIAL = (('Github', 'https://github.com/poiley'),
('Spotify', 'https://open.spotify.com/user/qqxne71rxqru593o2cg1y8avg?si=fb593f2b738f4402'),
('Twitter', 'https://twitter.com/_poile_'))
DEFAULT_PAGINATION = 3
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
THEME = 'theme'
#DIRECT_TEMPLATES = (('index', 'blog', 'tags', 'categories', 'archives'))
#PAGINATED_DIRECT_TEMPLATES = (('blog', ))
#TEMPLATE_PAGES = {'home.html': 'index.html',}
| author = 'Ben Poile'
sitename = 'blog'
siteurl = 'https://poiley.github.io'
path = 'content'
output_path = 'output'
static_paths = ['articles', 'downloads']
article_paths = ['articles']
article_url = 'articles/{date:%Y}/{date:%m}/{slug}.html'
article_save_as = 'articles/{date:%Y}/{date:%m}/{slug}.html'
timezone = 'America/Los_Angeles'
default_lang = 'en'
feed_all_atom = None
category_feed_atom = None
translation_feed_atom = None
author_feed_atom = None
author_feed_rss = None
links = (('Home', 'https://poile.dev/'), ('All Posts', 'https://www.python.org/'), ('Resume', 'https://docs.google.com/document/d/1T2MaWT8CHgR9t5hDoQqLDpXZYJ5eKKwgfJBa2nVceo0/edit?usp=sharing'))
social = (('Github', 'https://github.com/poiley'), ('Spotify', 'https://open.spotify.com/user/qqxne71rxqru593o2cg1y8avg?si=fb593f2b738f4402'), ('Twitter', 'https://twitter.com/_poile_'))
default_pagination = 3
theme = 'theme' |
class SomethingAbstract:
property_a: str
property_b: str
property_c: Optional[str]
property_d: Optional[str]
def __init__(
self,
property_a: str,
property_b: str,
property_c: Optional[str] = None,
property_d: Optional[str] = None,
) -> None:
self.property_a = property_a
self.property_b = property_b
self.property_c = property_c
self.property_d = property_d
class Something(SomethingAbstract):
property_e: str
property_f: str
property_g: Optional[str]
property_h: Optional[str]
# NOTE (mristin, 2022-03-25):
# The order of the inherited and defined properties do not match the order of
# the constructor arguments.
def __init__(
self,
property_e: str,
property_f: str,
property_a: str,
property_b: str,
property_g: Optional[str] = None,
property_h: Optional[str] = None,
property_c: Optional[str] = None,
property_d: Optional[str] = None,
) -> None:
SomethingAbstract.__init__(
self,
property_a=property_a,
property_b=property_b,
property_c=property_c,
property_d=property_d,
)
self.property_e = property_e
self.property_f = property_f
self.property_g = property_g
self.property_h = property_h
__book_url__ = "dummy"
__book_version__ = "dummy"
| class Somethingabstract:
property_a: str
property_b: str
property_c: Optional[str]
property_d: Optional[str]
def __init__(self, property_a: str, property_b: str, property_c: Optional[str]=None, property_d: Optional[str]=None) -> None:
self.property_a = property_a
self.property_b = property_b
self.property_c = property_c
self.property_d = property_d
class Something(SomethingAbstract):
property_e: str
property_f: str
property_g: Optional[str]
property_h: Optional[str]
def __init__(self, property_e: str, property_f: str, property_a: str, property_b: str, property_g: Optional[str]=None, property_h: Optional[str]=None, property_c: Optional[str]=None, property_d: Optional[str]=None) -> None:
SomethingAbstract.__init__(self, property_a=property_a, property_b=property_b, property_c=property_c, property_d=property_d)
self.property_e = property_e
self.property_f = property_f
self.property_g = property_g
self.property_h = property_h
__book_url__ = 'dummy'
__book_version__ = 'dummy' |
text = open("subInfo.txt").read()
def findCount(sub):
count = 0
terms = open(sub).readlines()
terms = [t.strip().lower() for t in terms]
for t in terms:
if t in text:
count += 1
return count
subArr = []
subArr.append((findCount("biology_terms.txt"), "biology_terms.txt"))
subArr.append((findCount("chemistry_terms.txt"), "chemistry_terms.txt"))
subArr.append((findCount("History_terms.txt"), "History_terms.txt"))
subArr.append((findCount("physics_terms.txt"), "physics_terms.txt"))
subArr.append((findCount("math_terms.txt"), "math_terms.txt"))
subArr = sorted(subArr)[::-1]
print(subArr)
print(subArr[0][1])
| text = open('subInfo.txt').read()
def find_count(sub):
count = 0
terms = open(sub).readlines()
terms = [t.strip().lower() for t in terms]
for t in terms:
if t in text:
count += 1
return count
sub_arr = []
subArr.append((find_count('biology_terms.txt'), 'biology_terms.txt'))
subArr.append((find_count('chemistry_terms.txt'), 'chemistry_terms.txt'))
subArr.append((find_count('History_terms.txt'), 'History_terms.txt'))
subArr.append((find_count('physics_terms.txt'), 'physics_terms.txt'))
subArr.append((find_count('math_terms.txt'), 'math_terms.txt'))
sub_arr = sorted(subArr)[::-1]
print(subArr)
print(subArr[0][1]) |
class eAxes:
xAxis, yAxis, zAxis = range(3)
class eTurn:
learner, simulator = range(2)
class eEPA:
evaluation, potency, activity = range(3)
evaluationSelf, potencySelf, activitySelf,\
evaluationAction, potencyAction, activityAction,\
evaluationOther, potencyOther, activityOther = range(9)
fundamental, tau = range(2)
class eIdentityParse:
identity, maleEvaluation, malePotency, maleActivity,\
femaleEvaluation, femalePotency, femaleActivity, institution = range(8)
class eAgentListBoxParam:
identity, maleSentiment, femaleSentiment, institution = range(4)
class eInstitutions:
gender, institution, undefined = range(3)
class eInteractants:
agent, client = range(2)
class eGender:
male, female = range(2)
class eGenderKey:
anyGender, male, female = range(3)
class eGui:
simulator, interactive = range(2)
class eRect:
fromLeft, fromBottom, fractionOfX, fractionOfY = range(4) | class Eaxes:
(x_axis, y_axis, z_axis) = range(3)
class Eturn:
(learner, simulator) = range(2)
class Eepa:
(evaluation, potency, activity) = range(3)
(evaluation_self, potency_self, activity_self, evaluation_action, potency_action, activity_action, evaluation_other, potency_other, activity_other) = range(9)
(fundamental, tau) = range(2)
class Eidentityparse:
(identity, male_evaluation, male_potency, male_activity, female_evaluation, female_potency, female_activity, institution) = range(8)
class Eagentlistboxparam:
(identity, male_sentiment, female_sentiment, institution) = range(4)
class Einstitutions:
(gender, institution, undefined) = range(3)
class Einteractants:
(agent, client) = range(2)
class Egender:
(male, female) = range(2)
class Egenderkey:
(any_gender, male, female) = range(3)
class Egui:
(simulator, interactive) = range(2)
class Erect:
(from_left, from_bottom, fraction_of_x, fraction_of_y) = range(4) |
"""
MyMCAdmin system
"""
| """
MyMCAdmin system
""" |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: Alan
@time: 2021/05/18
"""
| """
@author: Alan
@time: 2021/05/18
""" |
cars=["Maruthi","Honda","TataIndica"]
x = cars[0]
print("x=\n",x)
cars[0]="Ford"
print("cars=\n",cars)
L = len(cars)
print("Length of cars=",L)
#Print each item in the car array
for y in cars:
print(y)
cars.append("BMW")
print("cars=\n",cars)
#Delete the second element of the cars array
cars.pop(1)
print("cars=\n",cars)
#Delete the element that has the value "Honda"
cars.remove('TataIndica')
print("cars=\n",cars)
#Result
##x= Maruthi
##cars= ['Ford', 'Honda', 'TataIndica']
##Length of cars= 3
##Ford
##Honda
##TataIndica
##cars= ['Ford', 'Honda', 'TataIndica', 'BMW']
##cars= ['Ford', 'TataIndica', 'BMW']
##cars= ['Ford', 'BMW']
| cars = ['Maruthi', 'Honda', 'TataIndica']
x = cars[0]
print('x=\n', x)
cars[0] = 'Ford'
print('cars=\n', cars)
l = len(cars)
print('Length of cars=', L)
for y in cars:
print(y)
cars.append('BMW')
print('cars=\n', cars)
cars.pop(1)
print('cars=\n', cars)
cars.remove('TataIndica')
print('cars=\n', cars) |
guests = ["Mark", "Kevin", "Mellisa"]
msg = "I'd like to invite you to have a dinner with us on 5/18. Thanks, Andrew"
print(f"Hi {guests[0]}, {msg}")
print(f"Hi {guests[1]}, {msg}")
print(f"Hi {guests[2]}, {msg}")
print(f"\nSorry, {guests[1]} can't make it.\n")
guests[1] = "Ace"
print(f"Hi {guests[0]}, {msg}")
print(f"Hi {guests[1]}, {msg}")
print(f"Hi {guests[2]}, {msg}")
| guests = ['Mark', 'Kevin', 'Mellisa']
msg = "I'd like to invite you to have a dinner with us on 5/18. Thanks, Andrew"
print(f'Hi {guests[0]}, {msg}')
print(f'Hi {guests[1]}, {msg}')
print(f'Hi {guests[2]}, {msg}')
print(f"\nSorry, {guests[1]} can't make it.\n")
guests[1] = 'Ace'
print(f'Hi {guests[0]}, {msg}')
print(f'Hi {guests[1]}, {msg}')
print(f'Hi {guests[2]}, {msg}') |
# Problem Set 1a
# Name: Eloi Gil
# Time Spent: 1
#
balance = float(input('balance: '))
annualInterestRate = float(input('annual interest rate: '))
minMonthlyPaymentRate = float(input('minimum monthly payment rate: '))
month = 0.0
while month < 12.0:
month += 1.0
print('Month ' + str(month))
minMonthlyPayment = round(balance * minMonthlyPaymentRate, 2)
print('minimum monthly payment: ' + str(minMonthlyPayment))
interestPaid = round(annualInterestRate / 12.0 * balance, 2)
principlePaid = round(minMonthlyPayment - interestPaid, 2)
print('principle paid: ' + str(principlePaid))
balance -= round(principlePaid, 2)
print('remaining balance: ' + str(round(balance, 2)))
| balance = float(input('balance: '))
annual_interest_rate = float(input('annual interest rate: '))
min_monthly_payment_rate = float(input('minimum monthly payment rate: '))
month = 0.0
while month < 12.0:
month += 1.0
print('Month ' + str(month))
min_monthly_payment = round(balance * minMonthlyPaymentRate, 2)
print('minimum monthly payment: ' + str(minMonthlyPayment))
interest_paid = round(annualInterestRate / 12.0 * balance, 2)
principle_paid = round(minMonthlyPayment - interestPaid, 2)
print('principle paid: ' + str(principlePaid))
balance -= round(principlePaid, 2)
print('remaining balance: ' + str(round(balance, 2))) |
s=0
for c in range(0,4):
n= int(input('Digite um valor: '))
s += n
print('Somatorio deu: {}' .format(s)) | s = 0
for c in range(0, 4):
n = int(input('Digite um valor: '))
s += n
print('Somatorio deu: {}'.format(s)) |
__title__ = 'DRF Exception Handler'
__version__ = '1.0.1'
__author__ = 'Thomas'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 Thomas'
# Version synonym
VERSION = __version__
| __title__ = 'DRF Exception Handler'
__version__ = '1.0.1'
__author__ = 'Thomas'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 Thomas'
version = __version__ |
{
"targets": [
{
"target_name": "boost-property_tree",
"type": "none",
"include_dirs": [
"1.57.0/property_tree-boost-1.57.0/include"
],
"all_dependent_settings": {
"include_dirs": [
"1.57.0/property_tree-boost-1.57.0/include"
]
},
"dependencies": [
"../boost-config/boost-config.gyp:*",
"../boost-serialization/boost-serialization.gyp:*",
"../boost-assert/boost-assert.gyp:*",
"../boost-optional/boost-optional.gyp:*",
"../boost-throw_exception/boost-throw_exception.gyp:*",
"../boost-core/boost-core.gyp:*",
"../boost-spirit/boost-spirit.gyp:*",
"../boost-static_assert/boost-static_assert.gyp:*",
"../boost-multi_index/boost-multi_index.gyp:*",
"../boost-mpl/boost-mpl.gyp:*",
"../boost-any/boost-any.gyp:*",
"../boost-iterator/boost-iterator.gyp:*"
]
} ,
# note the json parser is the only part of boost-property_tree
# using boost-spirit
{
"target_name": "boost-property_tree_test_json_parser",
"type": "executable",
"test": {},
"sources": [ "1.57.0/property_tree-boost-1.57.0/test/test_json_parser.cpp" ],
"dependencies": [ "boost-property_tree"],
# this disables building the example on iOS
"conditions": [
["OS=='iOS'",
{
"type": "none"
}
],
["OS=='mac'",
{
"type": "none"
}
]
]
}
]
}
| {'targets': [{'target_name': 'boost-property_tree', 'type': 'none', 'include_dirs': ['1.57.0/property_tree-boost-1.57.0/include'], 'all_dependent_settings': {'include_dirs': ['1.57.0/property_tree-boost-1.57.0/include']}, 'dependencies': ['../boost-config/boost-config.gyp:*', '../boost-serialization/boost-serialization.gyp:*', '../boost-assert/boost-assert.gyp:*', '../boost-optional/boost-optional.gyp:*', '../boost-throw_exception/boost-throw_exception.gyp:*', '../boost-core/boost-core.gyp:*', '../boost-spirit/boost-spirit.gyp:*', '../boost-static_assert/boost-static_assert.gyp:*', '../boost-multi_index/boost-multi_index.gyp:*', '../boost-mpl/boost-mpl.gyp:*', '../boost-any/boost-any.gyp:*', '../boost-iterator/boost-iterator.gyp:*']}, {'target_name': 'boost-property_tree_test_json_parser', 'type': 'executable', 'test': {}, 'sources': ['1.57.0/property_tree-boost-1.57.0/test/test_json_parser.cpp'], 'dependencies': ['boost-property_tree'], 'conditions': [["OS=='iOS'", {'type': 'none'}], ["OS=='mac'", {'type': 'none'}]]}]} |
"""
hello_world.py
Simple Hello World program.
ECE196 Face Recognition Project
Author: Will Chen
1. Write a Write a program that prints "Hello World!" and uses the main function convention.
"""
# TODO: Write a program that prints "Hello World!" and uses a main function.
def main():
print("Hello World!")
if(__name__ == '__main__'):
main()
| """
hello_world.py
Simple Hello World program.
ECE196 Face Recognition Project
Author: Will Chen
1. Write a Write a program that prints "Hello World!" and uses the main function convention.
"""
def main():
print('Hello World!')
if __name__ == '__main__':
main() |
def between_markers(text,mark1,mark2):
'''
You are given a string and two markers (the initial one and final). You have to find a substring enclosed between these two markers. But there are a few important conditions.
This is a simplified version of the Between Markers mission.
The initial and final markers are always different.
The initial and final markers are always 1 char size.
The initial and final markers always exist in a string and go one after another.
Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers.
Output: A string.
Precondition: There can't be more than one final and one initial markers.
'''
if mark1 and mark2 in text:
i1 = text.index(mark1)
i2 = text.index(mark2)
if i1<i2:
return text[text.index(mark1)+1:text.index(mark2)]
if __name__ == '__main__':
print('Example:')
print(between_markers('What is >apple<', '>', '<'))
print(between_markers('What is [apple]', '[', ']'))
print(between_markers('What is ><', '>', '<'))
print(between_markers('>apple<', '>', '<'))
print(between_markers('an -apologize> to read', '-', '>'))
| def between_markers(text, mark1, mark2):
"""
You are given a string and two markers (the initial one and final). You have to find a substring enclosed between these two markers. But there are a few important conditions.
This is a simplified version of the Between Markers mission.
The initial and final markers are always different.
The initial and final markers are always 1 char size.
The initial and final markers always exist in a string and go one after another.
Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers.
Output: A string.
Precondition: There can't be more than one final and one initial markers.
"""
if mark1 and mark2 in text:
i1 = text.index(mark1)
i2 = text.index(mark2)
if i1 < i2:
return text[text.index(mark1) + 1:text.index(mark2)]
if __name__ == '__main__':
print('Example:')
print(between_markers('What is >apple<', '>', '<'))
print(between_markers('What is [apple]', '[', ']'))
print(between_markers('What is ><', '>', '<'))
print(between_markers('>apple<', '>', '<'))
print(between_markers('an -apologize> to read', '-', '>')) |
# Copyright (C) 2017 Tiancheng Zhao, Carnegie Mellon University
class KgCVAEConfig(object):
description= None
use_hcf = True # use dialog act in training (if turn off kgCVAE -> CVAE)
update_limit = 3000 # the number of mini-batch before evaluating the model
# how to encode utterance.
# bow: add word embedding together
# rnn: RNN utterance encoder
# bi_rnn: bi_directional RNN utterance encoder
sent_type = "bi_rnn"
# latent variable (gaussian variable)
latent_size = 200 # the dimension of latent variable
full_kl_step = 10000 # how many batch before KL cost weight reaches 1.0
dec_keep_prob = 1.0 # do we use word drop decoder [Bowman el al 2015]
# Network general
cell_type = "gru" # gru or lstm
embed_size = 200 # word embedding size
topic_embed_size = 30 # topic embedding size
da_embed_size = 30 # dialog act embedding size
cxt_cell_size = 600 # context encoder hidden size
sent_cell_size = 300 # utterance encoder hidden size
dec_cell_size = 400 # response decoder hidden size
backward_size = 10 # how many utterance kept in the context window
step_size = 1 # internal usage
max_utt_len = 40 # max number of words in an utterance
num_layer = 1 # number of context RNN layers
# Optimization parameters
op = "adam"
grad_clip = 5.0 # gradient abs max cut
init_w = 0.08 # uniform random from [-init_w, init_w]
batch_size = 30 # mini-batch size
init_lr = 0.001 # initial learning rate
lr_hold = 1 # only used by SGD
lr_decay = 0.6 # only used by SGD
keep_prob = 1.0 # drop out rate
improve_threshold = 0.996 # for early stopping
patient_increase = 2.0 # for early stopping
early_stop = True
max_epoch = 60 # max number of epoch of training
grad_noise = 0.0 # inject gradient noise?
| class Kgcvaeconfig(object):
description = None
use_hcf = True
update_limit = 3000
sent_type = 'bi_rnn'
latent_size = 200
full_kl_step = 10000
dec_keep_prob = 1.0
cell_type = 'gru'
embed_size = 200
topic_embed_size = 30
da_embed_size = 30
cxt_cell_size = 600
sent_cell_size = 300
dec_cell_size = 400
backward_size = 10
step_size = 1
max_utt_len = 40
num_layer = 1
op = 'adam'
grad_clip = 5.0
init_w = 0.08
batch_size = 30
init_lr = 0.001
lr_hold = 1
lr_decay = 0.6
keep_prob = 1.0
improve_threshold = 0.996
patient_increase = 2.0
early_stop = True
max_epoch = 60
grad_noise = 0.0 |
# Cast to int
x = int(100) # x will be 100
y = int(5.75) # y will be 5
z = int("32") # z will be 32
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
# cast to float
a = float(100) # x will be 100.0
b = float(5.75) # y will be 5.75
c = float("32") # z will be 32.0
d = float("32.5") # z will be 32.5
print(a)
print(b)
print(c)
print(d)
print(type(a))
print(type(b))
print(type(c))
print(type(d))
# cast to str
s1 = str("s1") # will be "s1"
s2 = str(100) # will be "100"
s3 = str(5.75) # will be "5.75"
print(s1)
print(s2)
print(s3)
print(type(s1))
print(type(s2))
print(type(s3))
# concatenate number (int/float) with str, bust be explicit casting
result = "The result is: " + str(b)
print(result)
| x = int(100)
y = int(5.75)
z = int('32')
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
a = float(100)
b = float(5.75)
c = float('32')
d = float('32.5')
print(a)
print(b)
print(c)
print(d)
print(type(a))
print(type(b))
print(type(c))
print(type(d))
s1 = str('s1')
s2 = str(100)
s3 = str(5.75)
print(s1)
print(s2)
print(s3)
print(type(s1))
print(type(s2))
print(type(s3))
result = 'The result is: ' + str(b)
print(result) |
class MetadataHolder():
def set_metadata(self, key, value):
self.client.api.call_function('set_metadata', {
'entity_type': self._data['type'],
'entity_id': self.id,
'key': key,
'value': value
})
def set_metadata_dict(self, metadata_dict):
self.client.api.call_function('set_metadata_dict', {
'entity_type': self._data['type'],
'entity_id': self.id,
'metadata': metadata_dict,
})
def get_metadata(self):
return self.client.api.call_function('get_metadata', {
'entity_type': self._data['type'],
'entity_id': self.id,
})
| class Metadataholder:
def set_metadata(self, key, value):
self.client.api.call_function('set_metadata', {'entity_type': self._data['type'], 'entity_id': self.id, 'key': key, 'value': value})
def set_metadata_dict(self, metadata_dict):
self.client.api.call_function('set_metadata_dict', {'entity_type': self._data['type'], 'entity_id': self.id, 'metadata': metadata_dict})
def get_metadata(self):
return self.client.api.call_function('get_metadata', {'entity_type': self._data['type'], 'entity_id': self.id}) |
"""VIMS generic errors."""
class VIMSError(Exception):
"""Generic VIMS error."""
class VIMSCameraError(VIMSError):
"""Generic VIMS Camera error."""
| """VIMS generic errors."""
class Vimserror(Exception):
"""Generic VIMS error."""
class Vimscameraerror(VIMSError):
"""Generic VIMS Camera error.""" |
'''
Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.
Example 1:
Input: preorder = [5,2,1,3,6]
Output: true
Example 2:
Input: preorder = [5,2,6,1,3]
Output: false
'''
# Convert to Inorder and check if sorted or not
# TC O(N) and Space O(N)
class Solution(object):
def to_inorder(self, preorder):
# O(N) TC and O(N) Space
stack = deque()
inorder = []
for pre in preorder:
while stack and pre > stack[-1]:
inorder.append(stack.pop())
stack.append(pre)
while stack:
inorder.append(stack.pop())
return inorder
def verifyPreorder(self, preorder):
inorder = self.to_inorder(preorder)
for elem in range(1, len(inorder)):
if inorder[elem - 1] > inorder[elem]:
return False
return True
| """
Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.
Example 1:
Input: preorder = [5,2,1,3,6]
Output: true
Example 2:
Input: preorder = [5,2,6,1,3]
Output: false
"""
class Solution(object):
def to_inorder(self, preorder):
stack = deque()
inorder = []
for pre in preorder:
while stack and pre > stack[-1]:
inorder.append(stack.pop())
stack.append(pre)
while stack:
inorder.append(stack.pop())
return inorder
def verify_preorder(self, preorder):
inorder = self.to_inorder(preorder)
for elem in range(1, len(inorder)):
if inorder[elem - 1] > inorder[elem]:
return False
return True |
'''
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
'''
# Since every node can only have one parent,
# in case we're inside a cycle the last node we visit
# will have 2 parents
# In the case we have an edge going in both directions
# we can just check if the number of parents of the current node and their
# childs is just equal to one
# In the case when we have 2 or more connected components, when we see
# A node that has no parent and it's different from 0 then we have found
# a connected component
def find_root(n, lC, rC): # The root can be any of the n nodes
aux_arr = [0]*n # See test case 36
# So first we have to find it
# We are just looking the node that No
# of parents == 0
for i in range(n):
l, r = lC[i], rC[i]
if l != -1:
aux_arr[l] += 1
if r != -1:
aux_arr[r] += 1
root = -1
for i in range(n):
if aux_arr[i] == 0:
root = i
break
return root
def validateBinaryTreeNodes(n, leftChild, rightChild):
root = find_root(n, leftChild, rightChild)
if root == -1:
return False
visited = [0]*n
queue = [root]
visited[root] = 1
while queue:
curr = queue.pop(0)
l, r = leftChild[curr], rightChild[curr]
if l != -1:
if visited[l] == 1:
return False
visited[l] = 1
queue.append(l)
if r != -1:
if visited[r] == 1:
return False
visited[r] = 1
queue.append(r)
for node in visited:
if node == 0:
return False
return True
| """
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
"""
def find_root(n, lC, rC):
aux_arr = [0] * n
for i in range(n):
(l, r) = (lC[i], rC[i])
if l != -1:
aux_arr[l] += 1
if r != -1:
aux_arr[r] += 1
root = -1
for i in range(n):
if aux_arr[i] == 0:
root = i
break
return root
def validate_binary_tree_nodes(n, leftChild, rightChild):
root = find_root(n, leftChild, rightChild)
if root == -1:
return False
visited = [0] * n
queue = [root]
visited[root] = 1
while queue:
curr = queue.pop(0)
(l, r) = (leftChild[curr], rightChild[curr])
if l != -1:
if visited[l] == 1:
return False
visited[l] = 1
queue.append(l)
if r != -1:
if visited[r] == 1:
return False
visited[r] = 1
queue.append(r)
for node in visited:
if node == 0:
return False
return True |
# Nesse exemplo retorna uma lista ordenada
lista = [1,5,3,2,7,50,9]
def bubbleSort(list):
for i in range(len(list)):
for j in range(0, len(list) - 1 - i):
if (list[j] > list[j+1]):
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
return list
if __name__ == "__main__":
bubbleSort(lista) | lista = [1, 5, 3, 2, 7, 50, 9]
def bubble_sort(list):
for i in range(len(list)):
for j in range(0, len(list) - 1 - i):
if list[j] > list[j + 1]:
temp = list[j]
list[j] = list[j + 1]
list[j + 1] = temp
return list
if __name__ == '__main__':
bubble_sort(lista) |
# General settings
HOST = "irc.twitch.tv"
PORT = 6667
COOLDOWN = 10 #Global cooldown for commands (in seconds)
# Bot account settings
PASS = "oauth:abcabcabcabcabcabcacb1231231231"
IDENT = "bot_username"
# Channel owner settings
CHANNEL = "channel_owner_username" #The username of your Twitch account (lowercase)
CHANNELPASS = "oauth:abcabcbaacbacbabcbac123456789" #The oauth token for the channel owner's Twitch account (the whole thing, including "oauth:")
GAMES = [['Sample Game', 'sg', 'Sample Platform', 'sp64'], ['Sample Game 2', 'sg2', 'Sample Platform', 'sp64']]
CATEGORIES = [['Sample Category 1', 'sample_1'], ['Sample Category 2', 'sample_2']]
SRC_USERNAME = CHANNEL
| host = 'irc.twitch.tv'
port = 6667
cooldown = 10
pass = 'oauth:abcabcabcabcabcabcacb1231231231'
ident = 'bot_username'
channel = 'channel_owner_username'
channelpass = 'oauth:abcabcbaacbacbabcbac123456789'
games = [['Sample Game', 'sg', 'Sample Platform', 'sp64'], ['Sample Game 2', 'sg2', 'Sample Platform', 'sp64']]
categories = [['Sample Category 1', 'sample_1'], ['Sample Category 2', 'sample_2']]
src_username = CHANNEL |
class Health(object):
"""
Represents a Health object used by the HealthDetails resource.
"""
def __init__(self, status, environment, application, timestamp):
self.status = status
self.environment = environment
self.application = application
self.timestamp = timestamp
| class Health(object):
"""
Represents a Health object used by the HealthDetails resource.
"""
def __init__(self, status, environment, application, timestamp):
self.status = status
self.environment = environment
self.application = application
self.timestamp = timestamp |
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/1399/A
A. Remove Smallest
Couldn't Solve it myself, answer borrowed.
'''
for _ in range(int(input())):
n = int(input())
a = set(map(int, input().split()))
print('YES' if max(a)-min(a) < len(a) else 'NO')
| __author__ = 'shukkkur'
"\nhttps://codeforces.com/problemset/problem/1399/A\nA. Remove Smallest\nCouldn't Solve it myself, answer borrowed.\n"
for _ in range(int(input())):
n = int(input())
a = set(map(int, input().split()))
print('YES' if max(a) - min(a) < len(a) else 'NO') |
N, *a = map(int, open(0).read().split())
i, j = 0, 0
c = 0
result = 0
while j < N:
if c <= N:
c += a[j]
j += 1
else:
c -= a[i]
i += 1
if c == N:
result += 1
while i < N:
c -= a[i]
i += 1
if c == N:
result += 1
print(result)
| (n, *a) = map(int, open(0).read().split())
(i, j) = (0, 0)
c = 0
result = 0
while j < N:
if c <= N:
c += a[j]
j += 1
else:
c -= a[i]
i += 1
if c == N:
result += 1
while i < N:
c -= a[i]
i += 1
if c == N:
result += 1
print(result) |
# test using cpu only
cpu = False
# type of network to be trained, can be bnn, full-bnn, qnn, full-qnn, tnn, full-tnn
network_type = 'full-qnn'
# bits can be None, 2, 4, 8 , whatever
bits=None
wbits = 4
abits = 4
# finetune an be false or true
finetune = False
architecture = 'RESNET'
# architecture = 'VGG'
dataset='CIFAR-10'
# dataset='MNIST'
if dataset == 'CIFAR-10':
dim=32
channels=3
else:
dim=28
channels=1
classes=10
data_augmentation=True
#regularization
kernel_regularizer=0.
kernel_initializer='glorot_uniform'
activity_regularizer=0.
# width and depth
nla=1
nfa=64
nlb=1
nfb=128
nlc=1
nfc=256
nres=3
pfilt=1
cuda="0"
#learning rate decay, factor => LR *= factor
decay_at_epoch = [0, 8, 12 ]
factor_at_epoch = [1, .1, .1]
kernel_lr_multiplier = 10
# debug and logging
progress_logging = 2 # can be 0 = no std logging, 1 = progress bar logging, 2 = one log line per epoch
epochs = 200
batch_size = 128
lr = 0.1
decay = 0.000025
date="00/00/0000"
# important paths
out_wght_path = './weights/{}_{}_{}b_{}b_{}_{}_{}_{}_{}_{}.hdf5'.format(dataset,network_type,abits,wbits,nla,nfa,nlb,nfb,nlc,nfc)
tensorboard_name = '{}_{}_{}b_{}b_{}_{}_{}_{}_{}_{}.hdf5'.format(dataset,network_type,abits,wbits,nla,nfa,nlb,nfb,nlc,nfc)
| cpu = False
network_type = 'full-qnn'
bits = None
wbits = 4
abits = 4
finetune = False
architecture = 'RESNET'
dataset = 'CIFAR-10'
if dataset == 'CIFAR-10':
dim = 32
channels = 3
else:
dim = 28
channels = 1
classes = 10
data_augmentation = True
kernel_regularizer = 0.0
kernel_initializer = 'glorot_uniform'
activity_regularizer = 0.0
nla = 1
nfa = 64
nlb = 1
nfb = 128
nlc = 1
nfc = 256
nres = 3
pfilt = 1
cuda = '0'
decay_at_epoch = [0, 8, 12]
factor_at_epoch = [1, 0.1, 0.1]
kernel_lr_multiplier = 10
progress_logging = 2
epochs = 200
batch_size = 128
lr = 0.1
decay = 2.5e-05
date = '00/00/0000'
out_wght_path = './weights/{}_{}_{}b_{}b_{}_{}_{}_{}_{}_{}.hdf5'.format(dataset, network_type, abits, wbits, nla, nfa, nlb, nfb, nlc, nfc)
tensorboard_name = '{}_{}_{}b_{}b_{}_{}_{}_{}_{}_{}.hdf5'.format(dataset, network_type, abits, wbits, nla, nfa, nlb, nfb, nlc, nfc) |
# JIG code from Stand-up Maths video "Why don't Jigsaw Puzzles have the correct number of pieces?"
def low_factors(n):
# all the factors which are the lower half of each factor pair
lf = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
lf.append(i)
return lf
def jig(w,h,n,b=0):
# percentage we'll check in either direction
threshold = 0.1
# the extra badness per piece
penalty = 1.005
ratio = max(w,h)/min(w,h) # switched to be greater than 1
print("")
print(f"{w} by {h} is picture ratio {round(ratio,4)}")
print("")
max_cap = int((1+threshold)*n)
min_cap = int((1-threshold)*n)
up_range = [i for i in range(n,max_cap+1)]
down_range = [i for i in range(min_cap,n)] # do not want n included again
down_range.reverse()
# start at 100 which is silly high and then move down.
up_best = 100
up_best_deets = []
down_best = 100
down_best_deets = []
# I am using the run marker so I know if looking above or below n
run = 0
for dis_range in [up_range,down_range]:
best_n = 0
best_n_ratio = 0
best_n_sides = []
if run == 0:
print(f"Looking for >= {n} solutions:")
print("")
else:
print("")
print("Just out of interest, here are smaller options:")
print("")
for i in dis_range:
this_best = 0
for j in low_factors(i):
j2 = int(i/j) # must be a whole number anyway
this_ratio = j2/j
if this_best == 0:
this_best = this_ratio
best_sides = [j,j2]
else:
if abs(this_ratio/ratio - 1) < abs(this_best/ratio - 1):
this_best = this_ratio
best_sides = [j,j2]
yes = 0
if best_n == 0:
yes = 1
else:
if abs(this_best/ratio - 1) < abs(best_n_ratio/ratio - 1):
yes = 1
if yes == 1:
best_n = i
best_n_ratio = this_best
best_n_sides = best_sides
piece_ratio = max(ratio,this_best)/min(ratio,this_best)
badness_score = (penalty**(abs(i-n)))*piece_ratio
if run == 0:
if badness_score < up_best:
up_best = badness_score
up_best_deets = [best_n,best_n_sides,best_n_ratio]
else:
if badness_score < down_best:
down_best = badness_score
down_best_deets = [best_n,best_n_sides,best_n_ratio]
print(f"{best_n} pieces in {best_n_sides} (grid ratio {round(best_n_ratio,4)}) needs piece ratio {round(piece_ratio,4)}")
if b==1:
print(f"[badness = {round(badness_score,5)}]")
print(f"for {n} the best is {best_n} pieces with size {best_n_sides}")
run += 1
print("")
print(f"If I had to guess: I think it's {up_best_deets[0]} pieces.")
if down_best < up_best:
print("")
print(f"BUT, fun fact, {down_best_deets[0]} would be even better.")
print("")
return 'DONE'
# I duplicated jig_v0 to make is easier to show in the video
def jig_v0(w,h,n,b=0):
# percentage we'll check in either direction
threshold = 0.1
penalty = 1.005
ratio = max(w,h)/min(w,h) # switched to be greater than 1
print("")
print(f"{w} by {h} is picture ratio {round(ratio,4)}")
print("")
max_cap = int((1+threshold)*n)
min_cap = int((1-threshold)*n)
up_range = [i for i in range(n,max_cap+1)]
down_range = [i for i in range(min_cap,n)] # do not want n included again
down_range.reverse()
# start at 100 which is silly high and then move down.
up_best = 100
up_best_deets = []
down_best = 100
down_best_deets = []
run = 0
for dis_range in [up_range,down_range]:
best_n = 0
best_n_ratio = 0
best_n_sides = []
if run == 0:
print(f"Looking for >= {n} solutions:")
print("")
else:
print("")
print("Just out of interest, here are smaller options:")
print("")
for i in dis_range:
this_best = 0
for j in low_factors(i):
j2 = int(i/j) # must be a whole number anyway
this_ratio = j2/j
if this_best == 0:
this_best = this_ratio
best_sides = [j,j2]
else:
if abs(this_ratio/ratio - 1) < abs(this_best/ratio - 1):
this_best = this_ratio
best_sides = [j,j2]
yes = 0
if best_n == 0:
yes = 1
else:
if abs(this_best/ratio - 1) < abs(best_n_ratio/ratio - 1):
yes = 1
if yes == 1:
best_n = i
best_n_ratio = this_best
best_n_sides = best_sides
piece_ratio = max(ratio,this_best)/min(ratio,this_best)
badness_score = (penalty**(abs(i-n)))*piece_ratio
if run == 0:
if badness_score < up_best:
up_best = badness_score
up_best_deets = [best_n,best_n_sides,best_n_ratio]
else:
if badness_score < down_best:
down_best = badness_score
down_best_deets = [best_n,best_n_sides,best_n_ratio]
print(f"{best_n} pieces in {best_n_sides} (grid ratio {round(best_n_ratio,4)}) needs piece ratio {round(piece_ratio,4)}")
if b==1:
print(f"[badness = {round(badness_score,5)}]")
run += 1
print("")
return 'DONE'
| def low_factors(n):
lf = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
lf.append(i)
return lf
def jig(w, h, n, b=0):
threshold = 0.1
penalty = 1.005
ratio = max(w, h) / min(w, h)
print('')
print(f'{w} by {h} is picture ratio {round(ratio, 4)}')
print('')
max_cap = int((1 + threshold) * n)
min_cap = int((1 - threshold) * n)
up_range = [i for i in range(n, max_cap + 1)]
down_range = [i for i in range(min_cap, n)]
down_range.reverse()
up_best = 100
up_best_deets = []
down_best = 100
down_best_deets = []
run = 0
for dis_range in [up_range, down_range]:
best_n = 0
best_n_ratio = 0
best_n_sides = []
if run == 0:
print(f'Looking for >= {n} solutions:')
print('')
else:
print('')
print('Just out of interest, here are smaller options:')
print('')
for i in dis_range:
this_best = 0
for j in low_factors(i):
j2 = int(i / j)
this_ratio = j2 / j
if this_best == 0:
this_best = this_ratio
best_sides = [j, j2]
elif abs(this_ratio / ratio - 1) < abs(this_best / ratio - 1):
this_best = this_ratio
best_sides = [j, j2]
yes = 0
if best_n == 0:
yes = 1
elif abs(this_best / ratio - 1) < abs(best_n_ratio / ratio - 1):
yes = 1
if yes == 1:
best_n = i
best_n_ratio = this_best
best_n_sides = best_sides
piece_ratio = max(ratio, this_best) / min(ratio, this_best)
badness_score = penalty ** abs(i - n) * piece_ratio
if run == 0:
if badness_score < up_best:
up_best = badness_score
up_best_deets = [best_n, best_n_sides, best_n_ratio]
elif badness_score < down_best:
down_best = badness_score
down_best_deets = [best_n, best_n_sides, best_n_ratio]
print(f'{best_n} pieces in {best_n_sides} (grid ratio {round(best_n_ratio, 4)}) needs piece ratio {round(piece_ratio, 4)}')
if b == 1:
print(f'[badness = {round(badness_score, 5)}]')
print(f'for {n} the best is {best_n} pieces with size {best_n_sides}')
run += 1
print('')
print(f"If I had to guess: I think it's {up_best_deets[0]} pieces.")
if down_best < up_best:
print('')
print(f'BUT, fun fact, {down_best_deets[0]} would be even better.')
print('')
return 'DONE'
def jig_v0(w, h, n, b=0):
threshold = 0.1
penalty = 1.005
ratio = max(w, h) / min(w, h)
print('')
print(f'{w} by {h} is picture ratio {round(ratio, 4)}')
print('')
max_cap = int((1 + threshold) * n)
min_cap = int((1 - threshold) * n)
up_range = [i for i in range(n, max_cap + 1)]
down_range = [i for i in range(min_cap, n)]
down_range.reverse()
up_best = 100
up_best_deets = []
down_best = 100
down_best_deets = []
run = 0
for dis_range in [up_range, down_range]:
best_n = 0
best_n_ratio = 0
best_n_sides = []
if run == 0:
print(f'Looking for >= {n} solutions:')
print('')
else:
print('')
print('Just out of interest, here are smaller options:')
print('')
for i in dis_range:
this_best = 0
for j in low_factors(i):
j2 = int(i / j)
this_ratio = j2 / j
if this_best == 0:
this_best = this_ratio
best_sides = [j, j2]
elif abs(this_ratio / ratio - 1) < abs(this_best / ratio - 1):
this_best = this_ratio
best_sides = [j, j2]
yes = 0
if best_n == 0:
yes = 1
elif abs(this_best / ratio - 1) < abs(best_n_ratio / ratio - 1):
yes = 1
if yes == 1:
best_n = i
best_n_ratio = this_best
best_n_sides = best_sides
piece_ratio = max(ratio, this_best) / min(ratio, this_best)
badness_score = penalty ** abs(i - n) * piece_ratio
if run == 0:
if badness_score < up_best:
up_best = badness_score
up_best_deets = [best_n, best_n_sides, best_n_ratio]
elif badness_score < down_best:
down_best = badness_score
down_best_deets = [best_n, best_n_sides, best_n_ratio]
print(f'{best_n} pieces in {best_n_sides} (grid ratio {round(best_n_ratio, 4)}) needs piece ratio {round(piece_ratio, 4)}')
if b == 1:
print(f'[badness = {round(badness_score, 5)}]')
run += 1
print('')
return 'DONE' |
class Grandpa:
basketball = 1
class Dad(Grandpa):
dance = 1
def d(this):
return f"Yes I Dance {this.dance} no of times"
class Grandson(Dad):
dance = 6
def d(this):
return f"Yes I Dance AWESOMELY {this.dance} no of times"
jo = Grandpa()
bo = Dad()
po = Grandson()
# Everything DAD[OR GANDPA] HAS GOES TO SON TOO --
print(po.basketball)
print(po.d()) | class Grandpa:
basketball = 1
class Dad(Grandpa):
dance = 1
def d(this):
return f'Yes I Dance {this.dance} no of times'
class Grandson(Dad):
dance = 6
def d(this):
return f'Yes I Dance AWESOMELY {this.dance} no of times'
jo = grandpa()
bo = dad()
po = grandson()
print(po.basketball)
print(po.d()) |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Coupon_validity, obj[4]: Gender, obj[5]: Age, obj[6]: Children, obj[7]: Education, obj[8]: Occupation, obj[9]: Income, obj[10]: Bar, obj[11]: Coffeehouse, obj[12]: Restaurant20to50, obj[13]: Direction_same, obj[14]: Distance
# {"feature": "Direction_same", "instances": 34, "metric_value": 0.9774, "depth": 1}
if obj[13]<=0:
# {"feature": "Passanger", "instances": 28, "metric_value": 1.0, "depth": 2}
if obj[0]<=2:
# {"feature": "Coupon", "instances": 18, "metric_value": 0.8524, "depth": 3}
if obj[2]<=3:
# {"feature": "Bar", "instances": 11, "metric_value": 0.994, "depth": 4}
if obj[10]<=1.0:
# {"feature": "Education", "instances": 7, "metric_value": 0.8631, "depth": 5}
if obj[7]<=1:
return 'True'
elif obj[7]>1:
# {"feature": "Gender", "instances": 3, "metric_value": 0.9183, "depth": 6}
if obj[4]<=0:
return 'False'
elif obj[4]>0:
return 'True'
else: return 'True'
else: return 'False'
elif obj[10]>1.0:
return 'False'
else: return 'False'
elif obj[2]>3:
return 'False'
else: return 'False'
elif obj[0]>2:
# {"feature": "Occupation", "instances": 10, "metric_value": 0.469, "depth": 3}
if obj[8]<=9:
return 'True'
elif obj[8]>9:
# {"feature": "Time", "instances": 2, "metric_value": 1.0, "depth": 4}
if obj[1]<=0:
return 'True'
elif obj[1]>0:
return 'False'
else: return 'False'
else: return 'True'
else: return 'True'
elif obj[13]>0:
return 'True'
else: return 'True'
| def find_decision(obj):
if obj[13] <= 0:
if obj[0] <= 2:
if obj[2] <= 3:
if obj[10] <= 1.0:
if obj[7] <= 1:
return 'True'
elif obj[7] > 1:
if obj[4] <= 0:
return 'False'
elif obj[4] > 0:
return 'True'
else:
return 'True'
else:
return 'False'
elif obj[10] > 1.0:
return 'False'
else:
return 'False'
elif obj[2] > 3:
return 'False'
else:
return 'False'
elif obj[0] > 2:
if obj[8] <= 9:
return 'True'
elif obj[8] > 9:
if obj[1] <= 0:
return 'True'
elif obj[1] > 0:
return 'False'
else:
return 'False'
else:
return 'True'
else:
return 'True'
elif obj[13] > 0:
return 'True'
else:
return 'True' |
DOMAIN = "meross"
CONF_KEY = "key"
CONF_VALIDATE = "validate"
CONF_UUID = "uuid"
DEVICE_OFF = 0
DEVICE_ON = 1
LISTEN_TOPIC = '/appliance/{}/publish'
PUBLISH_TOPIC = '/appliance/{}/subscribe'
APP_METHOD_PUSH = "PUSH"
APP_METHOD_GET = "GET"
APP_METHOD_SET = "SET"
APP_SYS_CLOCK = "Appliance.System.Clock"
APP_SYS_ALL = "Appliance.System.All"
APP_CONTROL_TOGGLE = "Appliance.Control.Toggle"
APP_CONTROL_ELEC = "Appliance.Control.Electricity"
ATTR_VERSION = "version"
ATTR_MAC = "mac_addr"
ATTR_IP = "ip_addr"
ATTR_CURRENT_A = "current_a" | domain = 'meross'
conf_key = 'key'
conf_validate = 'validate'
conf_uuid = 'uuid'
device_off = 0
device_on = 1
listen_topic = '/appliance/{}/publish'
publish_topic = '/appliance/{}/subscribe'
app_method_push = 'PUSH'
app_method_get = 'GET'
app_method_set = 'SET'
app_sys_clock = 'Appliance.System.Clock'
app_sys_all = 'Appliance.System.All'
app_control_toggle = 'Appliance.Control.Toggle'
app_control_elec = 'Appliance.Control.Electricity'
attr_version = 'version'
attr_mac = 'mac_addr'
attr_ip = 'ip_addr'
attr_current_a = 'current_a' |
#!/usr/bin/env python3
def main():
print( getProd2() )
print( getProd3() )
def getProd2():
with open( "expenses.txt" ) as f:
expenses = [ int( i.rstrip("\n") ) for i in f.readlines() ]
n = len( expenses )
for i in range( n ):
for j in range( i + 1, n ):
if expenses[ i ] + expenses[ j ] == 2020:
return( expenses[ i ] * expenses[ j ] )
def getProd3():
with open( "expenses.txt" ) as f:
expenses = [ int( i.rstrip("\n") ) for i in f.readlines() ]
n = len( expenses )
for i in range( n ):
for j in range( i + 1, n ):
for k in range( j + 1, n ):
if expenses[ i ] + expenses[ j ] + expenses[ k ] == 2020:
return( expenses[ i ] * expenses[ j ] * expenses[ k ] )
if __name__ == "__main__":
main()
| def main():
print(get_prod2())
print(get_prod3())
def get_prod2():
with open('expenses.txt') as f:
expenses = [int(i.rstrip('\n')) for i in f.readlines()]
n = len(expenses)
for i in range(n):
for j in range(i + 1, n):
if expenses[i] + expenses[j] == 2020:
return expenses[i] * expenses[j]
def get_prod3():
with open('expenses.txt') as f:
expenses = [int(i.rstrip('\n')) for i in f.readlines()]
n = len(expenses)
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if expenses[i] + expenses[j] + expenses[k] == 2020:
return expenses[i] * expenses[j] * expenses[k]
if __name__ == '__main__':
main() |
class LinkedListIterator:
def __init__(self, beginning):
self._current_cell = beginning
self._first = True
def __iter__(self):
return self
def __next__(self):
try:
getattr(self._current_cell, "value")
except AttributeError:
raise StopIteration()
else:
if self._first:
self._first = False
return self._current_cell
self._current_cell = self._current_cell.next
if self._current_cell is None:
raise StopIteration()
else:
return self._current_cell.value
| class Linkedlistiterator:
def __init__(self, beginning):
self._current_cell = beginning
self._first = True
def __iter__(self):
return self
def __next__(self):
try:
getattr(self._current_cell, 'value')
except AttributeError:
raise stop_iteration()
else:
if self._first:
self._first = False
return self._current_cell
self._current_cell = self._current_cell.next
if self._current_cell is None:
raise stop_iteration()
else:
return self._current_cell.value |
class groupcount(object):
"""Accept a (possibly infinite) iterable and yield a succession
of sub-iterators from it, each of which will yield N values.
>>> gc = groupcount('abcdefghij', 3)
>>> for subgroup in gc:
... for item in subgroup:
... print item,
... print
...
a b c
d e f
g h i
j
"""
def __init__(self, iterable, n=10):
self.it = iter(iterable)
self.n = n
def __iter__(self):
return self
def next(self):
return self._group(self.it.next())
def _group(self, ondeck):
yield ondeck
for i in xrange(1, self.n):
yield self.it.next()
| class Groupcount(object):
"""Accept a (possibly infinite) iterable and yield a succession
of sub-iterators from it, each of which will yield N values.
>>> gc = groupcount('abcdefghij', 3)
>>> for subgroup in gc:
... for item in subgroup:
... print item,
... print
...
a b c
d e f
g h i
j
"""
def __init__(self, iterable, n=10):
self.it = iter(iterable)
self.n = n
def __iter__(self):
return self
def next(self):
return self._group(self.it.next())
def _group(self, ondeck):
yield ondeck
for i in xrange(1, self.n):
yield self.it.next() |
'''https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1
Subarray with 0 sum
Easy Accuracy: 49.91% Submissions: 74975 Points: 2
Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.
Example 1:
Input:
5
4 2 -3 1 6
Output:
Yes
Explanation:
2, -3, 1 is the subarray
with sum 0.
Example 2:
Input:
5
4 2 0 1 6
Output:
Yes
Explanation:
0 is one of the element
in the array so there exist a
subarray with sum 0.
Your Task:
You only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(n).
Constraints:
1 <= n <= 104
-105 <= a[i] <= 105'''
# User function Template for python3
class Solution:
# Function to check whether there is a subarray present with 0-sum or not.
def subArrayExists(self, arr, n):
# Your code here
# Return true or false
s = set()
sum = 0
for i in range(n):
sum += arr[i]
if sum == 0 or sum in s:
return True
s.add(sum)
return False
# {
# Driver Code Starts
# Initial Template for Python 3
def main():
T = int(input())
while(T > 0):
n = int(input())
arr = [int(x) for x in input().strip().split()]
if(Solution().subArrayExists(arr, n)):
print("Yes")
else:
print("No")
T -= 1
if __name__ == "__main__":
main()
# } Driver Code Ends
| """https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1
Subarray with 0 sum
Easy Accuracy: 49.91% Submissions: 74975 Points: 2
Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.
Example 1:
Input:
5
4 2 -3 1 6
Output:
Yes
Explanation:
2, -3, 1 is the subarray
with sum 0.
Example 2:
Input:
5
4 2 0 1 6
Output:
Yes
Explanation:
0 is one of the element
in the array so there exist a
subarray with sum 0.
Your Task:
You only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(n).
Constraints:
1 <= n <= 104
-105 <= a[i] <= 105"""
class Solution:
def sub_array_exists(self, arr, n):
s = set()
sum = 0
for i in range(n):
sum += arr[i]
if sum == 0 or sum in s:
return True
s.add(sum)
return False
def main():
t = int(input())
while T > 0:
n = int(input())
arr = [int(x) for x in input().strip().split()]
if solution().subArrayExists(arr, n):
print('Yes')
else:
print('No')
t -= 1
if __name__ == '__main__':
main() |
all__ = ['jazPush', 'jazRvalue', 'jazLvalue', 'jazPop', 'jazAssign', 'jazCopy']
class jazPush:
def __init__(self):
self.command = "push"
def call(self, interpreter, arg):
interpreter.GetScope().stack.append(int(arg))
return None
class jazRvalue:
def __init__(self):
self.command = "rvalue"
def call(self, interpreter, arg):
value = interpreter.GetScope().GetVar(arg)
interpreter.GetScope().stack.append(value)
return None
class jazLvalue:
def __init__(self):
self.command = "lvalue"
def call(self, interpreter, arg):
address = interpreter.GetScope().GetAddress(arg)
interpreter.GetScope().stack.append(address)
return None
class jazPop:
def __init__(self):
self.command = "pop"
def call(self, interpreter, arg):
interpreter.GetScope().stack.pop()
return None
class jazAssign:
def __init__(self):
self.command = ":="
def call(self, interpreter, arg):
value = interpreter.GetScope().stack.pop()
addr = interpreter.GetScope().stack.pop()
interpreter.GetScope().SetVar(addr, value)
return None
class jazCopy:
def __init__(self):
self.command = "copy"
def call(self, interpreter, arg):
topStack = interpreter.GetScope().stack[-1]
interpreter.GetScope().stack.append(topStack)
return None
# A dictionary of the classes in this file
# used to autoload the functions
Functions = {'jazPush': jazPush, 'jazRvalue': jazRvalue, 'jazLvalue': jazRvalue, 'jazPop':jazPop, 'jazAssign':jazAssign, 'jazCopy':jazCopy}
| all__ = ['jazPush', 'jazRvalue', 'jazLvalue', 'jazPop', 'jazAssign', 'jazCopy']
class Jazpush:
def __init__(self):
self.command = 'push'
def call(self, interpreter, arg):
interpreter.GetScope().stack.append(int(arg))
return None
class Jazrvalue:
def __init__(self):
self.command = 'rvalue'
def call(self, interpreter, arg):
value = interpreter.GetScope().GetVar(arg)
interpreter.GetScope().stack.append(value)
return None
class Jazlvalue:
def __init__(self):
self.command = 'lvalue'
def call(self, interpreter, arg):
address = interpreter.GetScope().GetAddress(arg)
interpreter.GetScope().stack.append(address)
return None
class Jazpop:
def __init__(self):
self.command = 'pop'
def call(self, interpreter, arg):
interpreter.GetScope().stack.pop()
return None
class Jazassign:
def __init__(self):
self.command = ':='
def call(self, interpreter, arg):
value = interpreter.GetScope().stack.pop()
addr = interpreter.GetScope().stack.pop()
interpreter.GetScope().SetVar(addr, value)
return None
class Jazcopy:
def __init__(self):
self.command = 'copy'
def call(self, interpreter, arg):
top_stack = interpreter.GetScope().stack[-1]
interpreter.GetScope().stack.append(topStack)
return None
functions = {'jazPush': jazPush, 'jazRvalue': jazRvalue, 'jazLvalue': jazRvalue, 'jazPop': jazPop, 'jazAssign': jazAssign, 'jazCopy': jazCopy} |
a = int(input())
length = 0
sum_of_sequence = 0
while a != 0:
sum_of_sequence += a
length += 1
a = int(input())
print(sum_of_sequence / length) | a = int(input())
length = 0
sum_of_sequence = 0
while a != 0:
sum_of_sequence += a
length += 1
a = int(input())
print(sum_of_sequence / length) |
def swap(i):
i = i.swapcase()
return i
if __name__ == "__main__":
s = input()
res = swap(s)
print(res)
| def swap(i):
i = i.swapcase()
return i
if __name__ == '__main__':
s = input()
res = swap(s)
print(res) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.