content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Receiver1:
# action
def step_left(self):
print("Receiver1 steps left")
def step_right(self):
print("Receiver1 steps right")
class Receiver2:
# action
def step_forward(self):
print("Receiver2 steps forward")
def step_backward(self):
print("Receiver2 steps backwards")
| class Receiver1:
def step_left(self):
print('Receiver1 steps left')
def step_right(self):
print('Receiver1 steps right')
class Receiver2:
def step_forward(self):
print('Receiver2 steps forward')
def step_backward(self):
print('Receiver2 steps backwards') |
numero = int(input('Digite um numero: '))
if numero % 5 == 0:
print('Buzz')
else:
print(numero)
| numero = int(input('Digite um numero: '))
if numero % 5 == 0:
print('Buzz')
else:
print(numero) |
class WinData():
def __init__(self, wins=0, games=0):
assert games >= wins
self.wins = wins
self.games = games
def win_pct(self):
return f'{self.wins/self.games:.3%}' if self.games > 0 else 'N/A'
def incre_wins(self):
self.wins += 1
def incre_games(self):
self.games += 1
| class Windata:
def __init__(self, wins=0, games=0):
assert games >= wins
self.wins = wins
self.games = games
def win_pct(self):
return f'{self.wins / self.games:.3%}' if self.games > 0 else 'N/A'
def incre_wins(self):
self.wins += 1
def incre_games(self):
self.games += 1 |
def exibirLista(lista):
for item in lista:
print(item)
numeros = [1, 56, 5, 7, 29]
exibirLista(numeros)
print("Ordenados")
numeros.sort()
exibirLista(numeros)
| def exibir_lista(lista):
for item in lista:
print(item)
numeros = [1, 56, 5, 7, 29]
exibir_lista(numeros)
print('Ordenados')
numeros.sort()
exibir_lista(numeros) |
class Solution:
def fib(self, n: int) -> int:
fib_0, fib_1 = 0, 1
if n == 0:
return 0
if n == 1:
return 1
for i in range(2, n+1):
fib_0, fib_1 = fib_1, fib_0+fib_1
return fib_1
| class Solution:
def fib(self, n: int) -> int:
(fib_0, fib_1) = (0, 1)
if n == 0:
return 0
if n == 1:
return 1
for i in range(2, n + 1):
(fib_0, fib_1) = (fib_1, fib_0 + fib_1)
return fib_1 |
#
# PySNMP MIB module GRPSVCEXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GRPSVCEXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:19:53 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)
#
grpsvcExt, = mibBuilder.importSymbols("APENT-MIB", "grpsvcExt")
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, MibIdentifier, ModuleIdentity, IpAddress, NotificationType, Integer32, ObjectIdentity, Bits, Counter64, Unsigned32, Counter32, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "MibIdentifier", "ModuleIdentity", "IpAddress", "NotificationType", "Integer32", "ObjectIdentity", "Bits", "Counter64", "Unsigned32", "Counter32", "TimeTicks")
TextualConvention, RowStatus, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "DisplayString")
apGrpsvcExtMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 2467, 1, 19, 1))
if mibBuilder.loadTexts: apGrpsvcExtMib.setLastUpdated('9710092000Z')
if mibBuilder.loadTexts: apGrpsvcExtMib.setOrganization('ArrowPoint Communications Inc.')
if mibBuilder.loadTexts: apGrpsvcExtMib.setContactInfo(' Postal: ArrowPoint Communications Inc. 50 Nagog Park Acton, Massachusetts 01720 Tel: +1 978-206-3000 option 1 E-Mail: support@arrowpoint.com')
if mibBuilder.loadTexts: apGrpsvcExtMib.setDescription('The MIB module used to describe the ArrowPoint Communications content rule table')
apGrpsvcTable = MibTable((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2), )
if mibBuilder.loadTexts: apGrpsvcTable.setStatus('current')
if mibBuilder.loadTexts: apGrpsvcTable.setDescription('A list of group rule entries.')
apGrpsvcEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1), ).setIndexNames((0, "GRPSVCEXT-MIB", "apGrpsvcGrpName"), (0, "GRPSVCEXT-MIB", "apGrpsvcSvcName"))
if mibBuilder.loadTexts: apGrpsvcEntry.setStatus('current')
if mibBuilder.loadTexts: apGrpsvcEntry.setDescription('A group of information to uniquely identify a source grouping.')
apGrpsvcGrpName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpsvcGrpName.setStatus('current')
if mibBuilder.loadTexts: apGrpsvcGrpName.setDescription('The name of the content rule.')
apGrpsvcSvcName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpsvcSvcName.setStatus('current')
if mibBuilder.loadTexts: apGrpsvcSvcName.setDescription('The name of the service.')
apGrpsvcStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 3), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpsvcStatus.setStatus('current')
if mibBuilder.loadTexts: apGrpsvcStatus.setDescription('Status entry for this row ')
apGrpDestSvcTable = MibTable((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3), )
if mibBuilder.loadTexts: apGrpDestSvcTable.setStatus('current')
if mibBuilder.loadTexts: apGrpDestSvcTable.setDescription('A list of group destination service entries.')
apGrpDestSvcEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1), ).setIndexNames((0, "GRPSVCEXT-MIB", "apGrpDestSvcGrpName"), (0, "GRPSVCEXT-MIB", "apGrpDestSvcSvcName"))
if mibBuilder.loadTexts: apGrpDestSvcEntry.setStatus('current')
if mibBuilder.loadTexts: apGrpDestSvcEntry.setDescription('A group of information to uniquely identify a source grouping by a destination service.')
apGrpDestSvcGrpName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpDestSvcGrpName.setStatus('current')
if mibBuilder.loadTexts: apGrpDestSvcGrpName.setDescription('The name of the source group destination service.')
apGrpDestSvcSvcName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpDestSvcSvcName.setStatus('current')
if mibBuilder.loadTexts: apGrpDestSvcSvcName.setDescription('The name of the destination service.')
apGrpDestSvcStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 3), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpDestSvcStatus.setStatus('current')
if mibBuilder.loadTexts: apGrpDestSvcStatus.setDescription('Status entry for this row ')
mibBuilder.exportSymbols("GRPSVCEXT-MIB", apGrpDestSvcTable=apGrpDestSvcTable, apGrpDestSvcStatus=apGrpDestSvcStatus, apGrpsvcEntry=apGrpsvcEntry, PYSNMP_MODULE_ID=apGrpsvcExtMib, apGrpsvcStatus=apGrpsvcStatus, apGrpDestSvcEntry=apGrpDestSvcEntry, apGrpDestSvcGrpName=apGrpDestSvcGrpName, apGrpDestSvcSvcName=apGrpDestSvcSvcName, apGrpsvcTable=apGrpsvcTable, apGrpsvcSvcName=apGrpsvcSvcName, apGrpsvcExtMib=apGrpsvcExtMib, apGrpsvcGrpName=apGrpsvcGrpName)
| (grpsvc_ext,) = mibBuilder.importSymbols('APENT-MIB', 'grpsvcExt')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(iso, mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32, mib_identifier, module_identity, ip_address, notification_type, integer32, object_identity, bits, counter64, unsigned32, counter32, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32', 'MibIdentifier', 'ModuleIdentity', 'IpAddress', 'NotificationType', 'Integer32', 'ObjectIdentity', 'Bits', 'Counter64', 'Unsigned32', 'Counter32', 'TimeTicks')
(textual_convention, row_status, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'RowStatus', 'DisplayString')
ap_grpsvc_ext_mib = module_identity((1, 3, 6, 1, 4, 1, 2467, 1, 19, 1))
if mibBuilder.loadTexts:
apGrpsvcExtMib.setLastUpdated('9710092000Z')
if mibBuilder.loadTexts:
apGrpsvcExtMib.setOrganization('ArrowPoint Communications Inc.')
if mibBuilder.loadTexts:
apGrpsvcExtMib.setContactInfo(' Postal: ArrowPoint Communications Inc. 50 Nagog Park Acton, Massachusetts 01720 Tel: +1 978-206-3000 option 1 E-Mail: support@arrowpoint.com')
if mibBuilder.loadTexts:
apGrpsvcExtMib.setDescription('The MIB module used to describe the ArrowPoint Communications content rule table')
ap_grpsvc_table = mib_table((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2))
if mibBuilder.loadTexts:
apGrpsvcTable.setStatus('current')
if mibBuilder.loadTexts:
apGrpsvcTable.setDescription('A list of group rule entries.')
ap_grpsvc_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1)).setIndexNames((0, 'GRPSVCEXT-MIB', 'apGrpsvcGrpName'), (0, 'GRPSVCEXT-MIB', 'apGrpsvcSvcName'))
if mibBuilder.loadTexts:
apGrpsvcEntry.setStatus('current')
if mibBuilder.loadTexts:
apGrpsvcEntry.setDescription('A group of information to uniquely identify a source grouping.')
ap_grpsvc_grp_name = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(1, 31))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpsvcGrpName.setStatus('current')
if mibBuilder.loadTexts:
apGrpsvcGrpName.setDescription('The name of the content rule.')
ap_grpsvc_svc_name = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 31))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpsvcSvcName.setStatus('current')
if mibBuilder.loadTexts:
apGrpsvcSvcName.setDescription('The name of the service.')
ap_grpsvc_status = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 3), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpsvcStatus.setStatus('current')
if mibBuilder.loadTexts:
apGrpsvcStatus.setDescription('Status entry for this row ')
ap_grp_dest_svc_table = mib_table((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3))
if mibBuilder.loadTexts:
apGrpDestSvcTable.setStatus('current')
if mibBuilder.loadTexts:
apGrpDestSvcTable.setDescription('A list of group destination service entries.')
ap_grp_dest_svc_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1)).setIndexNames((0, 'GRPSVCEXT-MIB', 'apGrpDestSvcGrpName'), (0, 'GRPSVCEXT-MIB', 'apGrpDestSvcSvcName'))
if mibBuilder.loadTexts:
apGrpDestSvcEntry.setStatus('current')
if mibBuilder.loadTexts:
apGrpDestSvcEntry.setDescription('A group of information to uniquely identify a source grouping by a destination service.')
ap_grp_dest_svc_grp_name = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(1, 31))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpDestSvcGrpName.setStatus('current')
if mibBuilder.loadTexts:
apGrpDestSvcGrpName.setDescription('The name of the source group destination service.')
ap_grp_dest_svc_svc_name = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 31))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpDestSvcSvcName.setStatus('current')
if mibBuilder.loadTexts:
apGrpDestSvcSvcName.setDescription('The name of the destination service.')
ap_grp_dest_svc_status = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 3), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpDestSvcStatus.setStatus('current')
if mibBuilder.loadTexts:
apGrpDestSvcStatus.setDescription('Status entry for this row ')
mibBuilder.exportSymbols('GRPSVCEXT-MIB', apGrpDestSvcTable=apGrpDestSvcTable, apGrpDestSvcStatus=apGrpDestSvcStatus, apGrpsvcEntry=apGrpsvcEntry, PYSNMP_MODULE_ID=apGrpsvcExtMib, apGrpsvcStatus=apGrpsvcStatus, apGrpDestSvcEntry=apGrpDestSvcEntry, apGrpDestSvcGrpName=apGrpDestSvcGrpName, apGrpDestSvcSvcName=apGrpDestSvcSvcName, apGrpsvcTable=apGrpsvcTable, apGrpsvcSvcName=apGrpsvcSvcName, apGrpsvcExtMib=apGrpsvcExtMib, apGrpsvcGrpName=apGrpsvcGrpName) |
class TracableObject:
def __init__(self, object_id, centroid):
# store the object ID, then initialize a list of centroids
# using the current centroid
self.object_id = object_id
self.centroids = [centroid]
# initializa a boolean used to indicate if the object has
# already been counted or not
self.counted = False
| class Tracableobject:
def __init__(self, object_id, centroid):
self.object_id = object_id
self.centroids = [centroid]
self.counted = False |
# Pytathon if Stement
# if Statement
sandwich_order = "Ham Roll"
if sandwich_order == "Ham Roll":
print("Price: $1.75")
# if else Statement
tab = 29.95
if tab > 20:
print("This user has a tab over $20 that needs to be paid.")
else:
print("This user's tab is below $20 that does not require immediate payment.")
# elif Statement
sandwich_order = "Bacon Roll"
if sandwich_order == "Ham Roll":
print("Price: $1.75")
elif sandwich_order == "Cheese Roll":
print("Price: $1.80")
elif sandwich_order == "Bacon Roll":
print("Price: $2.10")
else:
print("Price: $2.00")
# Nested if Statement
sandwich_order = "Other Filled Roll"
if sandwich_order != "Other Filled Roll":
if sandwich_order == "Ham Roll":
print("Price: $1.75")
if sandwich_order == "Cheese Roll":
print("Price: $1.80")
elif sandwich_order == "Bacon Roll":
print("Price: $2.10")
else:
print("Price: $2.00") | sandwich_order = 'Ham Roll'
if sandwich_order == 'Ham Roll':
print('Price: $1.75')
tab = 29.95
if tab > 20:
print('This user has a tab over $20 that needs to be paid.')
else:
print("This user's tab is below $20 that does not require immediate payment.")
sandwich_order = 'Bacon Roll'
if sandwich_order == 'Ham Roll':
print('Price: $1.75')
elif sandwich_order == 'Cheese Roll':
print('Price: $1.80')
elif sandwich_order == 'Bacon Roll':
print('Price: $2.10')
else:
print('Price: $2.00')
sandwich_order = 'Other Filled Roll'
if sandwich_order != 'Other Filled Roll':
if sandwich_order == 'Ham Roll':
print('Price: $1.75')
if sandwich_order == 'Cheese Roll':
print('Price: $1.80')
elif sandwich_order == 'Bacon Roll':
print('Price: $2.10')
else:
print('Price: $2.00') |
# Leetcode 198. House Robber
#
# Link: https://leetcode.com/problems/house-robber/
# Difficulty: Medium
# Solution using DP
# Complexity:
# O(N) time | where N represent the number of homes
# O(1) space
class Solution:
def rob(self, nums: List[int]) -> int:
rob1, rob2 = 0, 0
for n in nums:
rob1, rob2 = rob2, max(rob1 + n, rob2)
return rob2
| class Solution:
def rob(self, nums: List[int]) -> int:
(rob1, rob2) = (0, 0)
for n in nums:
(rob1, rob2) = (rob2, max(rob1 + n, rob2))
return rob2 |
# %% [6. ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)
class Solution:
def convert(self, s: str, numRows: int) -> str:
lst = [[] for _ in range(numRows)]
for cc in use(s, numRows):
for i, c in enumerate(cc):
lst[i].append(c)
return "".join("".join(i) for i in lst)
def use(s, numRows):
p, n = 0, len(s)
while p < n:
yield [s[p + i] if p + i < n else "" for i in range(numRows)]
p += numRows
for i in range(1, numRows - 1):
if p < n:
yield [""] * (numRows - i - 1) + [s[p]] + [""] * i
p += 1
| class Solution:
def convert(self, s: str, numRows: int) -> str:
lst = [[] for _ in range(numRows)]
for cc in use(s, numRows):
for (i, c) in enumerate(cc):
lst[i].append(c)
return ''.join((''.join(i) for i in lst))
def use(s, numRows):
(p, n) = (0, len(s))
while p < n:
yield [s[p + i] if p + i < n else '' for i in range(numRows)]
p += numRows
for i in range(1, numRows - 1):
if p < n:
yield ([''] * (numRows - i - 1) + [s[p]] + [''] * i)
p += 1 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
def get_tensor_shape(tensor):
shape = []
for dim in tensor.type.tensor_type.shape.dim:
shape.append(dim.dim_value)
if len(shape) == 4:
shape = [shape[0], shape[2], shape[3], shape[1]]
return shape
| def get_tensor_shape(tensor):
shape = []
for dim in tensor.type.tensor_type.shape.dim:
shape.append(dim.dim_value)
if len(shape) == 4:
shape = [shape[0], shape[2], shape[3], shape[1]]
return shape |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, "/app/home/skins/default/style.css")
| def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, '/app/home/skins/default/style.css') |
class PluginNotInitialisableException(BaseException):
pass
class PluginNotActivatableException(BaseException):
pass
class PluginNotDeactivatableException(BaseException):
pass
class PluginAttributeMissingException(BaseException):
pass
class PluginRegistrationException(BaseException):
pass
| class Pluginnotinitialisableexception(BaseException):
pass
class Pluginnotactivatableexception(BaseException):
pass
class Pluginnotdeactivatableexception(BaseException):
pass
class Pluginattributemissingexception(BaseException):
pass
class Pluginregistrationexception(BaseException):
pass |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/xtark/ros_ws/install/include;/home/xtark/ros_ws/devel/lib/rtabmap-0.19/../../include/rtabmap-0.19;/opt/ros/kinetic/include/opencv-3.3.1-dev;/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv".split(';') if "/home/xtark/ros_ws/install/include;/home/xtark/ros_ws/devel/lib/rtabmap-0.19/../../include/rtabmap-0.19;/opt/ros/kinetic/include/opencv-3.3.1-dev;/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv" != "" else []
PROJECT_CATKIN_DEPENDS = "cv_bridge;roscpp;rospy;sensor_msgs;std_msgs;std_srvs;nav_msgs;geometry_msgs;visualization_msgs;image_transport;tf;tf_conversions;tf2_ros;eigen_conversions;laser_geometry;pcl_conversions;pcl_ros;nodelet;dynamic_reconfigure;message_filters;class_loader;rosgraph_msgs;stereo_msgs;move_base_msgs;image_geometry;costmap_2d;rviz".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lrtabmap_ros;/home/xtark/ros_ws/devel/lib/librtabmap_core.so;/home/xtark/ros_ws/devel/lib/librtabmap_utilite.so;/home/xtark/ros_ws/devel/lib/librtabmap_gui.so;/usr/lib/arm-linux-gnueabihf/libz.so;/usr/local/lib/libg2o_core.so;/usr/local/lib/libg2o_types_slam2d.so;/usr/local/lib/libg2o_types_slam3d.so;/usr/local/lib/libg2o_types_sba.so;/usr/local/lib/libg2o_stuff.so;/usr/local/lib/libg2o_solver_csparse.so;/usr/local/lib/libg2o_csparse_extension.so;/usr/lib/arm-linux-gnueabihf/libcxsparse.so;/usr/local/lib/libg2o_solver_cholmod.so;/usr/lib/arm-linux-gnueabihf/libcholmod.so;/usr/lib/libOpenNI2.so;/opt/ros/kinetic/lib/liboctomap.so;/opt/ros/kinetic/lib/liboctomath.so;/opt/ros/kinetic/lib/libopencv_calib3d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_core3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dnn3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_features2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_flann3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_highgui3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgcodecs3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ml3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_objdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_photo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_shape3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stitching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_superres3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_video3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videoio3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videostab3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_viz3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_aruco3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bgsegm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bioinspired3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ccalib3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_cvv3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_datasets3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dpm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_face3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_fuzzy3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_hdf3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_img_hash3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_line_descriptor3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_optflow3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_phase_unwrapping3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_plot3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_reg3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_rgbd3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_saliency3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stereo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_structured_light3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_surface_matching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_text3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_tracking3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xfeatures2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ximgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xobjdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xphoto3.so.3.3.1".split(';') if "-lrtabmap_ros;/home/xtark/ros_ws/devel/lib/librtabmap_core.so;/home/xtark/ros_ws/devel/lib/librtabmap_utilite.so;/home/xtark/ros_ws/devel/lib/librtabmap_gui.so;/usr/lib/arm-linux-gnueabihf/libz.so;/usr/local/lib/libg2o_core.so;/usr/local/lib/libg2o_types_slam2d.so;/usr/local/lib/libg2o_types_slam3d.so;/usr/local/lib/libg2o_types_sba.so;/usr/local/lib/libg2o_stuff.so;/usr/local/lib/libg2o_solver_csparse.so;/usr/local/lib/libg2o_csparse_extension.so;/usr/lib/arm-linux-gnueabihf/libcxsparse.so;/usr/local/lib/libg2o_solver_cholmod.so;/usr/lib/arm-linux-gnueabihf/libcholmod.so;/usr/lib/libOpenNI2.so;/opt/ros/kinetic/lib/liboctomap.so;/opt/ros/kinetic/lib/liboctomath.so;/opt/ros/kinetic/lib/libopencv_calib3d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_core3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dnn3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_features2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_flann3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_highgui3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgcodecs3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ml3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_objdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_photo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_shape3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stitching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_superres3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_video3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videoio3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videostab3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_viz3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_aruco3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bgsegm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bioinspired3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ccalib3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_cvv3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_datasets3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dpm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_face3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_fuzzy3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_hdf3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_img_hash3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_line_descriptor3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_optflow3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_phase_unwrapping3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_plot3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_reg3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_rgbd3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_saliency3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stereo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_structured_light3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_surface_matching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_text3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_tracking3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xfeatures2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ximgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xobjdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xphoto3.so.3.3.1" != "" else []
PROJECT_NAME = "rtabmap_ros"
PROJECT_SPACE_DIR = "/home/xtark/ros_ws/install"
PROJECT_VERSION = "0.19.3"
| catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/xtark/ros_ws/install/include;/home/xtark/ros_ws/devel/lib/rtabmap-0.19/../../include/rtabmap-0.19;/opt/ros/kinetic/include/opencv-3.3.1-dev;/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv'.split(';') if '/home/xtark/ros_ws/install/include;/home/xtark/ros_ws/devel/lib/rtabmap-0.19/../../include/rtabmap-0.19;/opt/ros/kinetic/include/opencv-3.3.1-dev;/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv' != '' else []
project_catkin_depends = 'cv_bridge;roscpp;rospy;sensor_msgs;std_msgs;std_srvs;nav_msgs;geometry_msgs;visualization_msgs;image_transport;tf;tf_conversions;tf2_ros;eigen_conversions;laser_geometry;pcl_conversions;pcl_ros;nodelet;dynamic_reconfigure;message_filters;class_loader;rosgraph_msgs;stereo_msgs;move_base_msgs;image_geometry;costmap_2d;rviz'.replace(';', ' ')
pkg_config_libraries_with_prefix = '-lrtabmap_ros;/home/xtark/ros_ws/devel/lib/librtabmap_core.so;/home/xtark/ros_ws/devel/lib/librtabmap_utilite.so;/home/xtark/ros_ws/devel/lib/librtabmap_gui.so;/usr/lib/arm-linux-gnueabihf/libz.so;/usr/local/lib/libg2o_core.so;/usr/local/lib/libg2o_types_slam2d.so;/usr/local/lib/libg2o_types_slam3d.so;/usr/local/lib/libg2o_types_sba.so;/usr/local/lib/libg2o_stuff.so;/usr/local/lib/libg2o_solver_csparse.so;/usr/local/lib/libg2o_csparse_extension.so;/usr/lib/arm-linux-gnueabihf/libcxsparse.so;/usr/local/lib/libg2o_solver_cholmod.so;/usr/lib/arm-linux-gnueabihf/libcholmod.so;/usr/lib/libOpenNI2.so;/opt/ros/kinetic/lib/liboctomap.so;/opt/ros/kinetic/lib/liboctomath.so;/opt/ros/kinetic/lib/libopencv_calib3d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_core3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dnn3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_features2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_flann3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_highgui3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgcodecs3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ml3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_objdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_photo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_shape3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stitching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_superres3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_video3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videoio3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videostab3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_viz3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_aruco3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bgsegm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bioinspired3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ccalib3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_cvv3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_datasets3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dpm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_face3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_fuzzy3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_hdf3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_img_hash3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_line_descriptor3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_optflow3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_phase_unwrapping3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_plot3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_reg3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_rgbd3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_saliency3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stereo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_structured_light3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_surface_matching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_text3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_tracking3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xfeatures2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ximgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xobjdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xphoto3.so.3.3.1'.split(';') if '-lrtabmap_ros;/home/xtark/ros_ws/devel/lib/librtabmap_core.so;/home/xtark/ros_ws/devel/lib/librtabmap_utilite.so;/home/xtark/ros_ws/devel/lib/librtabmap_gui.so;/usr/lib/arm-linux-gnueabihf/libz.so;/usr/local/lib/libg2o_core.so;/usr/local/lib/libg2o_types_slam2d.so;/usr/local/lib/libg2o_types_slam3d.so;/usr/local/lib/libg2o_types_sba.so;/usr/local/lib/libg2o_stuff.so;/usr/local/lib/libg2o_solver_csparse.so;/usr/local/lib/libg2o_csparse_extension.so;/usr/lib/arm-linux-gnueabihf/libcxsparse.so;/usr/local/lib/libg2o_solver_cholmod.so;/usr/lib/arm-linux-gnueabihf/libcholmod.so;/usr/lib/libOpenNI2.so;/opt/ros/kinetic/lib/liboctomap.so;/opt/ros/kinetic/lib/liboctomath.so;/opt/ros/kinetic/lib/libopencv_calib3d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_core3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dnn3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_features2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_flann3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_highgui3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgcodecs3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ml3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_objdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_photo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_shape3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stitching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_superres3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_video3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videoio3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videostab3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_viz3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_aruco3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bgsegm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bioinspired3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ccalib3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_cvv3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_datasets3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dpm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_face3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_fuzzy3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_hdf3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_img_hash3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_line_descriptor3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_optflow3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_phase_unwrapping3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_plot3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_reg3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_rgbd3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_saliency3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stereo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_structured_light3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_surface_matching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_text3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_tracking3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xfeatures2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ximgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xobjdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xphoto3.so.3.3.1' != '' else []
project_name = 'rtabmap_ros'
project_space_dir = '/home/xtark/ros_ws/install'
project_version = '0.19.3' |
# ------------------------------------
# CODE BOOLA 2015 PYTHON WORKSHOP
# Mike Wu, Jonathan Chang, Kevin Tan
# Puzzle Challenges Number 7
# ------------------------------------
# INSTRUCTIONS:
# Using only 1 line, write a function
# to reverse a list. The function is
# passed a list as an argument.
# EXAMPLE:
# reverse_lst([1, 2, 3]) => [3, 2, 1]
# reverse_lst([]) => []
# reverse_lst([1]) => [1]
# reverse_lst([1, 1, 1, 2, 1, 1]) => [1, 1, 2, 1, 1, 1]
# HINT:
# lists have a reverse function!
# If lst is a list, then lst.reverse() should
# do the trick! After calling lst.reverse()
# [you don't need to set it to a variable],
# you can just return lst!
def reverse_lst(lst):
pass # 1 line
return lst # Don't remove this! You want to return the lst.
| def reverse_lst(lst):
pass
return lst |
__all__ = ['UserScript']
class UserScript:
def __init__(self, id=None, activations=None):
self.functions = []
self._function_by_name = {}
self.id = id
self.activations = [] if activations is None else activations
def __len__(self):
return len(self.functions)
def __getitem__(self, index):
return self.functions[index]
def register(self, func):
self.functions.append(func)
self._function_by_name[func.__name__] = func
def exec(self, index=None, name=None, *args, **kwargs):
if index is not None:
return self.functions[index](*args, **kwargs)
elif name is not None:
return self._function_by_name[name](*args, **kwargs)
raise ValueError("index and name are both None")
| __all__ = ['UserScript']
class Userscript:
def __init__(self, id=None, activations=None):
self.functions = []
self._function_by_name = {}
self.id = id
self.activations = [] if activations is None else activations
def __len__(self):
return len(self.functions)
def __getitem__(self, index):
return self.functions[index]
def register(self, func):
self.functions.append(func)
self._function_by_name[func.__name__] = func
def exec(self, index=None, name=None, *args, **kwargs):
if index is not None:
return self.functions[index](*args, **kwargs)
elif name is not None:
return self._function_by_name[name](*args, **kwargs)
raise value_error('index and name are both None') |
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
n=len(nums);
c=[0]*n
ans=list()
for i in range(n):
c[nums[i]-1]+=1
for i in range(n):
if(c[i]==2):
ans.append(i+1)
return ans;
| class Solution:
def find_duplicates(self, nums: List[int]) -> List[int]:
n = len(nums)
c = [0] * n
ans = list()
for i in range(n):
c[nums[i] - 1] += 1
for i in range(n):
if c[i] == 2:
ans.append(i + 1)
return ans |
def is_isogram(s):
if isinstance(s, str):
s = [i for i in s.lower() if i.isalpha()]
return len(s) == len(set(s))
else:
raise TypeError("This doesn't look like a string.") | def is_isogram(s):
if isinstance(s, str):
s = [i for i in s.lower() if i.isalpha()]
return len(s) == len(set(s))
else:
raise type_error("This doesn't look like a string.") |
def zero_initializer(n):
assert isinstance(n, int) and n > 0
return [0] * n
def zeros_initializer(n, n_args):
if n_args == 1:
return zero_initializer(n)
return map(zero_initializer, [n] * n_args) | def zero_initializer(n):
assert isinstance(n, int) and n > 0
return [0] * n
def zeros_initializer(n, n_args):
if n_args == 1:
return zero_initializer(n)
return map(zero_initializer, [n] * n_args) |
## Gerador de tabuada.
canGenerateTabuada = False
#print("Tabuada de: ")
vInput = int(input("Tabuada de: "))
canGenerateTabuada = vInput >= 1 and vInput <= 10
while not canGenerateTabuada:
print("Digite um valor de 1 a 10.")
vInput = int(input("Tabuada de: "))
canGenerateTabuada = vInput >= 1 and vInput <= 10
pass
## Gerando tabuada
for i in range(10):
print(str(vInput) + " x " + str((i+1)) + " = " + str(vInput*(i+1)))
pass
| can_generate_tabuada = False
v_input = int(input('Tabuada de: '))
can_generate_tabuada = vInput >= 1 and vInput <= 10
while not canGenerateTabuada:
print('Digite um valor de 1 a 10.')
v_input = int(input('Tabuada de: '))
can_generate_tabuada = vInput >= 1 and vInput <= 10
pass
for i in range(10):
print(str(vInput) + ' x ' + str(i + 1) + ' = ' + str(vInput * (i + 1)))
pass |
# Space: O(n)
# Time: O(n!)
class Solution:
def combine(self, n: int, k: int):
if k > n: return []
data = [i for i in range(1, n + 1)] # list all numbers
status = [False for _ in range(len(data))] # identify if current item has been used or not
def dfs(data, index, temp_res, res, k):
if len(temp_res) == k:
res.append(temp_res[:])
return
for i in range(index, len(data)):
if status[i]: continue # if current number has been used, then pass to next one
status[i] = True
temp_res.append(data[i])
dfs(data, i, temp_res, res, k)
temp_res.pop()
status[i] = False
return res
return dfs(data, 0, [], [], k)
| class Solution:
def combine(self, n: int, k: int):
if k > n:
return []
data = [i for i in range(1, n + 1)]
status = [False for _ in range(len(data))]
def dfs(data, index, temp_res, res, k):
if len(temp_res) == k:
res.append(temp_res[:])
return
for i in range(index, len(data)):
if status[i]:
continue
status[i] = True
temp_res.append(data[i])
dfs(data, i, temp_res, res, k)
temp_res.pop()
status[i] = False
return res
return dfs(data, 0, [], [], k) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Approach 1
# O(N) - Space
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
hashmap = set()
node = head
while node:
if node is None:
return None
elif node in hashmap:
return node
else:
hashmap.add(node)
node = node.next
def detect(head):
if head is None:
return
hashmap = set()
curr = head
while curr:
if curr in hashmap:
return curr
hashmap.add(curr)
return None
def detect(head):
if head is None:
return
slow = head
fast = head
flag = None
while fast and fast.next :
slow = slow.next
fast = fast.next.next
if slow == fast:
flag = fast
break
if flag:
return
iter1 = head
iter2 = flag
while iter1 and iter2:
if iter1 is iter2:
return iter1
iter1 = iter1.next
iter2 = iter2.next
# Approach 2
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
def helper(head):
if head is None or head.next is None:
return None
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return slow
fast = helper(head)
if fast is None:
return None
slow = head
while fast is not slow:
fast = fast.next
slow = slow.next
return slow
| class Solution:
def detect_cycle(self, head: ListNode) -> ListNode:
hashmap = set()
node = head
while node:
if node is None:
return None
elif node in hashmap:
return node
else:
hashmap.add(node)
node = node.next
def detect(head):
if head is None:
return
hashmap = set()
curr = head
while curr:
if curr in hashmap:
return curr
hashmap.add(curr)
return None
def detect(head):
if head is None:
return
slow = head
fast = head
flag = None
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
flag = fast
break
if flag:
return
iter1 = head
iter2 = flag
while iter1 and iter2:
if iter1 is iter2:
return iter1
iter1 = iter1.next
iter2 = iter2.next
class Solution:
def detect_cycle(self, head: ListNode) -> ListNode:
def helper(head):
if head is None or head.next is None:
return None
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return slow
fast = helper(head)
if fast is None:
return None
slow = head
while fast is not slow:
fast = fast.next
slow = slow.next
return slow |
#!/Users/philip/opt/anaconda3/bin/python
a = [ "aa", "bb", "cc" ]
print ( "".join(a) )
| a = ['aa', 'bb', 'cc']
print(''.join(a)) |
class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
total_a = sum(A)
total_b = sum(B)
set_b = set(B)
for candy in A:
swap_item = candy + (total_b - total_a) / 2
if swap_item in set_b:
return [candy, candy + (total_b - total_a) / 2] | class Solution:
def fair_candy_swap(self, A: List[int], B: List[int]) -> List[int]:
total_a = sum(A)
total_b = sum(B)
set_b = set(B)
for candy in A:
swap_item = candy + (total_b - total_a) / 2
if swap_item in set_b:
return [candy, candy + (total_b - total_a) / 2] |
class ARMAModel():
def __init__(self, gamma=0.15, beta=0.8):
self.gamma_param = gamma
self.beta_param = beta
def predict(self, x):
x_simplified = x[0, 0, :] # convert to a simple array, ignoring batch size
return (self.beta_param * x_simplified[-1]) + \
(self.gamma_param * x_simplified[-2]) + \
((1 - (self.gamma_param + self.beta_param)) * x_simplified[-3])
| class Armamodel:
def __init__(self, gamma=0.15, beta=0.8):
self.gamma_param = gamma
self.beta_param = beta
def predict(self, x):
x_simplified = x[0, 0, :]
return self.beta_param * x_simplified[-1] + self.gamma_param * x_simplified[-2] + (1 - (self.gamma_param + self.beta_param)) * x_simplified[-3] |
class InterpretationParser:
def __init__(self, socketio):
self.interpreter = None
self.entity_intent_map = {'item_attribute_query': {'attribute': None, 'entity': None},
'batch_restriction_query': {'attribute': None, 'class': None},
'batch_restriction_query_numerical': {'class': None, 'attribute': None,
'comparison': None, 'numerical_value': None},
'batch_restriction_query_numerical_and_attribute': {'attribute': [],
'class': None, 'comparison': None,
'numerical_value': None}
}
self.socketio = socketio
def parse_question_interpretation(self, question):
result = self.interpreter.parse(question)
# get the key components and their types out
# get the intent of the question
intent = result['intent']['name']
entities = result['entities']
result = self.fill_in_components(intent, entities)
return result
def fill_in_components(self, intent, entities):
obj = self.entity_intent_map[intent]
for entity in entities:
entity_type = entity['entity']
term = entity['value'].lower()
slot = obj[entity_type]
if type(slot) is list:
obj[entity_type].append(term)
# more than one term should present ...
else:
obj[entity_type] = term
return {'type': intent, 'entities': obj}
| class Interpretationparser:
def __init__(self, socketio):
self.interpreter = None
self.entity_intent_map = {'item_attribute_query': {'attribute': None, 'entity': None}, 'batch_restriction_query': {'attribute': None, 'class': None}, 'batch_restriction_query_numerical': {'class': None, 'attribute': None, 'comparison': None, 'numerical_value': None}, 'batch_restriction_query_numerical_and_attribute': {'attribute': [], 'class': None, 'comparison': None, 'numerical_value': None}}
self.socketio = socketio
def parse_question_interpretation(self, question):
result = self.interpreter.parse(question)
intent = result['intent']['name']
entities = result['entities']
result = self.fill_in_components(intent, entities)
return result
def fill_in_components(self, intent, entities):
obj = self.entity_intent_map[intent]
for entity in entities:
entity_type = entity['entity']
term = entity['value'].lower()
slot = obj[entity_type]
if type(slot) is list:
obj[entity_type].append(term)
else:
obj[entity_type] = term
return {'type': intent, 'entities': obj} |
list_of_users=[] # it stores the list of usernames in form of strings
def fun(l1):
global list_of_users
list_of_users=l1
def fun2():
return list_of_users | list_of_users = []
def fun(l1):
global list_of_users
list_of_users = l1
def fun2():
return list_of_users |
# Scrapy settings for gettaiex project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/topics/settings.html
#
BOT_NAME = 'gettaiex'
BOT_VERSION = '1.0'
SPIDER_MODULES = ['gettaiex.spiders']
NEWSPIDER_MODULE = 'gettaiex.spiders'
USER_AGENT = '%s/%s' % (BOT_NAME, BOT_VERSION)
| bot_name = 'gettaiex'
bot_version = '1.0'
spider_modules = ['gettaiex.spiders']
newspider_module = 'gettaiex.spiders'
user_agent = '%s/%s' % (BOT_NAME, BOT_VERSION) |
penctutions = ".,;?()[]{}&_-@%<>:!~1234567890/*+$#^/"
newt = "" #text without penctutions
List2 = []
text = str("Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, Lorem ipsum dolor sit amet.., comes from a line in section 1.10.32.The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.")
for char in text:
if char not in penctutions:
newt += char
for char in newt:
y = ord(char)
x = 128 - y
List2.append(x)
print(List2[::-1])
| penctutions = '.,;?()[]{}&_-@%<>:!~1234567890/*+$#^/'
newt = ''
list2 = []
text = str('Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, Lorem ipsum dolor sit amet.., comes from a line in section 1.10.32.The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.')
for char in text:
if char not in penctutions:
newt += char
for char in newt:
y = ord(char)
x = 128 - y
List2.append(x)
print(List2[::-1]) |
_base_ = './rr_yolov3_d53_416_coco.py'
# model settings
model = dict(
type='SingleStageDetector',
pretrained=None,
backbone=dict(type='RRTinyYolov4Backbone'),
neck=None,
bbox_head=dict(
type='RRTinyYolov4Head',
num_classes=80,
in_channels=[512, 256],
out_channels=[256, 128],
anchor_generator=dict(
type='YOLOAnchorGenerator',
base_sizes=[[(81, 82), (135, 169), (344, 319)],
[(23, 27), (37, 58), (81, 82)]],
strides=[32, 16]),
bbox_coder=dict(type='YOLOBBoxCoder'),
featmap_strides=[32, 16],
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=True,
loss_weight=1.0,
reduction='sum'),
loss_conf=dict(
type='CrossEntropyLoss',
use_sigmoid=True,
loss_weight=1.0,
reduction='sum'),
loss_xy=dict(
type='CrossEntropyLoss',
use_sigmoid=True,
loss_weight=2.0,
reduction='sum'),
loss_wh=dict(type='MSELoss', loss_weight=2.0, reduction='sum')))
| _base_ = './rr_yolov3_d53_416_coco.py'
model = dict(type='SingleStageDetector', pretrained=None, backbone=dict(type='RRTinyYolov4Backbone'), neck=None, bbox_head=dict(type='RRTinyYolov4Head', num_classes=80, in_channels=[512, 256], out_channels=[256, 128], anchor_generator=dict(type='YOLOAnchorGenerator', base_sizes=[[(81, 82), (135, 169), (344, 319)], [(23, 27), (37, 58), (81, 82)]], strides=[32, 16]), bbox_coder=dict(type='YOLOBBoxCoder'), featmap_strides=[32, 16], loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0, reduction='sum'), loss_conf=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0, reduction='sum'), loss_xy=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=2.0, reduction='sum'), loss_wh=dict(type='MSELoss', loss_weight=2.0, reduction='sum'))) |
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN YOUR CODE HERE...
for each_letter in secretWord:
if each_letter not in lettersGuessed:
return False
return True
print(isWordGuessed('apple', ['e', 'a', 'l', 'i', 'k', 'p', 'r', 's']))
| def is_word_guessed(secretWord, lettersGuessed):
"""
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
"""
for each_letter in secretWord:
if each_letter not in lettersGuessed:
return False
return True
print(is_word_guessed('apple', ['e', 'a', 'l', 'i', 'k', 'p', 'r', 's'])) |
#!/usr/bin/env python3
'''
This is a
multiline
comment
'''
print("This is some dummy code") # Hi # This shouldn't count as another comment '''neither should this'''
| """
This is a
multiline
comment
"""
print('This is some dummy code') |
class Solution:
def halveArray(self, nums: List[int]) -> int:
halfSum = sum(nums) / 2
ans = 0
runningSum = 0.0
maxHeap = [-num for num in nums]
heapq.heapify(maxHeap)
while runningSum < halfSum:
maxValue = -heapq.heappop(maxHeap) / 2
runningSum += maxValue
heapq.heappush(maxHeap, -maxValue)
ans += 1
return ans
| class Solution:
def halve_array(self, nums: List[int]) -> int:
half_sum = sum(nums) / 2
ans = 0
running_sum = 0.0
max_heap = [-num for num in nums]
heapq.heapify(maxHeap)
while runningSum < halfSum:
max_value = -heapq.heappop(maxHeap) / 2
running_sum += maxValue
heapq.heappush(maxHeap, -maxValue)
ans += 1
return ans |
# TODO BenM/assessor_of_assessor/pick this up later; it isn't required for the
# initial working solution
class TestPyxnatSession:
def __init__(self, project, subject, session, scans, assessors):
self.scans_ = scans
self.assessors_ = assessors
self.project = project
self.subject = subject
self.session = session
def scans(self):
return self.scans_
def assessors(self):
return self.assessors_
class TestAttrs:
def __init__(self, properties):
pass
class TestPyxnatScan:
def __init__(self, project, subject, session, scanjson):
self.scanjson = scanjson
self.project = project
self.subject = subject
self.session = session
uristr = '/data/project/{}/subjects/{}/experiments/{}/scans/{}'
self._uri = uristr.format(project,
subject,
session,
self.scanjson['label'])
def id(self):
return self.scanjson['id']
def label(self):
return self.scanjson['label']
class TestPyxnatAssessor:
def __init__(self, project, subject, session, asrjson):
self.asrjson = asrjson
self.project = project
self.subject = subject
self.session = session
uristr = '/data/project/{}/subjects/{}/experiments/{}/assessors/{}'
self._uri = uristr.format(project,
subject,
session,
self.asrjson['label'])
def id(self):
return self.asrjson['id']
def label(self):
return self.asrjson['label']
def inputs(self):
return self.asrjson['xsitype'] + '/' + self.asrjson['inputs']
| class Testpyxnatsession:
def __init__(self, project, subject, session, scans, assessors):
self.scans_ = scans
self.assessors_ = assessors
self.project = project
self.subject = subject
self.session = session
def scans(self):
return self.scans_
def assessors(self):
return self.assessors_
class Testattrs:
def __init__(self, properties):
pass
class Testpyxnatscan:
def __init__(self, project, subject, session, scanjson):
self.scanjson = scanjson
self.project = project
self.subject = subject
self.session = session
uristr = '/data/project/{}/subjects/{}/experiments/{}/scans/{}'
self._uri = uristr.format(project, subject, session, self.scanjson['label'])
def id(self):
return self.scanjson['id']
def label(self):
return self.scanjson['label']
class Testpyxnatassessor:
def __init__(self, project, subject, session, asrjson):
self.asrjson = asrjson
self.project = project
self.subject = subject
self.session = session
uristr = '/data/project/{}/subjects/{}/experiments/{}/assessors/{}'
self._uri = uristr.format(project, subject, session, self.asrjson['label'])
def id(self):
return self.asrjson['id']
def label(self):
return self.asrjson['label']
def inputs(self):
return self.asrjson['xsitype'] + '/' + self.asrjson['inputs'] |
def operation(first,second,operator):
if(operator == 1):
return first + second
if(operator == 2):
return first - second
if(operator == 3):
return first / second
if(operator == 4):
return first * second
return "invalid selection or input"
print("Welcome to calculator.py, please enter 2 values to perform an operation")
firstValue = float(input("What is the first value? \n"))
secondValue = float(input("What is the second value? \n"))
print("Available operations")
print("1. add - add two numbers")
print("2. sub - subtract two numbers")
print("3. div - divide two numbers")
print("4. mul - multiply two numbers")
operator = int(input("What operation would you like to perform? \n"))
print(operation(firstValue,secondValue,operator))
| def operation(first, second, operator):
if operator == 1:
return first + second
if operator == 2:
return first - second
if operator == 3:
return first / second
if operator == 4:
return first * second
return 'invalid selection or input'
print('Welcome to calculator.py, please enter 2 values to perform an operation')
first_value = float(input('What is the first value? \n'))
second_value = float(input('What is the second value? \n'))
print('Available operations')
print('1. add - add two numbers')
print('2. sub - subtract two numbers')
print('3. div - divide two numbers')
print('4. mul - multiply two numbers')
operator = int(input('What operation would you like to perform? \n'))
print(operation(firstValue, secondValue, operator)) |
mod, maxn, cur, ans, r = 998244353, 1000005, 10, 0, 0
dp, x, a = [0] * maxn, [0] * maxn, [0] * 12,
x[1] = 1
dp[0] = 1
for i in range(2 , maxn):
x[i] = mod - (mod // i) * x[mod % i] % mod
n, k = map(int, input().split())
n = n // 2
p = [0] * k
for u in map(int, input().split()):
cur = min(cur, u)
p[r] = u
r += 1
for i in range(k):
a[p[i] - cur] = 1
for i in range(n * 10 + 1):
sm, j = 0, 0
while j < min(10, i + 1):
sm += dp[i-j] * (j+1) * a[j+1] * n % mod
j += 1
j = 1
while j < min(10, i + 1):
sm -= dp[i-j+1] * (i-j+1) * a[j]
j += 1
ans = (ans + dp[i] * dp[i]) % mod
dp[i+1] = sm * x[i+1] % mod
print(ans % mod)
| (mod, maxn, cur, ans, r) = (998244353, 1000005, 10, 0, 0)
(dp, x, a) = ([0] * maxn, [0] * maxn, [0] * 12)
x[1] = 1
dp[0] = 1
for i in range(2, maxn):
x[i] = mod - mod // i * x[mod % i] % mod
(n, k) = map(int, input().split())
n = n // 2
p = [0] * k
for u in map(int, input().split()):
cur = min(cur, u)
p[r] = u
r += 1
for i in range(k):
a[p[i] - cur] = 1
for i in range(n * 10 + 1):
(sm, j) = (0, 0)
while j < min(10, i + 1):
sm += dp[i - j] * (j + 1) * a[j + 1] * n % mod
j += 1
j = 1
while j < min(10, i + 1):
sm -= dp[i - j + 1] * (i - j + 1) * a[j]
j += 1
ans = (ans + dp[i] * dp[i]) % mod
dp[i + 1] = sm * x[i + 1] % mod
print(ans % mod) |
def nomina(salario, horasNormales, horasExtra):
if horasNormales+horasExtra>=36 and horasNormales+horasExtra<=43:
salario=salario+horasExtra*1.25
elif horasNormales+horasExtra>=44:
salario=salario+horasExtra*1.5
else:
salario=salario
return print(salario)
nomina(1500,35,0)
| def nomina(salario, horasNormales, horasExtra):
if horasNormales + horasExtra >= 36 and horasNormales + horasExtra <= 43:
salario = salario + horasExtra * 1.25
elif horasNormales + horasExtra >= 44:
salario = salario + horasExtra * 1.5
else:
salario = salario
return print(salario)
nomina(1500, 35, 0) |
print('The choice coin voting session has started!!!!!')
print('------------------------------------------------')
print ('should we continue with the proposal method')
nominee_1 = 'yes'
nominee_2 = 'no'
nom_1_votes = 0
nom_2_votes = 0
votes_id = [1,2,3,4,5,6,7,8,9,10]
num_of_voter = len(votes_id)
while True:
voter = int(input('enter your voter id no:'))
if votes_id ==[]:
print('voting session over')
if nom_1_votes >nom_2_votes:
percent = (nom_1_votes/num_of_voter)*100
print(nominee_1, 'has won', 'with', percent, '% votes')
break
if nom_2_votes > nom_1_votes:
percent = (nom_2_votes/num_of_voter)*100
print(nominee_2, 'has won', 'with', percent, '% votes')
break
else:
if voter in votes_id:
print('you are a voter')
votes_id.remove(voter)
vote = int(input('enter your vote 1 for yes, 2 for no: '))
if vote==1:
nom_1_votes+=1
print('thank you for voting')
elif vote == 2:
nom_2_votes+=1
print('thanks for voting')
else:
print('you are not a voter here or you have already voted')
| print('The choice coin voting session has started!!!!!')
print('------------------------------------------------')
print('should we continue with the proposal method')
nominee_1 = 'yes'
nominee_2 = 'no'
nom_1_votes = 0
nom_2_votes = 0
votes_id = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_of_voter = len(votes_id)
while True:
voter = int(input('enter your voter id no:'))
if votes_id == []:
print('voting session over')
if nom_1_votes > nom_2_votes:
percent = nom_1_votes / num_of_voter * 100
print(nominee_1, 'has won', 'with', percent, '% votes')
break
if nom_2_votes > nom_1_votes:
percent = nom_2_votes / num_of_voter * 100
print(nominee_2, 'has won', 'with', percent, '% votes')
break
elif voter in votes_id:
print('you are a voter')
votes_id.remove(voter)
vote = int(input('enter your vote 1 for yes, 2 for no: '))
if vote == 1:
nom_1_votes += 1
print('thank you for voting')
elif vote == 2:
nom_2_votes += 1
print('thanks for voting')
else:
print('you are not a voter here or you have already voted') |
''' The complete Intcode computer
N. B. Someone wrote an intcode computer in intcode
https://www.reddit.com/r/adventofcode/comments/e7wml1/2019_intcode_computer_in_intcode/
'''
fin = open('input_13.txt')
temp = fin.readline().split(',')
fin.close()
program_template = [int(x) for x in temp]
# program_template = [109, 1, 204, -1, 1001, 100,
# 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]
# program_template = [1102, 34915192, 34915192, 7, 4, 7, 99, 0]
# program_template = [104, 1125899906842624, 99]
# memory extension
program_template += [0] * 2000
def pexec(p, pc, in_queue, out_queue, rbase):
def g_o(pc, opnum): # get operand
modes = p[pc] // 100
m = [0, 0, 0, 0]
m[1] = modes % 10
modes = modes // 10
m[2] = modes % 10
modes = modes // 10
m[3] = modes % 10
if (opnum == 3): # target address for write operations
if m[3] == 0:
return p[pc + opnum]
else:
return p[pc + opnum] + rbase
if (p[pc] % 100 == 3): # target address for input write
if m[1] == 0:
return p[pc + opnum]
else:
return p[pc + opnum] + rbase
if m[opnum] == 0: # positional, immediate, relative target value
return p[p[pc + opnum]]
elif m[opnum] == 1:
return p[pc + opnum]
elif m[opnum] == 2:
return p[p[pc + opnum] + rbase]
else:
return None
while True:
# decode instruction
opcode = p[pc] % 100
if opcode == 99: # terminate
return 'END', pc, rbase
elif opcode == 1: # add
p[g_o(pc, 3)] = g_o(pc, 1) + g_o(pc, 2)
pc += 4
elif opcode == 2: # multiply
p[g_o(pc, 3)] = g_o(pc, 1) * g_o(pc, 2)
pc += 4
elif opcode == 3: # input
# inp = int(input('Input at location ' + str(pc) + ' : '))
if in_queue == []:
return 'WAIT', pc, rbase
inp = in_queue.pop(0)
p[g_o(pc, 1)] = inp
pc += 2
elif opcode == 4: # print
# print(g_o(pc, 1))
out_queue.append(g_o(pc, 1))
pc += 2
elif opcode == 5: # jump-if-true
if g_o(pc, 1) != 0:
pc = g_o(pc, 2)
else:
pc += 3
elif opcode == 6: # jump-if-false
if g_o(pc, 1) == 0:
pc = g_o(pc, 2)
else:
pc += 3
elif opcode == 7: # less than
if g_o(pc, 1) < g_o(pc, 2):
p[g_o(pc, 3)] = 1
else:
p[g_o(pc, 3)] = 0
pc += 4
elif opcode == 8: # equal
if g_o(pc, 1) == g_o(pc, 2):
p[g_o(pc, 3)] = 1
else:
p[g_o(pc, 3)] = 0
pc += 4
elif opcode == 9: # change relative base
rbase += g_o(pc, 1)
pc += 2
else: # unknown opcode
return 'ERROR', pc, rbase
pA = program_template[:]
qAin = []
qAout = []
pcA = 0
stateA = 'WAIT'
rbaseA = 0
while True:
if stateA == 'WAIT':
stateA, pcA, rbaseA = pexec(pA, pcA, qAin, qAout, rbaseA)
if stateA == 'END':
break
print(qAout[::3], qAout[1::3], qAout[2::3], qAout[2::3].count(2))
| """ The complete Intcode computer
N. B. Someone wrote an intcode computer in intcode
https://www.reddit.com/r/adventofcode/comments/e7wml1/2019_intcode_computer_in_intcode/
"""
fin = open('input_13.txt')
temp = fin.readline().split(',')
fin.close()
program_template = [int(x) for x in temp]
program_template += [0] * 2000
def pexec(p, pc, in_queue, out_queue, rbase):
def g_o(pc, opnum):
modes = p[pc] // 100
m = [0, 0, 0, 0]
m[1] = modes % 10
modes = modes // 10
m[2] = modes % 10
modes = modes // 10
m[3] = modes % 10
if opnum == 3:
if m[3] == 0:
return p[pc + opnum]
else:
return p[pc + opnum] + rbase
if p[pc] % 100 == 3:
if m[1] == 0:
return p[pc + opnum]
else:
return p[pc + opnum] + rbase
if m[opnum] == 0:
return p[p[pc + opnum]]
elif m[opnum] == 1:
return p[pc + opnum]
elif m[opnum] == 2:
return p[p[pc + opnum] + rbase]
else:
return None
while True:
opcode = p[pc] % 100
if opcode == 99:
return ('END', pc, rbase)
elif opcode == 1:
p[g_o(pc, 3)] = g_o(pc, 1) + g_o(pc, 2)
pc += 4
elif opcode == 2:
p[g_o(pc, 3)] = g_o(pc, 1) * g_o(pc, 2)
pc += 4
elif opcode == 3:
if in_queue == []:
return ('WAIT', pc, rbase)
inp = in_queue.pop(0)
p[g_o(pc, 1)] = inp
pc += 2
elif opcode == 4:
out_queue.append(g_o(pc, 1))
pc += 2
elif opcode == 5:
if g_o(pc, 1) != 0:
pc = g_o(pc, 2)
else:
pc += 3
elif opcode == 6:
if g_o(pc, 1) == 0:
pc = g_o(pc, 2)
else:
pc += 3
elif opcode == 7:
if g_o(pc, 1) < g_o(pc, 2):
p[g_o(pc, 3)] = 1
else:
p[g_o(pc, 3)] = 0
pc += 4
elif opcode == 8:
if g_o(pc, 1) == g_o(pc, 2):
p[g_o(pc, 3)] = 1
else:
p[g_o(pc, 3)] = 0
pc += 4
elif opcode == 9:
rbase += g_o(pc, 1)
pc += 2
else:
return ('ERROR', pc, rbase)
p_a = program_template[:]
q_ain = []
q_aout = []
pc_a = 0
state_a = 'WAIT'
rbase_a = 0
while True:
if stateA == 'WAIT':
(state_a, pc_a, rbase_a) = pexec(pA, pcA, qAin, qAout, rbaseA)
if stateA == 'END':
break
print(qAout[::3], qAout[1::3], qAout[2::3], qAout[2::3].count(2)) |
# Original Solution
def additionWithoutCarrying(param1, param2):
smaller = min(param1,param2)
larger = max(param1,param2)
small_list = list(str(smaller))
large_list = list(str(larger))
output = []
print(param1,param2)
print(small_list,large_list)
index_2= 0
for index,i in enumerate(large_list):
if index >= (len(large_list) - len(small_list)):
print('index1:',index)
print('index_two',index_2)
print('larger_num',i)
print('smaller_num',small_list[index_2])
number = int(i)+int(small_list[index_2])
if number > 9:
digit = list(str(number))[-1]
output.append(digit)
else:
output.append(str(number))
index_2+=1
else:
print('index1:',index)
print(i)
output.append(i)
return int("".join(output))
# Much cleaner solution (from reading the solutions)
# the reason that this works is because you stay in numeric space
# you are composing the number numerically not logically.
# I was composing the number logically, and so I was working in
# "string" space, and going back and forth. Here
# you don't have to translate back and forth.
def additionWithoutCarrying(param1, param2):
output = 0
tenPower = 1
while param1 or param2:
output += tenPower * ((param1+param2)%10)
param1 //= 10
param2 //= 10
tenPower *= 10
return output | def addition_without_carrying(param1, param2):
smaller = min(param1, param2)
larger = max(param1, param2)
small_list = list(str(smaller))
large_list = list(str(larger))
output = []
print(param1, param2)
print(small_list, large_list)
index_2 = 0
for (index, i) in enumerate(large_list):
if index >= len(large_list) - len(small_list):
print('index1:', index)
print('index_two', index_2)
print('larger_num', i)
print('smaller_num', small_list[index_2])
number = int(i) + int(small_list[index_2])
if number > 9:
digit = list(str(number))[-1]
output.append(digit)
else:
output.append(str(number))
index_2 += 1
else:
print('index1:', index)
print(i)
output.append(i)
return int(''.join(output))
def addition_without_carrying(param1, param2):
output = 0
ten_power = 1
while param1 or param2:
output += tenPower * ((param1 + param2) % 10)
param1 //= 10
param2 //= 10
ten_power *= 10
return output |
def soma (x,y):
return x+y
def subtrai (x,y):
return x-y
def mult():
pass
| def soma(x, y):
return x + y
def subtrai(x, y):
return x - y
def mult():
pass |
if __name__ == '__main__':
N = int(input())
Output = [];
for i in range(0,N):
ip = input().split();
if ip[0] == "print":
print(Output)
elif ip[0] == "insert":
Output.insert(int(ip[1]),int(ip[2]))
elif ip[0] == "remove":
Output.remove(int(ip[1]))
elif ip[0] == "pop":
Output.pop();
elif ip[0] == "append":
Output.append(int(ip[1]))
elif ip[0] == "sort":
Output.sort();
else:
Output.reverse();
| if __name__ == '__main__':
n = int(input())
output = []
for i in range(0, N):
ip = input().split()
if ip[0] == 'print':
print(Output)
elif ip[0] == 'insert':
Output.insert(int(ip[1]), int(ip[2]))
elif ip[0] == 'remove':
Output.remove(int(ip[1]))
elif ip[0] == 'pop':
Output.pop()
elif ip[0] == 'append':
Output.append(int(ip[1]))
elif ip[0] == 'sort':
Output.sort()
else:
Output.reverse() |
def capacity(K, weights):
if sum(weights) < K:
return None
weights = sorted(weights, reverse=True)
def solve(K, i):
print("Solve({0}, {1})".format(K, i))
if K == 0:
return []
while i < len(weights) and weights[i]> K:
i += 1
if i == len(weights):
return None
subK = K - weights[i]
subI = i + 1
subsolution = solve(subK, subI)
if subsolution is not None:
subsolution.append(weights[i])
return subsolution
subsolution = solve(K, subI)
if subsolution is not None:
return subsolution
return None
return solve(K, 0)
print(capacity(20000, [x**2 for x in range(100)]))
| def capacity(K, weights):
if sum(weights) < K:
return None
weights = sorted(weights, reverse=True)
def solve(K, i):
print('Solve({0}, {1})'.format(K, i))
if K == 0:
return []
while i < len(weights) and weights[i] > K:
i += 1
if i == len(weights):
return None
sub_k = K - weights[i]
sub_i = i + 1
subsolution = solve(subK, subI)
if subsolution is not None:
subsolution.append(weights[i])
return subsolution
subsolution = solve(K, subI)
if subsolution is not None:
return subsolution
return None
return solve(K, 0)
print(capacity(20000, [x ** 2 for x in range(100)])) |
flatmates = [
{
'name': "Fred",
'telegram_id': "930376906"
},
{
'name': "Kata",
'telegram_id': "1524429277"
},
{
'name': "Daniel",
'telegram_id': "1145198247"
},
{
'name': "Ricky",
'telegram_id': "930376906"
},
{
'name': "Ankit",
'telegram_id': "1519503399"
},
{
'name': "Csaba",
'telegram_id': "5044038381"
},
{
'name': "Lisa",
'telegram_id': "2087012195"
},
{
'name': "Raminta",
'telegram_id': "930376906"
}
]
| flatmates = [{'name': 'Fred', 'telegram_id': '930376906'}, {'name': 'Kata', 'telegram_id': '1524429277'}, {'name': 'Daniel', 'telegram_id': '1145198247'}, {'name': 'Ricky', 'telegram_id': '930376906'}, {'name': 'Ankit', 'telegram_id': '1519503399'}, {'name': 'Csaba', 'telegram_id': '5044038381'}, {'name': 'Lisa', 'telegram_id': '2087012195'}, {'name': 'Raminta', 'telegram_id': '930376906'}] |
# callback handlers: reloaded each time triggered
def message1(): # change me
print('BIMRI') # or could build a dialog...
def message2(self):
print('Nil!') # change me
self.method1() # access the 'Hello' instance...
| def message1():
print('BIMRI')
def message2(self):
print('Nil!')
self.method1() |
class Solution:
def largestNumber(self, num):
num_str = map(str, num)
num_str.sort(cmp=lambda str1, str2: -1 if str1 + str2 > str2 + str1 else 1)
if len(num_str) >= 2 and num_str[0] == num_str[1] == "0":
return "0"
return "".join(num_str)
| class Solution:
def largest_number(self, num):
num_str = map(str, num)
num_str.sort(cmp=lambda str1, str2: -1 if str1 + str2 > str2 + str1 else 1)
if len(num_str) >= 2 and num_str[0] == num_str[1] == '0':
return '0'
return ''.join(num_str) |
name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
emails = dict()
for line in handle:
words = line.split()
if not line.startswith('From') or len(words) < 3:
continue
email = words[1]
emails[email] = emails.get(email, 0) + 1
max = 0
max_email = None
for email, count in emails.items():
if count > max:
max = count
max_email = email
print(max_email, max)
| name = input('Enter file:')
if len(name) < 1:
name = 'mbox-short.txt'
handle = open(name)
emails = dict()
for line in handle:
words = line.split()
if not line.startswith('From') or len(words) < 3:
continue
email = words[1]
emails[email] = emails.get(email, 0) + 1
max = 0
max_email = None
for (email, count) in emails.items():
if count > max:
max = count
max_email = email
print(max_email, max) |
# -*- coding: utf-8 -*-
# @Time : 2021/8/25 4:25
# @Author : pixb
# @Email : tpxsky@163.com
# @File : main_model.py.py
# @Software: PyCharm
# @Description:
class main_model(object):
pass
| class Main_Model(object):
pass |
response.title = settings.title
response.subtitle = settings.subtitle
response.meta.author = '%(author)s <%(author_email)s>' % settings
response.meta.keywords = settings.keywords
response.meta.description = settings.description
response.menu = [
(T('Index'),URL('default','index')==URL(),URL('default','index'),[]),
(T('Book'),URL('default','book_manage')==URL(),URL('default','book_manage'),[]),
(T('Chapter'),URL('default','chapter_manage')==URL(),URL('default','chapter_manage'),[]),
(T('Character'),URL('default','character_manage')==URL(),URL('default','character_manage'),[]),
(T('Character Reference'),URL('default','character_reference_manage')==URL(),URL('default','character_reference_manage'),[]),
(T('Question'),URL('default','question_manage')==URL(),URL('default','question_manage'),[]),
] | response.title = settings.title
response.subtitle = settings.subtitle
response.meta.author = '%(author)s <%(author_email)s>' % settings
response.meta.keywords = settings.keywords
response.meta.description = settings.description
response.menu = [(t('Index'), url('default', 'index') == url(), url('default', 'index'), []), (t('Book'), url('default', 'book_manage') == url(), url('default', 'book_manage'), []), (t('Chapter'), url('default', 'chapter_manage') == url(), url('default', 'chapter_manage'), []), (t('Character'), url('default', 'character_manage') == url(), url('default', 'character_manage'), []), (t('Character Reference'), url('default', 'character_reference_manage') == url(), url('default', 'character_reference_manage'), []), (t('Question'), url('default', 'question_manage') == url(), url('default', 'question_manage'), [])] |
DEFAULT_GEASE_FILE_NAME = ".gease"
DEFAULT_RELEASE_MESSAGE = "A new release via gease."
NOT_ENOUGH_ARGS = "Not enough arguments"
KEY_GEASE_USER = "user"
KEY_GEASE_TOKEN = "personal_access_token"
MESSAGE_FMT_RELEASED = "Release is created at: %s"
| default_gease_file_name = '.gease'
default_release_message = 'A new release via gease.'
not_enough_args = 'Not enough arguments'
key_gease_user = 'user'
key_gease_token = 'personal_access_token'
message_fmt_released = 'Release is created at: %s' |
def paint_calc(height,width,cover):
number_of_cans = round((height * width) / coverage)
print(f"You'll need {number_of_cans} cans of paint.")
height = int(input("Height of Wall :\n"))
width = int(input("Width of wall : \n"))
coverage = 5
paint_calc(height=height,width=width,cover=coverage)
| def paint_calc(height, width, cover):
number_of_cans = round(height * width / coverage)
print(f"You'll need {number_of_cans} cans of paint.")
height = int(input('Height of Wall :\n'))
width = int(input('Width of wall : \n'))
coverage = 5
paint_calc(height=height, width=width, cover=coverage) |
class Tokenizer:
def __init__(self):
self.on_token_funcs = []
def read(self, chunk):
raise NotImplementedError
def token_fetched(self, token):
for func in self.on_token_funcs:
func(token)
def on_token_fetched(self, func):
self.on_token_funcs.append(func)
return func
class CharacterTokenizer(Tokenizer):
sep = ''
name = 'char'
def __init__(self):
super().__init__()
self.last_symbol_was_space = False
def read(self, chunk):
if len(chunk) != 1:
for char in chunk:
self.read(char)
else:
if chunk.isspace():
if not self.last_symbol_was_space:
self.token_fetched(' ')
self.last_symbol_was_space = True
else:
self.last_symbol_was_space = False
self.token_fetched(chunk)
class WordTokenizer(Tokenizer):
sep = ' '
name = 'word'
def __init__(self):
super().__init__()
self.word_buffer = []
def read(self, chunk):
if len(chunk) != 1:
for char in chunk:
self.read(char)
else:
if chunk.isspace():
if self.word_buffer:
self.token_fetched(''.join(self.word_buffer))
self.word_buffer.clear()
else:
self.word_buffer.append(chunk)
| class Tokenizer:
def __init__(self):
self.on_token_funcs = []
def read(self, chunk):
raise NotImplementedError
def token_fetched(self, token):
for func in self.on_token_funcs:
func(token)
def on_token_fetched(self, func):
self.on_token_funcs.append(func)
return func
class Charactertokenizer(Tokenizer):
sep = ''
name = 'char'
def __init__(self):
super().__init__()
self.last_symbol_was_space = False
def read(self, chunk):
if len(chunk) != 1:
for char in chunk:
self.read(char)
elif chunk.isspace():
if not self.last_symbol_was_space:
self.token_fetched(' ')
self.last_symbol_was_space = True
else:
self.last_symbol_was_space = False
self.token_fetched(chunk)
class Wordtokenizer(Tokenizer):
sep = ' '
name = 'word'
def __init__(self):
super().__init__()
self.word_buffer = []
def read(self, chunk):
if len(chunk) != 1:
for char in chunk:
self.read(char)
elif chunk.isspace():
if self.word_buffer:
self.token_fetched(''.join(self.word_buffer))
self.word_buffer.clear()
else:
self.word_buffer.append(chunk) |
DEFAULT_FIT_VAR_NAMES = tuple(['beta0', 'c_reduction'])
DEFAULT_FIT_GUESS = {
'beta0': 0.025,
'c_reduction': 0.5
}
DEFAULT_FIT_BOUNDS = {
'beta0': [0., 1.],
'c_reduction': [0., 1.]
}
| default_fit_var_names = tuple(['beta0', 'c_reduction'])
default_fit_guess = {'beta0': 0.025, 'c_reduction': 0.5}
default_fit_bounds = {'beta0': [0.0, 1.0], 'c_reduction': [0.0, 1.0]} |
for n in range(2, 100):
for x in range(2, n):
if n % x == 0:
print(n, '==', x, '*', n//x)
break
else:
print(n, 'is prime!')
| for n in range(2, 100):
for x in range(2, n):
if n % x == 0:
print(n, '==', x, '*', n // x)
break
else:
print(n, 'is prime!') |
'''
@author: Kittl
'''
def exportExternalNets(dpf, exportProfile, tables, colHeads):
# Get the index in the list of worksheets
if exportProfile is 2:
cmpStr = "ExternalNet"
elif exportProfile is 3:
cmpStr = ""
idxWs = [idx for idx,val in enumerate(tables[exportProfile-1]) if val == cmpStr]
if not idxWs:
dpf.PrintPlain('')
dpf.PrintInfo('There is no worksheet '+( cmpStr if not cmpStr == "" else "for external nets" )+' defined. Skip this one!')
return (None, None)
elif len(idxWs) > 1:
dpf.PrintError('There is more than one table with the name '+cmpStr+' defined. Cancel this script.')
exit(1)
else:
idxWs = idxWs[0]
colHead = list();
# Index 8 indicates the externalNet-Worksheet
for cHead in colHeads[exportProfile-1][idxWs]:
colHead.append(str(cHead.name))
dpf.PrintPlain('')
dpf.PrintPlain('#####################################')
dpf.PrintPlain('# Starting to export external nets. #')
dpf.PrintPlain('#####################################')
expMat = list()
expMat.append(colHead)
externalNets = dpf.GetCalcRelevantObjects('*.ElmXNet')
for externalNet in externalNets:
if exportProfile is 2:
# Get voltage setpoint from connected node, when this is chosen in PowerFactory
if externalNet.uset_mode is 1:
vtarget = externalNet.cpCtrlNode.vtarget
if not externalNet.cpCtrlNode.loc_name == externalNet.bus1.cterm.loc_name:
dpf.PrintWarn('The external net '+externalNet.loc_name+' regulates the voltage at node '+externalNet.cpCtrlNode.loc_name+', which is not the current node.')
else:
vtarget = externalNet.usetp
expMat.append([
externalNet.loc_name, # id
externalNet.bus1.cterm.loc_name, # node
vtarget, # vSetp
externalNet.phiini, # phiSetp
externalNet.cpArea.loc_name if externalNet.cpArea is not None else "", # subnet
externalNet.cpZone.loc_name if externalNet.cpZone is not None else "" # voltLvl
])
else:
dpf.PrintError("This export profile isn't implemented yet.")
exit(1)
return (idxWs, expMat) | """
@author: Kittl
"""
def export_external_nets(dpf, exportProfile, tables, colHeads):
if exportProfile is 2:
cmp_str = 'ExternalNet'
elif exportProfile is 3:
cmp_str = ''
idx_ws = [idx for (idx, val) in enumerate(tables[exportProfile - 1]) if val == cmpStr]
if not idxWs:
dpf.PrintPlain('')
dpf.PrintInfo('There is no worksheet ' + (cmpStr if not cmpStr == '' else 'for external nets') + ' defined. Skip this one!')
return (None, None)
elif len(idxWs) > 1:
dpf.PrintError('There is more than one table with the name ' + cmpStr + ' defined. Cancel this script.')
exit(1)
else:
idx_ws = idxWs[0]
col_head = list()
for c_head in colHeads[exportProfile - 1][idxWs]:
colHead.append(str(cHead.name))
dpf.PrintPlain('')
dpf.PrintPlain('#####################################')
dpf.PrintPlain('# Starting to export external nets. #')
dpf.PrintPlain('#####################################')
exp_mat = list()
expMat.append(colHead)
external_nets = dpf.GetCalcRelevantObjects('*.ElmXNet')
for external_net in externalNets:
if exportProfile is 2:
if externalNet.uset_mode is 1:
vtarget = externalNet.cpCtrlNode.vtarget
if not externalNet.cpCtrlNode.loc_name == externalNet.bus1.cterm.loc_name:
dpf.PrintWarn('The external net ' + externalNet.loc_name + ' regulates the voltage at node ' + externalNet.cpCtrlNode.loc_name + ', which is not the current node.')
else:
vtarget = externalNet.usetp
expMat.append([externalNet.loc_name, externalNet.bus1.cterm.loc_name, vtarget, externalNet.phiini, externalNet.cpArea.loc_name if externalNet.cpArea is not None else '', externalNet.cpZone.loc_name if externalNet.cpZone is not None else ''])
else:
dpf.PrintError("This export profile isn't implemented yet.")
exit(1)
return (idxWs, expMat) |
class DefaultQuotaPlugin(object):
def get_default_quota(self, user, provider):
raise NotImplementedError("Validation plugins must implement a get_default_quota function that "
"takes two arguments: 'user' and 'provider")
| class Defaultquotaplugin(object):
def get_default_quota(self, user, provider):
raise not_implemented_error("Validation plugins must implement a get_default_quota function that takes two arguments: 'user' and 'provider") |
# https://www.hackerrank.com/challenges/30-nested-logic/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
Da, Ma, Ya = map(int, input().split())
De, Me, Ye = map(int, input().split())
fine = 0
if Ya-Ye<0:
fine = 0
elif Ya-Ye == 0:
if Ma-Me < 0:
fine = 0
elif Ma-Me == 0:
if Da-De<=0:
fine = 0
else:
fine = 15 * (Da-De)
else:
fine = 500 * (Ma - Me)
else:
fine = 10000
print(fine); | (da, ma, ya) = map(int, input().split())
(de, me, ye) = map(int, input().split())
fine = 0
if Ya - Ye < 0:
fine = 0
elif Ya - Ye == 0:
if Ma - Me < 0:
fine = 0
elif Ma - Me == 0:
if Da - De <= 0:
fine = 0
else:
fine = 15 * (Da - De)
else:
fine = 500 * (Ma - Me)
else:
fine = 10000
print(fine) |
class Piece:
def __init__(self, s):
split = s.replace("\n", "").split(' ')
self.number = int(split[0][1:])
offset = split[2][:-1].split(',')
self._left_offset = int(offset[0])
self._top_offset = int(offset[1])
size = split[3].split('x')
self._width = int(size[0])
self._height = int(size[1])
self.Corners = [
(self.left_offset, self.top_offset),
(self.left_offset + self.width - 1, self.top_offset),
(self.left_offset + self.width - 1, self.top_offset + self.height - 1),
(self.left_offset, self.top_offset + self.height - 1)
]
@property
def top_offset(self):
return self._top_offset
@property
def left_offset(self):
return self._left_offset
@property
def width(self):
return self._width
@property
def height(self):
return self._height
def overlaps(self, piece):
for corner in piece.Corners:
if self.contains(corner):
return True
for corner in self.Corners:
if piece.contains(corner):
return True
if ((self.Corners[0][0] <= piece.Corners[0][0] < self.Corners[1][0]) or
(self.Corners[0][0] <= piece.Corners[1][0] < self.Corners[1][0])) and \
((piece.Corners[0][1] <= self.Corners[0][1] < piece.Corners[3][1]) or
(piece.Corners[0][1] <= self.Corners[3][1] < piece.Corners[3][1])):
return True
if ((piece.Corners[0][0] <= self.Corners[0][0] < piece.Corners[1][0]) or
(piece.Corners[0][0] <= self.Corners[1][0] < piece.Corners[1][0])) and \
((self.Corners[0][1] <= piece.Corners[0][1] < self.Corners[3][1]) or
(self.Corners[0][1] <= piece.Corners[3][1] < self.Corners[3][1])):
return True
return False
def contains(self, point):
return self.left_offset <= point[0] < self.left_offset + self.width and \
self.top_offset <= point[1] < self.top_offset + self.height
| class Piece:
def __init__(self, s):
split = s.replace('\n', '').split(' ')
self.number = int(split[0][1:])
offset = split[2][:-1].split(',')
self._left_offset = int(offset[0])
self._top_offset = int(offset[1])
size = split[3].split('x')
self._width = int(size[0])
self._height = int(size[1])
self.Corners = [(self.left_offset, self.top_offset), (self.left_offset + self.width - 1, self.top_offset), (self.left_offset + self.width - 1, self.top_offset + self.height - 1), (self.left_offset, self.top_offset + self.height - 1)]
@property
def top_offset(self):
return self._top_offset
@property
def left_offset(self):
return self._left_offset
@property
def width(self):
return self._width
@property
def height(self):
return self._height
def overlaps(self, piece):
for corner in piece.Corners:
if self.contains(corner):
return True
for corner in self.Corners:
if piece.contains(corner):
return True
if (self.Corners[0][0] <= piece.Corners[0][0] < self.Corners[1][0] or self.Corners[0][0] <= piece.Corners[1][0] < self.Corners[1][0]) and (piece.Corners[0][1] <= self.Corners[0][1] < piece.Corners[3][1] or piece.Corners[0][1] <= self.Corners[3][1] < piece.Corners[3][1]):
return True
if (piece.Corners[0][0] <= self.Corners[0][0] < piece.Corners[1][0] or piece.Corners[0][0] <= self.Corners[1][0] < piece.Corners[1][0]) and (self.Corners[0][1] <= piece.Corners[0][1] < self.Corners[3][1] or self.Corners[0][1] <= piece.Corners[3][1] < self.Corners[3][1]):
return True
return False
def contains(self, point):
return self.left_offset <= point[0] < self.left_offset + self.width and self.top_offset <= point[1] < self.top_offset + self.height |
dev_packages = [
"karbon",
"librsvg2-bin",
]
| dev_packages = ['karbon', 'librsvg2-bin'] |
s = input()
c = 0
for _ in range(int(input())):
if s in input() * 2:
c += 1
print(c)
| s = input()
c = 0
for _ in range(int(input())):
if s in input() * 2:
c += 1
print(c) |
#
# PySNMP MIB module NETBOTZ-SNMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETBOTZ-SNMP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:18:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint")
netBotz_snmp, = mibBuilder.importSymbols("NETBOTZ-MIB", "netBotz-snmp")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
IpAddress, iso, NotificationType, ObjectIdentity, TimeTicks, Gauge32, Counter32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Bits, Integer32, MibIdentifier, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "iso", "NotificationType", "ObjectIdentity", "TimeTicks", "Gauge32", "Counter32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Bits", "Integer32", "MibIdentifier", "Counter64")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
netBotz_snmp_traptarget = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 1), IpAddress()).setLabel("netBotz-snmp-traptarget").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_snmp_traptarget.setReference('Netbotz Trap Target')
if mibBuilder.loadTexts: netBotz_snmp_traptarget.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_snmp_traptarget.setDescription('Target of traps from the Netbotz device. This field contains the IP address where Netbotz traps are to be sent.')
netBotz_snmp_community = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 2), DisplayString()).setLabel("netBotz-snmp-community").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_snmp_community.setReference('Read/Write Community')
if mibBuilder.loadTexts: netBotz_snmp_community.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_snmp_community.setDescription('The read/write community of the Netbotz device.')
netBotz_snmp_timeout = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 3), Integer32()).setLabel("netBotz-snmp-timeout").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_snmp_timeout.setReference('SNMP Timeout')
if mibBuilder.loadTexts: netBotz_snmp_timeout.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_snmp_timeout.setDescription('SNMP Timeout period.')
netBotz_snmp_retries = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 4), Integer32()).setLabel("netBotz-snmp-retries").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_snmp_retries.setReference('SNMP Retries')
if mibBuilder.loadTexts: netBotz_snmp_retries.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_snmp_retries.setDescription('SNMP Retry count.')
netBotz_userid_1 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 5), DisplayString()).setLabel("netBotz-userid-1").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_userid_1.setReference('UserID 1')
if mibBuilder.loadTexts: netBotz_userid_1.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_userid_1.setDescription('The userID of the supervisor account (write-only).')
netBotz_password_1 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 6), DisplayString()).setLabel("netBotz-password-1").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_password_1.setReference('Password 1')
if mibBuilder.loadTexts: netBotz_password_1.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_password_1.setDescription('The password of the supervisor account (write-only).')
netBotz_userid_2 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 7), DisplayString()).setLabel("netBotz-userid-2").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_userid_2.setReference('UserID 2')
if mibBuilder.loadTexts: netBotz_userid_2.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_userid_2.setDescription('The userID of the full read access account (write-only).')
netBotz_password_2 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 8), DisplayString()).setLabel("netBotz-password-2").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_password_2.setReference('Password 2')
if mibBuilder.loadTexts: netBotz_password_2.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_password_2.setDescription('The password of the full read access account (write-only).')
netBotz_userid_3 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 9), DisplayString()).setLabel("netBotz-userid-3").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_userid_3.setReference('UserID 3')
if mibBuilder.loadTexts: netBotz_userid_3.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_userid_3.setDescription('The userID of the minimum read access account (write-only).')
netBotz_password_3 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 10), DisplayString()).setLabel("netBotz-password-3").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_password_3.setReference('Password 3')
if mibBuilder.loadTexts: netBotz_password_3.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_password_3.setDescription('The password of the minimum read access account (write-only).')
netBotz_snmp_traptarget2 = MibScalar((1, 3, 6, 1, 4, 1, 5528, 40, 11), IpAddress()).setLabel("netBotz-snmp-traptarget2").setMaxAccess("readwrite")
if mibBuilder.loadTexts: netBotz_snmp_traptarget2.setReference('Netbotz Trap Target 2')
if mibBuilder.loadTexts: netBotz_snmp_traptarget2.setStatus('mandatory')
if mibBuilder.loadTexts: netBotz_snmp_traptarget2.setDescription('Second target of traps from the Netbotz device. This field contains an additional IP address where Netbotz traps are to be sent.')
mibBuilder.exportSymbols("NETBOTZ-SNMP-MIB", netBotz_snmp_retries=netBotz_snmp_retries, netBotz_userid_1=netBotz_userid_1, netBotz_password_2=netBotz_password_2, netBotz_snmp_traptarget=netBotz_snmp_traptarget, netBotz_snmp_traptarget2=netBotz_snmp_traptarget2, netBotz_password_3=netBotz_password_3, netBotz_snmp_timeout=netBotz_snmp_timeout, netBotz_snmp_community=netBotz_snmp_community, netBotz_password_1=netBotz_password_1, netBotz_userid_2=netBotz_userid_2, netBotz_userid_3=netBotz_userid_3)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, value_size_constraint, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint')
(net_botz_snmp,) = mibBuilder.importSymbols('NETBOTZ-MIB', 'netBotz-snmp')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(ip_address, iso, notification_type, object_identity, time_ticks, gauge32, counter32, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, bits, integer32, mib_identifier, counter64) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'iso', 'NotificationType', 'ObjectIdentity', 'TimeTicks', 'Gauge32', 'Counter32', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Bits', 'Integer32', 'MibIdentifier', 'Counter64')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
net_botz_snmp_traptarget = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 1), ip_address()).setLabel('netBotz-snmp-traptarget').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_snmp_traptarget.setReference('Netbotz Trap Target')
if mibBuilder.loadTexts:
netBotz_snmp_traptarget.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_snmp_traptarget.setDescription('Target of traps from the Netbotz device. This field contains the IP address where Netbotz traps are to be sent.')
net_botz_snmp_community = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 2), display_string()).setLabel('netBotz-snmp-community').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_snmp_community.setReference('Read/Write Community')
if mibBuilder.loadTexts:
netBotz_snmp_community.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_snmp_community.setDescription('The read/write community of the Netbotz device.')
net_botz_snmp_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 3), integer32()).setLabel('netBotz-snmp-timeout').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_snmp_timeout.setReference('SNMP Timeout')
if mibBuilder.loadTexts:
netBotz_snmp_timeout.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_snmp_timeout.setDescription('SNMP Timeout period.')
net_botz_snmp_retries = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 4), integer32()).setLabel('netBotz-snmp-retries').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_snmp_retries.setReference('SNMP Retries')
if mibBuilder.loadTexts:
netBotz_snmp_retries.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_snmp_retries.setDescription('SNMP Retry count.')
net_botz_userid_1 = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 5), display_string()).setLabel('netBotz-userid-1').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_userid_1.setReference('UserID 1')
if mibBuilder.loadTexts:
netBotz_userid_1.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_userid_1.setDescription('The userID of the supervisor account (write-only).')
net_botz_password_1 = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 6), display_string()).setLabel('netBotz-password-1').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_password_1.setReference('Password 1')
if mibBuilder.loadTexts:
netBotz_password_1.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_password_1.setDescription('The password of the supervisor account (write-only).')
net_botz_userid_2 = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 7), display_string()).setLabel('netBotz-userid-2').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_userid_2.setReference('UserID 2')
if mibBuilder.loadTexts:
netBotz_userid_2.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_userid_2.setDescription('The userID of the full read access account (write-only).')
net_botz_password_2 = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 8), display_string()).setLabel('netBotz-password-2').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_password_2.setReference('Password 2')
if mibBuilder.loadTexts:
netBotz_password_2.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_password_2.setDescription('The password of the full read access account (write-only).')
net_botz_userid_3 = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 9), display_string()).setLabel('netBotz-userid-3').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_userid_3.setReference('UserID 3')
if mibBuilder.loadTexts:
netBotz_userid_3.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_userid_3.setDescription('The userID of the minimum read access account (write-only).')
net_botz_password_3 = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 10), display_string()).setLabel('netBotz-password-3').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_password_3.setReference('Password 3')
if mibBuilder.loadTexts:
netBotz_password_3.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_password_3.setDescription('The password of the minimum read access account (write-only).')
net_botz_snmp_traptarget2 = mib_scalar((1, 3, 6, 1, 4, 1, 5528, 40, 11), ip_address()).setLabel('netBotz-snmp-traptarget2').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
netBotz_snmp_traptarget2.setReference('Netbotz Trap Target 2')
if mibBuilder.loadTexts:
netBotz_snmp_traptarget2.setStatus('mandatory')
if mibBuilder.loadTexts:
netBotz_snmp_traptarget2.setDescription('Second target of traps from the Netbotz device. This field contains an additional IP address where Netbotz traps are to be sent.')
mibBuilder.exportSymbols('NETBOTZ-SNMP-MIB', netBotz_snmp_retries=netBotz_snmp_retries, netBotz_userid_1=netBotz_userid_1, netBotz_password_2=netBotz_password_2, netBotz_snmp_traptarget=netBotz_snmp_traptarget, netBotz_snmp_traptarget2=netBotz_snmp_traptarget2, netBotz_password_3=netBotz_password_3, netBotz_snmp_timeout=netBotz_snmp_timeout, netBotz_snmp_community=netBotz_snmp_community, netBotz_password_1=netBotz_password_1, netBotz_userid_2=netBotz_userid_2, netBotz_userid_3=netBotz_userid_3) |
setA = {"John", "Bob", "Mary", "Serena"}
setB = {"Jim", "Mary", "John", "Bob"}
setA ^ setB # symmetric difference of A and B
{'Jim', 'Serena'}
setA - setB # elements in A that are not in B
{'Serena'}
setB - setA # elements in B that are not in A
{'Jim'}
setA | setB # elements in A or B (union)
{'John', 'Bob', 'Jim', 'Serena', 'Mary'}
setA & setB # elements in both A and B (intersection)
{'Bob', 'John', 'Mary'}
| set_a = {'John', 'Bob', 'Mary', 'Serena'}
set_b = {'Jim', 'Mary', 'John', 'Bob'}
setA ^ setB
{'Jim', 'Serena'}
setA - setB
{'Serena'}
setB - setA
{'Jim'}
setA | setB
{'John', 'Bob', 'Jim', 'Serena', 'Mary'}
setA & setB
{'Bob', 'John', 'Mary'} |
def main():
size_of_tlb = input('Input size of TLB\n')
tlb(size_of_tlb, 'execution_large.txt')
def tlb(size, file):
f = open(file, 'r')
f1 = f.readlines()
page = ''
page_list = []
#reads in pages from file
for line in f1:
for bit in xrange(0,54):
page += str(line[bit])
page_list.append(page)
page = ''
#puts into dictionary and will replace key value pair with lowest value/count with new one.
tlb_dict = {}
tlb_miss = 0
for page in page_list:
if len(tlb_dict) < size:
if page not in tlb_dict:
tlb_dict[page] = 1
tlb_miss += 1
elif page in tlb_dict:
tlb_dict[page] += 1
elif len(tlb_dict) == size:
if page not in tlb_dict:
min_page_key = min(tlb_dict, key = tlb_dict.get)
del tlb_dict[min_page_key]
tlb_dict[page] = 1
tlb_miss += 1
elif page in tlb_dict:
tlb_dict[page] += 1
print('\n')
print('Amount of TLB Misses: {}'.format(tlb_miss))
if __name__ == '__main__':
main()
| def main():
size_of_tlb = input('Input size of TLB\n')
tlb(size_of_tlb, 'execution_large.txt')
def tlb(size, file):
f = open(file, 'r')
f1 = f.readlines()
page = ''
page_list = []
for line in f1:
for bit in xrange(0, 54):
page += str(line[bit])
page_list.append(page)
page = ''
tlb_dict = {}
tlb_miss = 0
for page in page_list:
if len(tlb_dict) < size:
if page not in tlb_dict:
tlb_dict[page] = 1
tlb_miss += 1
elif page in tlb_dict:
tlb_dict[page] += 1
elif len(tlb_dict) == size:
if page not in tlb_dict:
min_page_key = min(tlb_dict, key=tlb_dict.get)
del tlb_dict[min_page_key]
tlb_dict[page] = 1
tlb_miss += 1
elif page in tlb_dict:
tlb_dict[page] += 1
print('\n')
print('Amount of TLB Misses: {}'.format(tlb_miss))
if __name__ == '__main__':
main() |
'''
Queue - FIFO
Implementtaion of a queue using python List class
the end of the list = rear of the queue
the begining of the list = front of the queue
enqueue = O(n)
dequeue = O(1)
'''
class Queue:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items == []
def dequeue(self):
if self.isEmpty():
return float('-inf')
else:
return self.items.pop()
def enqueue(self,item):
self.items.insert(0,item)
def size(self):
return len(self.items)
def __repr__(self):
print('called')
return str(self.items)
if __name__ == '__main__':
s=Queue()
type(s)
s.enqueue(10)
s.enqueue(11)
s.dequeue()
print(s) # 11
| """
Queue - FIFO
Implementtaion of a queue using python List class
the end of the list = rear of the queue
the begining of the list = front of the queue
enqueue = O(n)
dequeue = O(1)
"""
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def dequeue(self):
if self.isEmpty():
return float('-inf')
else:
return self.items.pop()
def enqueue(self, item):
self.items.insert(0, item)
def size(self):
return len(self.items)
def __repr__(self):
print('called')
return str(self.items)
if __name__ == '__main__':
s = queue()
type(s)
s.enqueue(10)
s.enqueue(11)
s.dequeue()
print(s) |
S = input()
result = 0
for c in S:
if c in '0123456789':
result += int(c)
print(result)
| s = input()
result = 0
for c in S:
if c in '0123456789':
result += int(c)
print(result) |
if __name__ == '__main__':
n = 0
p = input('input a octal number:\n')
for i in range(len(p)):
n = n * 8 + ord(p[i]) - ord('0')
print(n)
# 8 ---> 10
| if __name__ == '__main__':
n = 0
p = input('input a octal number:\n')
for i in range(len(p)):
n = n * 8 + ord(p[i]) - ord('0')
print(n) |
def max_number(number1,number2,number3):
max1= max(number1,number2)
max2= max(max1,number3)
print(max2)
max_number(5,4,3)
def min_number(number1,number2,number3):
min1= min(number1,number2)
min2= min(min1,number3)
print(min2)
min_number(5,4,3)
| def max_number(number1, number2, number3):
max1 = max(number1, number2)
max2 = max(max1, number3)
print(max2)
max_number(5, 4, 3)
def min_number(number1, number2, number3):
min1 = min(number1, number2)
min2 = min(min1, number3)
print(min2)
min_number(5, 4, 3) |
sql_vals = {'host' : 'localhost',
'port' : 3306,
'db' : 'gaime',
'user' : 'gaimeAdmin',
'password' : 'BBEgaime3'}
| sql_vals = {'host': 'localhost', 'port': 3306, 'db': 'gaime', 'user': 'gaimeAdmin', 'password': 'BBEgaime3'} |
# https://www.hackerrank.com/challenges/staircase/problem
def staircase(size):
spaces = size - 1
for i in range(size):
print('{spaces}{hashes}'.format(spaces=' ' * spaces, hashes='#' * (size - spaces)))
spaces -= 1
staircase(4)
| def staircase(size):
spaces = size - 1
for i in range(size):
print('{spaces}{hashes}'.format(spaces=' ' * spaces, hashes='#' * (size - spaces)))
spaces -= 1
staircase(4) |
# see: https://leetcode.com/problems/two-sum/
class Solution:
def twoSum(self, nums: [int], target: int) -> [int]:
nums_size = len(nums)
complements = []
for i in range(nums_size):
complement = target - nums[i]
if complement in complements:
return [nums.index(complement), i]
complements.append(nums[i])
return []
if __name__ == '__main__':
solution = Solution()
print(solution.twoSum([2, 7, 11, 15], 9)) # [0, 1]
| class Solution:
def two_sum(self, nums: [int], target: int) -> [int]:
nums_size = len(nums)
complements = []
for i in range(nums_size):
complement = target - nums[i]
if complement in complements:
return [nums.index(complement), i]
complements.append(nums[i])
return []
if __name__ == '__main__':
solution = solution()
print(solution.twoSum([2, 7, 11, 15], 9)) |
self.description = "Install a package from a sync db, with a filesystem conflict"
sp = pmpkg("dummy")
sp.files = ["bin/dummy",
"usr/man/man1/dummy.1"]
self.addpkg2db("sync", sp)
self.filesystem = ["bin/dummy"]
self.args = "-S %s" % sp.name
self.addrule("PACMAN_RETCODE=1")
self.addrule("!PKG_EXIST=dummy")
| self.description = 'Install a package from a sync db, with a filesystem conflict'
sp = pmpkg('dummy')
sp.files = ['bin/dummy', 'usr/man/man1/dummy.1']
self.addpkg2db('sync', sp)
self.filesystem = ['bin/dummy']
self.args = '-S %s' % sp.name
self.addrule('PACMAN_RETCODE=1')
self.addrule('!PKG_EXIST=dummy') |
# to do: pytz support
class Timer(object):
def __init__(self, start_time: int, end_time: int, ticker_size: int):
self._start_time = start_time
self._end_time = end_time
self._step = ticker_size
self._current_time = start_time
@property
def time(self):
return self._current_time
def next(self) -> bool:
self._current_time += self._step
if self._current_time > self._end_time:
return True
else:
return False
| class Timer(object):
def __init__(self, start_time: int, end_time: int, ticker_size: int):
self._start_time = start_time
self._end_time = end_time
self._step = ticker_size
self._current_time = start_time
@property
def time(self):
return self._current_time
def next(self) -> bool:
self._current_time += self._step
if self._current_time > self._end_time:
return True
else:
return False |
_base_config_ = ["../cse.py","../defaults.py"]
dummy_anonymizer = True
generator = dict(
type="PixelationGenerator",
pixelation_size=16
)
| _base_config_ = ['../cse.py', '../defaults.py']
dummy_anonymizer = True
generator = dict(type='PixelationGenerator', pixelation_size=16) |
class UnionFind:
def __init__(self, n):
# Every element is a different component.
self.data = [i for i in range(n)]
def find(self, i):
if i != self.data[i]:
self.data[i] = self.find(self.data[i])
return self.data[i]
def union(self, i, j):
pi, pj = self.find(i), self.find(j)
if pi != pj:
self.data[pi] = pj
u = UnionFind(10)
connections = [(0, 1), (1, 2), (0, 9), (5, 6), (6, 4), (5, 9)]
# union
for i, j in connections:
u.union(i, j)
# find
for i in range(10):
print('item', i, '-> component', u.find(i)) | class Unionfind:
def __init__(self, n):
self.data = [i for i in range(n)]
def find(self, i):
if i != self.data[i]:
self.data[i] = self.find(self.data[i])
return self.data[i]
def union(self, i, j):
(pi, pj) = (self.find(i), self.find(j))
if pi != pj:
self.data[pi] = pj
u = union_find(10)
connections = [(0, 1), (1, 2), (0, 9), (5, 6), (6, 4), (5, 9)]
for (i, j) in connections:
u.union(i, j)
for i in range(10):
print('item', i, '-> component', u.find(i)) |
# Evaludate various kinds of diffs in files
class FileDiff:
def __init__(self):
'''
initialize for diffing files
'''
| class Filediff:
def __init__(self):
"""
initialize for diffing files
""" |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
# String for partition column badge
PARTITION_BADGE = 'partition column'
| partition_badge = 'partition column' |
n = int(input())
sum = 0
for i in range(0,n):
num = int(input())
sum+=num
print(sum)
| n = int(input())
sum = 0
for i in range(0, n):
num = int(input())
sum += num
print(sum) |
class Group(object):
def __init__(self, groupId, ownerJid, subject, subjectOwnerJid, subjectTime, creationTime):
self._groupId = groupId
self._ownerJid = ownerJid
self._subject = subject
self._subjectOwnerJid = subjectOwnerJid
self._subjectTime = int(subjectTime)
self._creationTime = int(creationTime)
def getId(self):
return self._groupId
def getOwner(self):
return self._ownerJid
def getSubject(self):
return self._subject
def getSubjectOwner(self):
return self._subjectOwnerJid
def getSubjectTime(self):
return self._subjectTime
def getCreationTime(self):
return self._creationTime
def __str__(self):
return "ID: %s, Subject: %s, Creation: %s, Owner: %s, Subject Owner: %s, Subject Time: %s" %\
(self.getId(), self.getSubject(), self.getCreationTime(), self.getOwner(), self.getSubjectOwner(), self.getSubjectTime())
| class Group(object):
def __init__(self, groupId, ownerJid, subject, subjectOwnerJid, subjectTime, creationTime):
self._groupId = groupId
self._ownerJid = ownerJid
self._subject = subject
self._subjectOwnerJid = subjectOwnerJid
self._subjectTime = int(subjectTime)
self._creationTime = int(creationTime)
def get_id(self):
return self._groupId
def get_owner(self):
return self._ownerJid
def get_subject(self):
return self._subject
def get_subject_owner(self):
return self._subjectOwnerJid
def get_subject_time(self):
return self._subjectTime
def get_creation_time(self):
return self._creationTime
def __str__(self):
return 'ID: %s, Subject: %s, Creation: %s, Owner: %s, Subject Owner: %s, Subject Time: %s' % (self.getId(), self.getSubject(), self.getCreationTime(), self.getOwner(), self.getSubjectOwner(), self.getSubjectTime()) |
# StompMessageBroker is a proxy class of StompDaemonConnection with only a sendMessage method
# This exposes a simple interface for a StompMessageController method to communicate via the broker
class StompMessageBroker():
def __init__(self, stomp_daemon_connection):
self.stomp_daemon_connection = stomp_daemon_connection
def sendMessage(self, message, queue):
print("stomp_message_broker.sendMessage() - {0} - {1}".format(queue, message))
#print(self.stomp_daemon_connection)
self.stomp_daemon_connection.stompConn.send(queue, message)
def brokerId():
return self.stomp_daemon_connection.msgSrvrClientId | class Stompmessagebroker:
def __init__(self, stomp_daemon_connection):
self.stomp_daemon_connection = stomp_daemon_connection
def send_message(self, message, queue):
print('stomp_message_broker.sendMessage() - {0} - {1}'.format(queue, message))
self.stomp_daemon_connection.stompConn.send(queue, message)
def broker_id():
return self.stomp_daemon_connection.msgSrvrClientId |
######################################
# CHECK AGAIN. NOT WORKING ACCORDINGLY
######################################
class Node(object):
def __init__(self, val, parent=None):
self.val = val
self.leftChild = None
self.rightChild = None
self.parent = parent
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def getParent(self):
return self.parent
def isRoot(self):
return self.parent != None
def hasLeftChild(self):
return self.leftChild != None
def hasRightChild(self):
return self.rightChild != None
def hasBothChildren(self):
return self.hasLeftChild() and self.hasRightChild()
def hasOneChild(self):
return self.hasLeftChild() or self.hasRightChild()
class BinarySearchTree(object):
def __init__(self):
self.size = 0
self.root = None
def insert(self, val):
if not self.root:
self.root = Node(val)
else:
temp = self.root
done = False
while not done:
if val < temp.val:
if temp.hasLeftChild():
temp = temp.getLeftChild()
else:
temp.leftChild = Node(val, temp)
done = True
else:
if temp.hasRightChild():
temp = temp.getRightChild()
else:
temp.rightChild = Node(val, temp)
done = True
self.size += 1
def inorder(self, root):
if root:
self.inorder(root.leftChild)
print(root.val, end=" ")
self.inorder(root.rightChild)
def trimBST(self, tree, minVal, maxVal):
if not tree:
return
tree.leftChild = self.trimBST(tree.leftChild, minVal, maxVal)
tree.rightChild = self.trimBST(tree.rightChild, minVal, maxVal)
if minVal <= tree.val <= maxVal:
return tree
if tree.val < minVal:
return tree.rightChild
if tree.val > maxVal:
return tree.leftChild
if __name__ == "__main__":
b = BinarySearchTree()
b.insert(25)
b.insert(15)
b.insert(8)
b.insert(20)
b.insert(17)
b.insert(16)
b.insert(18)
b.insert(40)
b.insert(35)
b.insert(46)
b.insert(42)
b.insert(50)
b.inorder(b.root)
print("Root:", b.root.val)
print("After trimming:")
b.trimBST(b.root, 20, 46)
b.inorder(b.root)
| class Node(object):
def __init__(self, val, parent=None):
self.val = val
self.leftChild = None
self.rightChild = None
self.parent = parent
def get_left_child(self):
return self.leftChild
def get_right_child(self):
return self.rightChild
def get_parent(self):
return self.parent
def is_root(self):
return self.parent != None
def has_left_child(self):
return self.leftChild != None
def has_right_child(self):
return self.rightChild != None
def has_both_children(self):
return self.hasLeftChild() and self.hasRightChild()
def has_one_child(self):
return self.hasLeftChild() or self.hasRightChild()
class Binarysearchtree(object):
def __init__(self):
self.size = 0
self.root = None
def insert(self, val):
if not self.root:
self.root = node(val)
else:
temp = self.root
done = False
while not done:
if val < temp.val:
if temp.hasLeftChild():
temp = temp.getLeftChild()
else:
temp.leftChild = node(val, temp)
done = True
elif temp.hasRightChild():
temp = temp.getRightChild()
else:
temp.rightChild = node(val, temp)
done = True
self.size += 1
def inorder(self, root):
if root:
self.inorder(root.leftChild)
print(root.val, end=' ')
self.inorder(root.rightChild)
def trim_bst(self, tree, minVal, maxVal):
if not tree:
return
tree.leftChild = self.trimBST(tree.leftChild, minVal, maxVal)
tree.rightChild = self.trimBST(tree.rightChild, minVal, maxVal)
if minVal <= tree.val <= maxVal:
return tree
if tree.val < minVal:
return tree.rightChild
if tree.val > maxVal:
return tree.leftChild
if __name__ == '__main__':
b = binary_search_tree()
b.insert(25)
b.insert(15)
b.insert(8)
b.insert(20)
b.insert(17)
b.insert(16)
b.insert(18)
b.insert(40)
b.insert(35)
b.insert(46)
b.insert(42)
b.insert(50)
b.inorder(b.root)
print('Root:', b.root.val)
print('After trimming:')
b.trimBST(b.root, 20, 46)
b.inorder(b.root) |
name = 'Amadikwa Joy N'
age = '25'
address = 'Owerri Imo State'
print(name)
print(age)
print(address)
| name = 'Amadikwa Joy N'
age = '25'
address = 'Owerri Imo State'
print(name)
print(age)
print(address) |
all_min = int(input())
hours = all_min // 60
minuts = all_min - hours*60
print(hours)
print(minuts) | all_min = int(input())
hours = all_min // 60
minuts = all_min - hours * 60
print(hours)
print(minuts) |
# optimizer
optimizer = dict(type='Adam', lr=0.0002, weight_decay=0)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[])
runner = dict(type='EpochBasedRunner', max_epochs=50)
| optimizer = dict(type='Adam', lr=0.0002, weight_decay=0)
optimizer_config = dict(grad_clip=None)
lr_config = dict(policy='step', step=[])
runner = dict(type='EpochBasedRunner', max_epochs=50) |
n=int(input())
r=""
while n>1:
r+=str(n)+" "
if n%2==0:
n=n//2
else:
n=3*n+1
r+=str(n)
print(r)
| n = int(input())
r = ''
while n > 1:
r += str(n) + ' '
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
r += str(n)
print(r) |
#this program makes a simple calculator which can aad,subtract,multiply,divide using functions
#this function adds two number
def add(a,b):
return a+b
#this function subtracts two numbers
def subtract(a,b):
return a-b
#this function multiplies two numbers
def multiply(a,b):
return a*b
#this function divides two numbers
def divide(a,b):
return a/b
print("select operation.")
print("1.add")
print("2.subtract")
print("3.multiply")
print("4.divide")
#take input from the user
choice=input("enter choice(1/2/3/4):")
num1=int(input("enter first number:"))
num2=int(input("enter second number:"))
if choice =='1':
print(num1,"+",num2,"=",add(num1,num2))
elif choice=='2':
print(num1,"-",num2,"=",subtract(num1,num2))
elif choice=='3':
print(num1,"*",num2,"=",multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=",divide(num1,num2))
else:
print("invalid input")
| def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
print('select operation.')
print('1.add')
print('2.subtract')
print('3.multiply')
print('4.divide')
choice = input('enter choice(1/2/3/4):')
num1 = int(input('enter first number:'))
num2 = int(input('enter second number:'))
if choice == '1':
print(num1, '+', num2, '=', add(num1, num2))
elif choice == '2':
print(num1, '-', num2, '=', subtract(num1, num2))
elif choice == '3':
print(num1, '*', num2, '=', multiply(num1, num2))
elif choice == '4':
print(num1, '/', num2, '=', divide(num1, num2))
else:
print('invalid input') |
class Config:
tmp_save_dir='../../models_python'
train_num_workers=6
test_num_workers=3
# train_num_workers=0
# test_num_workers=0
# data_path='../../CT_rotation_data_npy_128'
# model_name='Aug3D'
# lvl1_size=4
# is3d=True
# train_batch_size = 8
# test_batch_size = 4
# max_epochs = 14
# step_size=6
# gamma=0.1
# init_lr=0.001
data_path='../../CT_rotation_data_2D'
model_name='NoAug2D'
is3d=False
train_batch_size = 32
test_batch_size = 32
max_epochs = 12
step_size=5
gamma=0.1
init_lr=0.001
pretrained=True
| class Config:
tmp_save_dir = '../../models_python'
train_num_workers = 6
test_num_workers = 3
data_path = '../../CT_rotation_data_2D'
model_name = 'NoAug2D'
is3d = False
train_batch_size = 32
test_batch_size = 32
max_epochs = 12
step_size = 5
gamma = 0.1
init_lr = 0.001
pretrained = True |
# Num = numero digita
# ========================================================================
# titulo e coleta de dados
print("\033[35m============[ EX 006 ]============")
print(34 * "=", "\033[m")
Num = int(input("Digite um \033[35mnumero\033[m: "))
print(34 * "\033[35m=", "\033[m")
# ========================================================================
# mostra o dobro,triplo e raiz quadrado do numero digitado
print(f"dobro de \033[35m{Num}\033[m = \033[35m{Num * 2}\033[m")
print(f"triplo de \033[35m{Num}\033[m = \033[35m{Num * 3}\033[m")
print(f"raiz quadrada de \033[35m{Num}\033[m = \033[35m{Num * Num}\033[m")
print(34 * "\033[35m=", "\033[m")
# ========================================================================
| print('\x1b[35m============[ EX 006 ]============')
print(34 * '=', '\x1b[m')
num = int(input('Digite um \x1b[35mnumero\x1b[m: '))
print(34 * '\x1b[35m=', '\x1b[m')
print(f'dobro de \x1b[35m{Num}\x1b[m = \x1b[35m{Num * 2}\x1b[m')
print(f'triplo de \x1b[35m{Num}\x1b[m = \x1b[35m{Num * 3}\x1b[m')
print(f'raiz quadrada de \x1b[35m{Num}\x1b[m = \x1b[35m{Num * Num}\x1b[m')
print(34 * '\x1b[35m=', '\x1b[m') |
#!/usr/bin/env python3
inputs = list()
DEBUG = False
with open('input', 'r') as f:
inputs = f.read().splitlines()
balls = [int(ball) for ball in inputs.pop(0).split(',')]
if DEBUG:
print(balls)
inputs.pop(0)
card = 0
cards = list()
cards.append(list())
while(len(inputs) > 0):
line = inputs.pop(0)
if len(line) == 0:
if DEBUG:
print(cards[card])
card += 1
cards.append(list())
continue
cards[card].extend([int(n) for n in line.split()])
def winner(card):
for i in range(5):
# row all stamped
if card[(i*5):((i+1)*5)].count(-1) == 5:
return True
# column all stamped
if [card[i+r] for r in range(0,25,5)].count(-1) == 5:
return True
return False
stamp_idx = 0
for ball in balls:
for c in range(len(cards)):
try:
stamp_idx = cards[c].index(ball)
except:
continue
cards[c].pop(stamp_idx)
cards[c].insert(stamp_idx,-1)
if winner(cards[c]):
card_total = sum(filter(lambda x: x != -1, cards[c]))
if DEBUG:
print(f"c {c} card_total {card_total} ball {ball}")
print(f"called balls {balls[:balls.index(ball)]}")
print(f"card {cards[c]}")
print(card_total * ball)
exit()
| inputs = list()
debug = False
with open('input', 'r') as f:
inputs = f.read().splitlines()
balls = [int(ball) for ball in inputs.pop(0).split(',')]
if DEBUG:
print(balls)
inputs.pop(0)
card = 0
cards = list()
cards.append(list())
while len(inputs) > 0:
line = inputs.pop(0)
if len(line) == 0:
if DEBUG:
print(cards[card])
card += 1
cards.append(list())
continue
cards[card].extend([int(n) for n in line.split()])
def winner(card):
for i in range(5):
if card[i * 5:(i + 1) * 5].count(-1) == 5:
return True
if [card[i + r] for r in range(0, 25, 5)].count(-1) == 5:
return True
return False
stamp_idx = 0
for ball in balls:
for c in range(len(cards)):
try:
stamp_idx = cards[c].index(ball)
except:
continue
cards[c].pop(stamp_idx)
cards[c].insert(stamp_idx, -1)
if winner(cards[c]):
card_total = sum(filter(lambda x: x != -1, cards[c]))
if DEBUG:
print(f'c {c} card_total {card_total} ball {ball}')
print(f'called balls {balls[:balls.index(ball)]}')
print(f'card {cards[c]}')
print(card_total * ball)
exit() |
PANEL_DASHBOARD = 'project'
PANEL_GROUP = 'default'
PANEL = 'api_access'
DEFAULT_PANEL = 'api_access'
ADD_PANEL = \
('openstack_dashboard.dashboards.project.api_access.panel.ApiAccess')
| panel_dashboard = 'project'
panel_group = 'default'
panel = 'api_access'
default_panel = 'api_access'
add_panel = 'openstack_dashboard.dashboards.project.api_access.panel.ApiAccess' |
n, a, b = map(int, input().split())
total = 0
def sum_digits(digits):
return sum(int(digit) for digit in str(digits))
for i in range(1, n + 1):
if sum_digits(i) >= a and sum_digits(i) <= b:
total += i
print(total)
| (n, a, b) = map(int, input().split())
total = 0
def sum_digits(digits):
return sum((int(digit) for digit in str(digits)))
for i in range(1, n + 1):
if sum_digits(i) >= a and sum_digits(i) <= b:
total += i
print(total) |
'''
Created on Apr 8, 2010
@author: jose
'''
| """
Created on Apr 8, 2010
@author: jose
""" |
# calculations
print('plus:', 1 + 2, 'minus:', 1 - 2, 'multiple:', 4 * 5, 'division:', 7 / 5)
print('share:', 7 // 5, 'rest:', 7 % 5, 'square:', 3 ** 2)
# data types
print('types:', type(10), type(1.0), type('a'))
# variables
x = 10 # initialization and substisution
print('x:', x)
x = 100 # substisution
print('x:', x)
# list
arr = [1, 2, 3, 4, 5]
print('list:', arr, 'len of list:', len(arr))
arr[4] = 99 # substitution
print('list:', arr)
print('accessing:', arr[0])
print('slicing:', arr[0:2], arr[1:], arr[:3], arr[:-1])
# dictionary
dic = {'a': 1, 'b': 2}
print('accessing:', dic['a'])
dic['c'] = 3 # initialization and substisution
print('dict:', dic)
# booleans
a, b = True, False
print('booleans:', type(a))
print('compares:', a and b, a or b, not b)
# if
if a:
print('check: a is True.')
if not b:
print('check: b is False.')
# for
for i in [1, 2, 3, 4, 5]:
print(i, end=' ')
print()
# function
def greeting():
print('Hello, python!')
greeting()
| print('plus:', 1 + 2, 'minus:', 1 - 2, 'multiple:', 4 * 5, 'division:', 7 / 5)
print('share:', 7 // 5, 'rest:', 7 % 5, 'square:', 3 ** 2)
print('types:', type(10), type(1.0), type('a'))
x = 10
print('x:', x)
x = 100
print('x:', x)
arr = [1, 2, 3, 4, 5]
print('list:', arr, 'len of list:', len(arr))
arr[4] = 99
print('list:', arr)
print('accessing:', arr[0])
print('slicing:', arr[0:2], arr[1:], arr[:3], arr[:-1])
dic = {'a': 1, 'b': 2}
print('accessing:', dic['a'])
dic['c'] = 3
print('dict:', dic)
(a, b) = (True, False)
print('booleans:', type(a))
print('compares:', a and b, a or b, not b)
if a:
print('check: a is True.')
if not b:
print('check: b is False.')
for i in [1, 2, 3, 4, 5]:
print(i, end=' ')
print()
def greeting():
print('Hello, python!')
greeting() |
# Practice Quiz: Object-oriented programming
# 1. Let's test your knowledge of using dot notation to access methods
# and attributes in an object. Let's say we have a class called Birds.
# Birds has two attributes: color and number. Birds also has a
# method called count() that counts the number of birds (adds a
# value to number). Which of the following lines of code will correctly
# print the number of birds? Keep in mind, the number of birds is 0
# until they are counted!
# 2. Creating new instances of class objects can be a great way to keep
# track of values using attributes associated with the object. The
# values of these attributes can be easily changed at the object level.
# The following code illustrates a famous quote by George Bernard
# Shaw, using objects to represent people. Fill in the blanks to make
# the code satisfy the behavior described in the quote.
# "If you have an apple and I have an apple and we exchanged these apples then
# you and I will still each have one apple. But if you have an idea and I have
# an idea and we exchanged these ideas, then each of us will have two ideas."
# Geo Bernard Shaw
class Person:
apples = 0
ideas = 0
johanna = Person()
johanna.apples = 1
johanna.ideas = 1
martin = Person()
martin.apples = 2
martin.ideas = 1
def exchanges_apples(you, me):
# Here, despite G.B Shaw's quote, our characters have started with # different amount of apples so we can better observe the results.
# We're going to have Martin and Johanna exchange All their apples with # one another.
# Hint: how would you switch values of variables.
# so that "you" and "me" will exchange ALL their apples with one another?
# Do you need a temporary variable to store one of the values?
# You may need more than one line of code to do that, which is OK.
temp = you.apples
you.apples = me.apples
me.apples = temp
return you.apples, me.apples
def exchange_ideas(you, me):
# "you" and "me" will share our ideas with one another.
# What operations need to be performed, so that each object receives
# the shared number of ideas?
# Hint: how would you assign the total number of of ideas to
# each idea attribute? Do you need a temporary variable to store
# the sum of ideas, or can you find another way?
# Use as many lines of code as you need here.
temp = you.ideas
you.ideas = me.ideas
me.ideas = temp
return you.ideas, me.ideas
johanna.apples, martin.apples = exchanges_apples(johanna, martin)
print("Johanna has {} apples and Martin has {} apples".format(johanna.apples, martin.apples))
ohanna.ideas, martin.ideas = exchange_ideas(johanna, martin)
print("Johanna has {} ideas and Martin has {} ideas".format(johanna.ideas, martin.ideas))
# 3. The City class has the following attributes: name, country (where the city is located)
# elevation (measured in meters) and population (approximate, according to recent statistics).
# Fill in the blanks of the max_elevation_city function to return the name of the city and its
# country (separated by a comma). When comparing the 3 defined instances for a specified
# minimal population. For example, calling the function of a minimum population of 1 million:
# max_elevation_city(1000000) should return "Sofia, Bulgaria".
# define a basic city class
class City:
name = ""
country = ""
elevation = 0
population = 0
# create a new instance of the City class and
# define each attribute
City1 = City()
City1.name = "Cusco"
City1.country = "Peru"
City1.elevation = 3399
City1.population = 358052
# create a new instance of the City class adnd
# define each attribute
City2 = City()
City2.name = "Sofia"
City2.country = "Bulgaria"
City2.elevation = 2290
City2.population = 1241675
# create a new instance of the City class and
# define each attribute
City3 = City()
City3.name = "Seoul"
City3.country = "South Korea"
City3.elevation = 38
City3.population = 9733509
def max_elevation_city(min_population):
# Initialize the variable that will hold
# the information of the city with
# the highest elevation
return_city = City()
# Evaluate the 1st instance to meet the requirements:
# does city #1 have at least min_population and
# is its elevation the highest so far?
if min_population < City1.population and City1.elevation > return_city.elevation:
return_city = City1
# Evaluate the 1st instance to meet the requirements:
# does city #1 have at least min_population and
# is its elevation the highest so far?
if min_population < City2.population and City2.elevation > return_city.elevation:
return_city = City2
# Evaluate the 1st instance to meet the requirements:
# does city #1 have at least min_population and
# is its elevation the highest so far?
if min_population < City3.population and City3.elevation > return_city.elevation:
return_city = City3
# Format the return string
if return_city.name:
return f"{return_city.name}, {return_city.country}"
else:
return ""
print(max_elevation_city(100000)) # Should print "Cusco, Peru"
print(max_elevation_city(1000000)) # Should print "Sofia, Bulgaria"
print(max_elevation_city(10000000)) # Should print ""
# 5. We have two pieces of furniture: a brown wood table and red leather couch. Fill in the
# blanks creation of each Furniture class instance, so that describe_furniture function can
# format a sentence that describes these pieces as follows: "This piece of furniture is made
# of {color} {material}
class Furniture:
color = ""
material = ""
table = Furniture()
table.color = "brown"
table.material = "wood"
couch = Furniture()
couch.color = "red"
couch.material = "leather"
def describe_furniture(piece):
return ("This piece of furniture is made of {} {}".format(piece.color, piece.material))
print(describe_furniture(table))
# Should be "This piece of furniture is made of brown wood"
print(describe_furniture(couch))
# Should be "This piece of furniture is made of red leather"
| class Person:
apples = 0
ideas = 0
johanna = person()
johanna.apples = 1
johanna.ideas = 1
martin = person()
martin.apples = 2
martin.ideas = 1
def exchanges_apples(you, me):
temp = you.apples
you.apples = me.apples
me.apples = temp
return (you.apples, me.apples)
def exchange_ideas(you, me):
temp = you.ideas
you.ideas = me.ideas
me.ideas = temp
return (you.ideas, me.ideas)
(johanna.apples, martin.apples) = exchanges_apples(johanna, martin)
print('Johanna has {} apples and Martin has {} apples'.format(johanna.apples, martin.apples))
(ohanna.ideas, martin.ideas) = exchange_ideas(johanna, martin)
print('Johanna has {} ideas and Martin has {} ideas'.format(johanna.ideas, martin.ideas))
class City:
name = ''
country = ''
elevation = 0
population = 0
city1 = city()
City1.name = 'Cusco'
City1.country = 'Peru'
City1.elevation = 3399
City1.population = 358052
city2 = city()
City2.name = 'Sofia'
City2.country = 'Bulgaria'
City2.elevation = 2290
City2.population = 1241675
city3 = city()
City3.name = 'Seoul'
City3.country = 'South Korea'
City3.elevation = 38
City3.population = 9733509
def max_elevation_city(min_population):
return_city = city()
if min_population < City1.population and City1.elevation > return_city.elevation:
return_city = City1
if min_population < City2.population and City2.elevation > return_city.elevation:
return_city = City2
if min_population < City3.population and City3.elevation > return_city.elevation:
return_city = City3
if return_city.name:
return f'{return_city.name}, {return_city.country}'
else:
return ''
print(max_elevation_city(100000))
print(max_elevation_city(1000000))
print(max_elevation_city(10000000))
class Furniture:
color = ''
material = ''
table = furniture()
table.color = 'brown'
table.material = 'wood'
couch = furniture()
couch.color = 'red'
couch.material = 'leather'
def describe_furniture(piece):
return 'This piece of furniture is made of {} {}'.format(piece.color, piece.material)
print(describe_furniture(table))
print(describe_furniture(couch)) |
# Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original
# BST is changed to the original key plus sum of all keys greater than the original key in BST.
# ex
# Input: The root of a Binary Search Tree like this:
# 5
# / \
# 2 13
#
# Output: The root of a Greater Tree like this:
# 18
# / \
# 20 13
# High Level Idea:
# Use a depth first search to the very right node, and traverse the tree in descending order
# Keep a running total global variable called running sum that is accessable by each recursive call,
# and increase the current root's value by running sum at each function call.
# NOTE. Since variables in Python are immutable, we are declaring runningSum as a list instead--
# lists are mutable so this solves the issue.
class Solution:
def convertBST(self, root):
# lists are mutable
runningSum = [0]
return self.helper(root, runningSum)
#recursive function
def helper(self, root, runningSum):
if root == None:
return
#traverse all the way down to the right (greatest element)
self.helper(root.right, runningSum)
curVal = root.val
root.val += runningSum[0]
runningSum[0] += curVal
self.helper(root.left, runningSum)
#return value is just for the convertBST function
return root
| class Solution:
def convert_bst(self, root):
running_sum = [0]
return self.helper(root, runningSum)
def helper(self, root, runningSum):
if root == None:
return
self.helper(root.right, runningSum)
cur_val = root.val
root.val += runningSum[0]
runningSum[0] += curVal
self.helper(root.left, runningSum)
return root |
#: Regular expression for a valid GitHub username or organization name. As of
#: 2017-07-23, trying to sign up to GitHub with an invalid username or create
#: an organization with an invalid name gives the message "Username may only
#: contain alphanumeric characters or single hyphens, and cannot begin or end
#: with a hyphen". Additionally, trying to create a user named "none" (case
#: insensitive) gives the message "Username name 'none' is a reserved word."
#:
#: Unfortunately, there are a number of users who made accounts before the
#: current name restrictions were put in place, and so this regex also needs to
#: accept names that contain underscores, contain multiple consecutive hyphens,
#: begin with a hyphen, and/or end with a hyphen.
GH_USER_RGX = r'(?![Nn][Oo][Nn][Ee]($|[^-A-Za-z0-9]))[-_A-Za-z0-9]+'
#GH_USER_RGX_DE_JURE = r'(?![Nn][Oo][Nn][Ee]($|[^-A-Za-z0-9]))'\
# r'[A-Za-z0-9](?:-?[A-Za-z0-9])*'
#: Regular expression for a valid GitHub repository name. Testing as of
#: 2017-05-21 indicates that repository names can be composed of alphanumeric
#: ASCII characters, hyphens, periods, and/or underscores, with the names ``.``
#: and ``..`` being reserved and names ending with ``.git`` forbidden.
GH_REPO_RGX = r'(?:\.?[-A-Za-z0-9_][-A-Za-z0-9_.]*|\.\.[-A-Za-z0-9_.]+)'\
r'(?<!\.git)'
_REF_COMPONENT = r'(?!\.)[^\x00-\x20/~^:?*[\\\x7F]+(?<!\.lock)'
#: Regular expression for a (possibly one-level) valid normalized Git refname
#: (e.g., a branch or tag name) as specified in
#: :manpage:`git-check-ref-format(1)`
#: <https://git-scm.com/docs/git-check-ref-format> as of 2017-07-23 (Git
#: 2.13.1)
GIT_REFNAME_RGX = r'(?!@/?$)(?!.*(?:\.\.|@\{{)){0}(?:/{0})*(?<!\.)'\
.format(_REF_COMPONENT)
#: Convenience regular expression for ``<owner>/<repo>``, including named
#: capturing groups
OWNER_REPO_RGX = fr'(?P<owner>{GH_USER_RGX})/(?P<repo>{GH_REPO_RGX})'
API_REPO_RGX = r'(?:https?://)?api\.github\.com/repos/' + OWNER_REPO_RGX
WEB_REPO_RGX = r'(?:https?://)?(?:www\.)?github\.com/' + OWNER_REPO_RGX
| gh_user_rgx = '(?![Nn][Oo][Nn][Ee]($|[^-A-Za-z0-9]))[-_A-Za-z0-9]+'
gh_repo_rgx = '(?:\\.?[-A-Za-z0-9_][-A-Za-z0-9_.]*|\\.\\.[-A-Za-z0-9_.]+)(?<!\\.git)'
_ref_component = '(?!\\.)[^\\x00-\\x20/~^:?*[\\\\\\x7F]+(?<!\\.lock)'
git_refname_rgx = '(?!@/?$)(?!.*(?:\\.\\.|@\\{{)){0}(?:/{0})*(?<!\\.)'.format(_REF_COMPONENT)
owner_repo_rgx = f'(?P<owner>{GH_USER_RGX})/(?P<repo>{GH_REPO_RGX})'
api_repo_rgx = '(?:https?://)?api\\.github\\.com/repos/' + OWNER_REPO_RGX
web_repo_rgx = '(?:https?://)?(?:www\\.)?github\\.com/' + OWNER_REPO_RGX |
# test builtin abs
print(abs(False))
print(abs(True))
print(abs(1))
print(abs(-1))
print("PASS") | print(abs(False))
print(abs(True))
print(abs(1))
print(abs(-1))
print('PASS') |
# full run list
# shape: {number: type} (all string)
# select the run numbers or types to be opened with nRunToOpen...
nRun0 = {}
| n_run0 = {} |
# https://adventofcode.com/2020/day/5
#part 1
with open("./input_day5.txt", encoding="utf-8") as input:
seat_codes = input.readlines()
def half(direction, low, high, lower_half):
if high-low == 1:
return low if direction[0] == lower_half else high
if direction[0] == lower_half:
high = low + (high-low)//2
else:
low = low + (high-low)//2 +1
return half(direction[1:],low, high, lower_half)
seats=[]
for code in seat_codes:
code = code.strip() # remove newline
row, col = half(code[:7],0,127,"F"), half(code[7:],0,7,"L")
seats.append(row*8+col)
print(f"Highest seat: {max(seats)}")
#part 2
seats = sorted(seats)
#zipped seats: (513,514) (514,516) << my_seat is the gap: 514+1
my_seat = [seat[0]+1 for seat in zip(seats[:-1], seats[1:]) if seat[0]+1 != seat[1]][0]
print(f"My seat is {my_seat}")
#print([seat[0]+1 for seat in zip(seats[:-1], seats[1:]) if seat[0]+1 != seat[1]])
| with open('./input_day5.txt', encoding='utf-8') as input:
seat_codes = input.readlines()
def half(direction, low, high, lower_half):
if high - low == 1:
return low if direction[0] == lower_half else high
if direction[0] == lower_half:
high = low + (high - low) // 2
else:
low = low + (high - low) // 2 + 1
return half(direction[1:], low, high, lower_half)
seats = []
for code in seat_codes:
code = code.strip()
(row, col) = (half(code[:7], 0, 127, 'F'), half(code[7:], 0, 7, 'L'))
seats.append(row * 8 + col)
print(f'Highest seat: {max(seats)}')
seats = sorted(seats)
my_seat = [seat[0] + 1 for seat in zip(seats[:-1], seats[1:]) if seat[0] + 1 != seat[1]][0]
print(f'My seat is {my_seat}') |
# 1-T ismlar degan ro'yxat yarating va kamida 3 ta yaqin do'stingizning ismini kiriting
ismlar = ["Anvar","Ulug'bek","Umid"]
# 2- T Ro'yxatdagi har bir do'stingizga qisqa xabar yozib konsolga chiqaring:
print(f"Salom {ismlar[0]},bugun choyxona bormi.\n{ismlar[1]} bugun choyxonaga boramizmi?.\n{ismlar[2]} ishingdan chiqib menga tel qilgin.")
# 3-T sonlar deb nomlangan ro'yxat yarating va ichiga turli sonlarni yuklang (musbat, manfiy, butun, o'nlik).
sonlar = [3,5,546,-563,33.3,1]
# tuplamning 3-index ga 777 soni yuklandi
sonlar[3]=777
print(sonlar)
# tuplamning 2-indexiga 571 element yuklandi.
sonlar.insert(2,571)
# tuplamdan 33.3 elementi uchirib tashlandi.
sonlar.remove(33.3)
print(sonlar)
# tuplmaga 234324 elementi qushildi.
sonlar.append(234324)
# tuplamdan 4 -indexdagi eement uchirib tashlandi.
del sonlar[4]
print(sonlar)
# tuplamdan 3 elementi ug'irib olindi
son1=sonlar.pop(3)
print(son1)
# 7-T Yuqoridagi ro'yxatdan mehmonga kela olmaydigan odamlarni .remove() metodi yordamida o'chrib tashlang.
mehmonlar =["kursdoshlar","qarindoshlar","Do'stlar"]
mehmonlar.remove("kursdoshlar")
print(mehmonlar)
friends=[]
kk=mehmonlar.pop(0)
friends.append(kk)
print(friends) | ismlar = ['Anvar', "Ulug'bek", 'Umid']
print(f'Salom {ismlar[0]},bugun choyxona bormi.\n{ismlar[1]} bugun choyxonaga boramizmi?.\n{ismlar[2]} ishingdan chiqib menga tel qilgin.')
sonlar = [3, 5, 546, -563, 33.3, 1]
sonlar[3] = 777
print(sonlar)
sonlar.insert(2, 571)
sonlar.remove(33.3)
print(sonlar)
sonlar.append(234324)
del sonlar[4]
print(sonlar)
son1 = sonlar.pop(3)
print(son1)
mehmonlar = ['kursdoshlar', 'qarindoshlar', "Do'stlar"]
mehmonlar.remove('kursdoshlar')
print(mehmonlar)
friends = []
kk = mehmonlar.pop(0)
friends.append(kk)
print(friends) |
snake = "Python!"
langth = 42
sckary = True
if sckary:
print("Ahhh!!!")
else:
print("Phew!!!")
for letter in snake:
print(letter)
def grow(size):
global langth
langth = langth + size
print("The python is now {}m long!".format(langth))
grow(3)
class Employee:
# Common base count for all employees!
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayEmployee(self):
print("Name: {}, Salary: ${}".format(self.name, self.salary))
emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Employee Total: {}".format(Employee.empCount))
| snake = 'Python!'
langth = 42
sckary = True
if sckary:
print('Ahhh!!!')
else:
print('Phew!!!')
for letter in snake:
print(letter)
def grow(size):
global langth
langth = langth + size
print('The python is now {}m long!'.format(langth))
grow(3)
class Employee:
emp_count = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def display_employee(self):
print('Name: {}, Salary: ${}'.format(self.name, self.salary))
emp1 = employee('Zara', 2000)
emp2 = employee('Manni', 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print('Employee Total: {}'.format(Employee.empCount)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.