content
stringlengths 7
1.05M
|
---|
# -*- 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__
|
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()
|
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 )
|
# 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) |
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() |
#
# 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)
|
"""
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 |
# -*- coding: utf-8 -*-
__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')
|
# 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:
"""
"""
|
# 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 Cat:
__mew: str = 'муурр'*4
def make_happy(self) -> str:
return self.__mew
kuzya = Cat()
print(kuzya.__mew) # Не сработает
# print(kuzya.mew)
print(kuzya.make_happy())
|
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 |
""" Find a quote from a famous person you admire.
Print the quote and the name of its author. """
quote = 'Those who dream by day are cognizant of many things which escape those who dream only by night'
name = 'edgar allan poe'
print(f'{name.title()} once said, "{quote}".')
quote = 'Don’t compare yourself with anyone in this world… if you do so, you are insulting yourself'
name = 'bill gates'
print(f'{name.title()} once said, "{quote}".') |
# -*- 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.
""" |
# 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.")
|
def count(sequence, item):
amount = 0
for x in sequence:
if x == item:
amount += 1
return amount
|
# https://atcoder.jp/contests/atc001/tasks/unionfind_a
N,Q = map(int,input().split())
par = [i for i in range(N+1)]
def find(x):
if par[x] == x:
return x
else:
par[x] = find(par[x]) #経路圧縮
return par[x]
def same(x,y):
return find(x) == find(y)
def unite(x,y):
x = find(x)
y = find(y)
if x == y:
return 0
par[x] = y
for i in range(Q):
p,a,b = map(int,input().split())
if p == 0:
unite(a,b)
else:
if same(a,b):
print('Yes')
else:
print('No') |
'''
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) |
'#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')
''' |
# -*- coding: utf-8 -*-
__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)
|
{
"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()
|
"""
Você deve criar uma classe carro que vai possuir dois atributos compostos por outras duas classes.
Motor
Direção
O motor terá a responsabilidade de controlar a velocidade. Ele oferece os seguintes atributos:
1 - Atributo de dado Velocidade.
2 - Método acelerar que deverá incrementar a velocidade de uma unidade.
3 - Método frear que deverá decrementar a velocidade em duas unidades.
A direção terá a responsabilidade de controlar a direção. Ela ofecere os seguintes atributos:
1 - Valor de direção com valores possíveis: Norte, Sul, Leste, Oeste
2 - Método girar_a_direita (se está em N e gira a direita vai para L, se gira a direita de novo vai para O...)
3 - Método girar_a_esquerda (se está em N e gira a esquerda vai para O, se gira a esquerda de novo vai para S...)
N
O L
S
Exemplo:
# Testando motor.
>>> motor = Motor() # ao clicar com o botão direito no pycharm e executar "run doctests" vão retornar vários erros.
>>> motor.velocidade
0
>>> motor.acelerar()
>>> motor.velocidade
1
>>> motor.acelerar()
>>> motor.velocidade
2
>>> motor.acelerar()
>>> motor.velocidade
3
>>> motor.frear()
>>> motor.velocidade
1
>>> motor.frear()
>>> motor.velocidade
0
# Testando direção
>>> direcao = Direcao()
>>> direcao.valor
'Norte'
>>> direcao.girar_a_direita()
>>> direcao.valor
'Leste'
>>> direcao.girar_a_direita()
>>> direcao.valor
'Sul'
>>> direcao.girar_a_direita()
>>> direcao.valor
'Oeste'
>>> direcao.girar_a_direita()
>>> direcao.valor
'Norte'
>>> direcao.girar_a_esquerda()
>>> direcao.valor
'Oeste'
>>> direcao.girar_a_esquerda()
>>> direcao.valor
'Sul'
>>> direcao.girar_a_esquerda()
>>> direcao.valor
'Leste'
>>> direcao.girar_a_esquerda()
>>> direcao.valor
'Norte'
>>> carro = Carro(direcao, motor)
>>> carro.calcular_velocidade()
0
>>> carro.acelerar()
>>> carro.calcular_velocidade()
1
>>> carro.acelerar()
>>> carro.calcular_velocidade()
2
>>> carro.frear()
>>> carro.calcular_velocidade()
0
>>> carro.calcular_direcao()
'Norte'
>>> carro.girar_a_direita()
>>> carro.calcular_direcao()
'Leste'
>>> carro.girar_a_esquerda()
>>> carro.calcular_direcao()
'Norte'
>>> carro.girar_a_esquerda()
>>> carro.calcular_direcao()
'Oeste'
"""
# Primeiro criamos a classe direção e todos seus cálculos e movimentos;
# Segundo criamos a classe Motor;
# Por último criamos a classe carro, chamando os cálculos do motor e da direção.
class Carro():
def __init__(self, direcao, motor): #alt + enter em cima de direção cria o self.direcao = direcao automaticamente.
self.motor = motor
self.direcao = direcao
# Na classe motor já definimos como o carro acelera, freia e qual sua velocidade, portanto na classe carro só
# precisamos retornar estes cálculos nos respectivos métodos.
def calcular_velocidade(self):
return self.motor.velocidade
def acelerar(self):
self.motor.acelerar()
def frear(self):
self.motor.frear()
def calcular_direcao(self):
return self.direcao.valor
def girar_a_direita(self):
self.direcao.girar_a_direita()
def girar_a_esquerda(self):
self.direcao.girar_a_esquerda()
NORTE='Norte'
SUL='Sul'
LESTE='Leste'
OESTE='Oeste'
class Direcao():
rotacao_a_direita_dct = {NORTE: LESTE, LESTE: SUL, SUL: OESTE, OESTE: NORTE}
rotacao_a_esquerda_dct = {NORTE: OESTE, OESTE: SUL, SUL: LESTE, LESTE: NORTE}
def __init__(self):
self.valor = NORTE
def girar_a_direita(self):
self.valor = self.rotacao_a_direita_dct[self.valor]
# Poderia resolver com vários if else, mas nessa estrutura o dicionário funciona melhor e o código fica mais limpo.
def girar_a_esquerda(self):
self.valor = self.rotacao_a_esquerda_dct[self.valor]
class Motor():
def __init__(self):
self.velocidade = 0
def acelerar(self):
self.velocidade += 1
def frear(self):
self.velocidade -= 2
self.velocidade=max(0, self.velocidade) # entre o valor 0 e o valor da velocidade atual, prevalece o maior,
# usamos esta função para o carro não ter velocidade negativa, sempre que for maior que zero permanece a
# velocidade atual do carro.
# Uma convenção da PEP8 diz que se uma variável não deve ter seu valor alterado (constante) seu nome deve ser em caixa
# alta. O Python não vai impedir que seu valor seja alterado, por isso é uma convenção.
|
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) |
# -*- 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"],
)
|
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
|
# -*- 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)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
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
|
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
|
"""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/+'
|
# 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"
|
n = int(input())
total = 0
line = map(int, input().split())
for _ in line:
if _ < 0:
total += -_
print(total)
|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# ======================================================================================================================
# The MIT License (MIT)
# ======================================================================================================================
# Copyright (c) 2016 [Marco Aurélio Prado - [email protected]]
# ======================================================================================================================
DEBUG = False
STATIC_FOLDER = None
LOGGING_FORMAT = '[ %(levelname)8s | %(asctime)s ] - [ %(pathname)64s | %(funcName)32s | %(lineno)4d ] - %(message)s'
LOGGING_FILENAME = '/vagrant/logs/log'
LOGGING_WHEN = 'D'
LOGGING_INTERVAL = 7
LOGGING_BACKUP_COUNT = 4
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USERNAME = '[email protected]'
MAIL_USE_TLS = False
MAIL_USE_SSL = True
|
#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 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
|
AwayPlayerFoulClockStart=0
AwayLastPlayerFoul=''
HomePlayerFoulClockStart=0
HomeLastPlayerFoul=''
|
# -*- 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]
|
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"))
|
#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" |
# 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") |
w2vSize = 100
feature_dim = 100
max_len=21
debug = False
poolSize=32
topicNum = 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 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
定义一个类
1.
用 __name 表示一个私有成员变量,外部不可直接访问
2. __init__ 表示类初始化函数,当创建一个对象的时候,需要调用此方法
"""
class Person(object):
def __init__(self, name: str, age: int) -> None:
self.__name = name
self.__age = age
def print(self):
print('name=%s, age=%s' % (self.__name, self.__age))
p1 = Person('Walker', 20)
p1.age = 21
p1.print()
|
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))
|
"""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)
|
#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)
|
# 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
}
|
# 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
|
#!/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"
|
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
|
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'
|
__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
|
def main():
s = input("Please enter your sentence: ")
words = s.split()
wordCount = 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.
"""
|
"""
Programa 013
Área de estudos.
data 16.11.2020 (Indefinida) Hs
@Autor: Abraão A. Silva
"""
# Coleta do dia e peso pescado.
dia = int(input('Dia da pesca.: '))
peso = float(input('Quantidade de pescados(kg).: '))
# O "excesso" tem o valor da quantidade pescada, menos o peso maximo permitido.
excesso = (peso - 50)
# "Multa" tem o valor do excesso, multiplicado pelo valor da multa por kg excedente.
multa = excesso * 4
# Relatório da pesca.
print('=-'*10, 'Dados da Pesca', '-='*10)
print(f'Dia: {dia}')
print(f'Quantidade pescada(kg): {peso:.1f}kg')
print(f'peso excedente(kg): {excesso:.1f}kg')
print(f'Valor da multa: R${multa:.2f}')
print('='*30)
|
#!/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())
|
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
"""
|
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) + ">"
|
# 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)
|
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')
|
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)
|
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.')
|
"""
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:])
|
# 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 |
Import('env')
global_env = DefaultEnvironment()
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)
|
# 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
|
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"])) |
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)) |
#!/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
|
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
}
|
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]
|
# 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))
|
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) |
Produto = input('Produto: ')
Preco=float(input("Preço do produto em R$: ".format(Produto)))
Desconto = float(input("Desconto [%]: "))
desc = (Preco * Desconto)/100
PrecoDesconto = Preco - desc
print('A {} com desconto de {}% saira por {:.2f}R$'.format(Produto, Desconto, PrecoDesconto))
#Gabarito
print("com desconto o produto saira por:{:.2f}RS ".format(Preco - (Preco * Desconto / 100)))
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
print('欢迎来到恋爱大冒险')
input()
print('请按回车键来进行游戏')
input()
print('经过三年的学习,我终于和同年级的暗恋的女生考上了同一所大学')
input()
print('开学第一天,我在食堂遇到她了,我应该')
input()
print('1.直接上去要微信\t2.以老乡的名义上去聊天\t3.继续吃饭')
option1=int(input('请做出选择:按数字1-3,然后回车\n'))
if option1==1:
print('太仓促了,机会还不成熟')
input()
print('对不起,你失败了。GAME OVER')
elif option1==2:
print('似乎认识了,而且加了微信好友')
input()
print('下午上完课回到寝室,心情激动,发条什么微信呢?')
input()
print('1.你加了什么社团\t2.晚饭准备吃啥?\t3.周末有空吗?')
option2=int(input('请做出选择:按数字1-3,然后回车\n'))
if option2==1:
print('我知道她在哪个社团了,我也挺有兴趣,可以一同加入')
elif option2==2:
print('太庸俗了,这是尬聊')
input()
print('对不起,你失败了。GAME OVER')
elif option2==3:
print('还不熟,乱约什么')
input()
print('对不起,你失败了。GAME OVER')
else:
print('输入错误,请重头来过')
pass
elif option1==3:
print('太怂了,注定单身')
input()
print('对不起,你失败了。GAME OVER')
else:
print('输入错误,请重头来过')
pass
|
# 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))) |
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) |
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",
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.