content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#This program shows how many birds there are in each state.
def texas() -> None:
'''function output how many birds Texas has'''
bird = 5000
print("Texas has", bird, "birds")
def california() -> None:
'''function output how many birds California has'''
bird = 8000
print("California has", bird... | def texas() -> None:
"""function output how many birds Texas has"""
bird = 5000
print('Texas has', bird, 'birds')
def california() -> None:
"""function output how many birds California has"""
bird = 8000
print('California has', bird, 'birds')
def main():
texas()
california()
if __name_... |
# Figure A.6
ZIGZAG = (
0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63
)
| zigzag = (0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63) |
class Person:
def __init__(self, name: Name):
self.name = name
def test_barry_is_harry():
harry = Person(Name("Harry", "Percival"))
barry = harry
barry.name = Name("Barry", "Percival")
assert harry is barry and barry is harry
| class Person:
def __init__(self, name: Name):
self.name = name
def test_barry_is_harry():
harry = person(name('Harry', 'Percival'))
barry = harry
barry.name = name('Barry', 'Percival')
assert harry is barry and barry is harry |
def eh_par(n):
if n < 2:
return ''
if n % 2 != 0:
n -= 1
print(n)
return eh_par(n-2)
x = int(input())
print(eh_par(x))
| def eh_par(n):
if n < 2:
return ''
if n % 2 != 0:
n -= 1
print(n)
return eh_par(n - 2)
x = int(input())
print(eh_par(x)) |
# -*- coding: utf-8 -*-
__author__ ='Charles Keith Brown'
__email__ = 'charles.k.brown@gmail.com'
__version__ = '0.1.1'
| __author__ = 'Charles Keith Brown'
__email__ = 'charles.k.brown@gmail.com'
__version__ = '0.1.1' |
WOQL_IDGEN_JSON = {
"@type": "woql:IDGenerator",
"woql:base": {
"@type": "woql:Datatype",
"woql:datatype": {"@type": "xsd:string", "@value": "doc:Station"},
},
"woql:key_list": {
"@type": "woql:Array",
"woql:array_element": [
{
"@type": "woql:A... | woql_idgen_json = {'@type': 'woql:IDGenerator', 'woql:base': {'@type': 'woql:Datatype', 'woql:datatype': {'@type': 'xsd:string', '@value': 'doc:Station'}}, 'woql:key_list': {'@type': 'woql:Array', 'woql:array_element': [{'@type': 'woql:ArrayElement', 'woql:index': {'@type': 'xsd:nonNegativeInteger', '@value': 1 - 1}, '... |
#
# @lc app=leetcode.cn id=1632 lang=python3
#
# [1632] number-of-good-ways-to-split-a-string
#
None
# @lc code=end | None |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Path where remote_file_reader should be installed on the device.
REMOTE_FILE_READER_DEVICE_PATH = '/data/local/tmp/remote_file_reader'
# Path where remote... | remote_file_reader_device_path = '/data/local/tmp/remote_file_reader'
remote_file_reader_cloud_path = 'gs://mojo/devtools/remote_file_reader' |
def setup():
pass
def draw():
fill(255, 0, 0)
ellipse(mouseX, mouseY, 20, 20) | def setup():
pass
def draw():
fill(255, 0, 0)
ellipse(mouseX, mouseY, 20, 20) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class CacheDecorator:
def __init__(self):
self.cache = {}
self.func = None
def cachedFunc(self, *args):
if args not in self.cache:
print("Ergebnis berechnet")
self.cache[args] = self.func(*args)
else:... | class Cachedecorator:
def __init__(self):
self.cache = {}
self.func = None
def cached_func(self, *args):
if args not in self.cache:
print('Ergebnis berechnet')
self.cache[args] = self.func(*args)
else:
print('Ergebnis geladen')
return... |
#!/usr/bin/env python3
def gen_repr(obj, **kwargs):
fields = ', '.join([
f'{key}={value}' for key, value in dict(obj.__dict__, **kwargs).items()
])
return f'{obj.__class__.__name__}({fields})'
def __repr__(self):
return gen_repr(self)
| def gen_repr(obj, **kwargs):
fields = ', '.join([f'{key}={value}' for (key, value) in dict(obj.__dict__, **kwargs).items()])
return f'{obj.__class__.__name__}({fields})'
def __repr__(self):
return gen_repr(self) |
# Challenge 58, intermediate
# https://www.reddit.com/r/dailyprogrammer/comments/u8jn9/5282012_challenge_58_intermediate/
# Take an input number and return next palindrome
# f(808) = 818
# f(999) = 1001 -- need to take char length increases into account
# f(2133) = 2222
# what is f(3 ^ 39)?
# what is f(7 ^ 100)?
# B... | def p(input_number):
if len(str(input_number)) % 2 == 0:
number = str(input_number)
front_half = number[:int(len(number) / 2)]
new_palindrome = int(front_half + front_half[::-1])
if new_palindrome <= int(number):
new_front = str(int(front_half) + 1)
if len(new... |
#!/usr/bin/python
# test 1: seed top level, no MIP map
command += testtex_command (parent + " -res 256 256 -d uint8 -o out1.tif --testicwrite 1 blah")
# test 2: seed top level, automip
command += testtex_command (parent + " -res 256 256 -d uint8 -o out2.tif --testicwrite 1 --automip blah")
# test 3: procedural MIP m... | command += testtex_command(parent + ' -res 256 256 -d uint8 -o out1.tif --testicwrite 1 blah')
command += testtex_command(parent + ' -res 256 256 -d uint8 -o out2.tif --testicwrite 1 --automip blah')
command += testtex_command(parent + ' -res 256 256 -d uint8 -o out3.tif --testicwrite 2 blah')
command += testtex_comman... |
# --- internal paths --- #
mimic_root_dir = '/cluster/work/grlab/clinical/mimic/MIMIC-III/cdb_1.4/'
root_dir = '/cluster/work/grlab/clinical/Inselspital/DataReleases/01-19-2017/InselSpital/'
# --- all about mimic --- #
source_data = mimic_root_dir + 'source_data/'
derived = mimic_root_dir + 'derived_stephanie/'
charte... | mimic_root_dir = '/cluster/work/grlab/clinical/mimic/MIMIC-III/cdb_1.4/'
root_dir = '/cluster/work/grlab/clinical/Inselspital/DataReleases/01-19-2017/InselSpital/'
source_data = mimic_root_dir + 'source_data/'
derived = mimic_root_dir + 'derived_stephanie/'
chartevents_path = source_data + 'CHARTEVENTS.csv'
labevents_p... |
class CompositorNodeZcombine:
use_alpha = None
use_antialias_z = None
def update(self):
pass
| class Compositornodezcombine:
use_alpha = None
use_antialias_z = None
def update(self):
pass |
def tetra(n):
t = (n * (n + 1) * (n + 2)) / 6
return t
print(tetra(5)) | def tetra(n):
t = n * (n + 1) * (n + 2) / 6
return t
print(tetra(5)) |
class Platform(object):
def __init__(self, id=None, name=None, slug=None, napalm_driver=None, rpc_client=None):
self.id = id
self.name = name
self.slug = slug
self.napalm_driver = napalm_driver
self.rpc_client = rpc_client
@classmethod
def from_dict(cls, contents):
... | class Platform(object):
def __init__(self, id=None, name=None, slug=None, napalm_driver=None, rpc_client=None):
self.id = id
self.name = name
self.slug = slug
self.napalm_driver = napalm_driver
self.rpc_client = rpc_client
@classmethod
def from_dict(cls, contents):
... |
class Solution(object):
def combine(self, n, k):
ans = []
def dfs(list_start, list_end, k, start, depth, curr, ans):
if depth == k:
ans.append(curr[::])
for i in range(start, list_end):
curr.append(list_start+i)
... | class Solution(object):
def combine(self, n, k):
ans = []
def dfs(list_start, list_end, k, start, depth, curr, ans):
if depth == k:
ans.append(curr[:])
for i in range(start, list_end):
curr.append(list_start + i)
dfs(list_star... |
# -*- coding: utf-8 -*-
qte = int(input())
lista = {}
for i in range(qte):
v = int(input())
if(v in lista):
lista[v] += 1
else:
lista[v] = 1
chaves = lista.keys()
chaves = sorted(chaves)
for k in chaves:
print("{} aparece {} vez(es)".format(k,lista[k])) | qte = int(input())
lista = {}
for i in range(qte):
v = int(input())
if v in lista:
lista[v] += 1
else:
lista[v] = 1
chaves = lista.keys()
chaves = sorted(chaves)
for k in chaves:
print('{} aparece {} vez(es)'.format(k, lista[k])) |
ES_HOST = 'localhost:9200'
ES_INDEX = 'pending-mrcoc'
ES_DOC_TYPE = 'cooccurence'
API_PREFIX = 'mrcoc'
API_VERSION = ''
| es_host = 'localhost:9200'
es_index = 'pending-mrcoc'
es_doc_type = 'cooccurence'
api_prefix = 'mrcoc'
api_version = '' |
DEBUG = True
SECRET_KEY = 'no'
SQLALCHEMY_DATABASE_URI = 'sqlite:///master.sqlite3'
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
GITHUB_CLIENT_ID = 'da79a6b5868e690ab984'
GITHUB_CLIENT_SECRET = '1701d3bd20bbb29012592fd3a9c64b827e0682d6'
ALLOWED_EXTENSIONS = set(['csv', 'tsv', 'ods', 'xls', 'xlsx', 'txt']... | debug = True
secret_key = 'no'
sqlalchemy_database_uri = 'sqlite:///master.sqlite3'
celery_broker_url = 'amqp://guest:guest@localhost:5672//'
github_client_id = 'da79a6b5868e690ab984'
github_client_secret = '1701d3bd20bbb29012592fd3a9c64b827e0682d6'
allowed_extensions = set(['csv', 'tsv', 'ods', 'xls', 'xlsx', 'txt']) |
dict = {'a': 1, 'b': 2}
list = [1,2,3]
str = 'hh'
num = 123
num2 = 0.4
class Test:
def test(self):
print("gg")
t = Test()
print(type(dict))
print(type(list))
print(type(str))
print(type(num))
print(type(num2))
print(type(Test))
print(type(t))
| dict = {'a': 1, 'b': 2}
list = [1, 2, 3]
str = 'hh'
num = 123
num2 = 0.4
class Test:
def test(self):
print('gg')
t = test()
print(type(dict))
print(type(list))
print(type(str))
print(type(num))
print(type(num2))
print(type(Test))
print(type(t)) |
# -*- coding: utf-8 -*-
description = "Denex detector setup"
group = "optional"
includes = ["det_common"]
excludes = ["det2"]
tango_base = "tango://phys.maria.frm2:10000/maria/"
devices = dict(
detimg = device("nicos.devices.tango.ImageChannel",
description = "Denex detector image",
tangodevice ... | description = 'Denex detector setup'
group = 'optional'
includes = ['det_common']
excludes = ['det2']
tango_base = 'tango://phys.maria.frm2:10000/maria/'
devices = dict(detimg=device('nicos.devices.tango.ImageChannel', description='Denex detector image', tangodevice=tango_base + 'fastcomtec/detector', fmtstr='%d cts', ... |
n = int(input())
a = list(map(int, input().split(" ")))
a.sort()
for i in range(1, len(a)):
a[i] += a[i - 1]
print(sum(a))
| n = int(input())
a = list(map(int, input().split(' ')))
a.sort()
for i in range(1, len(a)):
a[i] += a[i - 1]
print(sum(a)) |
# arr[i] may be present at arr[i+1] or arr[i-1].
# TC: O(log(N)) | SC: O(1)
def search(nums, key):
start = 0
end = len(nums)-1
while start <= end:
mid = start+((end-start)//2)
if nums[mid] == key:
return mid
if mid < len(nums)-1 and nums[mid+1] == key:
re... | def search(nums, key):
start = 0
end = len(nums) - 1
while start <= end:
mid = start + (end - start) // 2
if nums[mid] == key:
return mid
if mid < len(nums) - 1 and nums[mid + 1] == key:
return mid + 1
if mid > 0 and nums[mid - 1] == key:
r... |
expected_output = {
"version": {
"bootldr": "System Bootstrap, Version 17.5.2r, RELEASE SOFTWARE (P)",
"build_label": "BLD_POLARIS_DEV_LATEST_20210302_012043",
"chassis": "C9300-24P",
"chassis_sn": "FCW2223G0B9",
"compiled_by": "mcpre",
"compiled_date": "Tue 02-Mar-21... | expected_output = {'version': {'bootldr': 'System Bootstrap, Version 17.5.2r, RELEASE SOFTWARE (P)', 'build_label': 'BLD_POLARIS_DEV_LATEST_20210302_012043', 'chassis': 'C9300-24P', 'chassis_sn': 'FCW2223G0B9', 'compiled_by': 'mcpre', 'compiled_date': 'Tue 02-Mar-21 00:07', 'copyright_years': '1986-2021', 'location': '... |
user_number = input("Please enter your digit : ")
total = 0
for i in range(1, 5):
number = user_number * i
total = total + int(number)
print(total) | user_number = input('Please enter your digit : ')
total = 0
for i in range(1, 5):
number = user_number * i
total = total + int(number)
print(total) |
primary_separator = '\n'
secondary_separator = ','
default_filename_classification = 'tests/test_classification.data'
dafault_filename_regression = 'tests/test_regression.data'
def load_data(data, isfile=True):
if isfile:
with open(data) as data_file:
data_set = data_file.read()
else:
... | primary_separator = '\n'
secondary_separator = ','
default_filename_classification = 'tests/test_classification.data'
dafault_filename_regression = 'tests/test_regression.data'
def load_data(data, isfile=True):
if isfile:
with open(data) as data_file:
data_set = data_file.read()
else:
... |
def getColors(color):
colors=set()
if color not in inverseRules.keys():
return colors
for c in inverseRules[color]:
colors.add(c)
colors.update(getColors(c))
return(colors)
with open('day7/input.txt') as f:
rules=dict([l.split(' contain') for l in f.read().replace(' bags', '... | def get_colors(color):
colors = set()
if color not in inverseRules.keys():
return colors
for c in inverseRules[color]:
colors.add(c)
colors.update(get_colors(c))
return colors
with open('day7/input.txt') as f:
rules = dict([l.split(' contain') for l in f.read().replace(' bags... |
#
# PySNMP MIB module OMNI-gx2Dm200-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OMNI-gx2Dm200-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:33:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection, constraints_union) ... |
mybooltr= True #We declare the mybooltrue equal to True
myboolfa= False #We declare the myboolfalse equal to False
print(mybooltr == myboolfa) #It will print false because my mybooltr doesnt equal to myboolfa
print(mybooltr != myboolfa) #it will print true for the same reason
print(2 == 3) #It will print fals... | mybooltr = True
myboolfa = False
print(mybooltr == myboolfa)
print(mybooltr != myboolfa)
print(2 == 3)
print(7 > 7.0)
print(9 >= 9.0) |
# from https://gist.github.com/jalavik/976294
# original XML at http://www.w3.org/Math/characters/unicode.xml
# XSL for conversion: https://gist.github.com/798546
unicode_to_latex = {
u"\u0020": "\\space ",
u"\u0023": "\\#",
u"\u0024": "\\textdollar ",
u"\u0025": "\\%",
u"\u0026": "\\&",
u... | unicode_to_latex = {u' ': '\\space ', u'#': '\\#', u'$': '\\textdollar ', u'%': '\\%', u'&': '\\&', u"'": '\\textquotesingle ', u'*': '\\ast ', u'\\': '\\textbackslash ', u'^': '\\^{}', u'_': '\\_', u'`': '\\textasciigrave ', u'{': '\\lbrace ', u'|': '\\vert ', u'}': '\\rbrace ', u'~': '\\textasciitilde ', u'¡': '\... |
# 445. Add Two Numbers II
'''
You are given two non-empty linked lists representing two non-negative integers.
The most significant digit comes first and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, exce... | """
You are given two non-empty linked lists representing two non-negative integers.
The most significant digit comes first and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
I... |
# If T-Rex is angry, hungry, and bored he will eat the Triceratops
# Otherwise if T-Rex is tired and hungry, he will eat the Iguanadon
# Otherwise if T-Rex is hungry and bored, he will eat the Stegasaurus.
# Otherwise if T-Rex is tired, he goes to sleep
# Otherwise if T-Rex is angry and bored, he will fight with the Ve... | angry = True
bored = True
hungry = False
tired = False
if angry and hungry and bored:
print('T-Rex eats the Triceratops!')
elif tired and hungry:
print('T-Rex eats the Iguanadon')
elif hungry and bored:
print('T-Rex eats the Stegasaurus')
elif tired:
print('T-Rex goes to sleep.')
elif angry and bored:
... |
# Gamemode Utilities
def get_gamemode_name(id):
if (id is 0):
return "Conquest"
if (id is 1):
return "Domination"
if (id is 2):
return "Team Deathmatch"
if (id is 3):
return "Zombies"
if (id is 4):
return "Disarm"
| def get_gamemode_name(id):
if id is 0:
return 'Conquest'
if id is 1:
return 'Domination'
if id is 2:
return 'Team Deathmatch'
if id is 3:
return 'Zombies'
if id is 4:
return 'Disarm' |
#: Mapping of files from unihan-etl (UNIHAN database)
UNIHAN_FILES = [
'Unihan_DictionaryLikeData.txt',
'Unihan_IRGSources.txt',
'Unihan_NumericValues.txt',
'Unihan_RadicalStrokeCounts.txt',
'Unihan_Readings.txt',
'Unihan_Variants.txt',
]
#: Mapping of field names from unihan-etl (UNIHAN datab... | unihan_files = ['Unihan_DictionaryLikeData.txt', 'Unihan_IRGSources.txt', 'Unihan_NumericValues.txt', 'Unihan_RadicalStrokeCounts.txt', 'Unihan_Readings.txt', 'Unihan_Variants.txt']
unihan_fields = ['kAccountingNumeric', 'kCangjie', 'kCantonese', 'kCheungBauer', 'kCihaiT', 'kCompatibilityVariant', 'kDefinition', 'kFenn... |
def is_email_valid(email):
if not '@' in email:
return False
name, domain = email.split('@', 1)
if not name:
return False
return '.' in domain
| def is_email_valid(email):
if not '@' in email:
return False
(name, domain) = email.split('@', 1)
if not name:
return False
return '.' in domain |
'''
Doctor's Secret
Cheeku is ill. He goes to Homeopathic Doctor - Dr. Thind.
Doctor always recommends medicines after reading from a secret book that he has. This secret book has recipe to cure any disease. Cheeku is chalak. He wants to know if Doctor is giving him correct medicine or not.
So he asks Doctor 2 quest... | """
Doctor's Secret
Cheeku is ill. He goes to Homeopathic Doctor - Dr. Thind.
Doctor always recommends medicines after reading from a secret book that he has. This secret book has recipe to cure any disease. Cheeku is chalak. He wants to know if Doctor is giving him correct medicine or not.
So he asks Doctor 2 quest... |
# This file holds metadata about the project. It should import only from
# standard library modules (this includes not importing other modules in the
# package) so that it can be loaded by setup.py before dependencies are
# installed.
source = "https://github.com/wikimedia/wmfdata-python"
version = "1.3.3"
| source = 'https://github.com/wikimedia/wmfdata-python'
version = '1.3.3' |
'''
Pattern
Enter number of rows: 5
54321
4321
321
21
1
'''
print('number pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(number_rows,0,-1):
for column in range(row,0,-1):
if column < 10:
print(f'0{column}',end=' ')
else:
print(column,end=' ')
print() | """
Pattern
Enter number of rows: 5
54321
4321
321
21
1
"""
print('number pattern: ')
number_rows = int(input('Enter number of rows: '))
for row in range(number_rows, 0, -1):
for column in range(row, 0, -1):
if column < 10:
print(f'0{column}', end=' ')
else:
print(column, end... |
class Solution:
def threeSum(self, nums):
arr = []
map = {nums[i]: i for i in range(len(nums))}
if (len(list(map.keys())) == 1 and nums[0] == 0 and len(nums) > 3):
return [[0]*3]
for m in range(len(nums)-1):
for n in range(m+1, len(nums)):
targ... | class Solution:
def three_sum(self, nums):
arr = []
map = {nums[i]: i for i in range(len(nums))}
if len(list(map.keys())) == 1 and nums[0] == 0 and (len(nums) > 3):
return [[0] * 3]
for m in range(len(nums) - 1):
for n in range(m + 1, len(nums)):
... |
class C():
pass
# a really complex class
class D(C, B):
pass
| class C:
pass
class D(C, B):
pass |
num = 353
reverse_num = 0
temp = num
# print(num,reverse_num)
while(temp != 0):
remainder = int(temp % 10)
print(remainder)
reverse_num = int((reverse_num*10) + remainder)
print(reverse_num)
temp = int(temp / 10)
# print(reverse_num)
if reverse_num == num:
print('It is Palindrome')
else:
p... | num = 353
reverse_num = 0
temp = num
while temp != 0:
remainder = int(temp % 10)
print(remainder)
reverse_num = int(reverse_num * 10 + remainder)
print(reverse_num)
temp = int(temp / 10)
if reverse_num == num:
print('It is Palindrome')
else:
print('not Palindrome') |
#
# Solution to Project Euler problem 6
# Copyright (c) Project Nayuki. All rights reserved.
#
# https://www.nayuki.io/page/project-euler-solutions
# https://github.com/nayuki/Project-Euler-solutions
#
# Computers are fast, so we can implement this solution directly without any clever math.
# However for the mathe... | def compute():
n = 100
s = sum((i for i in range(1, N + 1)))
s2 = sum((i ** 2 for i in range(1, N + 1)))
return str(s ** 2 - s2)
if __name__ == '__main__':
print(compute()) |
with open("sonar.txt") as sonar:
depthstr = sonar.readline()
previous = int(depthstr.strip())
increases = 0
for depthstr in sonar.readlines():
depth = int(depthstr.strip())
if depth > previous:
increases += 1
previous = depth
print(increases) | with open('sonar.txt') as sonar:
depthstr = sonar.readline()
previous = int(depthstr.strip())
increases = 0
for depthstr in sonar.readlines():
depth = int(depthstr.strip())
if depth > previous:
increases += 1
previous = depth
print(increases) |
class Solution:
def validPalindrome(self, s: str) -> bool:
if s == s[::-1]:
return True
left, right = 0 , len(s)-1
s = list(s)
while left < right:
if s[left] != s[right]:
s_l = s[left+1:right+1]
s_r = s[left:ri... | class Solution:
def valid_palindrome(self, s: str) -> bool:
if s == s[::-1]:
return True
(left, right) = (0, len(s) - 1)
s = list(s)
while left < right:
if s[left] != s[right]:
s_l = s[left + 1:right + 1]
s_r = s[left:right]
... |
#coding:utf-8
'''
filename:custom_exception.py
judge the number of age is even or odd
'''
class NegativeAgeException(RuntimeError):
def __init__(self,age):
super().__init__()
self.age = age
def enterage(age):
if age<0:
raise NegativeAgeException('Only *POSITIVE* integers ar... | """
filename:custom_exception.py
judge the number of age is even or odd
"""
class Negativeageexception(RuntimeError):
def __init__(self, age):
super().__init__()
self.age = age
def enterage(age):
if age < 0:
raise negative_age_exception('Only *POSITIVE* integers are allowed')
... |
def getExtensionObjectFromString(strExtension):
try:
assetID,tempData=strExtension.split("$")
itemVER, tempData=tempData.split("@")
itemID,tempData=tempData.split(";")
return extensions(assetID,itemVER,itemID,tempData)
except: return None
class extensions... | def get_extension_object_from_string(strExtension):
try:
(asset_id, temp_data) = strExtension.split('$')
(item_ver, temp_data) = tempData.split('@')
(item_id, temp_data) = tempData.split(';')
return extensions(assetID, itemVER, itemID, tempData)
except:
return None
class... |
# encoding: utf-8
# Copyright 2017 Virgil Dupras
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
def preprocess_paths(paths):
if not isinstance(pat... | def preprocess_paths(paths):
if not isinstance(paths, list):
paths = [paths]
paths = [path.__fspath__() if hasattr(path, '__fspath__') else path for path in paths]
return paths |
number = int(input())
salaperhour = int(input())
valorperhour = float(input())
print("NUMBER = {}".format(number))
print('SALARY = U$ {:.2f}'.format(salaperhour * valorperhour)) | number = int(input())
salaperhour = int(input())
valorperhour = float(input())
print('NUMBER = {}'.format(number))
print('SALARY = U$ {:.2f}'.format(salaperhour * valorperhour)) |
#
# PySNMP MIB module CISCO-LWAPP-DOT11-CLIENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-DOT11-CLIENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:05:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) ... |
'''
pyleaves/pyleaves/trainers/__init__.py
trainers submodule of the pyleaves package
contains trainer subclasses for use in pyleaves for assembling and executing full experiments.
e.g. data preprocessing -> data loading -> model training -> model testing
'''
| """
pyleaves/pyleaves/trainers/__init__.py
trainers submodule of the pyleaves package
contains trainer subclasses for use in pyleaves for assembling and executing full experiments.
e.g. data preprocessing -> data loading -> model training -> model testing
""" |
# n = int(input())
# for i in range(n):
# print("*"*i)
# n = int(input())
# i = n
# while i >=0:
# print("*"*i)
# i -= 1
# n = int(input())
# i = 0
# j = n
# while i <=n:
# print(" "*j+"*"*i)
# i += 1
# j -= 1
# n = int(input())
# i = n
# j = 0
# while i >=0:
# p... | n = int(input())
i = n
j = 0
while i >= 0:
print(' ' * j + '*' * i)
i -= 2
j += 1 |
# Space: O(n)
# Time: O(n)
class RecentCounter:
def __init__(self):
self.data = []
self.count = 0
def ping(self, t: int) -> int:
self.data.append(t)
self.count += 1
while self.data[0] < max(0, t - 3000):
self.data.pop(0)
self.count -= 1
... | class Recentcounter:
def __init__(self):
self.data = []
self.count = 0
def ping(self, t: int) -> int:
self.data.append(t)
self.count += 1
while self.data[0] < max(0, t - 3000):
self.data.pop(0)
self.count -= 1
return self.count |
languages = []
languages.append("Java")
languages.append("Python")
languages.append("C#")
languages.append("Ruby")
print(languages)
numbers = [1, 2, 3]
imdb_top_3 = [
"The Shawshank Redemption",
"The Godfather",
"The Godfather: Part II"
]
print(imdb_top_3)
empty = []
mixed = [1, True, "Three", [], Non... | languages = []
languages.append('Java')
languages.append('Python')
languages.append('C#')
languages.append('Ruby')
print(languages)
numbers = [1, 2, 3]
imdb_top_3 = ['The Shawshank Redemption', 'The Godfather', 'The Godfather: Part II']
print(imdb_top_3)
empty = []
mixed = [1, True, 'Three', [], None]
print(mixed)
if l... |
# Datasets
FACE_FORENSICS = 'ff++'
FACE_FORENSICS_DF = 'ff++_df'
FACE_FORENSICS_F2F = 'ff++_f2f'
FACE_FORENSICS_FSW = 'ff++_fsw'
FACE_FORENSICS_NT = 'ff++_nt'
FACE_FORENSICS_FSH = 'ff++_fsh'
CELEB_DF = 'celeb-df'
DEEPER_FORENSICS = 'deeperface'
DFDC = 'dfdc'
# Manipulation type of FaceForensics++
DF = 'Deepfakes'
F2F ... | face_forensics = 'ff++'
face_forensics_df = 'ff++_df'
face_forensics_f2_f = 'ff++_f2f'
face_forensics_fsw = 'ff++_fsw'
face_forensics_nt = 'ff++_nt'
face_forensics_fsh = 'ff++_fsh'
celeb_df = 'celeb-df'
deeper_forensics = 'deeperface'
dfdc = 'dfdc'
df = 'Deepfakes'
f2_f = 'Face2Face'
fsh = 'FaceShifter'
fsw = 'FaceSwap... |
def test_input_text(expected_result, actual_result):
assert expected_result == actual_result, \
"expected {}, got {}".format(expected_result, actual_result)
def main():
test_input_text(8, 8)
test_input_text(8, 11)
if __name__ == "__main__":
main()
| def test_input_text(expected_result, actual_result):
assert expected_result == actual_result, 'expected {}, got {}'.format(expected_result, actual_result)
def main():
test_input_text(8, 8)
test_input_text(8, 11)
if __name__ == '__main__':
main() |
pattern_zero=[0.0, 0.01492194674, 0.02938475666, 0.0303030303, 0.04338842975, 0.04522497704, 0.05693296602, 0.05968778696, 0.06060606061, 0.07001836547, 0.07369146006, 0.07552800735, 0.0826446281, 0.08723599633, 0.08999081726, 0.09090909091, 0.0948117539, 0.10032139578, 0.10399449036, 0.10583103765, 0.10651974288, 0.11... | pattern_zero = [0.0, 0.01492194674, 0.02938475666, 0.0303030303, 0.04338842975, 0.04522497704, 0.05693296602, 0.05968778696, 0.06060606061, 0.07001836547, 0.07369146006, 0.07552800735, 0.0826446281, 0.08723599633, 0.08999081726, 0.09090909091, 0.0948117539, 0.10032139578, 0.10399449036, 0.10583103765, 0.10651974288, 0.... |
LIMITS = {'BNB/BTC': {'amount': {'max': 90000000.0, 'min': 0.01},
'cost': {'max': None, 'min': 0.001},
'price': {'max': None, 'min': None}},
'BNB/ETH': {'amount': {'max': 90000000.0, 'min': 0.01},
'cost': {'max': None, 'min': 0.01},
... | limits = {'BNB/BTC': {'amount': {'max': 90000000.0, 'min': 0.01}, 'cost': {'max': None, 'min': 0.001}, 'price': {'max': None, 'min': None}}, 'BNB/ETH': {'amount': {'max': 90000000.0, 'min': 0.01}, 'cost': {'max': None, 'min': 0.01}, 'price': {'max': None, 'min': None}}, 'BNB/USDT': {'amount': {'max': 10000000.0, 'min':... |
class Bullet:
def __init__(self, x, y, vx, vy, sender, color):
self.pos = (x, y)
self.vel = (vx, vy)
self.sender = sender
self.color = color
bullets = []
bullets.append(Bullet(0, 1, 2, 3, 'mr. r', (13, 14, 15)))
print(bullets[0].sender) | class Bullet:
def __init__(self, x, y, vx, vy, sender, color):
self.pos = (x, y)
self.vel = (vx, vy)
self.sender = sender
self.color = color
bullets = []
bullets.append(bullet(0, 1, 2, 3, 'mr. r', (13, 14, 15)))
print(bullets[0].sender) |
SQLTYPECODE_CHAR = 1
# NUMERIC * /
SQLTYPECODE_NUMERIC = 2
SQLTYPECODE_NUMERIC_UNSIGNED = -201
# DECIMAL * /
SQLTYPECODE_DECIMAL = 3
SQLTYPECODE_DECIMAL_UNSIGNED = -301
SQLTYPECODE_DECIMAL_LARGE = -302
SQLTYPECODE_DECIMAL_LARGE_UNSIGNED = -303
# INTEGER / INT * /
SQLTYPECODE_INTEGER = 4
SQLTYPECODE_INTEGER_UNSIGNED = -... | sqltypecode_char = 1
sqltypecode_numeric = 2
sqltypecode_numeric_unsigned = -201
sqltypecode_decimal = 3
sqltypecode_decimal_unsigned = -301
sqltypecode_decimal_large = -302
sqltypecode_decimal_large_unsigned = -303
sqltypecode_integer = 4
sqltypecode_integer_unsigned = -401
sqltypecode_largeint = -402
sqltypecode_larg... |
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
class Robot:
def __init__(self, bearing=NORTH, x=0, y=0):
self.coordinates = (x, y)
self.bearing = bearing
def turn_right(self):
self.bearing += 1
self.bearing %= 4
def turn_left(self):
self.bearing += 3
self.bearing %... | north = 0
east = 1
south = 2
west = 3
class Robot:
def __init__(self, bearing=NORTH, x=0, y=0):
self.coordinates = (x, y)
self.bearing = bearing
def turn_right(self):
self.bearing += 1
self.bearing %= 4
def turn_left(self):
self.bearing += 3
self.bearing %... |
mydict = {'name':'albert','age':28,'city':'Beijing'}
print(mydict)
mydict2 = dict(name='allen',age=26,city='boston')
print(mydict2)
value = mydict['name']
print(value)
mydict['email'] = 'albert@hotmail.com'
print(mydict)
mydict['email'] = 'hello@hotmail.com'
print(mydict)
del mydict['name']
print(mydict)
mydict.p... | mydict = {'name': 'albert', 'age': 28, 'city': 'Beijing'}
print(mydict)
mydict2 = dict(name='allen', age=26, city='boston')
print(mydict2)
value = mydict['name']
print(value)
mydict['email'] = 'albert@hotmail.com'
print(mydict)
mydict['email'] = 'hello@hotmail.com'
print(mydict)
del mydict['name']
print(mydict)
mydict.... |
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
# Following action is not valid for tuples
# tup1[0] = 100
| tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
print('tup1[0]: ', tup1[0])
print('tup2[1:5]: ', tup2[1:5]) |
def validate_name(name):
if name.replace(" ", "").isalpha():
return True
else:
return False
def validate_height_in_cm(height):
if height < 300 and height > 10:
return True
else:
return False
def validate_weigth_in_kg(weight):
if weight < 200 and weight > 0:
... | def validate_name(name):
if name.replace(' ', '').isalpha():
return True
else:
return False
def validate_height_in_cm(height):
if height < 300 and height > 10:
return True
else:
return False
def validate_weigth_in_kg(weight):
if weight < 200 and weight > 0:
... |
fd = open('Sales.txt','a')
fd.write("1111,Ashish,63278648732,1001,5 Star,5,4,20 \n")
fd.close()
| fd = open('Sales.txt', 'a')
fd.write('1111,Ashish,63278648732,1001,5 Star,5,4,20 \n')
fd.close() |
def compact(lst):
return list(filter(bool,lst))
print(compact([0,1,False,True,2,'',3,'a','s',34]))
| def compact(lst):
return list(filter(bool, lst))
print(compact([0, 1, False, True, 2, '', 3, 'a', 's', 34])) |
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
transformations = set()... | class Solution:
def unique_morse_representations(self, words: List[str]) -> int:
morse = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..']
transformations = set()... |
def test_example_silver():
assert 567 == seat_id("BFFFBBFRRR")
assert 119 == seat_id("FFFBBBFRRR")
assert 820 == seat_id("BBFFBBFRLL")
def test_silver():
with open("input.txt") as file:
seats = file.read().split("\n")
assert 842 == max([seat_id(seat) for seat in seats])
def test_gold():... | def test_example_silver():
assert 567 == seat_id('BFFFBBFRRR')
assert 119 == seat_id('FFFBBBFRRR')
assert 820 == seat_id('BBFFBBFRLL')
def test_silver():
with open('input.txt') as file:
seats = file.read().split('\n')
assert 842 == max([seat_id(seat) for seat in seats])
def test_gold():
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def in_order_traverse_2(self, root, last_val) -> bool:
if root.left is None:
last_val.append(root.val)
else:... | class Solution:
def in_order_traverse_2(self, root, last_val) -> bool:
if root.left is None:
last_val.append(root.val)
else:
self.in_order_traverse_2(root.left, last_val)
last_val.append(root.val)
if root.right is None:
pass
else:
... |
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
size = len(s)
dp = [False] * (size + 1)
dp[0] = True
for i in range(1, size + 1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
... | class Solution:
def word_break(self, s: str, wordDict: List[str]) -> bool:
size = len(s)
dp = [False] * (size + 1)
dp[0] = True
for i in range(1, size + 1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
... |
# https://adventofcode.com/2018/day/3
total_overlaps = 0
fabric = {}
with open('./data.txt', 'r') as ffile:
data = ffile.read().strip().split('\n')
for data_row in data:
parts = data_row.split('@')
parts2 = parts[1].split(':')
left, top = parts2[0].split(',')
width, height = par... | total_overlaps = 0
fabric = {}
with open('./data.txt', 'r') as ffile:
data = ffile.read().strip().split('\n')
for data_row in data:
parts = data_row.split('@')
parts2 = parts[1].split(':')
(left, top) = parts2[0].split(',')
(width, height) = parts2[1].split('x')
width = i... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
def TicTacDraw(board):
n=len(board)
d={'0':'O','1':'X','2':' '}
for i in range(n):
s=' '
for j in range(n):
if j == (len(board[i])-1):
s=s+d[str(board[i][j])]
else:
s=s+d[str(board[i][j]... | def tic_tac_draw(board):
n = len(board)
d = {'0': 'O', '1': 'X', '2': ' '}
for i in range(n):
s = ' '
for j in range(n):
if j == len(board[i]) - 1:
s = s + d[str(board[i][j])]
else:
s = s + d[str(board[i][j])] + ' | '
if i == le... |
#import matplotlib.pyplot as plt
# import torch
# from torchvision import datasets, transforms
# import helper
# image = Image.open('new_digit.png')
# image = image.resize((400, 400))
# new_image.save('image_400.jpg')
results = ['a','b']
for ite, (brackets) in results:
print(ite)
print(brackets)
#print(c... | results = ['a', 'b']
for (ite, brackets) in results:
print(ite)
print(brackets) |
CONST_TIMED_ROTATING_FILE_HANDLER = 'TimedRotatingFileHandler'
CONST_SOCKET_HANDLER = 'SocketHandler'
CONST_FILE_HANDLER = 'FileHandler'
CONST_ROTATING_FILE_HANDLER = 'RotatingFileHandler'
CONST_STREAM_HANDLER = 'StreamHandler'
CONST_NULL_HANDLER = 'NullHandler'
CONST_WATCHED_FILE_HANDLER = 'WatchedFileHandler'
CONST_... | const_timed_rotating_file_handler = 'TimedRotatingFileHandler'
const_socket_handler = 'SocketHandler'
const_file_handler = 'FileHandler'
const_rotating_file_handler = 'RotatingFileHandler'
const_stream_handler = 'StreamHandler'
const_null_handler = 'NullHandler'
const_watched_file_handler = 'WatchedFileHandler'
const_d... |
def calc_pos(dna, temp):
n = len(dna)
m = len(temp)
pos = []
for i in range(n-m+1):
if dna[i:i+m] == temp:
pos.append(i+1)
return pos
fin = open('rosalind_subs.txt')
dna = fin.readline().strip()
temp = fin.readline().strip()
pos = calc_pos(dna, temp)
for i in pos:
print (i, end = " ")
print()
fin.close() | def calc_pos(dna, temp):
n = len(dna)
m = len(temp)
pos = []
for i in range(n - m + 1):
if dna[i:i + m] == temp:
pos.append(i + 1)
return pos
fin = open('rosalind_subs.txt')
dna = fin.readline().strip()
temp = fin.readline().strip()
pos = calc_pos(dna, temp)
for i in pos:
pri... |
fitbitSettings = {
'ClientID': '',
'ClientSecret':'',
'CallbackUrl': '',
'OAuthAuthorizeUri':'',
'OAuthAccessRefreshTokenRequestUri': '',
'LoggingApp':'FitbitDataImporter',
'LoggingDirectory':'',
'LogFileName': 'FitbitDataImport.log'
}
fitbitDataConfigSettings = []
HEART_RATE_SETTINGS = ... | fitbit_settings = {'ClientID': '', 'ClientSecret': '', 'CallbackUrl': '', 'OAuthAuthorizeUri': '', 'OAuthAccessRefreshTokenRequestUri': '', 'LoggingApp': 'FitbitDataImporter', 'LoggingDirectory': '', 'LogFileName': 'FitbitDataImport.log'}
fitbit_data_config_settings = []
heart_rate_settings = {'PrefixIndexName': 'fitbi... |
class UserResponse:
_raw_input = ""
_split_input = []
def __init__(self, prompt=""):
# get input with prompt
self._raw_input = input(prompt)
def get_key(self):
if self._raw_input == "":
return None
# if input is not null then slit it by space-characters an... | class Userresponse:
_raw_input = ''
_split_input = []
def __init__(self, prompt=''):
self._raw_input = input(prompt)
def get_key(self):
if self._raw_input == '':
return None
self._split_input = self._raw_input.split()
return self._split_input[0]
def get... |
def getMinimumUniqueSum(arr):
n = len(arr)
arr = sorted(arr)
unique = list(set(arr))
i = 0
if len(arr) != len(unique):
while len(arr) != len(unique):
temp = arr[i]
print(temp)
for j, item in enumerate(unique):
if temp == item:
... | def get_minimum_unique_sum(arr):
n = len(arr)
arr = sorted(arr)
unique = list(set(arr))
i = 0
if len(arr) != len(unique):
while len(arr) != len(unique):
temp = arr[i]
print(temp)
for (j, item) in enumerate(unique):
if temp == item:
... |
# -*- coding: utf-8 -*-
__version__ = "1.0"
__author__ = "Kacper Kowalik"
| __version__ = '1.0'
__author__ = 'Kacper Kowalik' |
# --------------------------------------------------------------------------
# Basic generation of the Fibonacci number sequence written in Python
# link: https://www.mycompiler.io/view/6S2zX4i
# author: milk
# --------------------------------------------------------------------------
# python fibonacci.py # to ... | count = 100
a = 0
b = 0
c = 1
i = 0
while i <= count:
print(c)
a = b
b = c
c = a + b
i += 1 |
MATCHING_TICKETS_KEYS = ['id', 'category', 'status', 'date', 'price_id', 'quantity',
'section', 'row', 'remarks', 'user_id', 'username', 'updated_at']
MATCHING_TICKETS = '''
SELECT src.id, src.category, src.status, src.`date`, src.price_id, src.quantity, src.section, src.row, src.remarks, src.u... | matching_tickets_keys = ['id', 'category', 'status', 'date', 'price_id', 'quantity', 'section', 'row', 'remarks', 'user_id', 'username', 'updated_at']
matching_tickets = '\nSELECT src.id, src.category, src.status, src.`date`, src.price_id, src.quantity, src.section, src.row, src.remarks, src.user_id, src.username, src.... |
description = 'Beam limiter at position 1'
group = 'lowlevel'
display_order = 25
pvprefix = 'SQ:ICON:board1:'
devices = dict(
bl1left = device('nicos_ess.devices.epics.motor.HomingProtectedEpicsMotor',
epicstimeout = 3.0,
description = 'Beam limiter 1 -X',
motorpv = pvprefix + 'B1nX',
... | description = 'Beam limiter at position 1'
group = 'lowlevel'
display_order = 25
pvprefix = 'SQ:ICON:board1:'
devices = dict(bl1left=device('nicos_ess.devices.epics.motor.HomingProtectedEpicsMotor', epicstimeout=3.0, description='Beam limiter 1 -X', motorpv=pvprefix + 'B1nX', errormsgpv=pvprefix + 'B1nX-MsgTxt', precis... |
class Counter:
def __init__(self,low,high):
self.current = low
self.last = high
def __iter__(self):
return self #instead of: return iter("...") - this way 'self' here is set up with 'next' below
def __next__(self): # here we define __next__ because the 'self' returned from the __iter__ above is not an iterat... | class Counter:
def __init__(self, low, high):
self.current = low
self.last = high
def __iter__(self):
return self
def __next__(self):
if self.current < self.last:
num = self.current
self.current += 1
return num
raise StopIteratio... |
test = { 'name': 'q3c',
'points': 2,
'suites': [ { 'cases': [ {'code': '>>> independents_with_ratings.num_rows == 91\nTrue', 'hidden': False, 'locked': False},
{ 'code': ">>> independents_with_ratings.labels == ('Rank', 'Restaurant', 'Sales', 'Average Check', 'City',... | test = {'name': 'q3c', 'points': 2, 'suites': [{'cases': [{'code': '>>> independents_with_ratings.num_rows == 91\nTrue', 'hidden': False, 'locked': False}, {'code': ">>> independents_with_ratings.labels == ('Rank', 'Restaurant', 'Sales', 'Average Check', 'City', 'State', 'Meals Served', 'Rating')\nTrue", 'hidden': Fals... |
def test_assert_false():
assert False, 'The assert should fail' # xfail
def test_assert_passed():
assert True, 'The assert should pass'
| def test_assert_false():
assert False, 'The assert should fail'
def test_assert_passed():
assert True, 'The assert should pass' |
#Dictionary:
Dict={1:'Hi','name': 'Hello',3:'how are you?'}
#accessing a element using key
print(f'Accessing a element using a key: {Dict["name"]}')
#accessing a element using key
print(f'Accessing an element using a key: {Dict[1]}')
#accessing a element using get()
print(f'Accessing an element using get()... | dict = {1: 'Hi', 'name': 'Hello', 3: 'how are you?'}
print(f"Accessing a element using a key: {Dict['name']}")
print(f'Accessing an element using a key: {Dict[1]}')
print(f'Accessing an element using get(): {Dict.get(3)}')
dict = {'Dict1': {1: 'Hey'}, 'Dict2': {1: "What's up?", 2: "Yo, let's party"}}
print(f'Nested Dic... |
class AumbryError(Exception):
def __init__(self, message):
self.message = message
super(AumbryError, self).__init__(message)
class LoadError(AumbryError):
pass
class SaveError(AumbryError):
pass
class ParsingError(AumbryError):
pass
class DependencyError(AumbryError):
def __i... | class Aumbryerror(Exception):
def __init__(self, message):
self.message = message
super(AumbryError, self).__init__(message)
class Loaderror(AumbryError):
pass
class Saveerror(AumbryError):
pass
class Parsingerror(AumbryError):
pass
class Dependencyerror(AumbryError):
def __ini... |
# Creamos un objeto como si fuese JSON
{
# targets son los objetivos donde va a tener que hacer la complilacion, como son mas de uno los ponemos en un array por ahroa un elemento!
"targets": [
{
# le ponemos el nombr que deseemos a nuestro modulo
"target_name" : "addon",
... | {'targets': [{'target_name': 'addon', 'sources': ['hola.cc']}]} |
@kernel
def sample(device, data, samples, wait):
for i in range(samples):
try:
device.sample_mu(data[i])
delay(wait)
except RTIOUnderflow:
continue
@kernel(flags={"fast-math"})
def ramp(board, channels, starts, stops, steps, duration, now):
at_mu(now)
dt ... | @kernel
def sample(device, data, samples, wait):
for i in range(samples):
try:
device.sample_mu(data[i])
delay(wait)
except RTIOUnderflow:
continue
@kernel(flags={'fast-math'})
def ramp(board, channels, starts, stops, steps, duration, now):
at_mu(now)
dt ... |
# Copyright (c) 2018-Present Advanced Micro Devices, Inc. See LICENSE.TXT for terms.
#!/usr/bin/evn python3
# tvals = [8, 16, 32, 64, 128, 256]
# nw_args = {f'-s {s} -t {t}':[] for s in [16384, 32768] for t in tvals}
# lud_args = {f'-s {s} -t {t}':[] for s in [16384, 8192] for t in tvals}
gEnvVars = {
'ATMI_D... | g_env_vars = {'ATMI_DEVICE_GPU_WORKERS': {'full': [1, 4, 8, 16, 24, 32], 'default': [1]}, 'ATMI_DEPENDENCY_SYNC_TYPE': {'full': ['ATMI_SYNC_CALLBACK', 'ATMI_SYNC_BARRIER_PKT'], 'default': ['ATMI_SYNC_CALLBACK']}, 'ATMI_MAX_HSA_SIGNALS': {'full': [32, 64, 128, 256, 512, 1024, 2048, 4096], 'default': [1024]}}
benchmarks ... |
#!/usr/bin/env python3
def fibonacci(n):
fib = [1, 1]
if n <= 2:
return fib
for num in range(2, n):
x = fib[num-1] + fib[num-2]
fib.append(x)
return fib
if __name__ == "__main__":
print(fibonacci(10))
| def fibonacci(n):
fib = [1, 1]
if n <= 2:
return fib
for num in range(2, n):
x = fib[num - 1] + fib[num - 2]
fib.append(x)
return fib
if __name__ == '__main__':
print(fibonacci(10)) |
number = float(input())
intervalos = ["[0,25]", "(25,50]", "(50,75]", "(75,100]"]
if(number < 0 or number > 100):
print("Fora de intervalo")
else:
if(number <= 25):
print("Intervalo", intervalos[0])
else:
if(number <= 50):
print("Intervalo", intervalos[1])
else:
if(number <= 75):
print("Intervalo", i... | number = float(input())
intervalos = ['[0,25]', '(25,50]', '(50,75]', '(75,100]']
if number < 0 or number > 100:
print('Fora de intervalo')
elif number <= 25:
print('Intervalo', intervalos[0])
elif number <= 50:
print('Intervalo', intervalos[1])
elif number <= 75:
print('Intervalo', intervalos[2])
elif ... |
{
"targets": [
{
"target_name": "iow_sht7x",
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"sources": [ "./src/iow_sht7x.cpp", "./src/sht7x.cpp" ],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")",
"./src/",
"/usr... | {'targets': [{'target_name': 'iow_sht7x', 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'sources': ['./src/iow_sht7x.cpp', './src/sht7x.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")', './src/', '/usr/include'], 'defines': ['NAPI_DISABLE_CPP_EXCEPTIONS'], 'link_settings... |
# Default config_dict
default_config_dict = {"MAIN": {}, "GUI": {}, "PLOT": {}}
default_config_dict["MAIN"]["MACHINE_DIR"] = ""
default_config_dict["MAIN"]["MATLIB_DIR"] = ""
default_config_dict["GUI"]["UNIT_M"] = 1 # length unit: 0 for m, 1 for mm
default_config_dict["GUI"]["UNIT_M2"] = 1 # Surface unit: 0 for m^2... | default_config_dict = {'MAIN': {}, 'GUI': {}, 'PLOT': {}}
default_config_dict['MAIN']['MACHINE_DIR'] = ''
default_config_dict['MAIN']['MATLIB_DIR'] = ''
default_config_dict['GUI']['UNIT_M'] = 1
default_config_dict['GUI']['UNIT_M2'] = 1
default_config_dict['PLOT']['COLOR_DICT_NAME'] = 'pyleecan_color.json'
default_confi... |
# 1. --------------------------------------
# 1. 1.1 * radiance = 1.1
# 2. 1.1 - 0.5 = 0.6
# 3. min(randiance, 0.6) = 0.6
# 4. 2.0 + 0.6 = 2.6
# 5. max(2.1, 2.6) = 2.6
# 2. --------------------------------------
radiance = 1.0
radiance = max(2.1, 2.0 + min(radiance, 1.1 * radiance - 0.5))
print(radiance) | radiance = 1.0
radiance = max(2.1, 2.0 + min(radiance, 1.1 * radiance - 0.5))
print(radiance) |
class Solution:
def bubble_sort(self, arr):
bub_flag = 1 # bubbling will occur until finished i.e. until flag not set
while bub_flag == 1:
bub_flag = 0 # reset flag on each pass
for i in range(0, len(arr)-1): # iterate over all elements
j = i+1
if arr[j] < arr[i]: # IF not in ascending order
... | class Solution:
def bubble_sort(self, arr):
bub_flag = 1
while bub_flag == 1:
bub_flag = 0
for i in range(0, len(arr) - 1):
j = i + 1
if arr[j] < arr[i]:
(arr[i], arr[j]) = (arr[j], arr[i])
bub_flag = 1
... |
class Singleton( type ) :
_instances = {}
def __call__( aClass , * aArgs , **kwargs ) :
if aClass not in aClass._instances:
aClass._instances[aClass] = super(Singleton , aClass).__call__(*aArgs , **kwargs)
return aClass._instances[aClass] | class Singleton(type):
_instances = {}
def __call__(aClass, *aArgs, **kwargs):
if aClass not in aClass._instances:
aClass._instances[aClass] = super(Singleton, aClass).__call__(*aArgs, **kwargs)
return aClass._instances[aClass] |
mark = float(input("Inserire voto: "))
if mark < .35:
print("F")
elif mark < .85:
print("D-")
elif mark < 1.15:
print("D")
elif mark < 1.50:
print("D+")
elif mark < 1.85:
print("C-")
elif mark < 2.15:
print("C")
elif mark < 2.50:
print("C+")
elif mark < 2.85:
print("B-")
elif mark < 3.1... | mark = float(input('Inserire voto: '))
if mark < 0.35:
print('F')
elif mark < 0.85:
print('D-')
elif mark < 1.15:
print('D')
elif mark < 1.5:
print('D+')
elif mark < 1.85:
print('C-')
elif mark < 2.15:
print('C')
elif mark < 2.5:
print('C+')
elif mark < 2.85:
print('B-')
elif mark < 3.15... |
class Solution:
def reverseStr(self, s: str, k: int) -> str:
s = list(s)
head = 0
jump = 2*k
while head < len(s):
start, end = head, min(head + k-1, len(s)-1)
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
... | class Solution:
def reverse_str(self, s: str, k: int) -> str:
s = list(s)
head = 0
jump = 2 * k
while head < len(s):
(start, end) = (head, min(head + k - 1, len(s) - 1))
while start < end:
(s[start], s[end]) = (s[end], s[start])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.