content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
with open ('2gram_output_birkbeck.txt') as f:
with open ('../data/birkbeck_correct.txt') as g:
corrects = []
i = 0
for line in g:
corrects.append(line.strip())
for line in f:
try:
A = line.split(' potential diatance_word:(')
misspell = A[0].split(':')[1]
B = A[1].split(') ')[0]
C = B.split(')(')
D = [item.split(', ') for item in C]
E = [item[1].strip("'") for item in D]
str = "".join([item + ',' for item in E])
out = ""
out += misspell + ", " +corrects[i] + ": " + str
print(out)
i += 1
except IndexError:
continue
|
with open('2gram_output_birkbeck.txt') as f:
with open('../data/birkbeck_correct.txt') as g:
corrects = []
i = 0
for line in g:
corrects.append(line.strip())
for line in f:
try:
a = line.split(' potential diatance_word:(')
misspell = A[0].split(':')[1]
b = A[1].split(') ')[0]
c = B.split(')(')
d = [item.split(', ') for item in C]
e = [item[1].strip("'") for item in D]
str = ''.join([item + ',' for item in E])
out = ''
out += misspell + ', ' + corrects[i] + ': ' + str
print(out)
i += 1
except IndexError:
continue
|
def set_session_user_profile(request, profile=None):
user_profile = {
'use_pop_article': True,
'theme': '',
'is_authenticated': request.user.is_authenticated
}
if profile:
user_profile['use_pop_article'] = profile.use_pop_article
user_profile['theme'] = profile.theme
request.session['user_profile'] = user_profile
|
def set_session_user_profile(request, profile=None):
user_profile = {'use_pop_article': True, 'theme': '', 'is_authenticated': request.user.is_authenticated}
if profile:
user_profile['use_pop_article'] = profile.use_pop_article
user_profile['theme'] = profile.theme
request.session['user_profile'] = user_profile
|
class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
ans=[]
for i in range(2**10):
if(bin(i).count('1')==num):
minute = i & 0b0000111111
hour = i>>6
if hour<12 and minute<60:
ans.append("%d:%02d"%(hour, minute))
return ans
|
class Solution(object):
def read_binary_watch(self, num):
"""
:type num: int
:rtype: List[str]
"""
ans = []
for i in range(2 ** 10):
if bin(i).count('1') == num:
minute = i & 63
hour = i >> 6
if hour < 12 and minute < 60:
ans.append('%d:%02d' % (hour, minute))
return ans
|
def squared(n):
return n * n
def cubed(n):
return n * n * n
def raise_power(n, power):
total = 1
for t in range (power) :
total = total * n
return total
def is_divisible(n, t):
return n % t == 0
def is_even(n):
return n % 2 == 0
def is_odd(n):
return n % 2 != 0
print(list(map(squared, [1, 3, 5, 7, 9, 11, 13, 15])))
print(list(map( lambda x: raise_power (x,3), [1, 2, 5, 7, 9, 11, 13, 15])))
# for functions with multiple args
# see: https://www.quora.com/How-do-I-put-multiple-arguments-into-a-map-function-in-Python
|
def squared(n):
return n * n
def cubed(n):
return n * n * n
def raise_power(n, power):
total = 1
for t in range(power):
total = total * n
return total
def is_divisible(n, t):
return n % t == 0
def is_even(n):
return n % 2 == 0
def is_odd(n):
return n % 2 != 0
print(list(map(squared, [1, 3, 5, 7, 9, 11, 13, 15])))
print(list(map(lambda x: raise_power(x, 3), [1, 2, 5, 7, 9, 11, 13, 15])))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if not postorder:
return None
node = postorder.pop()
root = TreeNode(node)
index = inorder.index(node)
root.left = self.buildTree(inorder[:index], postorder[:index])
root.right = self.buildTree(inorder[index+1:], postorder[index:])
return root
|
class Solution:
def build_tree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if not postorder:
return None
node = postorder.pop()
root = tree_node(node)
index = inorder.index(node)
root.left = self.buildTree(inorder[:index], postorder[:index])
root.right = self.buildTree(inorder[index + 1:], postorder[index:])
return root
|
# -*- coding: utf-8 -*-
"""
Top-level package for {{ cookiecutter.municipality }}
CDP instance backend.
"""
__author__ = "{{ cookiecutter.maintainer_full_name }}"
__version__ = "1.0.0"
def get_module_version() -> str:
return __version__
|
"""
Top-level package for {{ cookiecutter.municipality }}
CDP instance backend.
"""
__author__ = '{{ cookiecutter.maintainer_full_name }}'
__version__ = '1.0.0'
def get_module_version() -> str:
return __version__
|
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@berty_go//:repositories.bzl", "berty_go_repositories")
def berty_bridge_repositories():
# utils
maybe(
git_repository,
name = "bazel_skylib",
remote = "https://github.com/bazelbuild/bazel-skylib",
commit = "e59b620b392a8ebbcf25879fc3fde52b4dc77535",
shallow_since = "1570639401 -0400",
)
maybe(
http_archive,
name = "build_bazel_rules_nodejs",
sha256 = "ad4be2c6f40f5af70c7edf294955f9d9a0222c8e2756109731b25f79ea2ccea0",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/0.38.3/rules_nodejs-0.38.3.tar.gz"],
)
# gomobile
maybe(
git_repository,
name = "co_znly_rules_gomobile",
remote = "https://github.com/znly/rules_gomobile",
commit = "ef471f52c2b5cd7f7b8de417d9e6ded3f4d19e72",
shallow_since = "1566492765 +0200",
)
maybe(
git_repository,
name = "build_bazel_rules_swift",
remote = "https://github.com/bazelbuild/rules_swift.git",
commit = "ebef63d4fd639785e995b9a2b20622ece100286a",
shallow_since = "1570649187 -0700",
)
maybe(
git_repository,
name = "build_bazel_apple_support",
remote = "https://github.com/bazelbuild/apple_support.git",
commit = "8c585c66c29b9d528e5fcf78da8057a6f3a4f001",
shallow_since = "1570646613 -0700",
)
berty_go_repositories()
|
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('@bazel_tools//tools/build_defs/repo:git.bzl', 'git_repository')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@berty_go//:repositories.bzl', 'berty_go_repositories')
def berty_bridge_repositories():
maybe(git_repository, name='bazel_skylib', remote='https://github.com/bazelbuild/bazel-skylib', commit='e59b620b392a8ebbcf25879fc3fde52b4dc77535', shallow_since='1570639401 -0400')
maybe(http_archive, name='build_bazel_rules_nodejs', sha256='ad4be2c6f40f5af70c7edf294955f9d9a0222c8e2756109731b25f79ea2ccea0', urls=['https://github.com/bazelbuild/rules_nodejs/releases/download/0.38.3/rules_nodejs-0.38.3.tar.gz'])
maybe(git_repository, name='co_znly_rules_gomobile', remote='https://github.com/znly/rules_gomobile', commit='ef471f52c2b5cd7f7b8de417d9e6ded3f4d19e72', shallow_since='1566492765 +0200')
maybe(git_repository, name='build_bazel_rules_swift', remote='https://github.com/bazelbuild/rules_swift.git', commit='ebef63d4fd639785e995b9a2b20622ece100286a', shallow_since='1570649187 -0700')
maybe(git_repository, name='build_bazel_apple_support', remote='https://github.com/bazelbuild/apple_support.git', commit='8c585c66c29b9d528e5fcf78da8057a6f3a4f001', shallow_since='1570646613 -0700')
berty_go_repositories()
|
LOCATION_TERMS = ['city', 'sub_region', 'region', 'country']
def get_geographical_granularity(data):
"""Returns the index of the lowest granularity level available in data."""
for index, term in enumerate(LOCATION_TERMS):
if term in data.columns:
return index
def check_column_and_get_index(name, data, reference):
"""Check that name is present in data.columns and returns it's index."""
assert name in data.columns, f'If {reference} is provided, {name} should be present too'
return data.columns.get_loc(name)
def check_dataset_format(data):
message = 'All columns should be lowercase'
assert all(data.columns == [column.lower() for column in data.columns]), message
if 'latitude' in data.columns:
message = 'Latitude should be provided with Longitude'
assert 'longitude' in data.columns, message
granularity = get_geographical_granularity(data)
min_granularity_term = LOCATION_TERMS[granularity]
locations = [data.columns.get_loc(LOCATION_TERMS[granularity])]
for term in LOCATION_TERMS[granularity + 1:]:
locations.append(check_column_and_get_index(term, data, min_granularity_term))
message = 'The correct ordening of the columns is "country, region, sub_region, city"'
assert (locations[::-1] == sorted(locations)), message
message = 'date and timestamp columns should be of datetime dtype'
time_index = None
if 'date' in data.columns:
assert data.date.dtype == 'datetime64[ns]', message
time_index = data.columns.get_loc('date')
if 'timestamp' in data.columns:
assert data.timestamp.dtype == 'datetime64[ns]', message
time_index = data.columns.get_loc('timestamp')
if time_index is not None:
message = 'geographical columns should be before time columns.'
assert all(time_index > location for location in locations)
object_columns = data.select_dtypes(include='object').columns
for column in object_columns:
try:
data[column].astype(float)
assert False, f'Column {column} is of dtype object, but casteable to float.'
except ValueError:
pass
|
location_terms = ['city', 'sub_region', 'region', 'country']
def get_geographical_granularity(data):
"""Returns the index of the lowest granularity level available in data."""
for (index, term) in enumerate(LOCATION_TERMS):
if term in data.columns:
return index
def check_column_and_get_index(name, data, reference):
"""Check that name is present in data.columns and returns it's index."""
assert name in data.columns, f'If {reference} is provided, {name} should be present too'
return data.columns.get_loc(name)
def check_dataset_format(data):
message = 'All columns should be lowercase'
assert all(data.columns == [column.lower() for column in data.columns]), message
if 'latitude' in data.columns:
message = 'Latitude should be provided with Longitude'
assert 'longitude' in data.columns, message
granularity = get_geographical_granularity(data)
min_granularity_term = LOCATION_TERMS[granularity]
locations = [data.columns.get_loc(LOCATION_TERMS[granularity])]
for term in LOCATION_TERMS[granularity + 1:]:
locations.append(check_column_and_get_index(term, data, min_granularity_term))
message = 'The correct ordening of the columns is "country, region, sub_region, city"'
assert locations[::-1] == sorted(locations), message
message = 'date and timestamp columns should be of datetime dtype'
time_index = None
if 'date' in data.columns:
assert data.date.dtype == 'datetime64[ns]', message
time_index = data.columns.get_loc('date')
if 'timestamp' in data.columns:
assert data.timestamp.dtype == 'datetime64[ns]', message
time_index = data.columns.get_loc('timestamp')
if time_index is not None:
message = 'geographical columns should be before time columns.'
assert all((time_index > location for location in locations))
object_columns = data.select_dtypes(include='object').columns
for column in object_columns:
try:
data[column].astype(float)
assert False, f'Column {column} is of dtype object, but casteable to float.'
except ValueError:
pass
|
def score(name=tom,score=0):
print(name," scored ", score )
|
def score(name=tom, score=0):
print(name, ' scored ', score)
|
# estos es un cometario en python
#decalro una variable
x = 5
# imprime variable
print ("x =",x)
#operaciones aritmeticas
print ("x - 5 = ",x - 5)
print ("x + 5 = ",x + 5)
print ("x * 5 = ",x * 5)
print ("x % 5 = ",x % 5)
print ("x / 5 = ",x /5)
print ("x // 5 = ",x //5)
print ("x ** 5 = ",x **5)
|
x = 5
print('x =', x)
print('x - 5 = ', x - 5)
print('x + 5 = ', x + 5)
print('x * 5 = ', x * 5)
print('x % 5 = ', x % 5)
print('x / 5 = ', x / 5)
print('x // 5 = ', x // 5)
print('x ** 5 = ', x ** 5)
|
class PushwooshException(Exception):
pass
class PushwooshCommandException(PushwooshException):
pass
class PushwooshNotificationException(PushwooshException):
pass
class PushwooshFilterException(PushwooshException):
pass
class PushwooshFilterInvalidOperatorException(PushwooshFilterException):
pass
class PushwooshFilterInvalidOperandException(PushwooshFilterException):
pass
|
class Pushwooshexception(Exception):
pass
class Pushwooshcommandexception(PushwooshException):
pass
class Pushwooshnotificationexception(PushwooshException):
pass
class Pushwooshfilterexception(PushwooshException):
pass
class Pushwooshfilterinvalidoperatorexception(PushwooshFilterException):
pass
class Pushwooshfilterinvalidoperandexception(PushwooshFilterException):
pass
|
"""
The deal with super is that you can easily call
a function of a parent or a sister class that you have inherited, without
necessarily calling the classes then their functions
an example
"""
class Parent:
def __init__(self, i):
print(i)
class Sister:
def __init__(self):
print("asda")
class Daughter(Parent, Sister):
def __init__(self):
super().__init__("asa")
""" What we note in the above case is that it is the parent class' __init__
function that is called and not the sister's. We assume that this can be attributed
to the fact that the Parent was inherited first, and the Sister second. This
can be tested by exchanging the positions of the two classes when we inherit them
during the class declaration of Daughter.
"""
if __name__ == '__main__':
d = Daughter()
|
"""
The deal with super is that you can easily call
a function of a parent or a sister class that you have inherited, without
necessarily calling the classes then their functions
an example
"""
class Parent:
def __init__(self, i):
print(i)
class Sister:
def __init__(self):
print('asda')
class Daughter(Parent, Sister):
def __init__(self):
super().__init__('asa')
" What we note in the above case is that it is the parent class' __init__\nfunction that is called and not the sister's. We assume that this can be attributed \nto the fact that the Parent was inherited first, and the Sister second. This\ncan be tested by exchanging the positions of the two classes when we inherit them\nduring the class declaration of Daughter. \n"
if __name__ == '__main__':
d = daughter()
|
#
# PySNMP MIB module CISCO-ENTITY-SENSOR-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-SENSOR-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39: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)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint")
ciscoAgentCapability, = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability")
AgentCapabilities, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "ModuleCompliance", "NotificationGroup")
iso, IpAddress, TimeTicks, ModuleIdentity, Unsigned32, MibIdentifier, Integer32, Counter32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Gauge32, Counter64, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "IpAddress", "TimeTicks", "ModuleIdentity", "Unsigned32", "MibIdentifier", "Integer32", "Counter32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Gauge32", "Counter64", "ObjectIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
ciscoEntitySensorCapability = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 7, 350))
ciscoEntitySensorCapability.setRevisions(('2011-02-03 00:00', '2008-10-06 00:00', '2007-07-09 00:00', '2007-06-29 00:00', '2006-06-29 00:00', '2005-09-15 00:00', '2005-04-22 00:00', '2004-09-09 00:00', '2003-08-12 00:00', '2003-03-13 00:00',))
if mibBuilder.loadTexts: ciscoEntitySensorCapability.setLastUpdated('201102030000Z')
if mibBuilder.loadTexts: ciscoEntitySensorCapability.setOrganization('Cisco Systems, Inc.')
ciscoEntitySensorCapabilityV5R000 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEntitySensorCapabilityV5R000 = ciscoEntitySensorCapabilityV5R000.setProductRelease('MGX8850 Release 5.0.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEntitySensorCapabilityV5R000 = ciscoEntitySensorCapabilityV5R000.setStatus('current')
cEntitySensorCapV12R0119ECat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapV12R0119ECat6K = cEntitySensorCapV12R0119ECat6K.setProductRelease('Cisco IOS 12.1(19)E on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapV12R0119ECat6K = cEntitySensorCapV12R0119ECat6K.setStatus('current')
cEntitySensorCapV12R0214SXCat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapV12R0214SXCat6K = cEntitySensorCapV12R0214SXCat6K.setProductRelease('Cisco IOS 12.2(14)SX on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapV12R0214SXCat6K = cEntitySensorCapV12R0214SXCat6K.setStatus('current')
cEntitySensorCapCatOSV08R0101 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapCatOSV08R0101 = cEntitySensorCapCatOSV08R0101.setProductRelease('Cisco CatOS 8.1(1) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapCatOSV08R0101 = cEntitySensorCapCatOSV08R0101.setStatus('current')
cEntitySensorCapabilityV5R015 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 5))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapabilityV5R015 = cEntitySensorCapabilityV5R015.setProductRelease('MGX8850 Release 5.0.15')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapabilityV5R015 = cEntitySensorCapabilityV5R015.setStatus('current')
cEntitySensorCapMDS3R0 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 6))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapMDS3R0 = cEntitySensorCapMDS3R0.setProductRelease('Cisco MDS 3.0(1).')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapMDS3R0 = cEntitySensorCapMDS3R0.setStatus('current')
cEntitySensorCapCatOSV08R0601 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 7))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapCatOSV08R0601 = cEntitySensorCapCatOSV08R0601.setProductRelease('Cisco CatOS 8.6(1).')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapCatOSV08R0601 = cEntitySensorCapCatOSV08R0601.setStatus('current')
cEntitySensorCapIOSXRV3R06CRS1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 8))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapIOSXRV3R06CRS1 = cEntitySensorCapIOSXRV3R06CRS1.setProductRelease('Cisco IOS-XR Release 3.6 for CRS-1.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapIOSXRV3R06CRS1 = cEntitySensorCapIOSXRV3R06CRS1.setStatus('current')
cEntitySensorCapMDS3R1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 9))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapMDS3R1 = cEntitySensorCapMDS3R1.setProductRelease('Cisco MDS Series Storage switches\n Release 3.1 onwards.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapMDS3R1 = cEntitySensorCapMDS3R1.setStatus('current')
cEntitySensorCapDCOSNEXUS = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 10))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapDCOSNEXUS = cEntitySensorCapDCOSNEXUS.setProductRelease('Cisco Nexus7000 Series Storage switches.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapDCOSNEXUS = cEntitySensorCapDCOSNEXUS.setStatus('current')
cEntitySensorCapV12R0250SE = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 11))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapV12R0250SE = cEntitySensorCapV12R0250SE.setProductRelease('Cisco IOS 12.2(50)SE')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapV12R0250SE = cEntitySensorCapV12R0250SE.setStatus('current')
cEntitySensorCapV12R0250SYPCat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 12))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapV12R0250SYPCat6K = cEntitySensorCapV12R0250SYPCat6K.setProductRelease('Cisco IOS 12.2(50)SY on Catalyst 6000/6500\n series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cEntitySensorCapV12R0250SYPCat6K = cEntitySensorCapV12R0250SYPCat6K.setStatus('current')
mibBuilder.exportSymbols("CISCO-ENTITY-SENSOR-CAPABILITY", cEntitySensorCapMDS3R1=cEntitySensorCapMDS3R1, cEntitySensorCapCatOSV08R0101=cEntitySensorCapCatOSV08R0101, cEntitySensorCapCatOSV08R0601=cEntitySensorCapCatOSV08R0601, ciscoEntitySensorCapability=ciscoEntitySensorCapability, cEntitySensorCapMDS3R0=cEntitySensorCapMDS3R0, cEntitySensorCapV12R0214SXCat6K=cEntitySensorCapV12R0214SXCat6K, cEntitySensorCapV12R0119ECat6K=cEntitySensorCapV12R0119ECat6K, ciscoEntitySensorCapabilityV5R000=ciscoEntitySensorCapabilityV5R000, cEntitySensorCapIOSXRV3R06CRS1=cEntitySensorCapIOSXRV3R06CRS1, cEntitySensorCapV12R0250SE=cEntitySensorCapV12R0250SE, cEntitySensorCapV12R0250SYPCat6K=cEntitySensorCapV12R0250SYPCat6K, PYSNMP_MODULE_ID=ciscoEntitySensorCapability, cEntitySensorCapabilityV5R015=cEntitySensorCapabilityV5R015, cEntitySensorCapDCOSNEXUS=cEntitySensorCapDCOSNEXUS)
|
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, constraints_intersection, single_value_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueSizeConstraint')
(cisco_agent_capability,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoAgentCapability')
(agent_capabilities, module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'AgentCapabilities', 'ModuleCompliance', 'NotificationGroup')
(iso, ip_address, time_ticks, module_identity, unsigned32, mib_identifier, integer32, counter32, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, bits, gauge32, counter64, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'IpAddress', 'TimeTicks', 'ModuleIdentity', 'Unsigned32', 'MibIdentifier', 'Integer32', 'Counter32', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'Gauge32', 'Counter64', 'ObjectIdentity')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
cisco_entity_sensor_capability = module_identity((1, 3, 6, 1, 4, 1, 9, 7, 350))
ciscoEntitySensorCapability.setRevisions(('2011-02-03 00:00', '2008-10-06 00:00', '2007-07-09 00:00', '2007-06-29 00:00', '2006-06-29 00:00', '2005-09-15 00:00', '2005-04-22 00:00', '2004-09-09 00:00', '2003-08-12 00:00', '2003-03-13 00:00'))
if mibBuilder.loadTexts:
ciscoEntitySensorCapability.setLastUpdated('201102030000Z')
if mibBuilder.loadTexts:
ciscoEntitySensorCapability.setOrganization('Cisco Systems, Inc.')
cisco_entity_sensor_capability_v5_r000 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_entity_sensor_capability_v5_r000 = ciscoEntitySensorCapabilityV5R000.setProductRelease('MGX8850 Release 5.0.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_entity_sensor_capability_v5_r000 = ciscoEntitySensorCapabilityV5R000.setStatus('current')
c_entity_sensor_cap_v12_r0119_e_cat6_k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_v12_r0119_e_cat6_k = cEntitySensorCapV12R0119ECat6K.setProductRelease('Cisco IOS 12.1(19)E on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_v12_r0119_e_cat6_k = cEntitySensorCapV12R0119ECat6K.setStatus('current')
c_entity_sensor_cap_v12_r0214_sx_cat6_k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_v12_r0214_sx_cat6_k = cEntitySensorCapV12R0214SXCat6K.setProductRelease('Cisco IOS 12.2(14)SX on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_v12_r0214_sx_cat6_k = cEntitySensorCapV12R0214SXCat6K.setStatus('current')
c_entity_sensor_cap_cat_osv08_r0101 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_cat_osv08_r0101 = cEntitySensorCapCatOSV08R0101.setProductRelease('Cisco CatOS 8.1(1) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_cat_osv08_r0101 = cEntitySensorCapCatOSV08R0101.setStatus('current')
c_entity_sensor_capability_v5_r015 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 5))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_capability_v5_r015 = cEntitySensorCapabilityV5R015.setProductRelease('MGX8850 Release 5.0.15')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_capability_v5_r015 = cEntitySensorCapabilityV5R015.setStatus('current')
c_entity_sensor_cap_mds3_r0 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 6))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_mds3_r0 = cEntitySensorCapMDS3R0.setProductRelease('Cisco MDS 3.0(1).')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_mds3_r0 = cEntitySensorCapMDS3R0.setStatus('current')
c_entity_sensor_cap_cat_osv08_r0601 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 7))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_cat_osv08_r0601 = cEntitySensorCapCatOSV08R0601.setProductRelease('Cisco CatOS 8.6(1).')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_cat_osv08_r0601 = cEntitySensorCapCatOSV08R0601.setStatus('current')
c_entity_sensor_cap_iosxrv3_r06_crs1 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 8))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_iosxrv3_r06_crs1 = cEntitySensorCapIOSXRV3R06CRS1.setProductRelease('Cisco IOS-XR Release 3.6 for CRS-1.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_iosxrv3_r06_crs1 = cEntitySensorCapIOSXRV3R06CRS1.setStatus('current')
c_entity_sensor_cap_mds3_r1 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 9))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_mds3_r1 = cEntitySensorCapMDS3R1.setProductRelease('Cisco MDS Series Storage switches\n Release 3.1 onwards.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_mds3_r1 = cEntitySensorCapMDS3R1.setStatus('current')
c_entity_sensor_cap_dcosnexus = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 10))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_dcosnexus = cEntitySensorCapDCOSNEXUS.setProductRelease('Cisco Nexus7000 Series Storage switches.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_dcosnexus = cEntitySensorCapDCOSNEXUS.setStatus('current')
c_entity_sensor_cap_v12_r0250_se = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 11))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_v12_r0250_se = cEntitySensorCapV12R0250SE.setProductRelease('Cisco IOS 12.2(50)SE')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_v12_r0250_se = cEntitySensorCapV12R0250SE.setStatus('current')
c_entity_sensor_cap_v12_r0250_syp_cat6_k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 350, 12))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_v12_r0250_syp_cat6_k = cEntitySensorCapV12R0250SYPCat6K.setProductRelease('Cisco IOS 12.2(50)SY on Catalyst 6000/6500\n series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
c_entity_sensor_cap_v12_r0250_syp_cat6_k = cEntitySensorCapV12R0250SYPCat6K.setStatus('current')
mibBuilder.exportSymbols('CISCO-ENTITY-SENSOR-CAPABILITY', cEntitySensorCapMDS3R1=cEntitySensorCapMDS3R1, cEntitySensorCapCatOSV08R0101=cEntitySensorCapCatOSV08R0101, cEntitySensorCapCatOSV08R0601=cEntitySensorCapCatOSV08R0601, ciscoEntitySensorCapability=ciscoEntitySensorCapability, cEntitySensorCapMDS3R0=cEntitySensorCapMDS3R0, cEntitySensorCapV12R0214SXCat6K=cEntitySensorCapV12R0214SXCat6K, cEntitySensorCapV12R0119ECat6K=cEntitySensorCapV12R0119ECat6K, ciscoEntitySensorCapabilityV5R000=ciscoEntitySensorCapabilityV5R000, cEntitySensorCapIOSXRV3R06CRS1=cEntitySensorCapIOSXRV3R06CRS1, cEntitySensorCapV12R0250SE=cEntitySensorCapV12R0250SE, cEntitySensorCapV12R0250SYPCat6K=cEntitySensorCapV12R0250SYPCat6K, PYSNMP_MODULE_ID=ciscoEntitySensorCapability, cEntitySensorCapabilityV5R015=cEntitySensorCapabilityV5R015, cEntitySensorCapDCOSNEXUS=cEntitySensorCapDCOSNEXUS)
|
"""
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
"""
# dfs
class Solution:
def canPartitionKSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if not nums or len(nums) < k: return False
_sum = sum(nums)
div, mod = divmod(_sum, k)
if _sum % k or max(nums) > _sum / k: return False
nums.sort(reverse = True)
target = [div] * k
return self.dfs(nums, k, 0, target)
def dfs(self, nums, k, index, target):
if index == len(nums): return True
num = nums[index]
for i in range(k):
if target[i] >= num:
target[i] -= num
if self.dfs(nums, k, index + 1, target): return True
target[i] += num
return False
|
"""
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
"""
class Solution:
def can_partition_k_subsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if not nums or len(nums) < k:
return False
_sum = sum(nums)
(div, mod) = divmod(_sum, k)
if _sum % k or max(nums) > _sum / k:
return False
nums.sort(reverse=True)
target = [div] * k
return self.dfs(nums, k, 0, target)
def dfs(self, nums, k, index, target):
if index == len(nums):
return True
num = nums[index]
for i in range(k):
if target[i] >= num:
target[i] -= num
if self.dfs(nums, k, index + 1, target):
return True
target[i] += num
return False
|
# -*- coding: utf-8 -*-
__author__ = 'Alfredo Cobo'
__email__ = '[email protected]'
__version__ = '0.1.0'
|
__author__ = 'Alfredo Cobo'
__email__ = '[email protected]'
__version__ = '0.1.0'
|
in_file = 'report_suis.tsv'
biovar_list = ['bv01', 'bv02', 'bv03', 'bv04', 'bv05']
for biovar in biovar_list:
if biovar == 'bv04':
t=1
bv = biovar[-1]
preID = 0
pos = 0
pcrID = 0
anyID = 0
justPCR = 0
false_pos = 0
false_neg = 0
with open(in_file, 'r') as f:
for line in f:
line = line.rstrip()
if line == '':
continue
filename, ident = line.split('\t')
if 'suis' in filename and 'bv-' + bv in filename:
preID += 1
if biovar in ident:
pcrID += 1
if ('suis' in filename and 'bv-' + bv in filename) or biovar in ident:
anyID += 1
if 'suis' not in filename and biovar in ident:
justPCR += 1
if 'suis' in filename and 'bv-' + bv in filename and biovar in ident:
pos += 1
if 'suis' in filename and 'bv-' + bv in filename and biovar not in ident:
false_neg += 1
if 'suis' not in filename and biovar in ident:
false_pos += 1
print('Total ID (pre-ID or by PCR) {}: {}'.format(biovar, anyID))
print('Genomes pre-ID as suis {}: {}'.format(biovar, preID))
if anyID > 0:
print('ID by PCR: {}/{} ({}%)'.format(pcrID, anyID, round(pcrID / anyID * 100, 1)))
else:
print('ID by PCR: {}/{}'.format(pcrID, anyID))
if pcrID > 0:
print('Just ID by PCR: {}/{} ({}%)'.format(justPCR, pcrID, round(justPCR / pcrID * 100, 1)))
else:
print('Just ID by PCR: {}/{}'.format(justPCR, pcrID))
if preID > 0:
# print('Correct biovar ID: {}/{} ({}%)'.format(pos, pcrID, round(pos / pcrID * 100, 1)))
print('False positives: {}/{} ({}%)'.format(false_pos, preID, round(false_pos / preID * 100, 1)))
print('False negatives: {}/{} ({}%)'.format(false_neg, anyID, round(false_neg / anyID * 100, 1)))
print('\n')
|
in_file = 'report_suis.tsv'
biovar_list = ['bv01', 'bv02', 'bv03', 'bv04', 'bv05']
for biovar in biovar_list:
if biovar == 'bv04':
t = 1
bv = biovar[-1]
pre_id = 0
pos = 0
pcr_id = 0
any_id = 0
just_pcr = 0
false_pos = 0
false_neg = 0
with open(in_file, 'r') as f:
for line in f:
line = line.rstrip()
if line == '':
continue
(filename, ident) = line.split('\t')
if 'suis' in filename and 'bv-' + bv in filename:
pre_id += 1
if biovar in ident:
pcr_id += 1
if 'suis' in filename and 'bv-' + bv in filename or biovar in ident:
any_id += 1
if 'suis' not in filename and biovar in ident:
just_pcr += 1
if 'suis' in filename and 'bv-' + bv in filename and (biovar in ident):
pos += 1
if 'suis' in filename and 'bv-' + bv in filename and (biovar not in ident):
false_neg += 1
if 'suis' not in filename and biovar in ident:
false_pos += 1
print('Total ID (pre-ID or by PCR) {}: {}'.format(biovar, anyID))
print('Genomes pre-ID as suis {}: {}'.format(biovar, preID))
if anyID > 0:
print('ID by PCR: {}/{} ({}%)'.format(pcrID, anyID, round(pcrID / anyID * 100, 1)))
else:
print('ID by PCR: {}/{}'.format(pcrID, anyID))
if pcrID > 0:
print('Just ID by PCR: {}/{} ({}%)'.format(justPCR, pcrID, round(justPCR / pcrID * 100, 1)))
else:
print('Just ID by PCR: {}/{}'.format(justPCR, pcrID))
if preID > 0:
print('False positives: {}/{} ({}%)'.format(false_pos, preID, round(false_pos / preID * 100, 1)))
print('False negatives: {}/{} ({}%)'.format(false_neg, anyID, round(false_neg / anyID * 100, 1)))
print('\n')
|
# 18. Write a Python program to calculate the sum of three given numbers, if the values are equal then return three times of their sum.
# Question:
# Input:
# Output:
# Solution: https://www.w3resource.com/python-exercises/python-basic-exercise-18.php
# Ideas:
"""
1.
"""
# Steps:
"""
"""
# Notes:
"""
"""
# Code:
def sum_three_times(a, b, c):
if a == b == c:
return (a + b + c) * 3
else:
return a + b + c
print(sum_three_times(1, 2, 3))
print(sum_three_times(6, 6, 6))
# Testing:
"""
"""
|
"""
1.
"""
' \n'
'\n'
def sum_three_times(a, b, c):
if a == b == c:
return (a + b + c) * 3
else:
return a + b + c
print(sum_three_times(1, 2, 3))
print(sum_three_times(6, 6, 6))
' \n'
|
# Create a class called Triangle with 3 instances variables that represents 3 angles of triangle. Its __init__() method should take self, angle1, angle2, and angle3 as
# arguments. Make sure to set these appropriately in the body of the __init__() method. Create a method named check_angles(self). It should return True if the sum of the three
# angles is equal to 180, and False otherwise.
# Note: Do not create any objects of the class and do not call any method.
class Triangle:
def _init_(self, angle1,angle2, angle3):
self.angle1=angle1
self.angle2=angle2
self.angle3=angle3
# initialize the 3 angles in this method
def check_angles(self):
if self.angle1+self.angle2+self.angle3 ==180:
return True
else:
return False
|
class Triangle:
def _init_(self, angle1, angle2, angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
def check_angles(self):
if self.angle1 + self.angle2 + self.angle3 == 180:
return True
else:
return False
|
fields_masks = {
'background': "sheets/data/rowData/values/effectiveFormat/backgroundColor",
'value': "sheets/data/rowData/values/formattedValue",
'note': "sheets/data/rowData/values/note",
'font_color': "sheets/data/rowData/values/effectiveFormat/textFormat/foregroundColor"
}
|
fields_masks = {'background': 'sheets/data/rowData/values/effectiveFormat/backgroundColor', 'value': 'sheets/data/rowData/values/formattedValue', 'note': 'sheets/data/rowData/values/note', 'font_color': 'sheets/data/rowData/values/effectiveFormat/textFormat/foregroundColor'}
|
def tuple_to_string(tuple):
string = ''
for i in range(0, len(tuple)):
num = tuple[i]
char = chr(num)
string += str(char)
return string
|
def tuple_to_string(tuple):
string = ''
for i in range(0, len(tuple)):
num = tuple[i]
char = chr(num)
string += str(char)
return string
|
# -*- coding: utf-8 -*-
"""
resultsExport.py
A small command-line tool to calculate mileage statistics for a personally-owned vehicle.
Handles results export to Python objects, ready for use in a Jinja HTML template.
"""
|
"""
resultsExport.py
A small command-line tool to calculate mileage statistics for a personally-owned vehicle.
Handles results export to Python objects, ready for use in a Jinja HTML template.
"""
|
# formatting colors
reset = "\033[0m"
red = "\033[0;31m"
green = "\033[0;32m"
yellow = "\033[0;33m"
blue = "\033[0;34m"
purple = "\033[0;35m"
BRed = "\033[1;31m"
BYellow = "\033[1;33m"
BBlue = "\033[1;34m"
BPurple = "\033[1;35m"
On_Black = "\033[40m"
BIRed = "\033[1;91m"
BIYellow = "\033[1;93m"
BIBlue = "\033[1;94m"
BIPurple = "\033[1;95m"
IWhite = "\033[0;97m"
black = "\033[0;30m"
iblack = "\033[0;90m"
p1 = f"{red}P1{reset}"
p2 = f"{blue}P2{reset}"
p1k = "p1k"
p2k = "p2k"
p1l = [p1, p1k]
p2l = [p2, p2k]
# Default board reference
d_board = ["0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "11", "12", "13", "14", "15",
"16", "17", "18", "19", "20", "21", "22", "23",
"24", "25", "26", "27", "28", "29", "30", "31",
"32", "33", "34", "35", "36", "37", "38", "39",
"40", "41", "42", "43", "44", "45", "46", "47",
"48", "49", "50", "51", "52", "53", "54", "55",
"56", "57", "58", "59", "60", "61", "62", "63"]
available_spots = ["1", "3", "5", "7",
"8", "10", "12", "14",
"17", "19", "21", "23",
"24", "26", "28", "30",
"33", "35", "37", "39",
"40", "42", "44", "46",
"49", "51", "53", "55",
"56", "58", "60", "62"]
# Realtime board and reset
board = ["0", p2, "2", p2, "4", p2, "6", p2,
p2, "9", p2, "11", p2, "13", p2, "15",
"16", p2, "18", p2, "20", p2, "22", p2,
"24", "25", "26", "27", "28", "29", "30", "31",
"32", "33", "34", "35", "36", "37", "38", "39",
p1, "41", p1, "43", p1, "45", p1, "47",
"48", p1, "50", p1, "52", p1, "54", p1,
p1, "57", p1, "59", p1, "61", p1, "63"]
# TESTING BOARD
boardr = ["0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", p2, "11", "12", "13", "14", "15",
"16", "17", "18", "19", "20", "21", "22", "23",
"24", "25", "26", "27", "28", "29", "30", "31",
"32", p1, "34", p1, "36", "37", "38", "39",
p1, "41", p1, "43", p1, "45", "46", "47",
"48", "49", "50", "51", "52", "53", "54", "55",
"56", "57", "58", "59", "60", "61", "62", "63"]
def display_board():
b = []
p1_pieces = [each for each in board if each in p1l]
p1_pieces = len(p1_pieces)
p2_pieces = [each for each in board if each in p2l]
p2_pieces = len(p2_pieces)
spaces = " " * ((p1_pieces < 10) + (p2_pieces < 10))
for index, each in enumerate(board):
color2 = purple # available_pieces color
color3 = yellow # selected piece color
if each == p1:
color = red
elif each == p2:
color = blue
elif each == p1k:
color = BIRed
color2 = BIPurple
color3 = BIYellow
elif each == p2k:
color = BIBlue
color2 = BIPurple
color3 = BIYellow
elif each.isdigit() and each in available_spots:
color = iblack # available squares
else:
color = black # unused squares
if index < 10:
findex = f"0{index}"
else:
findex = f"{index}"
if selection_process is True:
if index in available_pieces:
b.append(f"{color}[{color2}{findex}{color}]")
else:
b.append(f"{color}[{findex}]")
elif cord_process is True:
if index == int(selection):
b.append(f"{color}[{color3}{findex}{color}]")
elif index in available_cords:
b.append(f"{iblack}[{green}{findex}{iblack}]")
else:
b.append(f"{color}[{findex}]")
else:
b.append(f"{color}[{findex}]")
print(f"""
{On_Black} {reset}
{On_Black} {reset} {current_player}{reset}'s turn. {spaces}{red}{p1_pieces}{reset} - {blue}{p2_pieces}{On_Black} {reset}
{On_Black} {reset}
{On_Black} {b[0]}{b[1]}{b[2]}{b[3]}{b[4]}{b[5]}{b[6]}{b[7]}{On_Black} {reset}
{On_Black} {b[8]}{b[9]}{b[10]}{b[11]}{b[12]}{b[13]}{b[14]}{b[15]}{On_Black} {reset}
{On_Black} {b[16]}{b[17]}{b[18]}{b[19]}{b[20]}{b[21]}{b[22]}{b[23]}{On_Black} {reset}
{On_Black} {b[24]}{b[25]}{b[26]}{b[27]}{b[28]}{b[29]}{b[30]}{b[31]}{On_Black} {reset}
{On_Black} {b[32]}{b[33]}{b[34]}{b[35]}{b[36]}{b[37]}{b[38]}{b[39]}{On_Black} {reset}
{On_Black} {b[40]}{b[41]}{b[42]}{b[43]}{b[44]}{b[45]}{b[46]}{b[47]}{On_Black} {reset}
{On_Black} {b[48]}{b[49]}{b[50]}{b[51]}{b[52]}{b[53]}{b[54]}{b[55]}{On_Black} {reset}
{On_Black} {b[56]}{b[57]}{b[58]}{b[59]}{b[60]}{b[61]}{b[62]}{b[63]}{On_Black} {reset}
{On_Black} {reset}""")
def space_empty(direction, pos):
# is the space corresponding to the pawn empty?
directions = {"up_right": -7, "up_left": -9, "down_right": 9, "down_left": 7, "2up_right": -14, "2up_left": -18, "2down_right": 18, "2down_left": 14}
direction_number = directions[direction]
pos = int(pos)
if str(pos + direction_number) in available_spots and board[pos + direction_number] in available_spots:
return True
return False
def space_enemy(direction, pos):
# is the space corresponding to the pawn an enemy?
directions = {"up_right": -7, "up_left": -9, "down_right": 9, "down_left": 7}
direction_number = directions[direction]
pos = int(pos)
if board[pos] in p1l:
enemy_list = p2l
else:
enemy_list = p1l
if str(pos + direction_number) in available_spots and board[pos + direction_number] in enemy_list:
return True
return False
def can_eat(pos):
pos = int(pos)
if str(pos) not in available_spots:
return False
if board[pos] in p1l or is_king(pos):
if space_enemy("up_right", pos) and space_empty("2up_right", pos):
return True
if space_enemy("up_left", pos) and space_empty("2up_left", pos):
return True
if board[pos] in p2l or is_king(pos):
if space_enemy("down_left", pos) and space_empty("2down_left", pos):
return True
if space_enemy("down_right", pos) and space_empty("2down_right", pos):
return True
return False
def can_move(pos):
pos = int(pos)
if str(pos) not in available_spots:
return False
if can_eat(pos):
return True
if space_empty("up_right", pos) or space_empty("up_left", pos):
if board[pos] in p1l or is_king(pos):
return True
if space_empty("down_right", pos) or space_empty("down_left", pos):
if board[pos] in p2l or is_king(pos):
return True
return False
def does_list_have_eaters(list_):
for each in list_:
if can_eat(each):
return True
return False
selection = ''
selection_process = False
available_pieces = []
def select_pawn():
global selection_process, available_pieces, selection
available_pieces = [index for index, each in enumerate(board) if each in current_player_list and can_move(index)]
if force_eat is True and does_list_have_eaters(available_pieces):
for each in available_pieces[:]:
if not can_eat(each):
available_pieces.remove(each)
selection_process = True
display_board()
selection = input(f"{current_player} select a piece. Available pieces: {purple}{available_pieces}{reset} ")
while True:
if not selection.isdigit():
selection = input(f"Invalid input. Possible options: {purple}{available_pieces}{reset} Try again: ")
continue
if int(selection) not in available_pieces:
selection = input(f"Invalid input. Possible options: {purple}{available_pieces}{reset} Try again: ")
continue
else:
break
selection = selection.lstrip('0')
selection_process = False
cord_process = False
available_cords = []
def select_cord():
global board, selection, cord_process, available_cords
# creating a list with the only possible cordinates the selected piece can go:
double_jump = False
while True:
cord = None
available_cords = []
if not (force_eat is True and can_eat(selection)) and (double_jump is False):
if current_player == p1 or is_king(selection):
if space_empty("up_right", selection):
available_cords.append(int(selection) - 7)
if space_empty("up_left", selection):
available_cords.append(int(selection) - 9)
if current_player == p2 or is_king(selection):
if space_empty("down_left", selection):
available_cords.append(int(selection) + 7)
if space_empty("down_right", selection):
available_cords.append(int(selection) + 9)
if can_eat(selection):
if current_player == p1 or is_king(selection):
if space_empty("2up_right", selection) and space_enemy("up_right", selection):
available_cords.append(int(selection) - 14)
if space_empty("2up_left", selection) and space_enemy("up_left", selection):
available_cords.append(int(selection) - 18)
if current_player == p2 or is_king(selection):
if space_empty("2down_left", selection) and space_enemy("down_left", selection):
available_cords.append(int(selection) + 14)
if space_empty("2down_right", selection) and space_enemy("down_right", selection):
available_cords.append(int(selection) + 18)
available_cords.sort()
# starting the cord_process, choosing a cord the piece will move to.
cord_process = True
display_board()
if double_jump is False:
print(f"{current_player} selected piece at {yellow}{selection}{reset}.")
cord = input(f"Select a coordinate to go to: ")
while True:
cord = cord.lstrip('0')
if not cord.isdigit() or cord not in available_spots:
cord = input(f"Invalid coordinate. Available coordinates: {green}{available_cords}{reset}. Try again: ")
continue
elif int(cord) not in available_cords:
cord = input(f"Invalid coordinate. Available coordinates: {green}{available_cords}{reset}. Try again: ")
continue
else:
break
# capturing pieces
captured_piece = None
if int(cord) < int(selection) - 10 or int(cord) > int(selection) + 10:
if current_player == p1 or is_king(selection):
if int(cord) == int(selection) - 14:
captured_piece = int(selection) - 7
elif int(cord) == int(selection) - 18:
captured_piece = int(selection) - 9
if current_player == p2 or is_king(selection):
if int(cord) == int(selection) + 14:
captured_piece = int(selection) + 7
elif int(cord) == int(selection) + 18:
captured_piece = int(selection) + 9
if captured_piece is not None:
board[captured_piece] = d_board[captured_piece]
if current_player == p1 and not is_king(selection) and board[int(cord)] in ["1", "3", "5", "7"]:
board[int(cord)] = p1k
elif current_player == p2 and not is_king(selection) and board[int(cord)] in ["56", "58", "60", "62"]:
board[int(cord)] = p2k
else:
board[int(cord)] = board[int(selection)]
board[int(selection)] = d_board[int(selection)]
if captured_piece is None:
if current_player == p1:
print(f"Pawn {red}{selection}{reset} moved to square {green}{cord}{reset} without capturing any pieces.")
elif current_player == p2:
print(f"Pawn {blue}{selection}{reset} moved to square {green}{cord}{reset} without capturing any pieces.")
else:
if current_player == p1:
print(
f"Pawn {red}{selection}{reset} moved to square {green}{cord}{reset} and captured: {blue}{captured_piece}{reset}")
elif current_player == p2:
print(
f"Pawn {blue}{selection}{reset} moved to square {green}{cord}{reset} and captured: {red}{captured_piece}{reset}")
if can_eat(cord) and captured_piece is not None:
if force_eat is False:
input1 = None
selection = cord
available_cords = []
if current_player == p1 or is_king(selection):
if space_empty("2up_right", selection) and space_enemy("up_right", selection):
available_cords.append(int(selection) - 14)
if space_empty("2up_left", selection) and space_enemy("up_left", selection):
available_cords.append(int(selection) - 18)
if current_player == p2 or is_king(selection):
if space_empty("2down_left", selection) and space_enemy("down_left", selection):
available_cords.append(int(selection) + 14)
if space_empty("2down_right", selection) and space_enemy("down_right", selection):
available_cords.append(int(selection) + 18)
available_cords.sort()
display_board()
while input1 not in ["yes", "no"]:
input1 = input("Do you want to continue capturing? (yes, no): ")
if input1 == "yes":
double_jump = True
continue
else:
break
else:
print("You are forced to capture again.")
double_jump = True
selection = cord
continue
else:
break
cord_process = False
def is_king(pawn):
pawn = int(pawn)
if d_board[pawn] not in available_spots:
return False
if board[pawn] == p1k or board[pawn] == p2k:
return True
return False
def check_for_win():
global winner, game_is_active
p1_list = []
p2_list = []
for index, each in enumerate(board):
if each in p1l:
p1_list.append(index)
if each in p2l:
p2_list.append(index)
if p1_list == []:
winner = p2
game_is_active = False
elif p2_list == []:
winner = p1
game_is_active = False
else:
p1_can_move = 0
p2_can_move = 0
for each in p1_list:
if can_move(each):
p1_can_move = 1
for each in p2_list:
if can_move(each):
p2_can_move = 1
if p1_can_move == 0:
winner = p2
game_is_active = False
elif p2_can_move == 0:
winner = p1
game_is_active = False
def switch_player():
global current_player, current_player_list
if current_player == p1:
current_player = p2
current_player_list = p2l
else:
current_player = p1
current_player_list = p1l
# start of game
winner = None
force_eat = False
game_is_active = True
current_player = p1
current_player_list = p1l
while game_is_active:
select_pawn()
select_cord()
check_for_win()
switch_player()
display_board()
print(f"{winner} {reset}has won the game.")
|
reset = '\x1b[0m'
red = '\x1b[0;31m'
green = '\x1b[0;32m'
yellow = '\x1b[0;33m'
blue = '\x1b[0;34m'
purple = '\x1b[0;35m'
b_red = '\x1b[1;31m'
b_yellow = '\x1b[1;33m'
b_blue = '\x1b[1;34m'
b_purple = '\x1b[1;35m'
on__black = '\x1b[40m'
bi_red = '\x1b[1;91m'
bi_yellow = '\x1b[1;93m'
bi_blue = '\x1b[1;94m'
bi_purple = '\x1b[1;95m'
i_white = '\x1b[0;97m'
black = '\x1b[0;30m'
iblack = '\x1b[0;90m'
p1 = f'{red}P1{reset}'
p2 = f'{blue}P2{reset}'
p1k = 'p1k'
p2k = 'p2k'
p1l = [p1, p1k]
p2l = [p2, p2k]
d_board = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63']
available_spots = ['1', '3', '5', '7', '8', '10', '12', '14', '17', '19', '21', '23', '24', '26', '28', '30', '33', '35', '37', '39', '40', '42', '44', '46', '49', '51', '53', '55', '56', '58', '60', '62']
board = ['0', p2, '2', p2, '4', p2, '6', p2, p2, '9', p2, '11', p2, '13', p2, '15', '16', p2, '18', p2, '20', p2, '22', p2, '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', p1, '41', p1, '43', p1, '45', p1, '47', '48', p1, '50', p1, '52', p1, '54', p1, p1, '57', p1, '59', p1, '61', p1, '63']
boardr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', p2, '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', p1, '34', p1, '36', '37', '38', '39', p1, '41', p1, '43', p1, '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63']
def display_board():
b = []
p1_pieces = [each for each in board if each in p1l]
p1_pieces = len(p1_pieces)
p2_pieces = [each for each in board if each in p2l]
p2_pieces = len(p2_pieces)
spaces = ' ' * ((p1_pieces < 10) + (p2_pieces < 10))
for (index, each) in enumerate(board):
color2 = purple
color3 = yellow
if each == p1:
color = red
elif each == p2:
color = blue
elif each == p1k:
color = BIRed
color2 = BIPurple
color3 = BIYellow
elif each == p2k:
color = BIBlue
color2 = BIPurple
color3 = BIYellow
elif each.isdigit() and each in available_spots:
color = iblack
else:
color = black
if index < 10:
findex = f'0{index}'
else:
findex = f'{index}'
if selection_process is True:
if index in available_pieces:
b.append(f'{color}[{color2}{findex}{color}]')
else:
b.append(f'{color}[{findex}]')
elif cord_process is True:
if index == int(selection):
b.append(f'{color}[{color3}{findex}{color}]')
elif index in available_cords:
b.append(f'{iblack}[{green}{findex}{iblack}]')
else:
b.append(f'{color}[{findex}]')
else:
b.append(f'{color}[{findex}]')
print(f"\n{On_Black} {reset}\n{On_Black} {reset} {current_player}{reset}'s turn. {spaces}{red}{p1_pieces}{reset} - {blue}{p2_pieces}{On_Black} {reset} \n{On_Black} {reset}\n{On_Black} {b[0]}{b[1]}{b[2]}{b[3]}{b[4]}{b[5]}{b[6]}{b[7]}{On_Black} {reset}\n{On_Black} {b[8]}{b[9]}{b[10]}{b[11]}{b[12]}{b[13]}{b[14]}{b[15]}{On_Black} {reset}\n{On_Black} {b[16]}{b[17]}{b[18]}{b[19]}{b[20]}{b[21]}{b[22]}{b[23]}{On_Black} {reset}\n{On_Black} {b[24]}{b[25]}{b[26]}{b[27]}{b[28]}{b[29]}{b[30]}{b[31]}{On_Black} {reset}\n{On_Black} {b[32]}{b[33]}{b[34]}{b[35]}{b[36]}{b[37]}{b[38]}{b[39]}{On_Black} {reset}\n{On_Black} {b[40]}{b[41]}{b[42]}{b[43]}{b[44]}{b[45]}{b[46]}{b[47]}{On_Black} {reset}\n{On_Black} {b[48]}{b[49]}{b[50]}{b[51]}{b[52]}{b[53]}{b[54]}{b[55]}{On_Black} {reset}\n{On_Black} {b[56]}{b[57]}{b[58]}{b[59]}{b[60]}{b[61]}{b[62]}{b[63]}{On_Black} {reset}\n{On_Black} {reset}")
def space_empty(direction, pos):
directions = {'up_right': -7, 'up_left': -9, 'down_right': 9, 'down_left': 7, '2up_right': -14, '2up_left': -18, '2down_right': 18, '2down_left': 14}
direction_number = directions[direction]
pos = int(pos)
if str(pos + direction_number) in available_spots and board[pos + direction_number] in available_spots:
return True
return False
def space_enemy(direction, pos):
directions = {'up_right': -7, 'up_left': -9, 'down_right': 9, 'down_left': 7}
direction_number = directions[direction]
pos = int(pos)
if board[pos] in p1l:
enemy_list = p2l
else:
enemy_list = p1l
if str(pos + direction_number) in available_spots and board[pos + direction_number] in enemy_list:
return True
return False
def can_eat(pos):
pos = int(pos)
if str(pos) not in available_spots:
return False
if board[pos] in p1l or is_king(pos):
if space_enemy('up_right', pos) and space_empty('2up_right', pos):
return True
if space_enemy('up_left', pos) and space_empty('2up_left', pos):
return True
if board[pos] in p2l or is_king(pos):
if space_enemy('down_left', pos) and space_empty('2down_left', pos):
return True
if space_enemy('down_right', pos) and space_empty('2down_right', pos):
return True
return False
def can_move(pos):
pos = int(pos)
if str(pos) not in available_spots:
return False
if can_eat(pos):
return True
if space_empty('up_right', pos) or space_empty('up_left', pos):
if board[pos] in p1l or is_king(pos):
return True
if space_empty('down_right', pos) or space_empty('down_left', pos):
if board[pos] in p2l or is_king(pos):
return True
return False
def does_list_have_eaters(list_):
for each in list_:
if can_eat(each):
return True
return False
selection = ''
selection_process = False
available_pieces = []
def select_pawn():
global selection_process, available_pieces, selection
available_pieces = [index for (index, each) in enumerate(board) if each in current_player_list and can_move(index)]
if force_eat is True and does_list_have_eaters(available_pieces):
for each in available_pieces[:]:
if not can_eat(each):
available_pieces.remove(each)
selection_process = True
display_board()
selection = input(f'{current_player} select a piece. Available pieces: {purple}{available_pieces}{reset} ')
while True:
if not selection.isdigit():
selection = input(f'Invalid input. Possible options: {purple}{available_pieces}{reset} Try again: ')
continue
if int(selection) not in available_pieces:
selection = input(f'Invalid input. Possible options: {purple}{available_pieces}{reset} Try again: ')
continue
else:
break
selection = selection.lstrip('0')
selection_process = False
cord_process = False
available_cords = []
def select_cord():
global board, selection, cord_process, available_cords
double_jump = False
while True:
cord = None
available_cords = []
if not (force_eat is True and can_eat(selection)) and double_jump is False:
if current_player == p1 or is_king(selection):
if space_empty('up_right', selection):
available_cords.append(int(selection) - 7)
if space_empty('up_left', selection):
available_cords.append(int(selection) - 9)
if current_player == p2 or is_king(selection):
if space_empty('down_left', selection):
available_cords.append(int(selection) + 7)
if space_empty('down_right', selection):
available_cords.append(int(selection) + 9)
if can_eat(selection):
if current_player == p1 or is_king(selection):
if space_empty('2up_right', selection) and space_enemy('up_right', selection):
available_cords.append(int(selection) - 14)
if space_empty('2up_left', selection) and space_enemy('up_left', selection):
available_cords.append(int(selection) - 18)
if current_player == p2 or is_king(selection):
if space_empty('2down_left', selection) and space_enemy('down_left', selection):
available_cords.append(int(selection) + 14)
if space_empty('2down_right', selection) and space_enemy('down_right', selection):
available_cords.append(int(selection) + 18)
available_cords.sort()
cord_process = True
display_board()
if double_jump is False:
print(f'{current_player} selected piece at {yellow}{selection}{reset}.')
cord = input(f'Select a coordinate to go to: ')
while True:
cord = cord.lstrip('0')
if not cord.isdigit() or cord not in available_spots:
cord = input(f'Invalid coordinate. Available coordinates: {green}{available_cords}{reset}. Try again: ')
continue
elif int(cord) not in available_cords:
cord = input(f'Invalid coordinate. Available coordinates: {green}{available_cords}{reset}. Try again: ')
continue
else:
break
captured_piece = None
if int(cord) < int(selection) - 10 or int(cord) > int(selection) + 10:
if current_player == p1 or is_king(selection):
if int(cord) == int(selection) - 14:
captured_piece = int(selection) - 7
elif int(cord) == int(selection) - 18:
captured_piece = int(selection) - 9
if current_player == p2 or is_king(selection):
if int(cord) == int(selection) + 14:
captured_piece = int(selection) + 7
elif int(cord) == int(selection) + 18:
captured_piece = int(selection) + 9
if captured_piece is not None:
board[captured_piece] = d_board[captured_piece]
if current_player == p1 and (not is_king(selection)) and (board[int(cord)] in ['1', '3', '5', '7']):
board[int(cord)] = p1k
elif current_player == p2 and (not is_king(selection)) and (board[int(cord)] in ['56', '58', '60', '62']):
board[int(cord)] = p2k
else:
board[int(cord)] = board[int(selection)]
board[int(selection)] = d_board[int(selection)]
if captured_piece is None:
if current_player == p1:
print(f'Pawn {red}{selection}{reset} moved to square {green}{cord}{reset} without capturing any pieces.')
elif current_player == p2:
print(f'Pawn {blue}{selection}{reset} moved to square {green}{cord}{reset} without capturing any pieces.')
elif current_player == p1:
print(f'Pawn {red}{selection}{reset} moved to square {green}{cord}{reset} and captured: {blue}{captured_piece}{reset}')
elif current_player == p2:
print(f'Pawn {blue}{selection}{reset} moved to square {green}{cord}{reset} and captured: {red}{captured_piece}{reset}')
if can_eat(cord) and captured_piece is not None:
if force_eat is False:
input1 = None
selection = cord
available_cords = []
if current_player == p1 or is_king(selection):
if space_empty('2up_right', selection) and space_enemy('up_right', selection):
available_cords.append(int(selection) - 14)
if space_empty('2up_left', selection) and space_enemy('up_left', selection):
available_cords.append(int(selection) - 18)
if current_player == p2 or is_king(selection):
if space_empty('2down_left', selection) and space_enemy('down_left', selection):
available_cords.append(int(selection) + 14)
if space_empty('2down_right', selection) and space_enemy('down_right', selection):
available_cords.append(int(selection) + 18)
available_cords.sort()
display_board()
while input1 not in ['yes', 'no']:
input1 = input('Do you want to continue capturing? (yes, no): ')
if input1 == 'yes':
double_jump = True
continue
else:
break
else:
print('You are forced to capture again.')
double_jump = True
selection = cord
continue
else:
break
cord_process = False
def is_king(pawn):
pawn = int(pawn)
if d_board[pawn] not in available_spots:
return False
if board[pawn] == p1k or board[pawn] == p2k:
return True
return False
def check_for_win():
global winner, game_is_active
p1_list = []
p2_list = []
for (index, each) in enumerate(board):
if each in p1l:
p1_list.append(index)
if each in p2l:
p2_list.append(index)
if p1_list == []:
winner = p2
game_is_active = False
elif p2_list == []:
winner = p1
game_is_active = False
else:
p1_can_move = 0
p2_can_move = 0
for each in p1_list:
if can_move(each):
p1_can_move = 1
for each in p2_list:
if can_move(each):
p2_can_move = 1
if p1_can_move == 0:
winner = p2
game_is_active = False
elif p2_can_move == 0:
winner = p1
game_is_active = False
def switch_player():
global current_player, current_player_list
if current_player == p1:
current_player = p2
current_player_list = p2l
else:
current_player = p1
current_player_list = p1l
winner = None
force_eat = False
game_is_active = True
current_player = p1
current_player_list = p1l
while game_is_active:
select_pawn()
select_cord()
check_for_win()
switch_player()
display_board()
print(f'{winner} {reset}has won the game.')
|
def count(sequence, item):
amount = 0
for x in sequence:
if x == item:
amount += 1
return amount
|
def count(sequence, item):
amount = 0
for x in sequence:
if x == item:
amount += 1
return amount
|
'''
Write a Python program to get the sum of a non-negative integer.
'''
class Solution:
def __init__(self, num):
self.num = num
def sum_digits(self, x):
if x == 1:
return int(str(self.num)[-1])
else:
return int(str(self.num)[-x]) + self.sum_digits(x-1)
def sumDigits(n):
if n == 0:
return 0
else:
return n % 10 + sumDigits(int(n / 10))
print(sumDigits(345))
print(sumDigits(45))
if __name__ == '__main__':
res = Solution(12348).sum_digits(5)
|
"""
Write a Python program to get the sum of a non-negative integer.
"""
class Solution:
def __init__(self, num):
self.num = num
def sum_digits(self, x):
if x == 1:
return int(str(self.num)[-1])
else:
return int(str(self.num)[-x]) + self.sum_digits(x - 1)
def sum_digits(n):
if n == 0:
return 0
else:
return n % 10 + sum_digits(int(n / 10))
print(sum_digits(345))
print(sum_digits(45))
if __name__ == '__main__':
res = solution(12348).sum_digits(5)
|
'#La nomenclatura utilizada es INSTANCIA_ESQUEMA_PWD'
FISCO_USER = 'FISCAR'
FISCO_FISCAR_PWD = 'FISCAR'
'#String de conexion '
FISCO_CONNECTION_STRING = '10.30.205.127/fisco'
|
"""#La nomenclatura utilizada es INSTANCIA_ESQUEMA_PWD"""
fisco_user = 'FISCAR'
fisco_fiscar_pwd = 'FISCAR'
'#String de conexion '
fisco_connection_string = '10.30.205.127/fisco'
|
def hamming_distance(string1, string2):
assert len(string1) == len(string2)
distance = 0
for i in range(len(string1)):
if string1[i] != string2[i]:
distance += 1
return distance
'''def results(string1, string2):
print(hamming_distance(string1, string2))
results('CGTGAGATAGCATATGGTAAATGTTCCGCAATCGCTACCGCCAACAACTCGTTCATCCCAATAATGTGCCCGGAGGGACAGTAACAGACTACGTGTACGGACGAGCCTGACCCAGCAAGGGTGGGAGTGACTCCATGCCATCTCCAATAACAAGCACCAACCAATGTCGCCGGCCTAAGGTAGCGCAGATCTAGTTTCATGTCCGAAGTTGGCTAGCCCTCTCTGCCGCGGTTAGGGAGGAAAAGCATGGCTAGTGTCGAGACGTACAACTAATCCGTGGCGTCAATCTCCCCTGCACTCGAGTACGCATATTGGTCCGCCACTCAGCGAATTATCTTATTGGAATGCCTCTTACAACACGGTATTGATTTAAACAGGATTAGAAGATTACTATACCTTTAGTAATTGGAGTGTTGAGTTTACGGAATCCTAATAATCAATCAGATACGCAGGTAAAGTATGTCACGTTACTGAGAAGTGGGTCGTCTATACATGAGGTCGTGTTCTTGCCTATTATATAGCAACCCTGTCAAGGCTTCTCTCCGAGCAAGCCGGACTCTGTCGCTTAGAGTCATGTGGGCACGTGTTACGTCGTCGTCAGCACGGGCTCAGGCCAATAGGGTATATAAATTGGAATGCTCCACGGTGAAAAGACTGGCTGCCGAATCCTGCCGCTGGGTACCCGTATTGCCGGCAATACAGGCCTAGTCGGTAGCTGCAGGAGAATACCGATTAACGGCGAAGGCGCCAGCCTCCGTAGTACCTGAGTTGTCGATCTACGGCGGAACCCGTGTACGCTTCATCAGCCCCTAACGGTTCGTTATTCATGATCCTGTTGCAAGTTCACGAACTCTAGCCCGGCGCACCAATAGCTTAATGTCGAAGTGTTCGTCATCTGGTGGAGCCCGTGCCCCGGAAGTCGGGGTAGTGATGTTCTACTTTCTATAAGTTGAGCGCCACCAGGAAGAGCTTCATCTTAAGCACCTGTTCCATTCAGAGAGCAGGTTCCTTTCGAAGTTTGGATACAGTCTGGAATGAGAGGCCAGTGTCACTGAATCGCTTTTTCAGCCTCCCATACGAATGC', 'GTTTCGCAAATATCGGGAACATATGGCTTTTGGCCTCTCCCTGGTCGGACGCTCGGATACAAAAGATCGCCCGAGCGTGCCATAGAACAACCAGTATGATTTTCAAGGATCGCGTATCAGCAGAGCAACTTCGTCGGACACGCGTATACCAGACTCACTGGTTTCGGGGCACGCTAAGAGGACTGAGTGTAACACTTCCTAATCATTGCCGATTAAGTCGGCGGAACAGGTTTTTCTGGCGGGACTCACTGTACGCGCGCGTTCGCCGCGGCTGCTGCCGACCTTAGTTGGCGGGGACGCCTCGGACATATAAGATGAAACTTGTTGAGCACTCCAGCGTAATGAGACGATTACCCAGCGTGCGTGACCACGGAAAACCTGCTAGTGCTTACTATTCCTTTTCCAGCCCATGCAACTACTTAGGGGCCGCCGGCGACAAGCGGACTTCATATCATCTGGTCTTAGTAAAGCTTTACGTATTATTGATAGATGGGAGGAATTAACAGCAGTTCCTACCGCACTTGGGTTTATCCGGATATAGGGATTAACTCGTTGGGATTATGCGTCTGCCTACTATCGACTTGCGCGTAGACCTGTGTGCGGAACACCCGATCCCTATTAACTTTAACCAGGGTCATGCCGGATTGACCTGAACTACGCCAAAATAAGGGAACCAAATGGTGTGCGGCGTTTGTATCCAAAGCCGGAAACTATTGGCCTACAACCCGATGACTCCTTTCAATCGGGACGTCCCTATACACTAGGTACATGATCGAAAGGTCTTGCTGGATGGATGCCGACAACATTGTAAGACAGCCTTGATAATGCGAATGTCTGACCCCGCGGCTGTGTCACGAGCTCAATCTCGGTCCTAGCGCCCAAACATCAGAGGATATCTCGACGGGTGAACATTATAACCCTTGATCGGTTGGTAGAAGTAAATCTACTTATCACTTCCCTTGGTGTGGATAATCACAGGGATGTTGAAGTTAGCGGTCCACCAACAGGCGAGTACGGGACTTCACACTCCGCAAGGTTACTCTTAATATCACATATCGCTGTCCCTAGTATTAAGTTGATGCGC')
'''
|
def hamming_distance(string1, string2):
assert len(string1) == len(string2)
distance = 0
for i in range(len(string1)):
if string1[i] != string2[i]:
distance += 1
return distance
"def results(string1, string2):\n\tprint(hamming_distance(string1, string2))\n\nresults('CGTGAGATAGCATATGGTAAATGTTCCGCAATCGCTACCGCCAACAACTCGTTCATCCCAATAATGTGCCCGGAGGGACAGTAACAGACTACGTGTACGGACGAGCCTGACCCAGCAAGGGTGGGAGTGACTCCATGCCATCTCCAATAACAAGCACCAACCAATGTCGCCGGCCTAAGGTAGCGCAGATCTAGTTTCATGTCCGAAGTTGGCTAGCCCTCTCTGCCGCGGTTAGGGAGGAAAAGCATGGCTAGTGTCGAGACGTACAACTAATCCGTGGCGTCAATCTCCCCTGCACTCGAGTACGCATATTGGTCCGCCACTCAGCGAATTATCTTATTGGAATGCCTCTTACAACACGGTATTGATTTAAACAGGATTAGAAGATTACTATACCTTTAGTAATTGGAGTGTTGAGTTTACGGAATCCTAATAATCAATCAGATACGCAGGTAAAGTATGTCACGTTACTGAGAAGTGGGTCGTCTATACATGAGGTCGTGTTCTTGCCTATTATATAGCAACCCTGTCAAGGCTTCTCTCCGAGCAAGCCGGACTCTGTCGCTTAGAGTCATGTGGGCACGTGTTACGTCGTCGTCAGCACGGGCTCAGGCCAATAGGGTATATAAATTGGAATGCTCCACGGTGAAAAGACTGGCTGCCGAATCCTGCCGCTGGGTACCCGTATTGCCGGCAATACAGGCCTAGTCGGTAGCTGCAGGAGAATACCGATTAACGGCGAAGGCGCCAGCCTCCGTAGTACCTGAGTTGTCGATCTACGGCGGAACCCGTGTACGCTTCATCAGCCCCTAACGGTTCGTTATTCATGATCCTGTTGCAAGTTCACGAACTCTAGCCCGGCGCACCAATAGCTTAATGTCGAAGTGTTCGTCATCTGGTGGAGCCCGTGCCCCGGAAGTCGGGGTAGTGATGTTCTACTTTCTATAAGTTGAGCGCCACCAGGAAGAGCTTCATCTTAAGCACCTGTTCCATTCAGAGAGCAGGTTCCTTTCGAAGTTTGGATACAGTCTGGAATGAGAGGCCAGTGTCACTGAATCGCTTTTTCAGCCTCCCATACGAATGC', 'GTTTCGCAAATATCGGGAACATATGGCTTTTGGCCTCTCCCTGGTCGGACGCTCGGATACAAAAGATCGCCCGAGCGTGCCATAGAACAACCAGTATGATTTTCAAGGATCGCGTATCAGCAGAGCAACTTCGTCGGACACGCGTATACCAGACTCACTGGTTTCGGGGCACGCTAAGAGGACTGAGTGTAACACTTCCTAATCATTGCCGATTAAGTCGGCGGAACAGGTTTTTCTGGCGGGACTCACTGTACGCGCGCGTTCGCCGCGGCTGCTGCCGACCTTAGTTGGCGGGGACGCCTCGGACATATAAGATGAAACTTGTTGAGCACTCCAGCGTAATGAGACGATTACCCAGCGTGCGTGACCACGGAAAACCTGCTAGTGCTTACTATTCCTTTTCCAGCCCATGCAACTACTTAGGGGCCGCCGGCGACAAGCGGACTTCATATCATCTGGTCTTAGTAAAGCTTTACGTATTATTGATAGATGGGAGGAATTAACAGCAGTTCCTACCGCACTTGGGTTTATCCGGATATAGGGATTAACTCGTTGGGATTATGCGTCTGCCTACTATCGACTTGCGCGTAGACCTGTGTGCGGAACACCCGATCCCTATTAACTTTAACCAGGGTCATGCCGGATTGACCTGAACTACGCCAAAATAAGGGAACCAAATGGTGTGCGGCGTTTGTATCCAAAGCCGGAAACTATTGGCCTACAACCCGATGACTCCTTTCAATCGGGACGTCCCTATACACTAGGTACATGATCGAAAGGTCTTGCTGGATGGATGCCGACAACATTGTAAGACAGCCTTGATAATGCGAATGTCTGACCCCGCGGCTGTGTCACGAGCTCAATCTCGGTCCTAGCGCCCAAACATCAGAGGATATCTCGACGGGTGAACATTATAACCCTTGATCGGTTGGTAGAAGTAAATCTACTTATCACTTCCCTTGGTGTGGATAATCACAGGGATGTTGAAGTTAGCGGTCCACCAACAGGCGAGTACGGGACTTCACACTCCGCAAGGTTACTCTTAATATCACATATCGCTGTCCCTAGTATTAAGTTGATGCGC')\n"
|
# -*- coding: utf-8 -*-
__author__ = 'Hamish Downer'
__email__ = '[email protected]'
__version__ = '0.1.0'
|
__author__ = 'Hamish Downer'
__email__ = '[email protected]'
__version__ = '0.1.0'
|
class SparkPostException(Exception):
pass
class SparkPostAPIException(SparkPostException):
"Handle 4xx and 5xx errors from the SparkPost API"
def __init__(self, response, *args, **kwargs):
# noinspection PyBroadException
try:
errors = response.json()['errors']
error_template = "{message} Code: {code} Description: {desc} \n"
errors = [error_template.format(message=e.get('message', ''),
code=e.get('code', 'none'),
desc=e.get('description', 'none'))
for e in errors]
# TODO: select exception to catch here
except: # noqa: E722
errors = [response.text or ""]
self.status = response.status_code
self.response = response
self.errors = errors
message = """Call to {uri} returned {status_code}, errors:
{errors}
""".format(
uri=response.url,
status_code=response.status_code,
errors='\n'.join(errors)
)
super(SparkPostAPIException, self).__init__(message, *args, **kwargs)
|
class Sparkpostexception(Exception):
pass
class Sparkpostapiexception(SparkPostException):
"""Handle 4xx and 5xx errors from the SparkPost API"""
def __init__(self, response, *args, **kwargs):
try:
errors = response.json()['errors']
error_template = '{message} Code: {code} Description: {desc} \n'
errors = [error_template.format(message=e.get('message', ''), code=e.get('code', 'none'), desc=e.get('description', 'none')) for e in errors]
except:
errors = [response.text or '']
self.status = response.status_code
self.response = response
self.errors = errors
message = 'Call to {uri} returned {status_code}, errors:\n\n {errors}\n\n '.format(uri=response.url, status_code=response.status_code, errors='\n'.join(errors))
super(SparkPostAPIException, self).__init__(message, *args, **kwargs)
|
{
"targets": [
{
"target_name": "switch_bindings",
"sources": [
"src/switch_bindings.cpp",
"src/log-utils/logging.c",
"src/log-utils/log_core.c",
"src/common-utils/common_utils.c",
"src/shm_core/shm_dup.c",
"src/shm_core/shm_data.c",
"src/shm_core/shm_mutex.c",
"src/shm_core/shm_datatypes.c",
"src/shm_core/shm_apr.c",
"src/http-utils/http_client.c",
"src/stomp-utils/stomp_utils.c",
"src/stomp-utils/stomp.c",
"src/xml-core/xml_core.c",
"src/xml-core/token_utils.c",
"src/config_core2.c",
"src/config_messaging_parsing2.c",
"src/config_messaging2.c",
"src/config_bindings2.c",
"src/config_error2.c",
"src/switch_config_core.c",
"src/switch_config_xml.c",
"src/switch_config.c",
"src/db_core2.c",
"src/libswitch_conf.c",
"src/switch_types.c",
"src/sqlite3.c"
],
"include_dirs": [
"./src",
"./src/common-utils",
"./src/apache-utils",
"./src/shm_core",
"./src/log-utils",
"./src/stomp-utils",
"./src/xml-core",
"./src/http-utils",
"/usr/include/apr-1"
],
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
'conditions': [
['OS=="linux"', {
'libraries': [ '-lapr-1 -laprutil-1 -lexpat -lz -lpcreposix -lcurl' ]
}],
['OS=="mac"', {
'libraries': [ '-lapr-1 -laprutil-1 -lexpat -lz -lpcreposix -lcurl' ],
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'GCC_ENABLE_CPP_RTTI': 'NO',
'INSTALL_PATH': '@rpath',
'LD_DYLIB_INSTALL_NAME': '',
'OTHER_LDFLAGS': [
'-Wl,-search_paths_first',
'-Wl,-rpath,<(module_root_dir)/src/http-utils/osx',
'-L<(module_root_dir)/src/http-utils/osx'
]
}
}]
]
}
]
}
|
{'targets': [{'target_name': 'switch_bindings', 'sources': ['src/switch_bindings.cpp', 'src/log-utils/logging.c', 'src/log-utils/log_core.c', 'src/common-utils/common_utils.c', 'src/shm_core/shm_dup.c', 'src/shm_core/shm_data.c', 'src/shm_core/shm_mutex.c', 'src/shm_core/shm_datatypes.c', 'src/shm_core/shm_apr.c', 'src/http-utils/http_client.c', 'src/stomp-utils/stomp_utils.c', 'src/stomp-utils/stomp.c', 'src/xml-core/xml_core.c', 'src/xml-core/token_utils.c', 'src/config_core2.c', 'src/config_messaging_parsing2.c', 'src/config_messaging2.c', 'src/config_bindings2.c', 'src/config_error2.c', 'src/switch_config_core.c', 'src/switch_config_xml.c', 'src/switch_config.c', 'src/db_core2.c', 'src/libswitch_conf.c', 'src/switch_types.c', 'src/sqlite3.c'], 'include_dirs': ['./src', './src/common-utils', './src/apache-utils', './src/shm_core', './src/log-utils', './src/stomp-utils', './src/xml-core', './src/http-utils', '/usr/include/apr-1'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'conditions': [['OS=="linux"', {'libraries': ['-lapr-1 -laprutil-1 -lexpat -lz -lpcreposix -lcurl']}], ['OS=="mac"', {'libraries': ['-lapr-1 -laprutil-1 -lexpat -lz -lpcreposix -lcurl'], 'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'GCC_ENABLE_CPP_RTTI': 'NO', 'INSTALL_PATH': '@rpath', 'LD_DYLIB_INSTALL_NAME': '', 'OTHER_LDFLAGS': ['-Wl,-search_paths_first', '-Wl,-rpath,<(module_root_dir)/src/http-utils/osx', '-L<(module_root_dir)/src/http-utils/osx']}}]]}]}
|
def main():
n = int(input())
for a in range(1, 10):
b = n / a
if 1 <= b and b <= 9 and b % 1 == 0:
print('Yes')
exit()
print('No')
if __name__ == '__main__':
main()
|
def main():
n = int(input())
for a in range(1, 10):
b = n / a
if 1 <= b and b <= 9 and (b % 1 == 0):
print('Yes')
exit()
print('No')
if __name__ == '__main__':
main()
|
x = int(input("Enter number"))
for i in range(x):
a = list(str(i))
sum1 = 0
for j in range(len(a)):
b = int(a[j])**len(a)
sum1 = sum1 + b
if i == sum1:
print (i,"amstrong")
|
x = int(input('Enter number'))
for i in range(x):
a = list(str(i))
sum1 = 0
for j in range(len(a)):
b = int(a[j]) ** len(a)
sum1 = sum1 + b
if i == sum1:
print(i, 'amstrong')
|
x = int(input("Please enter the first digit"))
y = int(input("Please enter the second digit"))
output_list = []
while len(output_list) < x - 1:
for i in range(0, x):
list_2d = []
output_list.append(list_2d)
for j in range(0 ,y):
number = i * j
output_list[i].append(number)
print(output_list)
|
x = int(input('Please enter the first digit'))
y = int(input('Please enter the second digit'))
output_list = []
while len(output_list) < x - 1:
for i in range(0, x):
list_2d = []
output_list.append(list_2d)
for j in range(0, y):
number = i * j
output_list[i].append(number)
print(output_list)
|
# -*- Python -*-
# Copyright 2021 The Verible Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Rule to generate json-serializable simple structs
"""
def jcxxgen(name, src, out, namespace = ""):
"""Generate C/C++ language source from a jcxxgen schema file.
Args:
name: Name of the rule, producing a cc-library with the same name.
src: The schema yaml input file.
out: Name of the generated header file.
namespace: Optional name of the C++ namespace for generated structs.
"""
tool = "//common/tools:jcxxgen"
json_header = '"nlohmann/json.hpp"'
native.genrule(
name = name + "_gen",
srcs = [src],
outs = [out],
cmd = ("$(location //common/tools:jcxxgen) --json_header='" +
json_header + "' --class_namespace " +
namespace + " --output $@ $<"),
tools = [tool],
)
native.cc_library(
name = name,
hdrs = [out],
deps = ["@jsonhpp"],
)
|
"""
Rule to generate json-serializable simple structs
"""
def jcxxgen(name, src, out, namespace=''):
"""Generate C/C++ language source from a jcxxgen schema file.
Args:
name: Name of the rule, producing a cc-library with the same name.
src: The schema yaml input file.
out: Name of the generated header file.
namespace: Optional name of the C++ namespace for generated structs.
"""
tool = '//common/tools:jcxxgen'
json_header = '"nlohmann/json.hpp"'
native.genrule(name=name + '_gen', srcs=[src], outs=[out], cmd="$(location //common/tools:jcxxgen) --json_header='" + json_header + "' --class_namespace " + namespace + ' --output $@ $<', tools=[tool])
native.cc_library(name=name, hdrs=[out], deps=['@jsonhpp'])
|
class Player():
def __init__(self, name):
self.name = name
self.force = 0.0
def set_force(self, force):
self.force = force
|
class Player:
def __init__(self, name):
self.name = name
self.force = 0.0
def set_force(self, force):
self.force = force
|
def combine_nonblank_lines(content: list[str], sep: str = " ") -> list[str]:
content = [item.strip() for item in content]
i, new_content, clean_content = 0, "", []
while i < len(content):
if content[i] == "":
clean_content.append(new_content.strip())
new_content = ""
else:
new_content += sep + content[i]
i += 1
if new_content:
clean_content.append(new_content.strip())
return clean_content
|
def combine_nonblank_lines(content: list[str], sep: str=' ') -> list[str]:
content = [item.strip() for item in content]
(i, new_content, clean_content) = (0, '', [])
while i < len(content):
if content[i] == '':
clean_content.append(new_content.strip())
new_content = ''
else:
new_content += sep + content[i]
i += 1
if new_content:
clean_content.append(new_content.strip())
return clean_content
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 3 07:32:06 2018
@author: James Jiang
"""
all_lines = [line.rstrip('\n') for line in open('Data.txt')]
all_triples = [line.split('x') for line in all_lines]
all_triples_int = []
for triple in all_triples:
all_triples_int.append([int(num) for num in triple])
total = 0
for triple in all_triples_int:
total += triple[0]*triple[1]*triple[2] + min(2*(triple[0] + triple[1]), 2*(triple[0] + triple[2]), 2*(triple[1] + triple[2]))
print(total)
|
"""
Created on Wed Jan 3 07:32:06 2018
@author: James Jiang
"""
all_lines = [line.rstrip('\n') for line in open('Data.txt')]
all_triples = [line.split('x') for line in all_lines]
all_triples_int = []
for triple in all_triples:
all_triples_int.append([int(num) for num in triple])
total = 0
for triple in all_triples_int:
total += triple[0] * triple[1] * triple[2] + min(2 * (triple[0] + triple[1]), 2 * (triple[0] + triple[2]), 2 * (triple[1] + triple[2]))
print(total)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 14:05:46 2020
@author: jwiesner
"""
|
"""
Created on Tue Feb 25 14:05:46 2020
@author: jwiesner
"""
|
def phoneCall(min1, min2_10, min11, s):
minutes = 0
rate = min1
while s > 0:
minutes += 1
if minutes == 2:
rate = min2_10
elif minutes > 10:
rate = min11
s -= rate
if s < 0:
minutes -= 1
return minutes
|
def phone_call(min1, min2_10, min11, s):
minutes = 0
rate = min1
while s > 0:
minutes += 1
if minutes == 2:
rate = min2_10
elif minutes > 10:
rate = min11
s -= rate
if s < 0:
minutes -= 1
return minutes
|
print('hello\tworld')
print('hello\nworld')
print( len('hello world'))
print('hello world'[0])
my_letter_list = ['a','a','b','b','c']
print(my_letter_list)
print( set(my_letter_list))
my_unique_letters = set(my_letter_list)
print(my_unique_letters)
print( len(my_unique_letters))
print( 'd' in my_unique_letters)
|
print('hello\tworld')
print('hello\nworld')
print(len('hello world'))
print('hello world'[0])
my_letter_list = ['a', 'a', 'b', 'b', 'c']
print(my_letter_list)
print(set(my_letter_list))
my_unique_letters = set(my_letter_list)
print(my_unique_letters)
print(len(my_unique_letters))
print('d' in my_unique_letters)
|
# -*- coding: utf-8 -*-
def get_height_magnet(self):
"""get the height of the hole magnets
Parameters
----------
self : HoleM53
A HoleM53 object
Returns
-------
Hmag: float
height of the 2 Magnets [m]
"""
# magnet_0 and magnet_1 have the same height
Hmag = self.H2
return Hmag
|
def get_height_magnet(self):
"""get the height of the hole magnets
Parameters
----------
self : HoleM53
A HoleM53 object
Returns
-------
Hmag: float
height of the 2 Magnets [m]
"""
hmag = self.H2
return Hmag
|
"""Message type identifiers for Trust Pings."""
SPEC_URI = (
"https://github.com/hyperledger/aries-rfcs/tree/"
"527849ec3aa2a8fd47a7bb6c57f918ff8bcb5e8c/features/0048-trust-ping"
)
PROTOCOL_URI = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0"
PING = f"{PROTOCOL_URI}/ping"
PING_RESPONSE = f"{PROTOCOL_URI}/ping_response"
NEW_PROTOCOL_URI = "https://didcomm.org/trust_ping/1.0"
NEW_PING = f"{NEW_PROTOCOL_URI}/ping"
NEW_PING_RESPONSE = f"{NEW_PROTOCOL_URI}/ping_response"
PROTOCOL_PACKAGE = "aries_cloudagency.protocols.trustping.v1_0"
MESSAGE_TYPES = {
PING: f"{PROTOCOL_PACKAGE}.messages.ping.Ping",
PING_RESPONSE: f"{PROTOCOL_PACKAGE}.messages.ping_response.PingResponse",
NEW_PING: f"{PROTOCOL_PACKAGE}.messages.ping.Ping",
NEW_PING_RESPONSE: f"{PROTOCOL_PACKAGE}.messages.ping_response.PingResponse",
}
|
"""Message type identifiers for Trust Pings."""
spec_uri = 'https://github.com/hyperledger/aries-rfcs/tree/527849ec3aa2a8fd47a7bb6c57f918ff8bcb5e8c/features/0048-trust-ping'
protocol_uri = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0'
ping = f'{PROTOCOL_URI}/ping'
ping_response = f'{PROTOCOL_URI}/ping_response'
new_protocol_uri = 'https://didcomm.org/trust_ping/1.0'
new_ping = f'{NEW_PROTOCOL_URI}/ping'
new_ping_response = f'{NEW_PROTOCOL_URI}/ping_response'
protocol_package = 'aries_cloudagency.protocols.trustping.v1_0'
message_types = {PING: f'{PROTOCOL_PACKAGE}.messages.ping.Ping', PING_RESPONSE: f'{PROTOCOL_PACKAGE}.messages.ping_response.PingResponse', NEW_PING: f'{PROTOCOL_PACKAGE}.messages.ping.Ping', NEW_PING_RESPONSE: f'{PROTOCOL_PACKAGE}.messages.ping_response.PingResponse'}
|
"""
Constants used by the packageinstaller module
Copyright (C) 2017-2022 Intel Corporation
SPDX-License-Identifier: Apache-2.0
"""
# Configuration command/response channel
REMEDIATION_CONTAINER_CMD_CHANNEL = 'remediation/container'
REMEDIATION_IMAGE_CMD_CHANNEL = 'remediation/image'
EVENTS_CHANNEL = 'manageability/event'
CONFIGURATION_UPDATE_CHANNEL = 'configuration/update/dispatcher/+'
|
"""
Constants used by the packageinstaller module
Copyright (C) 2017-2022 Intel Corporation
SPDX-License-Identifier: Apache-2.0
"""
remediation_container_cmd_channel = 'remediation/container'
remediation_image_cmd_channel = 'remediation/image'
events_channel = 'manageability/event'
configuration_update_channel = 'configuration/update/dispatcher/+'
|
# The value to indicate NO LIMIT parameter
NO_LIMIT = -1
# PER_CPU_SHARES has been set to 1024 because CPU shares' quota
# is commonly used in cloud frameworks like Kubernetes[1],
# AWS[2] and Mesos[3] in a similar way. They spawn containers with
# --cpu-shares option values scaled by PER_CPU_SHARES.
PER_CPU_SHARES = 1024
SUBSYS_MEMORY = "memory"
SUBSYS_CPUSET = "cpuset"
SUBSYS_CPU = "cpu"
SUBSYS_CPUACCT = "cpuacct"
SUBSYS_PIDS = "pids"
CGROUP_TYPE_V2 = "cgroup2"
CGROUP_TYPE_V1 = "cgroup"
|
no_limit = -1
per_cpu_shares = 1024
subsys_memory = 'memory'
subsys_cpuset = 'cpuset'
subsys_cpu = 'cpu'
subsys_cpuacct = 'cpuacct'
subsys_pids = 'pids'
cgroup_type_v2 = 'cgroup2'
cgroup_type_v1 = 'cgroup'
|
n = int(input())
total = 0
line = map(int, input().split())
for _ in line:
if _ < 0:
total += -_
print(total)
|
n = int(input())
total = 0
line = map(int, input().split())
for _ in line:
if _ < 0:
total += -_
print(total)
|
#common variables!
def set_loop(lp):
global loop #not to use local variable
loop=lp
def set_nm(nm):
global noisymode
noisymode=nm
def get_loop():
return loop
def get_nm(): return noisymode
loop=[]
noisymode=False
|
def set_loop(lp):
global loop
loop = lp
def set_nm(nm):
global noisymode
noisymode = nm
def get_loop():
return loop
def get_nm():
return noisymode
loop = []
noisymode = False
|
def maior():
for c in range(10):
num = int(input())
if c == 0:
maior = primeiro = num
if num > maior:
maior = num
print(maior)
if maior % primeiro == 0:
print(primeiro)
maior()
|
def maior():
for c in range(10):
num = int(input())
if c == 0:
maior = primeiro = num
if num > maior:
maior = num
print(maior)
if maior % primeiro == 0:
print(primeiro)
maior()
|
# coding: utf-8
# 2021/3/17 @ tongshiwei
def etl(*args, **kwargs) -> ...: # pragma: no cover
"""
extract - transform - load
"""
pass
def train(*args, **kwargs) -> ...: # pragma: no cover
pass
def evaluate(*args, **kwargs) -> ...: # pragma: no cover
pass
class CDM(object):
def __init__(self, *args, **kwargs) -> ...:
pass
def train(self, *args, **kwargs) -> ...:
raise NotImplementedError
def eval(self, *args, **kwargs) -> ...:
raise NotImplementedError
def save(self, *args, **kwargs) -> ...:
raise NotImplementedError
def load(self, *args, **kwargs) -> ...:
raise NotImplementedError
|
def etl(*args, **kwargs) -> ...:
"""
extract - transform - load
"""
pass
def train(*args, **kwargs) -> ...:
pass
def evaluate(*args, **kwargs) -> ...:
pass
class Cdm(object):
def __init__(self, *args, **kwargs) -> ...:
pass
def train(self, *args, **kwargs) -> ...:
raise NotImplementedError
def eval(self, *args, **kwargs) -> ...:
raise NotImplementedError
def save(self, *args, **kwargs) -> ...:
raise NotImplementedError
def load(self, *args, **kwargs) -> ...:
raise NotImplementedError
|
AwayPlayerFoulClockStart=0
AwayLastPlayerFoul=''
HomePlayerFoulClockStart=0
HomeLastPlayerFoul=''
|
away_player_foul_clock_start = 0
away_last_player_foul = ''
home_player_foul_clock_start = 0
home_last_player_foul = ''
|
# -*- coding: utf-8 -*-
# Copyright (c) 2008-2016 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:[email protected]
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Functions to generate files readable with Georg Sander's vcg
(Visualization of Compiler Graphs).
You can download vcg at http://rw4.cs.uni-sb.de/~sander/html/gshome.html
Note that vcg exists as a debian package.
See vcg's documentation for explanation about the different values that
maybe used for the functions parameters.
"""
ATTRS_VAL = {
'algos': ('dfs', 'tree', 'minbackward',
'left_to_right', 'right_to_left',
'top_to_bottom', 'bottom_to_top',
'maxdepth', 'maxdepthslow', 'mindepth', 'mindepthslow',
'mindegree', 'minindegree', 'minoutdegree',
'maxdegree', 'maxindegree', 'maxoutdegree'),
'booleans': ('yes', 'no'),
'colors': ('black', 'white', 'blue', 'red', 'green', 'yellow',
'magenta', 'lightgrey',
'cyan', 'darkgrey', 'darkblue', 'darkred', 'darkgreen',
'darkyellow', 'darkmagenta', 'darkcyan', 'gold',
'lightblue', 'lightred', 'lightgreen', 'lightyellow',
'lightmagenta', 'lightcyan', 'lilac', 'turquoise',
'aquamarine', 'khaki', 'purple', 'yellowgreen', 'pink',
'orange', 'orchid'),
'shapes': ('box', 'ellipse', 'rhomb', 'triangle'),
'textmodes': ('center', 'left_justify', 'right_justify'),
'arrowstyles': ('solid', 'line', 'none'),
'linestyles': ('continuous', 'dashed', 'dotted', 'invisible'),
}
# meaning of possible values:
# O -> string
# 1 -> int
# list -> value in list
GRAPH_ATTRS = {
'title': 0,
'label': 0,
'color': ATTRS_VAL['colors'],
'textcolor': ATTRS_VAL['colors'],
'bordercolor': ATTRS_VAL['colors'],
'width': 1,
'height': 1,
'borderwidth': 1,
'textmode': ATTRS_VAL['textmodes'],
'shape': ATTRS_VAL['shapes'],
'shrink': 1,
'stretch': 1,
'orientation': ATTRS_VAL['algos'],
'vertical_order': 1,
'horizontal_order': 1,
'xspace': 1,
'yspace': 1,
'layoutalgorithm': ATTRS_VAL['algos'],
'late_edge_labels': ATTRS_VAL['booleans'],
'display_edge_labels': ATTRS_VAL['booleans'],
'dirty_edge_labels': ATTRS_VAL['booleans'],
'finetuning': ATTRS_VAL['booleans'],
'manhattan_edges': ATTRS_VAL['booleans'],
'smanhattan_edges': ATTRS_VAL['booleans'],
'port_sharing': ATTRS_VAL['booleans'],
'edges': ATTRS_VAL['booleans'],
'nodes': ATTRS_VAL['booleans'],
'splines': ATTRS_VAL['booleans'],
}
NODE_ATTRS = {
'title': 0,
'label': 0,
'color': ATTRS_VAL['colors'],
'textcolor': ATTRS_VAL['colors'],
'bordercolor': ATTRS_VAL['colors'],
'width': 1,
'height': 1,
'borderwidth': 1,
'textmode': ATTRS_VAL['textmodes'],
'shape': ATTRS_VAL['shapes'],
'shrink': 1,
'stretch': 1,
'vertical_order': 1,
'horizontal_order': 1,
}
EDGE_ATTRS = {
'sourcename': 0,
'targetname': 0,
'label': 0,
'linestyle': ATTRS_VAL['linestyles'],
'class': 1,
'thickness': 0,
'color': ATTRS_VAL['colors'],
'textcolor': ATTRS_VAL['colors'],
'arrowcolor': ATTRS_VAL['colors'],
'backarrowcolor': ATTRS_VAL['colors'],
'arrowsize': 1,
'backarrowsize': 1,
'arrowstyle': ATTRS_VAL['arrowstyles'],
'backarrowstyle': ATTRS_VAL['arrowstyles'],
'textmode': ATTRS_VAL['textmodes'],
'priority': 1,
'anchor': 1,
'horizontal_order': 1,
}
# Misc utilities ###############################################################
class VCGPrinter(object):
"""A vcg graph writer.
"""
def __init__(self, output_stream):
self._stream = output_stream
self._indent = ''
def open_graph(self, **args):
"""open a vcg graph
"""
self._stream.write('%sgraph:{\n'%self._indent)
self._inc_indent()
self._write_attributes(GRAPH_ATTRS, **args)
def close_graph(self):
"""close a vcg graph
"""
self._dec_indent()
self._stream.write('%s}\n'%self._indent)
def node(self, title, **args):
"""draw a node
"""
self._stream.write('%snode: {title:"%s"' % (self._indent, title))
self._write_attributes(NODE_ATTRS, **args)
self._stream.write('}\n')
def edge(self, from_node, to_node, edge_type='', **args):
"""draw an edge from a node to another.
"""
self._stream.write(
'%s%sedge: {sourcename:"%s" targetname:"%s"' % (
self._indent, edge_type, from_node, to_node))
self._write_attributes(EDGE_ATTRS, **args)
self._stream.write('}\n')
# private ##################################################################
def _write_attributes(self, attributes_dict, **args):
"""write graph, node or edge attributes
"""
for key, value in args.items():
try:
_type = attributes_dict[key]
except KeyError:
raise Exception('''no such attribute %s
possible attributes are %s''' % (key, attributes_dict.keys()))
if not _type:
self._stream.write('%s%s:"%s"\n' % (self._indent, key, value))
elif _type == 1:
self._stream.write('%s%s:%s\n' % (self._indent, key,
int(value)))
elif value in _type:
self._stream.write('%s%s:%s\n' % (self._indent, key, value))
else:
raise Exception('''value %s isn\'t correct for attribute %s
correct values are %s''' % (value, key, _type))
def _inc_indent(self):
"""increment indentation
"""
self._indent = ' %s' % self._indent
def _dec_indent(self):
"""decrement indentation
"""
self._indent = self._indent[:-2]
|
"""Functions to generate files readable with Georg Sander's vcg
(Visualization of Compiler Graphs).
You can download vcg at http://rw4.cs.uni-sb.de/~sander/html/gshome.html
Note that vcg exists as a debian package.
See vcg's documentation for explanation about the different values that
maybe used for the functions parameters.
"""
attrs_val = {'algos': ('dfs', 'tree', 'minbackward', 'left_to_right', 'right_to_left', 'top_to_bottom', 'bottom_to_top', 'maxdepth', 'maxdepthslow', 'mindepth', 'mindepthslow', 'mindegree', 'minindegree', 'minoutdegree', 'maxdegree', 'maxindegree', 'maxoutdegree'), 'booleans': ('yes', 'no'), 'colors': ('black', 'white', 'blue', 'red', 'green', 'yellow', 'magenta', 'lightgrey', 'cyan', 'darkgrey', 'darkblue', 'darkred', 'darkgreen', 'darkyellow', 'darkmagenta', 'darkcyan', 'gold', 'lightblue', 'lightred', 'lightgreen', 'lightyellow', 'lightmagenta', 'lightcyan', 'lilac', 'turquoise', 'aquamarine', 'khaki', 'purple', 'yellowgreen', 'pink', 'orange', 'orchid'), 'shapes': ('box', 'ellipse', 'rhomb', 'triangle'), 'textmodes': ('center', 'left_justify', 'right_justify'), 'arrowstyles': ('solid', 'line', 'none'), 'linestyles': ('continuous', 'dashed', 'dotted', 'invisible')}
graph_attrs = {'title': 0, 'label': 0, 'color': ATTRS_VAL['colors'], 'textcolor': ATTRS_VAL['colors'], 'bordercolor': ATTRS_VAL['colors'], 'width': 1, 'height': 1, 'borderwidth': 1, 'textmode': ATTRS_VAL['textmodes'], 'shape': ATTRS_VAL['shapes'], 'shrink': 1, 'stretch': 1, 'orientation': ATTRS_VAL['algos'], 'vertical_order': 1, 'horizontal_order': 1, 'xspace': 1, 'yspace': 1, 'layoutalgorithm': ATTRS_VAL['algos'], 'late_edge_labels': ATTRS_VAL['booleans'], 'display_edge_labels': ATTRS_VAL['booleans'], 'dirty_edge_labels': ATTRS_VAL['booleans'], 'finetuning': ATTRS_VAL['booleans'], 'manhattan_edges': ATTRS_VAL['booleans'], 'smanhattan_edges': ATTRS_VAL['booleans'], 'port_sharing': ATTRS_VAL['booleans'], 'edges': ATTRS_VAL['booleans'], 'nodes': ATTRS_VAL['booleans'], 'splines': ATTRS_VAL['booleans']}
node_attrs = {'title': 0, 'label': 0, 'color': ATTRS_VAL['colors'], 'textcolor': ATTRS_VAL['colors'], 'bordercolor': ATTRS_VAL['colors'], 'width': 1, 'height': 1, 'borderwidth': 1, 'textmode': ATTRS_VAL['textmodes'], 'shape': ATTRS_VAL['shapes'], 'shrink': 1, 'stretch': 1, 'vertical_order': 1, 'horizontal_order': 1}
edge_attrs = {'sourcename': 0, 'targetname': 0, 'label': 0, 'linestyle': ATTRS_VAL['linestyles'], 'class': 1, 'thickness': 0, 'color': ATTRS_VAL['colors'], 'textcolor': ATTRS_VAL['colors'], 'arrowcolor': ATTRS_VAL['colors'], 'backarrowcolor': ATTRS_VAL['colors'], 'arrowsize': 1, 'backarrowsize': 1, 'arrowstyle': ATTRS_VAL['arrowstyles'], 'backarrowstyle': ATTRS_VAL['arrowstyles'], 'textmode': ATTRS_VAL['textmodes'], 'priority': 1, 'anchor': 1, 'horizontal_order': 1}
class Vcgprinter(object):
"""A vcg graph writer.
"""
def __init__(self, output_stream):
self._stream = output_stream
self._indent = ''
def open_graph(self, **args):
"""open a vcg graph
"""
self._stream.write('%sgraph:{\n' % self._indent)
self._inc_indent()
self._write_attributes(GRAPH_ATTRS, **args)
def close_graph(self):
"""close a vcg graph
"""
self._dec_indent()
self._stream.write('%s}\n' % self._indent)
def node(self, title, **args):
"""draw a node
"""
self._stream.write('%snode: {title:"%s"' % (self._indent, title))
self._write_attributes(NODE_ATTRS, **args)
self._stream.write('}\n')
def edge(self, from_node, to_node, edge_type='', **args):
"""draw an edge from a node to another.
"""
self._stream.write('%s%sedge: {sourcename:"%s" targetname:"%s"' % (self._indent, edge_type, from_node, to_node))
self._write_attributes(EDGE_ATTRS, **args)
self._stream.write('}\n')
def _write_attributes(self, attributes_dict, **args):
"""write graph, node or edge attributes
"""
for (key, value) in args.items():
try:
_type = attributes_dict[key]
except KeyError:
raise exception('no such attribute %s\npossible attributes are %s' % (key, attributes_dict.keys()))
if not _type:
self._stream.write('%s%s:"%s"\n' % (self._indent, key, value))
elif _type == 1:
self._stream.write('%s%s:%s\n' % (self._indent, key, int(value)))
elif value in _type:
self._stream.write('%s%s:%s\n' % (self._indent, key, value))
else:
raise exception("value %s isn't correct for attribute %s\ncorrect values are %s" % (value, key, _type))
def _inc_indent(self):
"""increment indentation
"""
self._indent = ' %s' % self._indent
def _dec_indent(self):
"""decrement indentation
"""
self._indent = self._indent[:-2]
|
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
length = 0
current = ""
i = 0
j = 0
while i < len(s) and j < len(s):
if s[j] in current:
while s[j] in current:
i = i + 1
current = s[i:j]
j = j + 1
current = s[i:j]
else:
j = j + 1
current = s[i:j]
if len(current) > length:
length = len(current)
return length
a = Solution()
print(a.lengthOfLongestSubstring("pwwkew"))
|
class Solution:
def length_of_longest_substring(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
length = 0
current = ''
i = 0
j = 0
while i < len(s) and j < len(s):
if s[j] in current:
while s[j] in current:
i = i + 1
current = s[i:j]
j = j + 1
current = s[i:j]
else:
j = j + 1
current = s[i:j]
if len(current) > length:
length = len(current)
return length
a = solution()
print(a.lengthOfLongestSubstring('pwwkew'))
|
#Global
PARENT_DIR = "PARENT_DIR"
#Logging
LOG_FILE = "LOG_FILE"
SAVE_DIR = "SAVE_DIR"
TENSORBOARD_LOG_DIR = "TENSORBOARD_LOG_DIR"
#Preprocessing Dataset
DATASET_PATH = "DATASET_PATH"
#DeepSense Parameters
##Dataset Parameters
BATCH_SIZE = "BATCH_SIZE"
HISTORY_LENGTH = "HISTORY_LENGTH"
HORIZON = "HORIZON"
MEMORY_SIZE = "MEMORY_SIZE"
NUM_ACTIONS = "NUM_ACTIONS"
NUM_CHANNELS = "NUM_CHANNELS"
SPLIT_SIZE = "SPLIT_SIZE"
WINDOW_SIZE = "WINDOW_SIZE"
##Dropout Layer Parameters
CONV_KEEP_PROB = "CONV_KEEP_PROB"
DENSE_KEEP_PROB = "DENSE_KEEP_PROB"
GRU_KEEP_PROB = "GRU_KEEP_PROB"
## Convolution Layer Parameters
FILTER_SIZES = "FILTER_SIZES"
KERNEL_SIZES = "KERNEL_SIZES"
PADDING = "PADDING"
SAME = "SAME"
VALID = "VALID"
## GRU Parameters
GRU_CELL_SIZE = "GRU_CELL_SIZE"
GRU_NUM_CELLS = "GRU_NUM_CELLS"
##FullyConnected Layer Parameters
DENSE_LAYER_SIZES = "DENSE_LAYER_SIZES"
#configuration section names
CONVOLUTION = "convolution"
DATASET = "dataset"
DENSE = "dense"
DROPOUT = "dropout"
GLOBAL = "global"
GRU = "gru"
LOGGING = "logging"
PREPROCESSING = "preprocessing"
|
parent_dir = 'PARENT_DIR'
log_file = 'LOG_FILE'
save_dir = 'SAVE_DIR'
tensorboard_log_dir = 'TENSORBOARD_LOG_DIR'
dataset_path = 'DATASET_PATH'
batch_size = 'BATCH_SIZE'
history_length = 'HISTORY_LENGTH'
horizon = 'HORIZON'
memory_size = 'MEMORY_SIZE'
num_actions = 'NUM_ACTIONS'
num_channels = 'NUM_CHANNELS'
split_size = 'SPLIT_SIZE'
window_size = 'WINDOW_SIZE'
conv_keep_prob = 'CONV_KEEP_PROB'
dense_keep_prob = 'DENSE_KEEP_PROB'
gru_keep_prob = 'GRU_KEEP_PROB'
filter_sizes = 'FILTER_SIZES'
kernel_sizes = 'KERNEL_SIZES'
padding = 'PADDING'
same = 'SAME'
valid = 'VALID'
gru_cell_size = 'GRU_CELL_SIZE'
gru_num_cells = 'GRU_NUM_CELLS'
dense_layer_sizes = 'DENSE_LAYER_SIZES'
convolution = 'convolution'
dataset = 'dataset'
dense = 'dense'
dropout = 'dropout'
global = 'global'
gru = 'gru'
logging = 'logging'
preprocessing = 'preprocessing'
|
# https://www.codechef.com/problems/TWOSTR
for T in range(int(input())):
a,b,s=input(),input(),0
for i in range(len(a)):
if(a[i]==b[i] or a[i]=="?" or b[i]=="?"): s+=1
print("Yes") if(s==len(a)) else print("No")
|
for t in range(int(input())):
(a, b, s) = (input(), input(), 0)
for i in range(len(a)):
if a[i] == b[i] or a[i] == '?' or b[i] == '?':
s += 1
print('Yes') if s == len(a) else print('No')
|
w2vSize = 100
feature_dim = 100
max_len=21
debug = False
poolSize=32
topicNum = 100
fresh = True
|
w2v_size = 100
feature_dim = 100
max_len = 21
debug = False
pool_size = 32
topic_num = 100
fresh = True
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
"""
class Solution:
def getlen(self,node):
count = 0
while node is not None:
count+=1
node = node.next
return count
def getsumlist(self,node1,node2,m):
if node1 is None:
return None
cur = ListNode(node1.val)
if m<=0:
cur.val += node2.val
cur.next = self.getsumlist(node1.next,node2.next,m-1)
else:
cur.next = self.getsumlist(node1.next,node2,m-1)
if cur.next is not None and cur.next.val >=10:
cur.next.val-=10
cur.val+=1
return cur
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
len1 =self.getlen(l1)
len2 =self.getlen(l2)
if len1 >= len2:
tmp1 = l1
tmp2 = l2
m = len1-len2
else:
tmp1 = l2
tmp2 = l1
m = len2-len1
cur = self.getsumlist(tmp1,tmp2,m)
if cur.val >=10:
head= ListNode(1)
head.next = cur
cur.val-=10
return head
else:
return cur
"""
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
stack1 = []
stack2 = []
while l1:
stack1.append(l1.val)
l1 = l1.next
while l2:
stack2.append(l2.val)
l2 = l2.next
carry = 0
prev = None
while stack1 or stack2 or carry:
num1 = stack1.pop() if stack1 else 0
num2 = stack2.pop() if stack2 else 0
sum_node = num1+num2+carry
newnode = ListNode(sum_node%10,prev)
carry = sum_node//10
prev = newnode
return prev
|
class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
'\nclass Solution:\n def getlen(self,node):\n count = 0\n while node is not None:\n count+=1\n node = node.next\n return count\n def getsumlist(self,node1,node2,m):\n if node1 is None:\n return None\n cur = ListNode(node1.val)\n if m<=0:\n cur.val += node2.val\n cur.next = self.getsumlist(node1.next,node2.next,m-1)\n else:\n cur.next = self.getsumlist(node1.next,node2,m-1)\n if cur.next is not None and cur.next.val >=10:\n cur.next.val-=10\n cur.val+=1\n return cur\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n len1 =self.getlen(l1)\n len2 =self.getlen(l2)\n if len1 >= len2:\n tmp1 = l1\n tmp2 = l2\n m = len1-len2\n else:\n tmp1 = l2\n tmp2 = l1\n m = len2-len1\n cur = self.getsumlist(tmp1,tmp2,m)\n if cur.val >=10:\n head= ListNode(1)\n head.next = cur\n cur.val-=10\n return head\n else:\n return cur\n'
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
stack1 = []
stack2 = []
while l1:
stack1.append(l1.val)
l1 = l1.next
while l2:
stack2.append(l2.val)
l2 = l2.next
carry = 0
prev = None
while stack1 or stack2 or carry:
num1 = stack1.pop() if stack1 else 0
num2 = stack2.pop() if stack2 else 0
sum_node = num1 + num2 + carry
newnode = list_node(sum_node % 10, prev)
carry = sum_node // 10
prev = newnode
return prev
|
E = [[ 0, 1, 0, 0, 0, 0],
[E21, 0, 0, E24, E25, 0],
[ 0, 0, 0, 1, 0, 0],
[ 0, 0, E43, 0, 0, -1],
[ 0, 0, 0, 0, 0, 1],
[E61, 0, 0, E64, E65, 0]]
|
e = [[0, 1, 0, 0, 0, 0], [E21, 0, 0, E24, E25, 0], [0, 0, 0, 1, 0, 0], [0, 0, E43, 0, 0, -1], [0, 0, 0, 0, 0, 1], [E61, 0, 0, E64, E65, 0]]
|
class ComponentMeta(type):
"""Metaclass that builds a Component class.
This class transforms the _properties class property into a __slots__
property on the class before it is created, which suppresses the normal
creation of the __dict__ property and the memory overhead that brings.
"""
def __new__(cls, name, bases, namespace, **kwargs):
slots = tuple([p[0] for p in namespace['_properties']])
# Define our class's slots
namespace['__slots__'] = slots
# Generate the class for our component
return type.__new__(cls,
name,
bases,
namespace)
class ComponentBase(object, metaclass=ComponentMeta):
"""Base class for Components to inherit from.
Components should primarily just be data containers; logic should live
elsewhere, mostly in Systems."""
__slots__ = ()
_properties = ()
def __init__(self, *args, **kwargs):
"""A generic init method for initializing properties.
Properties can be set on initialization via either positional or
keyword arguments. The _properties property should be a tuple of
2-tuples in the form (k,v), where k is the property name and v is the
property's default value; positional initialization follows the same
order as _properties.
"""
# Start by initializing our properties to default values
for k,v in self._properties:
setattr(self, k, v)
# For any positional arguments, assign those values to our properties
# This is done in order of our __slots__ property
for k,v in zip(self.__slots__, args):
setattr(self, k, v)
# For any keyword arguments, assign those values to our properties
# Keywords must of course match one of our properties
for k in kwargs:
setattr(self, k, kwargs[k])
def __repr__(self):
values = []
for k, default in self._properties:
values.append("{k}={v}".format(k=k, v=getattr(self, k)))
values = ", ".join(values)
return "{cls}({values})".format(
cls = self.__class__.__name__,
values = values)
class MultiComponentMeta(ComponentMeta):
"""Metaclass that builds a MultiComponent class.
This class is responsible for creating and assigning the "sub-component"
class as a class property of the new MultiComponent subclass.
"""
def __new__(cls, name, bases, namespace, **kwargs):
try:
component_name = namespace['_component_name']
except KeyError:
# Generate the name of the sub-component by stripping off "Component"
# from the container's name. Also remove trailing 's'.
component_name = name.replace('Component','').rstrip('s')
namespace[component_name] = type(component_name,
(ComponentBase,),
{'_properties': namespace['_properties']})
# Now create our container
return type.__new__(cls,
name,
bases,
namespace)
class MultiComponentBase(dict, ComponentBase, metaclass=MultiComponentMeta):
"""Base class for MultiComponents to inherit from.
MultiComponent are dict-style containers for Components, allowing a single
Entity to have multiple instance of the Component.
A Component class will be automatically created using the _properties
property; by default the name will be derived by removing the "Component"
suffix as well as any trailing 's' characters left (e.g. SkillsComponent
would have a Component named Skill), but this can be overridden with a
_component_name property in the class definition. The Component will then
be available as a class property of the MultiComponent class.
For example, a SkillsComponent class that subclasses MultiComponentBase by
default will result in the creation of the SkillsComponent.Skill Component
class. An InventoryComponent class with a _component_name property of
'Item' will instead result in the creation of the InventoryComponent.Item
Component class.
"""
_properties = ()
def __repr__(self):
return "{cls}(<{size} Components>)".format(
cls = self.__class__.__name__,
size = len(self))
|
class Componentmeta(type):
"""Metaclass that builds a Component class.
This class transforms the _properties class property into a __slots__
property on the class before it is created, which suppresses the normal
creation of the __dict__ property and the memory overhead that brings.
"""
def __new__(cls, name, bases, namespace, **kwargs):
slots = tuple([p[0] for p in namespace['_properties']])
namespace['__slots__'] = slots
return type.__new__(cls, name, bases, namespace)
class Componentbase(object, metaclass=ComponentMeta):
"""Base class for Components to inherit from.
Components should primarily just be data containers; logic should live
elsewhere, mostly in Systems."""
__slots__ = ()
_properties = ()
def __init__(self, *args, **kwargs):
"""A generic init method for initializing properties.
Properties can be set on initialization via either positional or
keyword arguments. The _properties property should be a tuple of
2-tuples in the form (k,v), where k is the property name and v is the
property's default value; positional initialization follows the same
order as _properties.
"""
for (k, v) in self._properties:
setattr(self, k, v)
for (k, v) in zip(self.__slots__, args):
setattr(self, k, v)
for k in kwargs:
setattr(self, k, kwargs[k])
def __repr__(self):
values = []
for (k, default) in self._properties:
values.append('{k}={v}'.format(k=k, v=getattr(self, k)))
values = ', '.join(values)
return '{cls}({values})'.format(cls=self.__class__.__name__, values=values)
class Multicomponentmeta(ComponentMeta):
"""Metaclass that builds a MultiComponent class.
This class is responsible for creating and assigning the "sub-component"
class as a class property of the new MultiComponent subclass.
"""
def __new__(cls, name, bases, namespace, **kwargs):
try:
component_name = namespace['_component_name']
except KeyError:
component_name = name.replace('Component', '').rstrip('s')
namespace[component_name] = type(component_name, (ComponentBase,), {'_properties': namespace['_properties']})
return type.__new__(cls, name, bases, namespace)
class Multicomponentbase(dict, ComponentBase, metaclass=MultiComponentMeta):
"""Base class for MultiComponents to inherit from.
MultiComponent are dict-style containers for Components, allowing a single
Entity to have multiple instance of the Component.
A Component class will be automatically created using the _properties
property; by default the name will be derived by removing the "Component"
suffix as well as any trailing 's' characters left (e.g. SkillsComponent
would have a Component named Skill), but this can be overridden with a
_component_name property in the class definition. The Component will then
be available as a class property of the MultiComponent class.
For example, a SkillsComponent class that subclasses MultiComponentBase by
default will result in the creation of the SkillsComponent.Skill Component
class. An InventoryComponent class with a _component_name property of
'Item' will instead result in the creation of the InventoryComponent.Item
Component class.
"""
_properties = ()
def __repr__(self):
return '{cls}(<{size} Components>)'.format(cls=self.__class__.__name__, size=len(self))
|
"""Utility functions for processing connection tables and related data."""
def clean_atom(atom_line):
"""Removes reaction-specific properties (e.g. atom-atom mapping) from the
atom_line and returns the updated line."""
return atom_line[:60] + ' 0 0 0'
def clean_bond(bond_line):
"""Removes reaction center status from the bond_line and returns the
updated line."""
return bond_line[:18] + ' 0'
def clean_molecule(molfile):
"""Removes reaction information from the specified molfile and returns
the cleaned-up version."""
counts_line = molfile[3]
num_atoms = int(counts_line[:3])
num_bonds = int(counts_line[3:6])
clean_mol = []
clean_mol[:4] = molfile[:4]
for atom_line in molfile[4:num_atoms+4]:
clean_mol.append(clean_atom(atom_line))
for bond_line in molfile[num_atoms+4:num_atoms+num_bonds+4]:
clean_mol.append(clean_bond(bond_line))
m_len = len(molfile)
clean_mol[num_atoms+num_bonds+4:m_len] = molfile[num_atoms+num_bonds+4:m_len]
return clean_mol
def find_end_of_molfile(rxn, start):
end = start + 1
while rxn[end] != 'M END':
end += 1
return end + 1 # Include "M END"
def clean_reaction(rxn_block):
"""Remove atom-atom mappings and reaction centres from the given RXN
block and return the cleaned version."""
reaction = rxn_block.split('\n')
clean_reaction = []
clean_reaction[:5] = reaction[:5]
line = reaction[4]
num_reactants = int(line[:3])
num_products = int(line[3:6])
start_line = 5
for n in range(0, num_reactants + num_products):
clean_reaction.append(reaction[start_line]) # $MOL line
# print('>>', reaction[start_line], num_reactants, num_products)
start_line += 1
end_line = find_end_of_molfile(reaction, start_line)
clean_reaction.extend(clean_molecule(reaction[start_line:end_line]))
start_line = end_line
# print(len(clean_reaction))
return '\n'.join(clean_reaction)
|
"""Utility functions for processing connection tables and related data."""
def clean_atom(atom_line):
"""Removes reaction-specific properties (e.g. atom-atom mapping) from the
atom_line and returns the updated line."""
return atom_line[:60] + ' 0 0 0'
def clean_bond(bond_line):
"""Removes reaction center status from the bond_line and returns the
updated line."""
return bond_line[:18] + ' 0'
def clean_molecule(molfile):
"""Removes reaction information from the specified molfile and returns
the cleaned-up version."""
counts_line = molfile[3]
num_atoms = int(counts_line[:3])
num_bonds = int(counts_line[3:6])
clean_mol = []
clean_mol[:4] = molfile[:4]
for atom_line in molfile[4:num_atoms + 4]:
clean_mol.append(clean_atom(atom_line))
for bond_line in molfile[num_atoms + 4:num_atoms + num_bonds + 4]:
clean_mol.append(clean_bond(bond_line))
m_len = len(molfile)
clean_mol[num_atoms + num_bonds + 4:m_len] = molfile[num_atoms + num_bonds + 4:m_len]
return clean_mol
def find_end_of_molfile(rxn, start):
end = start + 1
while rxn[end] != 'M END':
end += 1
return end + 1
def clean_reaction(rxn_block):
"""Remove atom-atom mappings and reaction centres from the given RXN
block and return the cleaned version."""
reaction = rxn_block.split('\n')
clean_reaction = []
clean_reaction[:5] = reaction[:5]
line = reaction[4]
num_reactants = int(line[:3])
num_products = int(line[3:6])
start_line = 5
for n in range(0, num_reactants + num_products):
clean_reaction.append(reaction[start_line])
start_line += 1
end_line = find_end_of_molfile(reaction, start_line)
clean_reaction.extend(clean_molecule(reaction[start_line:end_line]))
start_line = end_line
return '\n'.join(clean_reaction)
|
#Represents the entire memory bank of the TB-3 (64 patterns in total)
class TB3Bank:
BANK_SIZE = 64
def __init__(self,patterns=None):
if(patterns != None):
self.patterns = patterns
else:
self.patterns = []
def get_patterns(self):
return self.patterns
def get_pattern(self,index):
return self.patterns[index]
def add_pattern(self,pattern):
self.patterns.append(pattern)
|
class Tb3Bank:
bank_size = 64
def __init__(self, patterns=None):
if patterns != None:
self.patterns = patterns
else:
self.patterns = []
def get_patterns(self):
return self.patterns
def get_pattern(self, index):
return self.patterns[index]
def add_pattern(self, pattern):
self.patterns.append(pattern)
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# Representation of the hudson.model.Result class
SUCCESS = {
'name': 'SUCCESS',
'ordinal': '0',
'color': 'BLUE',
'complete': True
}
UNSTABLE = {
'name': 'UNSTABLE',
'ordinal': '1',
'color': 'YELLOW',
'complete': True
}
FAILURE = {
'name': 'FAILURE',
'ordinal': '2',
'color': 'RED',
'complete': True
}
NOTBUILD = {
'name': 'NOT_BUILD',
'ordinal': '3',
'color': 'NOTBUILD',
'complete': False
}
ABORTED = {
'name': 'ABORTED',
'ordinal': '4',
'color': 'ABORTED',
'complete': False
}
THRESHOLDS = {
'SUCCESS': SUCCESS,
'UNSTABLE': UNSTABLE,
'FAILURE': FAILURE,
'NOT_BUILD': NOTBUILD,
'ABORTED': ABORTED
}
|
success = {'name': 'SUCCESS', 'ordinal': '0', 'color': 'BLUE', 'complete': True}
unstable = {'name': 'UNSTABLE', 'ordinal': '1', 'color': 'YELLOW', 'complete': True}
failure = {'name': 'FAILURE', 'ordinal': '2', 'color': 'RED', 'complete': True}
notbuild = {'name': 'NOT_BUILD', 'ordinal': '3', 'color': 'NOTBUILD', 'complete': False}
aborted = {'name': 'ABORTED', 'ordinal': '4', 'color': 'ABORTED', 'complete': False}
thresholds = {'SUCCESS': SUCCESS, 'UNSTABLE': UNSTABLE, 'FAILURE': FAILURE, 'NOT_BUILD': NOTBUILD, 'ABORTED': ABORTED}
|
# Time: O(nlogn)
# Space: O(n)
class Solution(object):
def intersectionSizeTwo(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
intervals.sort(key = lambda s_e: (s_e[0], -s_e[1]))
cnts = [2] * len(intervals)
result = 0
while intervals:
(start, _), cnt = intervals.pop(), cnts.pop()
for s in range(start, start+cnt):
for i in range(len(intervals)):
if cnts[i] and s <= intervals[i][1]:
cnts[i] -= 1
result += cnt
return result
|
class Solution(object):
def intersection_size_two(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
intervals.sort(key=lambda s_e: (s_e[0], -s_e[1]))
cnts = [2] * len(intervals)
result = 0
while intervals:
((start, _), cnt) = (intervals.pop(), cnts.pop())
for s in range(start, start + cnt):
for i in range(len(intervals)):
if cnts[i] and s <= intervals[i][1]:
cnts[i] -= 1
result += cnt
return result
|
#!/usr/bin/env python
#######################################
# Installation module for mana-toolkit
#######################################
# AUTHOR OF MODULE NAME
AUTHOR="jklaz"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install/update the mana-toolkit"
# INSTALL TYPE GIT, SVN, FILE DOWNLOAD
# OPTIONS = GIT, SVN, FILE
INSTALL_TYPE="GIT"
# LOCATION OF THE FILE OR GIT/SVN REPOSITORY
REPOSITORY_LOCATION="https://github.com/sensepost/mana"
# WHERE DO YOU WANT TO INSTALL IT
INSTALL_LOCATION="mana"
# DEPENDS FOR DEBIAN INSTALLS
DEBIAN="libnl-dev,isc-dhcp-server,tinyproxy,libssl-dev,apache2,macchanger,python-dnspython,python-pcapy,dsniff,stunnel4,python-scapy"
# DEPENDS FOR FEDORA INSTALLS
FEDORA="git,libnl,dhcp-forwarder,tinyproxy,openssl,httpd,macchanger,python-dns,pcapy,dsniff,stunnel,scapy,sslsplit"
#In order to check new versions of sslstrip+ and net-creds
BYPASS_UPDATE="YES"
# COMMANDS TO RUN AFTER
AFTER_COMMANDS="git clone --depth 1 https://github.com/sensepost/mana {INSTALL_LOCATION},cd {INSTALL_LOCATION},git submodule init,git submodule update,make,make install"
|
author = 'jklaz'
description = 'This module will install/update the mana-toolkit'
install_type = 'GIT'
repository_location = 'https://github.com/sensepost/mana'
install_location = 'mana'
debian = 'libnl-dev,isc-dhcp-server,tinyproxy,libssl-dev,apache2,macchanger,python-dnspython,python-pcapy,dsniff,stunnel4,python-scapy'
fedora = 'git,libnl,dhcp-forwarder,tinyproxy,openssl,httpd,macchanger,python-dns,pcapy,dsniff,stunnel,scapy,sslsplit'
bypass_update = 'YES'
after_commands = 'git clone --depth 1 https://github.com/sensepost/mana {INSTALL_LOCATION},cd {INSTALL_LOCATION},git submodule init,git submodule update,make,make install'
|
class Holding_Registers:
Winch_ID, \
DIP_Switch_Status, \
Soft_Reset, \
Max_Velocity, \
Max_Acceleration, \
Encoder_Radius, \
Target_Setpoint, \
Target_Setpoint_Offset, \
Kp_velocity, \
Ki_velocity, \
Kd_velocity, \
Max_Encoder_Feedrate, \
Kp_position, \
Ki_position, \
Kd_position, \
Kp, \
Ki, \
Kd, \
PID_Setpoint, \
Target_X, \
Target_Y, \
Target_Z, \
Target_X_Offset, \
Target_Y_Offset, \
Target_Z_Offset, \
Field_Length, \
Field_Width, \
Current_Encoder_Count, \
Current_PWM, \
Current_RPM, \
Homing_Flag, \
Homing_switch, \
Current_X, \
Current_Y, \
Current_Z, \
Current_Length_Winch0, \
Current_Length_Winch1, \
Current_Length_Winch2, \
Current_Length_Winch3, \
Target_Length_Winch0, \
Target_Length_Winch1, \
Target_Length_Winch2, \
Target_Length_Winch3, \
Current_Force_Winch0, \
Current_Force_Winch1, \
Current_Force_Winch2, \
Current_Force_Winch3, \
ADC0, \
ADC1, \
ADC2, \
ADC3, \
Follow_Waypoints, \
Current_Waypoints_Pointer, \
Number_of_Waypoints, \
Dwell_Time, \
load_cell_neg, \
load_cell_H, \
load_cell_L, \
load_cell_zero, \
load_cell_cal, \
load_cell_error, \
mcp266_error, \
underrun_error, \
underload_error, \
overload_error, \
tether_reached_target, \
minimum_duty_cycle, \
minimum_tension, \
maximum_tension, \
kinematics_test_X, \
kinematics_test_Y, \
kinematics_test_Z, \
kinematics_test_U, \
kinematics_test_M, \
kinematics_test_N, \
kinematics_test_A, \
kinematics_test_B, \
kinematics_test_C, \
kinematics_test_D, \
X1, \
Y1, \
Z1, \
X2, \
Y2, \
Z2 = range(85)
Map = Holding_Registers
|
class Holding_Registers:
(winch_id, dip__switch__status, soft__reset, max__velocity, max__acceleration, encoder__radius, target__setpoint, target__setpoint__offset, kp_velocity, ki_velocity, kd_velocity, max__encoder__feedrate, kp_position, ki_position, kd_position, kp, ki, kd, pid__setpoint, target_x, target_y, target_z, target_x__offset, target_y__offset, target_z__offset, field__length, field__width, current__encoder__count, current_pwm, current_rpm, homing__flag, homing_switch, current_x, current_y, current_z, current__length__winch0, current__length__winch1, current__length__winch2, current__length__winch3, target__length__winch0, target__length__winch1, target__length__winch2, target__length__winch3, current__force__winch0, current__force__winch1, current__force__winch2, current__force__winch3, adc0, adc1, adc2, adc3, follow__waypoints, current__waypoints__pointer, number_of__waypoints, dwell__time, load_cell_neg, load_cell_h, load_cell_l, load_cell_zero, load_cell_cal, load_cell_error, mcp266_error, underrun_error, underload_error, overload_error, tether_reached_target, minimum_duty_cycle, minimum_tension, maximum_tension, kinematics_test_x, kinematics_test_y, kinematics_test_z, kinematics_test_u, kinematics_test_m, kinematics_test_n, kinematics_test_a, kinematics_test_b, kinematics_test_c, kinematics_test_d, x1, y1, z1, x2, y2, z2) = range(85)
map = Holding_Registers
|
first_term = int(input('Insert the first term of an arithmetic progression: '))
reason = int(input('Insert the reason of the arithmetic progression: '))
for c in range (1, 11):
if reason == 0:
print(first_term)
elif reason > 0:
c = first_term + (c - 1)*reason
print(c)
else:
c = first_term + (c - 1)*reason
print(c)
# first_term + (c - 1)*reason is the general term formula of the arithmetic progression
|
first_term = int(input('Insert the first term of an arithmetic progression: '))
reason = int(input('Insert the reason of the arithmetic progression: '))
for c in range(1, 11):
if reason == 0:
print(first_term)
elif reason > 0:
c = first_term + (c - 1) * reason
print(c)
else:
c = first_term + (c - 1) * reason
print(c)
|
self = [1]*11000
for i in range(1,10):
self[2*i-1] = 0
for j in range(10,100):
self[j+int(str(j)[0])+int(str(j)[1])-1] = 0
for k in range(100,1000):
self[k+int(str(k)[0])+int(str(k)[1])+int(str(k)[2])-1] = 0
for m in range(1000,10000):
self[m+int(str(m)[0])+int(str(m)[1])+int(str(m)[2])+int(str(m)[3])-1] = 0
for n in range(10000):
if self[n] == 1:
print(n+1)
|
self = [1] * 11000
for i in range(1, 10):
self[2 * i - 1] = 0
for j in range(10, 100):
self[j + int(str(j)[0]) + int(str(j)[1]) - 1] = 0
for k in range(100, 1000):
self[k + int(str(k)[0]) + int(str(k)[1]) + int(str(k)[2]) - 1] = 0
for m in range(1000, 10000):
self[m + int(str(m)[0]) + int(str(m)[1]) + int(str(m)[2]) + int(str(m)[3]) - 1] = 0
for n in range(10000):
if self[n] == 1:
print(n + 1)
|
APP_KEY = 'your APP_KEY'
APP_SECRET = 'your APP_SECRET'
OAUTH_TOKEN = 'your OAUTH_TOKEN'
OAUTH_TOKEN_SECRET = 'your OAUTH_TOKEN_SECRET'
ROUTE = 'your ROUTE'
|
app_key = 'your APP_KEY'
app_secret = 'your APP_SECRET'
oauth_token = 'your OAUTH_TOKEN'
oauth_token_secret = 'your OAUTH_TOKEN_SECRET'
route = 'your ROUTE'
|
__about__ = """Merge Sorted Linked List only single traverse allowed."""
class Node:
def __init__(self,value):
self.data = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.current = None
def push(self,value):
push_node = Node(value)
if self.head is None:
self.head = push_node
self.current = self.head
else:
self.current.next = push_node
self.current = push_node
# def merge(self,head1,head2):
# temp = None
#
# if head1 is None:
# temp = head2
#
# elif head2 is None:
# temp = head1
#
#
# if head1.data <= head2.data:
#
# temp = head1
#
# temp.next = self.merge(head1.next,head2)
#
# else:
#
# temp = head2
#
# temp.next = self.merge(head1,head2.next)
#
# return temp
if __name__ =="__main__":
l1 = LinkedList()
l1.push(4)
l1.push(6)
l1.push(7)
l1.push(9)
l1.push(12)
l1.push(14)
l1.push(24)
# l2 = LinkedList()
# l2.push(1)
# l2.push(2)
# l2.push(3)
# l2.push(5)
# l2.push(8)
# l2.push(10)
# l2.push(18)
# l2.push(35)
# l3 = LinkedList()
# merged_list = l3.merge(l1,l2)
tmp = l1
print("NEW LIST IS:")
while tmp.next:
print(tmp.data)
tmp = tmp.Next
|
__about__ = 'Merge Sorted Linked List only single traverse allowed.'
class Node:
def __init__(self, value):
self.data = value
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
self.current = None
def push(self, value):
push_node = node(value)
if self.head is None:
self.head = push_node
self.current = self.head
else:
self.current.next = push_node
self.current = push_node
if __name__ == '__main__':
l1 = linked_list()
l1.push(4)
l1.push(6)
l1.push(7)
l1.push(9)
l1.push(12)
l1.push(14)
l1.push(24)
tmp = l1
print('NEW LIST IS:')
while tmp.next:
print(tmp.data)
tmp = tmp.Next
|
def main():
s = input("Please enter your sentence: ")
words = s.split()
wordCount = len(words)
print ("Your word and letter counts are:", wordCount)
main()
|
def main():
s = input('Please enter your sentence: ')
words = s.split()
word_count = len(words)
print('Your word and letter counts are:', wordCount)
main()
|
"""
Model-Based Configuration
=========================
This app allows other apps to easily define a configuration model
that can be hooked into the admin site to allow configuration management
with auditing.
Installation
------------
Add ``config_models`` to your ``INSTALLED_APPS`` list.
Usage
-----
Create a subclass of ``ConfigurationModel``, with fields for each
value that needs to be configured::
class MyConfiguration(ConfigurationModel):
frobble_timeout = IntField(default=10)
frazzle_target = TextField(defalut="debug")
This is a normal django model, so it must be synced and migrated as usual.
The default values for the fields in the ``ConfigurationModel`` will be
used if no configuration has yet been created.
Register that class with the Admin site, using the ``ConfigurationAdminModel``::
from django.contrib import admin
from config_models.admin import ConfigurationModelAdmin
admin.site.register(MyConfiguration, ConfigurationModelAdmin)
Use the configuration in your code::
def my_view(self, request):
config = MyConfiguration.current()
fire_the_missiles(config.frazzle_target, timeout=config.frobble_timeout)
Use the admin site to add new configuration entries. The most recently created
entry is considered to be ``current``.
Configuration
-------------
The current ``ConfigurationModel`` will be cached in the ``configuration`` django cache,
or in the ``default`` cache if ``configuration`` doesn't exist. You can specify the cache
timeout in each ``ConfigurationModel`` by setting the ``cache_timeout`` property.
You can change the name of the cache key used by the ``ConfigurationModel`` by overriding
the ``cache_key_name`` function.
Extension
---------
``ConfigurationModels`` are just django models, so they can be extended with new fields
and migrated as usual. Newly added fields must have default values and should be nullable,
so that rollbacks to old versions of configuration work correctly.
"""
|
"""
Model-Based Configuration
=========================
This app allows other apps to easily define a configuration model
that can be hooked into the admin site to allow configuration management
with auditing.
Installation
------------
Add ``config_models`` to your ``INSTALLED_APPS`` list.
Usage
-----
Create a subclass of ``ConfigurationModel``, with fields for each
value that needs to be configured::
class MyConfiguration(ConfigurationModel):
frobble_timeout = IntField(default=10)
frazzle_target = TextField(defalut="debug")
This is a normal django model, so it must be synced and migrated as usual.
The default values for the fields in the ``ConfigurationModel`` will be
used if no configuration has yet been created.
Register that class with the Admin site, using the ``ConfigurationAdminModel``::
from django.contrib import admin
from config_models.admin import ConfigurationModelAdmin
admin.site.register(MyConfiguration, ConfigurationModelAdmin)
Use the configuration in your code::
def my_view(self, request):
config = MyConfiguration.current()
fire_the_missiles(config.frazzle_target, timeout=config.frobble_timeout)
Use the admin site to add new configuration entries. The most recently created
entry is considered to be ``current``.
Configuration
-------------
The current ``ConfigurationModel`` will be cached in the ``configuration`` django cache,
or in the ``default`` cache if ``configuration`` doesn't exist. You can specify the cache
timeout in each ``ConfigurationModel`` by setting the ``cache_timeout`` property.
You can change the name of the cache key used by the ``ConfigurationModel`` by overriding
the ``cache_key_name`` function.
Extension
---------
``ConfigurationModels`` are just django models, so they can be extended with new fields
and migrated as usual. Newly added fields must have default values and should be nullable,
so that rollbacks to old versions of configuration work correctly.
"""
|
#!/usr/bin/env python3
def calculate():
L = 100000
rads = [0] + [1] * L
for i in range(2, len(rads)):
if rads[i] == 1:
for j in range(i, len(rads), i):
rads[j] *= i
data = sorted((rad, i) for(i, rad) in enumerate(rads))
return str(data[10000][1])
if __name__ == "__main__":
print(calculate())
|
def calculate():
l = 100000
rads = [0] + [1] * L
for i in range(2, len(rads)):
if rads[i] == 1:
for j in range(i, len(rads), i):
rads[j] *= i
data = sorted(((rad, i) for (i, rad) in enumerate(rads)))
return str(data[10000][1])
if __name__ == '__main__':
print(calculate())
|
temperatures = []
with open('lab_05.txt') as infile:
for row in infile:
temperatures.append(float(row.strip()))
min_tem = min(temperatures)
max_tem = max(temperatures)
avr_tem = sum(temperatures)/len(temperatures)
temperatures.sort()
median = temperatures[len(temperatures)//2]
unique = len(set(temperatures))
def results():
print('Lowest temperature: {}'.format(min_tem))
print('Highest temperature: {}'.format(max_tem))
print('Average temperature: {}'.format(avr_tem))
print('Median temperature: {}'.format(median))
print('Unique temperatures: {}'.format(unique))
results()
|
temperatures = []
with open('lab_05.txt') as infile:
for row in infile:
temperatures.append(float(row.strip()))
min_tem = min(temperatures)
max_tem = max(temperatures)
avr_tem = sum(temperatures) / len(temperatures)
temperatures.sort()
median = temperatures[len(temperatures) // 2]
unique = len(set(temperatures))
def results():
print('Lowest temperature: {}'.format(min_tem))
print('Highest temperature: {}'.format(max_tem))
print('Average temperature: {}'.format(avr_tem))
print('Median temperature: {}'.format(median))
print('Unique temperatures: {}'.format(unique))
results()
|
class KeyGesture(InputGesture):
"""
Defines a keyboard combination that can be used to invoke a command.
KeyGesture(key: Key)
KeyGesture(key: Key,modifiers: ModifierKeys)
KeyGesture(key: Key,modifiers: ModifierKeys,displayString: str)
"""
def GetDisplayStringForCulture(self,culture):
"""
GetDisplayStringForCulture(self: KeyGesture,culture: CultureInfo) -> str
Returns a string that can be used to display the
System.Windows.Input.KeyGesture.
culture: The culture specific information.
Returns: The string to display
"""
pass
def Matches(self,targetElement,inputEventArgs):
"""
Matches(self: KeyGesture,targetElement: object,inputEventArgs: InputEventArgs) -> bool
Determines whether this System.Windows.Input.KeyGesture matches the input
associated with the specified System.Windows.Input.InputEventArgs object.
targetElement: The target.
inputEventArgs: The input event data to compare this gesture to.
Returns: true if the event data matches this System.Windows.Input.KeyGesture; otherwise,
false.
"""
pass
@staticmethod
def __new__(self,key,modifiers=None,displayString=None):
"""
__new__(cls: type,key: Key)
__new__(cls: type,key: Key,modifiers: ModifierKeys)
__new__(cls: type,key: Key,modifiers: ModifierKeys,displayString: str)
"""
pass
DisplayString=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a string representation of this System.Windows.Input.KeyGesture.
Get: DisplayString(self: KeyGesture) -> str
"""
Key=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the key associated with this System.Windows.Input.KeyGesture.
Get: Key(self: KeyGesture) -> Key
"""
Modifiers=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the modifier keys associated with this System.Windows.Input.KeyGesture.
Get: Modifiers(self: KeyGesture) -> ModifierKeys
"""
|
class Keygesture(InputGesture):
"""
Defines a keyboard combination that can be used to invoke a command.
KeyGesture(key: Key)
KeyGesture(key: Key,modifiers: ModifierKeys)
KeyGesture(key: Key,modifiers: ModifierKeys,displayString: str)
"""
def get_display_string_for_culture(self, culture):
"""
GetDisplayStringForCulture(self: KeyGesture,culture: CultureInfo) -> str
Returns a string that can be used to display the
System.Windows.Input.KeyGesture.
culture: The culture specific information.
Returns: The string to display
"""
pass
def matches(self, targetElement, inputEventArgs):
"""
Matches(self: KeyGesture,targetElement: object,inputEventArgs: InputEventArgs) -> bool
Determines whether this System.Windows.Input.KeyGesture matches the input
associated with the specified System.Windows.Input.InputEventArgs object.
targetElement: The target.
inputEventArgs: The input event data to compare this gesture to.
Returns: true if the event data matches this System.Windows.Input.KeyGesture; otherwise,
false.
"""
pass
@staticmethod
def __new__(self, key, modifiers=None, displayString=None):
"""
__new__(cls: type,key: Key)
__new__(cls: type,key: Key,modifiers: ModifierKeys)
__new__(cls: type,key: Key,modifiers: ModifierKeys,displayString: str)
"""
pass
display_string = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets a string representation of this System.Windows.Input.KeyGesture.\n\n\n\nGet: DisplayString(self: KeyGesture) -> str\n\n\n\n'
key = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the key associated with this System.Windows.Input.KeyGesture.\n\n\n\nGet: Key(self: KeyGesture) -> Key\n\n\n\n'
modifiers = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the modifier keys associated with this System.Windows.Input.KeyGesture.\n\n\n\nGet: Modifiers(self: KeyGesture) -> ModifierKeys\n\n\n\n'
|
s = 0
for c in range(0, 4):
n = int(input('Digite um numero:'))
s += n
print('O somatorio de todos os valores foi {}'.format(s))
|
s = 0
for c in range(0, 4):
n = int(input('Digite um numero:'))
s += n
print('O somatorio de todos os valores foi {}'.format(s))
|
def dict_to_str(src_dict):
dst_str = ""
for key in src_dict.keys():
dst_str += " %s: %.4f " %(key, src_dict[key])
return dst_str
class Storage(dict):
"""
A Storage object is like a dictionary except `obj.foo` can be used inadition to `obj['foo']`
ref: https://blog.csdn.net/a200822146085/article/details/88430450
"""
def __getattr__(self, key):
try:
return self[key] if key in self else False
except KeyError as k:
raise AttributeError(k)
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError as k:
raise AttributeError(k)
def __str__(self):
return "<" + self.__class__.__name__ + dict.__repr__(self) + ">"
|
def dict_to_str(src_dict):
dst_str = ''
for key in src_dict.keys():
dst_str += ' %s: %.4f ' % (key, src_dict[key])
return dst_str
class Storage(dict):
"""
A Storage object is like a dictionary except `obj.foo` can be used inadition to `obj['foo']`
ref: https://blog.csdn.net/a200822146085/article/details/88430450
"""
def __getattr__(self, key):
try:
return self[key] if key in self else False
except KeyError as k:
raise attribute_error(k)
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError as k:
raise attribute_error(k)
def __str__(self):
return '<' + self.__class__.__name__ + dict.__repr__(self) + '>'
|
# string di python bisa menggunakan
# petik satu dan petik dua
# contoh
# "Hello World" sama dengan 'hello world'
# 'hello world' sama dengan "hello world"
kata_pertama = "warung"
# bisa juga menggunakan multi string
# bisa menggunakan 3 tanda petik dua atau satu
kata_saya = """indonesia adalah negara yang indah
berada di bawah garis khatulistiwa
aku cinta indonesia
"""
# print(kata_pertama)
print(kata_saya)
# mengubah kata ke huruf besar
print(kata_pertama.upper())
# mengubah kata ke huruf kecil
print(kata_pertama.lower())
# mengambil salah satu karakter dari string
# contoh
print(kata_pertama[0])
# menghitung jumlah karatker dari string
# contoh
print(len(kata_pertama))
# kita juga dapat mengecek kata khusus dalam sebuah string
# contoh
print("indonesia" in kata_saya)
|
kata_pertama = 'warung'
kata_saya = 'indonesia adalah negara yang indah\nberada di bawah garis khatulistiwa\naku cinta indonesia\n'
print(kata_saya)
print(kata_pertama.upper())
print(kata_pertama.lower())
print(kata_pertama[0])
print(len(kata_pertama))
print('indonesia' in kata_saya)
|
faces = fetch_olivetti_faces()
# set up the figure
fig = plt.figure(figsize=(6, 6)) # figure size in inches
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
# plot the faces:
for i in range(64):
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
ax.imshow(faces.images[i], cmap=plt.cm.bone, interpolation='nearest')
|
faces = fetch_olivetti_faces()
fig = plt.figure(figsize=(6, 6))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(64):
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
ax.imshow(faces.images[i], cmap=plt.cm.bone, interpolation='nearest')
|
class Solution:
def findLucky(self, arr: List[int]) -> int:
x=[i for i in arr if arr.count(i)==i]
if not x:
return -1
else:
return max(x)
|
class Solution:
def find_lucky(self, arr: List[int]) -> int:
x = [i for i in arr if arr.count(i) == i]
if not x:
return -1
else:
return max(x)
|
VERSION = (0, 2, 1)
"""Application version number tuple."""
VERSION_STR = '.'.join(map(str, VERSION))
"""Application version number string."""
default_app_config = 'sitetables.apps.SitetablesConfig'
|
version = (0, 2, 1)
'Application version number tuple.'
version_str = '.'.join(map(str, VERSION))
'Application version number string.'
default_app_config = 'sitetables.apps.SitetablesConfig'
|
i = input("Enter a number: ")
d = '0369'
if i[-1] in d:
print('Last digit is divisible by 3.')
else:
print('Last digit is not divisible by 3.')
|
i = input('Enter a number: ')
d = '0369'
if i[-1] in d:
print('Last digit is divisible by 3.')
else:
print('Last digit is not divisible by 3.')
|
"""
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word
in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
Given s = "Hello World",
return 5 as length("World") = 5.
Please make sure you try to solve this problem without using library functions. Make sure you only traverse the string
once.
"""
class Solution:
# @param A : string
# @return an integer
def lengthOfLastWord(self, s):
s.strip(" ")
if s:
for i in range(len(s) - 1, -1, -1):
if s[i].isalnum():
continue
else:
break
else:
return 0
return len(s[i:])
|
"""
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word
in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
Given s = "Hello World",
return 5 as length("World") = 5.
Please make sure you try to solve this problem without using library functions. Make sure you only traverse the string
once.
"""
class Solution:
def length_of_last_word(self, s):
s.strip(' ')
if s:
for i in range(len(s) - 1, -1, -1):
if s[i].isalnum():
continue
else:
break
else:
return 0
return len(s[i:])
|
# Get the config object
c = get_config()
# Inline figures when using Matplotlib
c.IPKernelApp.pylab = 'inline'
c.NotebookApp.ip = '*'
c.NotebookApp.allow_remote_access = True
# Do not open a browser window by default when using notebooks
c.NotebookApp.open_browser = False
# INSECURE: No token. Always use jupyter over ssh tunnel
c.NotebookApp.token = ''
c.NotebookApp.notebook_dir = '/git'
# Allow to run Jupyter from root user inside Docker container
c.NotebookApp.allow_root = True
|
c = get_config()
c.IPKernelApp.pylab = 'inline'
c.NotebookApp.ip = '*'
c.NotebookApp.allow_remote_access = True
c.NotebookApp.open_browser = False
c.NotebookApp.token = ''
c.NotebookApp.notebook_dir = '/git'
c.NotebookApp.allow_root = True
|
Import('env')
global_env = DefaultEnvironment()
global_env.Append(
CPPDEFINES=[
"MSGPACK_ENDIAN_LITTLE_BYTE",
]
)
|
import('env')
global_env = default_environment()
global_env.Append(CPPDEFINES=['MSGPACK_ENDIAN_LITTLE_BYTE'])
|
def get_label_lower(opts):
if hasattr(opts, 'label_lower'):
return opts.label_lower
model_label = opts.model_name
app_label = opts.app_label
return "{app_label}.{model_label}".format(app_label=app_label,
model_label=model_label)
|
def get_label_lower(opts):
if hasattr(opts, 'label_lower'):
return opts.label_lower
model_label = opts.model_name
app_label = opts.app_label
return '{app_label}.{model_label}'.format(app_label=app_label, model_label=model_label)
|
# list the uses of all certificates
res = client.get_certificates_uses()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
# list the uses of certificates named "ad-cert-1" and "posix-cert"
res = client.get_certificates_uses(names=['ad-cert-1', 'posix-cert'])
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
# Other valid fields: continuation_token, filter, ids, limit, offset, sort
# See section "Common Fields" for examples
|
res = client.get_certificates_uses()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
res = client.get_certificates_uses(names=['ad-cert-1', 'posix-cert'])
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
|
def allLongestStrings(inputArray):
'''
Given an array of strings, return another array containing all of its longest strings.
'''
resultArray = []
currentMax = len(inputArray[0])
for i in range(len(inputArray) ):
currentLen = len(inputArray[i])
if currentLen > currentMax :
resultArray = [inputArray[i]]
currentMax = currentLen
elif currentLen == currentMax :
resultArray.append(inputArray[i])
return resultArray
print(allLongestStrings(["aba", "aa", "ad", "vcd", "aba"]))
|
def all_longest_strings(inputArray):
"""
Given an array of strings, return another array containing all of its longest strings.
"""
result_array = []
current_max = len(inputArray[0])
for i in range(len(inputArray)):
current_len = len(inputArray[i])
if currentLen > currentMax:
result_array = [inputArray[i]]
current_max = currentLen
elif currentLen == currentMax:
resultArray.append(inputArray[i])
return resultArray
print(all_longest_strings(['aba', 'aa', 'ad', 'vcd', 'aba']))
|
n , m = map(int, input().split())
array = list(map(int, input().split()))
A = list(set(map(int, input().split())))
B = list(set(map(int, input().split())))
happiness = 0
for i in range(n):
for j in range(m):
if array[i] == A[j]:
happiness += 1
elif array[i] == B[j]:
happiness -= 1
print(happiness)
|
(n, m) = map(int, input().split())
array = list(map(int, input().split()))
a = list(set(map(int, input().split())))
b = list(set(map(int, input().split())))
happiness = 0
for i in range(n):
for j in range(m):
if array[i] == A[j]:
happiness += 1
elif array[i] == B[j]:
happiness -= 1
print(happiness)
|
def relativeSorting(A1,A2):
common_elements = set(A1).intersection(set(A2))
extra = set(A1).difference(set(A2))
out = []
for i in A2:
s = [i] * A1.count(i)
out.extend(s)
extra_out = []
for j in extra:
u = [j] * A1.count(j)
extra_out.extend(u)
out = out + sorted(extra_out)
return " ".join(str(i) for i in out)
if __name__ == '__main__':
t = int(input())
for tcase in range(t):
N,M = list(map(int,input().strip().split()))
A1 = list(map(int,input().strip().split()))
A2 = list(map(int,input().strip().split()))
print (relativeSorting(A1,A2))
|
def relative_sorting(A1, A2):
common_elements = set(A1).intersection(set(A2))
extra = set(A1).difference(set(A2))
out = []
for i in A2:
s = [i] * A1.count(i)
out.extend(s)
extra_out = []
for j in extra:
u = [j] * A1.count(j)
extra_out.extend(u)
out = out + sorted(extra_out)
return ' '.join((str(i) for i in out))
if __name__ == '__main__':
t = int(input())
for tcase in range(t):
(n, m) = list(map(int, input().strip().split()))
a1 = list(map(int, input().strip().split()))
a2 = list(map(int, input().strip().split()))
print(relative_sorting(A1, A2))
|
#!/usr/bin/env python3.8
# Copyright 2021 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def f():
print('lib.f')
def truthy():
return True
def falsy():
return False
|
def f():
print('lib.f')
def truthy():
return True
def falsy():
return False
|
n=int(input())
a=list(map(int,input().split()))
jump=0
i=0
while i<=n:
if i+2<n and a[i+2]==0:
jump+=1
i+=2
elif i+1<n and a[i+1]==0:
jump+=1
i+=1
else:
i+=1
print(jump)
|
n = int(input())
a = list(map(int, input().split()))
jump = 0
i = 0
while i <= n:
if i + 2 < n and a[i + 2] == 0:
jump += 1
i += 2
elif i + 1 < n and a[i + 1] == 0:
jump += 1
i += 1
else:
i += 1
print(jump)
|
"""
AvaTax Software Development Kit for Python.
Copyright 2019 Avalara, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@author Robert Bronson
@author Phil Werner
@author Adrienne Karnoski
@author Han Bao
@copyright 2019 Avalara, Inc.
@license https://www.apache.org/licenses/LICENSE-2.0
@version TBD
@link https://github.com/avadev/AvaTax-REST-V2-Python-SDK
Transaction Builder methods(to be auto generated)
"""
class Mixin:
"""Mixin containing methods attached to TransactionBuilder Class."""
def with_commit(self):
"""
Set the commit flag of the transaction.
If commit is set to False, the transaction will only be saved.
"""
self.create_model['commit'] = True
return self
def with_transaction_code(self, code):
"""
Set a specific transaction code.
:param string code: Specific tansaction code
:return: TransactionBuilder
"""
self.create_model['code'] = code
return self
def with_type(self, type_):
r"""
Set the document type.
:param string type: Address Type \
(See DocumentType::* for a list of allowable values)
:return: TransactionBuilder
"""
self.create_model['type'] = type_
return self
def with_address(self, address_type, address):
r"""
Add an address to this transaction.
:param string address_type: Address Type \
(See AddressType::* for a list of allowable values)
:param dictionary address: A dictionary containing the following
line1 The street address, attention line, or business name
of the location.
line2 The street address, business name, or apartment/unit
number of the location.
line3 The street address or apartment/unit number
of the location.
city City of the location.
region State or Region of the location.
postal_code Postal/zip code of the location.
country The two-letter country code of the location.
:return: TransactionBuilder
"""
self.create_model.setdefault('addresses', {})
self.create_model['addresses'][address_type] = address
return self
def with_line_address(self, address_type, address):
r"""
Add an address to this line.
:param string address_type: Address Type \
(See AddressType::* for a list of allowable values)
:param dictionary address: A dictionary containing the following
line1 The street address, attention line, or business name
of the location.
line2 The street address, business name, or apartment/unit
number of the location.
line3 The street address or apartment/unit number
of the location.
city City of the location.
region State or Region of the location.
postal_code Postal/zip code of the location.
country The two-letter country code of the location.
:return: TransactionBuilder
"""
temp = self.get_most_recent_line('WithLineAddress')
temp.setdefault('addresses', {})
temp['addresses'][address_type] = address
return self
def with_latlong(self, address_type, lat, long_):
r"""
Add a lat/long coordinate to this transaction.
:param string type: Address Type \
(See AddressType::* for a list of allowable values)
:param float lat: The geolocated latitude for this transaction
:param float long_: The geolocated longitude for this transaction
:return: TransactionBuilder
"""
self.create_model.setdefault('addresses', {})
self.create_model['addresses'][address_type] = {'latitude': float(lat),
'longitude': float(long_)}
return self
def with_line(self, amount, quantity, item_code, tax_code, line_number=None):
r"""
Add a line to the transaction.
:param float amount: Value of the item.
:param float quantity: Quantity of the item.
:param string item_code: Code of the item.
:param string tax_code: Tax Code of the item. If left blank, \
the default item (P0000000) is assumed.
:param [int] line_number: Value of the line number.
:return: TransactionBuilder
"""
if line_number is not None:
self.line_num = line_number;
temp = {
'number': str(self.line_num),
'amount': amount,
'quantity': quantity,
'itemCode': str(item_code),
'taxCode': str(tax_code)
}
self.create_model['lines'].append(temp)
self.line_num += 1
return self
def with_exempt_line(self, amount, item_code, exemption_code):
"""
Add a line with an exemption to this transaction.
:param float amount: The amount of this line item
:param string item_code: The code for the item
:param string exemption_code: The exemption code for this line item
:return: TransactionBuilder
"""
temp = {
'number': str(self.line_num),
'quantity': 1,
'amount': amount,
'exemptionCode': str(exemption_code),
'itemCode': str(item_code)
}
self.create_model['lines'].append(temp)
self.line_num += 1
return self
def with_diagnostics(self):
"""
Enable diagnostic information.
- Sets the debugLevel to 'Diagnostic'
:return: TransactionBuilder
"""
self.create_model['debugLevel'] = 'Diagnostic'
return self
def with_discount_amount(self, discount):
"""
Set a specific discount amount.
:param float discount: Amount of the discount
:return: TransactionBuilder
"""
self.create_model['discount'] = discount
return self
def with_item_discount(self, discounted):
"""
Set if discount is applicable for the current line.
:param boolean discounted: Set true or false for discounted
:return: TransactionBuilder
"""
temp = self.get_most_recent_line('WithItemDiscount')
temp['discounted'] = discounted
return self
def with_parameter(self, name, value):
"""
Add a parameter at the document level.
:param string name: Name of the parameter
:param string value: Value to be assigned to the parameter
:return: TransactionBuilder
"""
self.create_model.setdefault('parameters', {})
self.create_model['parameters'][name] = value
return self
def with_line_parameter(self, name, value):
"""
Add a parameter to the current line.
:param string name: Name of the parameter
:param string value: Value to be assigned to the parameter
:return: TransactionBuilder
"""
temp = self.get_most_recent_line('WithLineParameter')
temp.setdefault('parameters', {})
temp['parameters'][name] = value
return self
def get_most_recent_line(self, member_name=None):
"""
Check to see if the current model has a line.
:return: TransactionBuilder
"""
line = self.create_model['lines']
if not len(line): # if length is zero
raise Exception('No lines have been added. The {} method applies to the most recent line. To use this function, first add a line.'.format(member_name))
return line[-1]
def create(self, include=None):
"""
Create this transaction.
:return: TransactionModel
"""
return self.client.create_transaction(self.create_model, include)
def with_line_tax_override(self, type_, reason, tax_amount, tax_date):
r"""
Add a line-level Tax Override to the current line.
A TaxDate override requires a valid DateTime object to be passed.
:param string type: Type of the Tax Override \
(See TaxOverrideType::* for a list of allowable values)
:param string reason: Reason of the Tax Override.
:param float tax_amount: Amount of tax to apply. \
Required for a TaxAmount Override.
:param date tax_date: Date of a Tax Override. \
Required for a TaxDate Override.
:return: TransactionBuilder
"""
line = self.get_most_recent_line('WithLineTaxOverride')
line['taxOverride'] = {
'type': str(type_),
'reason': str(reason),
'taxAmount': float(tax_amount),
'taxDate': tax_date
}
return self
def with_tax_override(self, type_, reason, tax_amount, tax_date):
r"""
Add a document-level Tax Override to the transaction.
- A TaxDate override requires a valid DateTime object to be passed
:param string type_: Type of the Tax Override \
(See TaxOverrideType::* for a list of allowable values)
:param string reason: Reason of the Tax Override.
:param float tax_amount: Amount of tax to apply. Required for \
a TaxAmount Override.
:param date tax_date: Date of a Tax Override. Required for \
a TaxDate Override.
:return: TransactionBuilder
"""
self.create_model['taxOverride'] = {
'type': str(type_),
'reason': str(reason),
'taxAmount': tax_amount,
'taxDate': tax_date
}
return self
def with_separate_address_line(self, amount, type_, address):
r"""
Add a line to this transaction.
:param float amount: Value of the line
:param string type_: Address Type \
(See AddressType::* for a list of allowable values)
:param dictionary address: A dictionary containing the following
line1 The street address, attention line, or business name
of the location.
line2 The street address, business name, or apartment/unit
number of the location.
line3 The street address or apartment/unit number
of the location.
city City of the location.
region State or Region of the location.
postal_code Postal/zip code of the location.
country The two-letter country code of the location.
:return: TransactionBuilder
"""
temp = {
'number': self.line_num,
'quantity': 1,
'amount': amount,
'addresses': {
type_: address
}
}
self.create_model['lines'].append(temp)
self.line_num += 1
return self
def create_adjustment_request(self, desc, reason):
r""".
Create a transaction adjustment request that can be used with the \
AdjustTransaction() API call.
:return: AdjustTransactionModel
"""
return {
'newTransaction': self.create_model,
'adjustmentDescription': desc,
'adjustmentReason': reason
}
|
"""
AvaTax Software Development Kit for Python.
Copyright 2019 Avalara, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@author Robert Bronson
@author Phil Werner
@author Adrienne Karnoski
@author Han Bao
@copyright 2019 Avalara, Inc.
@license https://www.apache.org/licenses/LICENSE-2.0
@version TBD
@link https://github.com/avadev/AvaTax-REST-V2-Python-SDK
Transaction Builder methods(to be auto generated)
"""
class Mixin:
"""Mixin containing methods attached to TransactionBuilder Class."""
def with_commit(self):
"""
Set the commit flag of the transaction.
If commit is set to False, the transaction will only be saved.
"""
self.create_model['commit'] = True
return self
def with_transaction_code(self, code):
"""
Set a specific transaction code.
:param string code: Specific tansaction code
:return: TransactionBuilder
"""
self.create_model['code'] = code
return self
def with_type(self, type_):
"""
Set the document type.
:param string type: Address Type \\
(See DocumentType::* for a list of allowable values)
:return: TransactionBuilder
"""
self.create_model['type'] = type_
return self
def with_address(self, address_type, address):
"""
Add an address to this transaction.
:param string address_type: Address Type \\
(See AddressType::* for a list of allowable values)
:param dictionary address: A dictionary containing the following
line1 The street address, attention line, or business name
of the location.
line2 The street address, business name, or apartment/unit
number of the location.
line3 The street address or apartment/unit number
of the location.
city City of the location.
region State or Region of the location.
postal_code Postal/zip code of the location.
country The two-letter country code of the location.
:return: TransactionBuilder
"""
self.create_model.setdefault('addresses', {})
self.create_model['addresses'][address_type] = address
return self
def with_line_address(self, address_type, address):
"""
Add an address to this line.
:param string address_type: Address Type \\
(See AddressType::* for a list of allowable values)
:param dictionary address: A dictionary containing the following
line1 The street address, attention line, or business name
of the location.
line2 The street address, business name, or apartment/unit
number of the location.
line3 The street address or apartment/unit number
of the location.
city City of the location.
region State or Region of the location.
postal_code Postal/zip code of the location.
country The two-letter country code of the location.
:return: TransactionBuilder
"""
temp = self.get_most_recent_line('WithLineAddress')
temp.setdefault('addresses', {})
temp['addresses'][address_type] = address
return self
def with_latlong(self, address_type, lat, long_):
"""
Add a lat/long coordinate to this transaction.
:param string type: Address Type \\
(See AddressType::* for a list of allowable values)
:param float lat: The geolocated latitude for this transaction
:param float long_: The geolocated longitude for this transaction
:return: TransactionBuilder
"""
self.create_model.setdefault('addresses', {})
self.create_model['addresses'][address_type] = {'latitude': float(lat), 'longitude': float(long_)}
return self
def with_line(self, amount, quantity, item_code, tax_code, line_number=None):
"""
Add a line to the transaction.
:param float amount: Value of the item.
:param float quantity: Quantity of the item.
:param string item_code: Code of the item.
:param string tax_code: Tax Code of the item. If left blank, \\
the default item (P0000000) is assumed.
:param [int] line_number: Value of the line number.
:return: TransactionBuilder
"""
if line_number is not None:
self.line_num = line_number
temp = {'number': str(self.line_num), 'amount': amount, 'quantity': quantity, 'itemCode': str(item_code), 'taxCode': str(tax_code)}
self.create_model['lines'].append(temp)
self.line_num += 1
return self
def with_exempt_line(self, amount, item_code, exemption_code):
"""
Add a line with an exemption to this transaction.
:param float amount: The amount of this line item
:param string item_code: The code for the item
:param string exemption_code: The exemption code for this line item
:return: TransactionBuilder
"""
temp = {'number': str(self.line_num), 'quantity': 1, 'amount': amount, 'exemptionCode': str(exemption_code), 'itemCode': str(item_code)}
self.create_model['lines'].append(temp)
self.line_num += 1
return self
def with_diagnostics(self):
"""
Enable diagnostic information.
- Sets the debugLevel to 'Diagnostic'
:return: TransactionBuilder
"""
self.create_model['debugLevel'] = 'Diagnostic'
return self
def with_discount_amount(self, discount):
"""
Set a specific discount amount.
:param float discount: Amount of the discount
:return: TransactionBuilder
"""
self.create_model['discount'] = discount
return self
def with_item_discount(self, discounted):
"""
Set if discount is applicable for the current line.
:param boolean discounted: Set true or false for discounted
:return: TransactionBuilder
"""
temp = self.get_most_recent_line('WithItemDiscount')
temp['discounted'] = discounted
return self
def with_parameter(self, name, value):
"""
Add a parameter at the document level.
:param string name: Name of the parameter
:param string value: Value to be assigned to the parameter
:return: TransactionBuilder
"""
self.create_model.setdefault('parameters', {})
self.create_model['parameters'][name] = value
return self
def with_line_parameter(self, name, value):
"""
Add a parameter to the current line.
:param string name: Name of the parameter
:param string value: Value to be assigned to the parameter
:return: TransactionBuilder
"""
temp = self.get_most_recent_line('WithLineParameter')
temp.setdefault('parameters', {})
temp['parameters'][name] = value
return self
def get_most_recent_line(self, member_name=None):
"""
Check to see if the current model has a line.
:return: TransactionBuilder
"""
line = self.create_model['lines']
if not len(line):
raise exception('No lines have been added. The {} method applies to the most recent line. To use this function, first add a line.'.format(member_name))
return line[-1]
def create(self, include=None):
"""
Create this transaction.
:return: TransactionModel
"""
return self.client.create_transaction(self.create_model, include)
def with_line_tax_override(self, type_, reason, tax_amount, tax_date):
"""
Add a line-level Tax Override to the current line.
A TaxDate override requires a valid DateTime object to be passed.
:param string type: Type of the Tax Override \\
(See TaxOverrideType::* for a list of allowable values)
:param string reason: Reason of the Tax Override.
:param float tax_amount: Amount of tax to apply. \\
Required for a TaxAmount Override.
:param date tax_date: Date of a Tax Override. \\
Required for a TaxDate Override.
:return: TransactionBuilder
"""
line = self.get_most_recent_line('WithLineTaxOverride')
line['taxOverride'] = {'type': str(type_), 'reason': str(reason), 'taxAmount': float(tax_amount), 'taxDate': tax_date}
return self
def with_tax_override(self, type_, reason, tax_amount, tax_date):
"""
Add a document-level Tax Override to the transaction.
- A TaxDate override requires a valid DateTime object to be passed
:param string type_: Type of the Tax Override \\
(See TaxOverrideType::* for a list of allowable values)
:param string reason: Reason of the Tax Override.
:param float tax_amount: Amount of tax to apply. Required for \\
a TaxAmount Override.
:param date tax_date: Date of a Tax Override. Required for \\
a TaxDate Override.
:return: TransactionBuilder
"""
self.create_model['taxOverride'] = {'type': str(type_), 'reason': str(reason), 'taxAmount': tax_amount, 'taxDate': tax_date}
return self
def with_separate_address_line(self, amount, type_, address):
"""
Add a line to this transaction.
:param float amount: Value of the line
:param string type_: Address Type \\
(See AddressType::* for a list of allowable values)
:param dictionary address: A dictionary containing the following
line1 The street address, attention line, or business name
of the location.
line2 The street address, business name, or apartment/unit
number of the location.
line3 The street address or apartment/unit number
of the location.
city City of the location.
region State or Region of the location.
postal_code Postal/zip code of the location.
country The two-letter country code of the location.
:return: TransactionBuilder
"""
temp = {'number': self.line_num, 'quantity': 1, 'amount': amount, 'addresses': {type_: address}}
self.create_model['lines'].append(temp)
self.line_num += 1
return self
def create_adjustment_request(self, desc, reason):
""".
Create a transaction adjustment request that can be used with the \\
AdjustTransaction() API call.
:return: AdjustTransactionModel
"""
return {'newTransaction': self.create_model, 'adjustmentDescription': desc, 'adjustmentReason': reason}
|
class config(object):
rank_norm = 0
run_list = str.split("zh2en_w2vv_attention w2vv_attention")
nr_of_runs = len(run_list)
#weights = [1.0/nr_of_runs] * nr_of_runs
weights = [0.73, 0.27]
|
class Config(object):
rank_norm = 0
run_list = str.split('zh2en_w2vv_attention w2vv_attention')
nr_of_runs = len(run_list)
weights = [0.73, 0.27]
|
# pylint: disable=line-too-long
# SPDX-FileCopyrightText: Copyright (c) 2021 ajs256
#
# SPDX-License-Identifier: MIT
"""
`seriallcd`
================================================================================
CircuitPython helper library for Parallax's serial LCDs
* Author(s): ajs256
Implementation Notes
--------------------
**Hardware:**
* `16x2 Parallax Serial LCD <https://www.parallax.com/product/parallax-2-x-16-serial-lcd-with-piezo-speaker-backlit/>`_
* `20x4 Serial LCD <https://www.parallax.com/product/parallax-4-x-20-serial-lcd-with-piezospeaker-backlit/>`_
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
"""
# pylint: enable=line-too-long
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/ajs256/CircuitPython_SerialLCD.git"
# Definitions of constants
CURSOR_OFF = 0b10
CURSOR_ON = 0b00
CHARACTER_BLINK = 0b01
NO_BLINK = 0b11
LIGHT_ON = 0b1
LIGHT_OFF = 0b0
# For these, I'm just using the commands that need to be output over serial to save some time.
NOTE_1_32 = 0xD1
NOTE_1_16 = 0xD2
NOTE_EIGHTH = 0xD3
NOTE_QUARTER = 0xD4
NOTE_HALF = 0xD5
NOTE_WHOLE = 0xD6 # 2 sec long
SCALE_3 = 0xD7 # A = 220 Hz
SCALE_4 = 0xD8 # A = 440 Hz
SCALE_5 = 0xD9 # A = 880 Hz
SCALE_6 = 0xDA # A = 1760 Hz
SCALE_7 = 0xDB # A = 3520 Hz
NOTE_A = 0xDC
NOTE_A_SHARP = 0xDD
NOTE_B = 0xDE
NOTE_B_SHARP = 0xDF
NOTE_C = 0xE0
NOTE_C_SHARP = 0xE1
NOTE_D = 0xE2
NOTE_D_SHARP = 0xE3
NOTE_E = 0xE4
NOTE_F = 0xE5
NOTE_F_SHARP = 0xE6
NOTE_G = 0xE7
NOTE_G_SHARP = 0xE8
def _hex_to_bytes(cmd):
"""
A helper function to convert a hexadecimal byte to a bytearray.
"""
return bytes([cmd])
class Display:
"""
A display.
:param uart: A ``busio.UART`` or ``serial.Serial`` (on SBCs) object.
:param bool ignore_bad_baud: Whether or not to ignore baud rates \
that a display may not support. Defaults to ``False``.
"""
def __init__(self, uart, *, ignore_bad_baud=False):
self._display_uart = uart
try: # Failsafe if they're using a weird serial object that doesn't
# have a baud rate attribute
if uart.baudrate not in [2400, 9600, 19200] and ignore_bad_baud:
print(
"WARN: Your serial object has a baud rate that the display does not support: ",
uart.baudrate,
". Set ignore_bad_baud to True in the constructor to silence this warning.",
)
except AttributeError:
pass
# Printing
def print(self, text):
"""
Standard printing function.
:param str text: The text to print.
"""
buf = bytes(text, "utf-8")
self._display_uart.write(buf)
def println(self, text):
"""
Standard printing function, but it adds a newline at the end.
:param str text: The text to print.
"""
buf = bytes(text, "utf-8")
self._display_uart.write(buf)
self.carriage_return()
def write(self, data):
"""
Sends raw data as a byte or bytearray.
:param data: The data to write.
"""
self._display_uart.write(data)
# Cursor manipulation
def cursor_left(self):
"""
Moves the cursor left one space. This does not erase any characters.
"""
self._display_uart.write(_hex_to_bytes(0x08))
def cursor_right(self):
"""
Moves the cursor right one space. This does not erase any characters.
"""
self._display_uart.write(_hex_to_bytes(0x09))
def line_feed(self):
"""
Moves the cursor down one line. This does not erase any characters.
"""
self._display_uart.write(_hex_to_bytes(0x0A))
def form_feed(self):
"""
Clears the display and resets the cursor to the top left corner.
You must pause 5 ms after using this command.
"""
# Must pause 5 ms after use
self._display_uart.write(_hex_to_bytes(0x0C))
def clear(self):
"""
A more user-friendly name for ``form_feed``. You must pause 5 ms after using this command.
"""
self.form_feed()
def carriage_return(self):
"""
Moves the cursor to position 0 on the next line down.
"""
self._display_uart.write(_hex_to_bytes(0x0D))
def new_line(self):
"""
A more user-friendly name for ``carriage_return``.
"""
self.carriage_return()
# Mode setting
def set_mode(self, cursor, blink):
"""
Set the "mode" of the display (whether to show the cursor \
or blink the character under the cursor).
:param cursor: Whether to show the cursor. Pass in ``seriallcd.CURSOR_ON`` \
or ``seriallcd.CURSOR_OFF``.
:param blink: Whether to blink the character under the cursor. Pass \
in ``seriallcd.CHARACTER_BLINK`` or ``seriallcd.NO_BLINK``
"""
if cursor == CURSOR_ON and blink == CHARACTER_BLINK:
self._display_uart.write(_hex_to_bytes(0x19))
elif cursor == CURSOR_ON and blink == NO_BLINK:
self._display_uart.write(_hex_to_bytes(0x18))
elif cursor == CURSOR_OFF and blink == CHARACTER_BLINK:
self._display_uart.write(_hex_to_bytes(0x17))
elif cursor == CURSOR_OFF and blink == NO_BLINK:
self._display_uart.write(_hex_to_bytes(0x16))
else:
raise TypeError("Pass in constants for set_mode. See the docs.")
def set_backlight(self, light):
"""
Enables or disables the display's backlight.
:param light: Whether or not the light should be on. Pass in \
``seriallcd.LIGHT_ON`` or ``seriallcd.LIGHT_OFF``.
"""
if light == LIGHT_ON:
self._display_uart.write(_hex_to_bytes(0x11))
elif light == LIGHT_OFF:
self._display_uart.write(_hex_to_bytes(0x12))
else:
raise TypeError("Pass in constants for set_backlight. See the docs.")
def move_cursor(self, row, col):
"""
Move the cursor to a specific position.
:param row: The row of the display to move to. Top is 0.
:param col: The column of the display to move to. Left is 0.
"""
cmd = _hex_to_bytes(0x80 + (row * 0x14 + col))
self._display_uart.write(cmd)
# Custom characters
def display_custom_char(self, char_id=0):
"""
Display a custom character.
:param char_id: The ID of the character to show, from 0 to 7. Defaults to 0.
"""
cmd = _hex_to_bytes(hex(char_id))
self._display_uart.write(cmd)
def set_custom_character(self, char_id, char_bytes):
"""
Set a custom character.
:param char_id: The ID of the character to set.
:param bytes: An array of 8 bytes, one for each row of the display. Use 5 bits for each \
row. `This <https://www.quinapalus.com/hd44780udg.html>`_ is a great site - \
make sure to choose "Character size: 5x8".
"""
start_char = _hex_to_bytes(0xF8 + char_id)
self._display_uart.write(start_char)
for byte in char_bytes:
self._display_uart.write(byte)
# Music functionality
def set_note_length(self, length):
"""
Set the length of note to play next.
:param length: A constant representing the length of the note to play \
for example, ``seriallcd.NOTE_1_16`` or ``seriallcd.NOTE_HALF``. \
A whole note is two seconds long.
"""
self._display_uart.write(_hex_to_bytes(length))
def set_scale(self, scale):
"""
Set the scale of the note to play next. The 4th scale is A = 440.
:param scale: The scale to set, in the form of a constant, like \
``seriallcd.SCALE_4`` for A = 440, or ``seriallcd.SCALE_3`` \
for A = 220.
"""
self._display_uart.write(_hex_to_bytes(scale))
def play_note(self, note):
"""
Play a note.
:param note: The note to play, in the form of a constant, like \
``seriallcd.NOTE_A`` or ``seriallcd.NOTE_B_SHARP``.
"""
self._display_uart.write(_hex_to_bytes(note))
|
"""
`seriallcd`
================================================================================
CircuitPython helper library for Parallax's serial LCDs
* Author(s): ajs256
Implementation Notes
--------------------
**Hardware:**
* `16x2 Parallax Serial LCD <https://www.parallax.com/product/parallax-2-x-16-serial-lcd-with-piezo-speaker-backlit/>`_
* `20x4 Serial LCD <https://www.parallax.com/product/parallax-4-x-20-serial-lcd-with-piezospeaker-backlit/>`_
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
"""
__version__ = '0.0.0-auto.0'
__repo__ = 'https://github.com/ajs256/CircuitPython_SerialLCD.git'
cursor_off = 2
cursor_on = 0
character_blink = 1
no_blink = 3
light_on = 1
light_off = 0
note_1_32 = 209
note_1_16 = 210
note_eighth = 211
note_quarter = 212
note_half = 213
note_whole = 214
scale_3 = 215
scale_4 = 216
scale_5 = 217
scale_6 = 218
scale_7 = 219
note_a = 220
note_a_sharp = 221
note_b = 222
note_b_sharp = 223
note_c = 224
note_c_sharp = 225
note_d = 226
note_d_sharp = 227
note_e = 228
note_f = 229
note_f_sharp = 230
note_g = 231
note_g_sharp = 232
def _hex_to_bytes(cmd):
"""
A helper function to convert a hexadecimal byte to a bytearray.
"""
return bytes([cmd])
class Display:
"""
A display.
:param uart: A ``busio.UART`` or ``serial.Serial`` (on SBCs) object.
:param bool ignore_bad_baud: Whether or not to ignore baud rates that a display may not support. Defaults to ``False``.
"""
def __init__(self, uart, *, ignore_bad_baud=False):
self._display_uart = uart
try:
if uart.baudrate not in [2400, 9600, 19200] and ignore_bad_baud:
print('WARN: Your serial object has a baud rate that the display does not support: ', uart.baudrate, '. Set ignore_bad_baud to True in the constructor to silence this warning.')
except AttributeError:
pass
def print(self, text):
"""
Standard printing function.
:param str text: The text to print.
"""
buf = bytes(text, 'utf-8')
self._display_uart.write(buf)
def println(self, text):
"""
Standard printing function, but it adds a newline at the end.
:param str text: The text to print.
"""
buf = bytes(text, 'utf-8')
self._display_uart.write(buf)
self.carriage_return()
def write(self, data):
"""
Sends raw data as a byte or bytearray.
:param data: The data to write.
"""
self._display_uart.write(data)
def cursor_left(self):
"""
Moves the cursor left one space. This does not erase any characters.
"""
self._display_uart.write(_hex_to_bytes(8))
def cursor_right(self):
"""
Moves the cursor right one space. This does not erase any characters.
"""
self._display_uart.write(_hex_to_bytes(9))
def line_feed(self):
"""
Moves the cursor down one line. This does not erase any characters.
"""
self._display_uart.write(_hex_to_bytes(10))
def form_feed(self):
"""
Clears the display and resets the cursor to the top left corner.
You must pause 5 ms after using this command.
"""
self._display_uart.write(_hex_to_bytes(12))
def clear(self):
"""
A more user-friendly name for ``form_feed``. You must pause 5 ms after using this command.
"""
self.form_feed()
def carriage_return(self):
"""
Moves the cursor to position 0 on the next line down.
"""
self._display_uart.write(_hex_to_bytes(13))
def new_line(self):
"""
A more user-friendly name for ``carriage_return``.
"""
self.carriage_return()
def set_mode(self, cursor, blink):
"""
Set the "mode" of the display (whether to show the cursor or blink the character under the cursor).
:param cursor: Whether to show the cursor. Pass in ``seriallcd.CURSOR_ON`` or ``seriallcd.CURSOR_OFF``.
:param blink: Whether to blink the character under the cursor. Pass in ``seriallcd.CHARACTER_BLINK`` or ``seriallcd.NO_BLINK``
"""
if cursor == CURSOR_ON and blink == CHARACTER_BLINK:
self._display_uart.write(_hex_to_bytes(25))
elif cursor == CURSOR_ON and blink == NO_BLINK:
self._display_uart.write(_hex_to_bytes(24))
elif cursor == CURSOR_OFF and blink == CHARACTER_BLINK:
self._display_uart.write(_hex_to_bytes(23))
elif cursor == CURSOR_OFF and blink == NO_BLINK:
self._display_uart.write(_hex_to_bytes(22))
else:
raise type_error('Pass in constants for set_mode. See the docs.')
def set_backlight(self, light):
"""
Enables or disables the display's backlight.
:param light: Whether or not the light should be on. Pass in ``seriallcd.LIGHT_ON`` or ``seriallcd.LIGHT_OFF``.
"""
if light == LIGHT_ON:
self._display_uart.write(_hex_to_bytes(17))
elif light == LIGHT_OFF:
self._display_uart.write(_hex_to_bytes(18))
else:
raise type_error('Pass in constants for set_backlight. See the docs.')
def move_cursor(self, row, col):
"""
Move the cursor to a specific position.
:param row: The row of the display to move to. Top is 0.
:param col: The column of the display to move to. Left is 0.
"""
cmd = _hex_to_bytes(128 + (row * 20 + col))
self._display_uart.write(cmd)
def display_custom_char(self, char_id=0):
"""
Display a custom character.
:param char_id: The ID of the character to show, from 0 to 7. Defaults to 0.
"""
cmd = _hex_to_bytes(hex(char_id))
self._display_uart.write(cmd)
def set_custom_character(self, char_id, char_bytes):
"""
Set a custom character.
:param char_id: The ID of the character to set.
:param bytes: An array of 8 bytes, one for each row of the display. Use 5 bits for each row. `This <https://www.quinapalus.com/hd44780udg.html>`_ is a great site - make sure to choose "Character size: 5x8".
"""
start_char = _hex_to_bytes(248 + char_id)
self._display_uart.write(start_char)
for byte in char_bytes:
self._display_uart.write(byte)
def set_note_length(self, length):
"""
Set the length of note to play next.
:param length: A constant representing the length of the note to play for example, ``seriallcd.NOTE_1_16`` or ``seriallcd.NOTE_HALF``. A whole note is two seconds long.
"""
self._display_uart.write(_hex_to_bytes(length))
def set_scale(self, scale):
"""
Set the scale of the note to play next. The 4th scale is A = 440.
:param scale: The scale to set, in the form of a constant, like ``seriallcd.SCALE_4`` for A = 440, or ``seriallcd.SCALE_3`` for A = 220.
"""
self._display_uart.write(_hex_to_bytes(scale))
def play_note(self, note):
"""
Play a note.
:param note: The note to play, in the form of a constant, like ``seriallcd.NOTE_A`` or ``seriallcd.NOTE_B_SHARP``.
"""
self._display_uart.write(_hex_to_bytes(note))
|
def duplicate_number(arr):
"""
:param - array containing numbers in the range [0, len(arr) - 2]
return - the number that is duplicate in the arr
"""
current_sum = 0
expected_sum = 0
for num in arr:
current_sum += num
for i in range(len(arr) - 1):
expected_sum += i
return current_sum - expected_sum
def test_function(test_case):
arr = test_case[0]
solution = test_case[1]
output = duplicate_number(arr)
if output == solution:
print("Pass")
else:
print("Fail")
arr = [0, 0]
solution = 0
test_case = [arr, solution]
test_function(test_case)
arr = [0, 2, 3, 1, 4, 5, 3]
solution = 3
test_case = [arr, solution]
test_function(test_case)
arr = [0, 1, 5, 4, 3, 2, 0]
solution = 0
test_case = [arr, solution]
test_function(test_case)
arr = [0, 1, 5, 5, 3, 2, 4]
solution = 5
# print(arr)
test_case = [arr, solution]
test_function(test_case)
# arr = list(range(100000))
# # print(len(arr))
# arr.insert(823, 23)
# # print(len(arr))
# solution = 23
# test_case = [arr, solution]
# test_function(test_case)
|
def duplicate_number(arr):
"""
:param - array containing numbers in the range [0, len(arr) - 2]
return - the number that is duplicate in the arr
"""
current_sum = 0
expected_sum = 0
for num in arr:
current_sum += num
for i in range(len(arr) - 1):
expected_sum += i
return current_sum - expected_sum
def test_function(test_case):
arr = test_case[0]
solution = test_case[1]
output = duplicate_number(arr)
if output == solution:
print('Pass')
else:
print('Fail')
arr = [0, 0]
solution = 0
test_case = [arr, solution]
test_function(test_case)
arr = [0, 2, 3, 1, 4, 5, 3]
solution = 3
test_case = [arr, solution]
test_function(test_case)
arr = [0, 1, 5, 4, 3, 2, 0]
solution = 0
test_case = [arr, solution]
test_function(test_case)
arr = [0, 1, 5, 5, 3, 2, 4]
solution = 5
test_case = [arr, solution]
test_function(test_case)
|
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( n ) :
if ( n == 0 ) :
return "0" ;
bin = "" ;
while ( n > 0 ) :
if ( n & 1 == 0 ) :
bin = '0' + bin ;
else :
bin = '1' + bin ;
n = n >> 1 ;
return bin ;
#TOFILL
if __name__ == '__main__':
param = [
(35,),
(17,),
(8,),
(99,),
(57,),
(39,),
(99,),
(14,),
(22,),
(7,)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param)))
|
def f_gold(n):
if n == 0:
return '0'
bin = ''
while n > 0:
if n & 1 == 0:
bin = '0' + bin
else:
bin = '1' + bin
n = n >> 1
return bin
if __name__ == '__main__':
param = [(35,), (17,), (8,), (99,), (57,), (39,), (99,), (14,), (22,), (7,)]
n_success = 0
for (i, parameters_set) in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success += 1
print('#Results: %i, %i' % (n_success, len(param)))
|
class Clip:
def __init__(self, start_time: float, end_time: float):
self.start_time: float = start_time
self.end_time: float = end_time
@property
def length_in_seconds(self) -> float:
return self.end_time - self.start_time
|
class Clip:
def __init__(self, start_time: float, end_time: float):
self.start_time: float = start_time
self.end_time: float = end_time
@property
def length_in_seconds(self) -> float:
return self.end_time - self.start_time
|
# LISTAS INTERNAS - ISINSTANCE
minhaLista = [[1, "a", 2], [3, 4, "b"], ["c", 5, "d"]]
letras = []
numeros = []
for listaInterna in minhaLista:
for elementos in listaInterna:
if (isinstance(elementos, str)):
letras.append(elementos)
else:
numeros.append(elementos)
print(letras)
print(numeros)
|
minha_lista = [[1, 'a', 2], [3, 4, 'b'], ['c', 5, 'd']]
letras = []
numeros = []
for lista_interna in minhaLista:
for elementos in listaInterna:
if isinstance(elementos, str):
letras.append(elementos)
else:
numeros.append(elementos)
print(letras)
print(numeros)
|
slackInfo = {
"url": "https://hooks.slack.com/services/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",
"username": "leaderboard-bot",
}
hackerrankInfo = {
"url": "https://www.hackerrank.com/rest/contests/wissen-coding-challenge-2021/leaderboard",
}
|
slack_info = {'url': 'https://hooks.slack.com/services/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', 'username': 'leaderboard-bot'}
hackerrank_info = {'url': 'https://www.hackerrank.com/rest/contests/wissen-coding-challenge-2021/leaderboard'}
|
class AdditionExpression:
def __init__(self, left, right):
self.right = right
self.left = left
def print(self, buffer):
buffer.append('(')
self.left.print(buffer)
buffer.append('+')
self.right.print(buffer)
buffer.append(')')
def eval(self):
return self.left.eval() + self.right.eval()
|
class Additionexpression:
def __init__(self, left, right):
self.right = right
self.left = left
def print(self, buffer):
buffer.append('(')
self.left.print(buffer)
buffer.append('+')
self.right.print(buffer)
buffer.append(')')
def eval(self):
return self.left.eval() + self.right.eval()
|
'''
3. Swap string variable values
fname = "rahul"
lname = "dravid"
Swap the value of variable with fname & fname with lname
Output:: print(fname) # dravid
print(lname) # rahul
'''
fname = "rahul"
lname = "dravid"
#fname.swap(lname)
#lname.swap(fname)
fname="dravid"
lname="rahul"
print(fname)
print(lname)
print('-------------------------------------')
fname = "rahul"
lname = "dravid"
fname, lname = lname, fname
print(fname)
print(lname)
|
"""
3. Swap string variable values
fname = "rahul"
lname = "dravid"
Swap the value of variable with fname & fname with lname
Output:: print(fname) # dravid
print(lname) # rahul
"""
fname = 'rahul'
lname = 'dravid'
fname = 'dravid'
lname = 'rahul'
print(fname)
print(lname)
print('-------------------------------------')
fname = 'rahul'
lname = 'dravid'
(fname, lname) = (lname, fname)
print(fname)
print(lname)
|
{
'includes': [
'../common.gypi',
'../config.gypi',
],
'targets': [
{
'target_name': 'linuxapp',
'product_name': 'mapbox-gl',
'type': 'executable',
'sources': [
'./main.cpp',
'../common/settings_json.cpp',
'../common/settings_json.hpp',
'../common/platform_default.cpp',
'../common/glfw_view.hpp',
'../common/glfw_view.cpp',
'../common/curl_request.cpp',
'../common/stderr_log.hpp',
'../common/stderr_log.cpp',
],
'conditions': [
['OS == "mac"',
# Mac OS X
{
'xcode_settings': {
'OTHER_CPLUSPLUSFLAGS':[
'<@(glfw3_cflags)',
'<@(curl_cflags)',
],
'OTHER_LDFLAGS': [
'<@(glfw3_libraries)',
'<@(curl_libraries)',
],
}
},
# Non-Mac OS X
{
'cflags': [
'<@(glfw3_cflags)',
'<@(curl_cflags)',
],
'link_settings': {
'libraries': [
'<@(glfw3_libraries)',
'<@(curl_libraries)',
'-lboost_regex'
],
},
}],
],
'dependencies': [
'../mapboxgl.gyp:mapboxgl',
'../mapboxgl.gyp:copy_styles',
'../mapboxgl.gyp:copy_certificate_bundle',
],
},
],
}
|
{'includes': ['../common.gypi', '../config.gypi'], 'targets': [{'target_name': 'linuxapp', 'product_name': 'mapbox-gl', 'type': 'executable', 'sources': ['./main.cpp', '../common/settings_json.cpp', '../common/settings_json.hpp', '../common/platform_default.cpp', '../common/glfw_view.hpp', '../common/glfw_view.cpp', '../common/curl_request.cpp', '../common/stderr_log.hpp', '../common/stderr_log.cpp'], 'conditions': [['OS == "mac"', {'xcode_settings': {'OTHER_CPLUSPLUSFLAGS': ['<@(glfw3_cflags)', '<@(curl_cflags)'], 'OTHER_LDFLAGS': ['<@(glfw3_libraries)', '<@(curl_libraries)']}}, {'cflags': ['<@(glfw3_cflags)', '<@(curl_cflags)'], 'link_settings': {'libraries': ['<@(glfw3_libraries)', '<@(curl_libraries)', '-lboost_regex']}}]], 'dependencies': ['../mapboxgl.gyp:mapboxgl', '../mapboxgl.gyp:copy_styles', '../mapboxgl.gyp:copy_certificate_bundle']}]}
|
#Source : https://leetcode.com/problems/linked-list-cycle/
#Author : Yuan Wang
#Date : 2018-08-01
'''
**********************************************************************************
*Given a linked list, determine if it has a cycle in it.
*
*Follow up:
*Can you solve it without using extra space?
**********************************************************************************/
'''
#Self solution, Time complexity:O(n) Space complexity:O(n)
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
dic={}
current=head
while current != None:
if current not in dic:
dic[current]=False
else:
return True
current=current.next
return False
'''
Other solution, Time complexity:O(n) Space complexity:O(1)
Algorithm
The space complexity can be reduced to O(1)O(1) by considering two pointers at different speed
- a slow pointer and a fast pointer. The slow pointer moves one step at a time while the
fast pointer moves two steps at a time.
If there is no cycle in the list, the fast pointer will eventually reach the end and we can
return false in this case.
Now consider a cyclic list and imagine the slow and fast pointers are two runners racing around
a circle track. The fast runner will eventually meet the slow runner. Why? Consider this case
(we name it case A) - The fast runner is just one step behind the slow runner. In the next iteration,
they both increment one and two steps respectively and meet each other.
How about other cases? For example, we have not considered cases where the fast runner is two or
three steps behind the slow runner yet. This is simple, because in the next or next's next iteration,
this case will be reduced to case A mentioned above.
'''
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
try:
slow = head
fast = head.next
while slow is not fast:
slow = slow.next
fast = fast.next.next
return True
except:
return False
|
"""
**********************************************************************************
*Given a linked list, determine if it has a cycle in it.
*
*Follow up:
*Can you solve it without using extra space?
**********************************************************************************/
"""
def has_cycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
dic = {}
current = head
while current != None:
if current not in dic:
dic[current] = False
else:
return True
current = current.next
return False
"\nOther solution, Time complexity:O(n) Space complexity:O(1)\nAlgorithm\n\nThe space complexity can be reduced to O(1)O(1) by considering two pointers at different speed\n - a slow pointer and a fast pointer. The slow pointer moves one step at a time while the \n fast pointer moves two steps at a time.\n\nIf there is no cycle in the list, the fast pointer will eventually reach the end and we can \nreturn false in this case.\n\nNow consider a cyclic list and imagine the slow and fast pointers are two runners racing around \na circle track. The fast runner will eventually meet the slow runner. Why? Consider this case \n(we name it case A) - The fast runner is just one step behind the slow runner. In the next iteration,\n they both increment one and two steps respectively and meet each other.\n\nHow about other cases? For example, we have not considered cases where the fast runner is two or \nthree steps behind the slow runner yet. This is simple, because in the next or next's next iteration,\nthis case will be reduced to case A mentioned above.\n"
def has_cycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
try:
slow = head
fast = head.next
while slow is not fast:
slow = slow.next
fast = fast.next.next
return True
except:
return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.