content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
indexWords = list()
def PreviousWord(_list, _word):
if _list[_list.index(_word)-1] :
return _list[_list.index(_word)-1]
else:
return
phrase = str(input())
phraseList = phrase.split(" ")
length = len(phraseList)
for item in phraseList :
item = item.strip()
if phrase != "" :
fo... | index_words = list()
def previous_word(_list, _word):
if _list[_list.index(_word) - 1]:
return _list[_list.index(_word) - 1]
else:
return
phrase = str(input())
phrase_list = phrase.split(' ')
length = len(phraseList)
for item in phraseList:
item = item.strip()
if phrase != '':
for i in ... |
city_country = {}
for _ in range(int(input())):
country, *cities = input().split()
for city in cities:
city_country[city] = country
for _ in range(int(input())):
print(city_country[input()]) | city_country = {}
for _ in range(int(input())):
(country, *cities) = input().split()
for city in cities:
city_country[city] = country
for _ in range(int(input())):
print(city_country[input()]) |
nume1 = int(input("Digite um numero"))
nume2 = int(input("Digite um numero"))
nume3 = int(input("Digite um numero"))
nume4 = int(input("Digite um numero"))
nume5 = int(input("Digite um numero"))
table = [nume1,nume2,nume3,nume4,nume5]
tableM = (float((nume1 + nume2 + nume3 + nume4 + nume5)))
print(float(tableM)) | nume1 = int(input('Digite um numero'))
nume2 = int(input('Digite um numero'))
nume3 = int(input('Digite um numero'))
nume4 = int(input('Digite um numero'))
nume5 = int(input('Digite um numero'))
table = [nume1, nume2, nume3, nume4, nume5]
table_m = float(nume1 + nume2 + nume3 + nume4 + nume5)
print(float(tableM)) |
class Solution:
def combinationSum(self, candidates, target):
def lookup(candidates, index, target, combine, result):
if target == 0:
result.append(combine)
return
if index >= len(candidates) and target > 0:
return
... | class Solution:
def combination_sum(self, candidates, target):
def lookup(candidates, index, target, combine, result):
if target == 0:
result.append(combine)
return
if index >= len(candidates) and target > 0:
return
if tar... |
# version of the graw package
__version__ = "0.1.0"
| __version__ = '0.1.0' |
'''
@author Gabriel Flores
Checks the primality of an integer.
'''
def is_prime(x):
'''
Checks the primality of an integer.
'''
sqrt = int(x ** (1/2))
for i in range(2, sqrt, 1):
if x % i == 0:
return False
return True
def main():
try:
print("\n\n")
a = int(input(" Enter an integer to check if ... | """
@author Gabriel Flores
Checks the primality of an integer.
"""
def is_prime(x):
"""
Checks the primality of an integer.
"""
sqrt = int(x ** (1 / 2))
for i in range(2, sqrt, 1):
if x % i == 0:
return False
return True
def main():
try:
print('\n\n')
a = i... |
"""
Created by akiselev on 2019-06-14
There is a horizontal row of cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if is on top of then
.
When stacking the cubes, you can only pick up either the leftmost or the rightmost cube ... | """
Created by akiselev on 2019-06-14
There is a horizontal row of cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if is on top of then
.
When stacking the cubes, you can only pick up either the leftmost or the rightmost cube ... |
def fibonacci_iterative(n):
previous = 0
current = 1
for i in range(n - 1):
current_old = current
current = previous + current
previous = current_old
return current
def fibonacci_recursive(n):
if n == 0 or n == 1:
return n
else:
return fibonacci_recursive... | def fibonacci_iterative(n):
previous = 0
current = 1
for i in range(n - 1):
current_old = current
current = previous + current
previous = current_old
return current
def fibonacci_recursive(n):
if n == 0 or n == 1:
return n
else:
return fibonacci_recursive... |
__all__ = [
'session',
'event',
'profile',
'consent',
'segment',
'source',
'rule',
'entity'
]
| __all__ = ['session', 'event', 'profile', 'consent', 'segment', 'source', 'rule', 'entity'] |
def global_alignment(seq1, seq2, score_matrix, penalty):
len1, len2 = len(seq1), len(seq2)
s = [[0] * (len2 + 1) for i in range(len1 + 1)]
backtrack = [[0] * (len2 + 1) for i in range(len1 + 1)]
for i in range(1, len1 + 1):
s[i][0] = - i * penalty
for j in range(1, len2 + 1):
s[0][j]... | def global_alignment(seq1, seq2, score_matrix, penalty):
(len1, len2) = (len(seq1), len(seq2))
s = [[0] * (len2 + 1) for i in range(len1 + 1)]
backtrack = [[0] * (len2 + 1) for i in range(len1 + 1)]
for i in range(1, len1 + 1):
s[i][0] = -i * penalty
for j in range(1, len2 + 1):
s[0]... |
def main(file: str) -> None:
depth = 0
distance = 0
aim = 0
with open(f"{file}.in") as f:
for line in f.readlines():
line = line.rstrip().split(" ")
command = line[0]
unit = int(line[1])
if command == "forward":
distance += unit
... | def main(file: str) -> None:
depth = 0
distance = 0
aim = 0
with open(f'{file}.in') as f:
for line in f.readlines():
line = line.rstrip().split(' ')
command = line[0]
unit = int(line[1])
if command == 'forward':
distance += unit
... |
# coding=utf8
class MetaSingleton(type):
def __init__(cls, *args):
type.__init__(cls, *args)
cls.instance = None
def __call__(cls, *args, **kwargs):
if not cls.instance:
cls.instance = type.__call__(cls, *args, **kwargs)
return cls.instance
| class Metasingleton(type):
def __init__(cls, *args):
type.__init__(cls, *args)
cls.instance = None
def __call__(cls, *args, **kwargs):
if not cls.instance:
cls.instance = type.__call__(cls, *args, **kwargs)
return cls.instance |
how_many_snakes = 1
snake_string = """
Welcome to Python3!
____
/ . .\\
\\ ---<
\\ /
__________/ /
-=:___________/
<3, Juno
"""
print(snake_string * how_many_snakes) | how_many_snakes = 1
snake_string = '\nWelcome to Python3!\n\n ____\n / . .\\\n \\ ---<\n \\ /\n __________/ /\n-=:___________/\n\n<3, Juno\n'
print(snake_string * how_many_snakes) |
class Person:
olhos = 2
def __init__(self, *children, name=None, year=0):
self.year = year
self.name = name
self.children = list(children)
def cumprimentar(self):
return 'Hello'
@staticmethod
def metodo_estatico():
return 123
@classmethod
def metod... | class Person:
olhos = 2
def __init__(self, *children, name=None, year=0):
self.year = year
self.name = name
self.children = list(children)
def cumprimentar(self):
return 'Hello'
@staticmethod
def metodo_estatico():
return 123
@classmethod
def metod... |
class Animal:
def __init__(self):
self.name = ""
self.weight = 0
self.sound = ""
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setWeight(self, weight):
self.weight = weight
def getWeight(self):
return sel... | class Animal:
def __init__(self):
self.name = ''
self.weight = 0
self.sound = ''
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def set_weight(self, weight):
self.weight = weight
def get_weight(self):
retur... |
#!/usr/bin/python3
lines = open("inputs/07.in", "r").readlines()
for i,line in enumerate(lines):
lines[i] = line.split("\n")[0]
l = lines.copy();
wires = {}
def func_set(p, i):
if p[0].isdigit():
wires[p[2]] = int(p[0])
lines.pop(i)
elif p[0] in wires.keys():
wires[p[2]] = wires[p... | lines = open('inputs/07.in', 'r').readlines()
for (i, line) in enumerate(lines):
lines[i] = line.split('\n')[0]
l = lines.copy()
wires = {}
def func_set(p, i):
if p[0].isdigit():
wires[p[2]] = int(p[0])
lines.pop(i)
elif p[0] in wires.keys():
wires[p[2]] = wires[p[0]]
lines.... |
#Variables
#Working with build 2234
saberPort = "/dev/ttyUSB0"
#Initializing Motorcontroller
saber = Runtime.start("saber", "Sabertooth")
saber.connect(saberPort)
sleep(1)
#Initializing Joystick
joystick = Runtime.start("joystick","Joystick")
print(joystick.getControllers())
python.subscribe("joystick","publishJoysti... | saber_port = '/dev/ttyUSB0'
saber = Runtime.start('saber', 'Sabertooth')
saber.connect(saberPort)
sleep(1)
joystick = Runtime.start('joystick', 'Joystick')
print(joystick.getControllers())
python.subscribe('joystick', 'publishJoystickInput')
joystick.setController(0)
for x in range(0, 100):
print('power', x)
sa... |
# Author: Guilherme Aldeia
# Contact: guilherme.aldeia@ufabc.edu.br
# Version: 1.0.0
# Last modified: 08-20-2021 by Guilherme Aldeia
"""
Simple exception that is raised by explainers when they don't support local
or global explanations, or when they are not model agnostic. This should be
catched and handled i... | """
Simple exception that is raised by explainers when they don't support local
or global explanations, or when they are not model agnostic. This should be
catched and handled in the experiments.
"""
class Notapplicableexception(Exception):
def __init__(self, message=''):
self.message = message |
# ASSIGNMENT 3
"""
During a programming contest, each contestant had to solve 3 problems (named P1, P2 and P3).
Afterwards, an evaluation committee graded the solutions to each of the problems using integers between 0 and 10.
The committee needs a program that will allow managing the list of scores and esta... | """
During a programming contest, each contestant had to solve 3 problems (named P1, P2 and P3).
Afterwards, an evaluation committee graded the solutions to each of the problems using integers between 0 and 10.
The committee needs a program that will allow managing the list of scores and establishing the wi... |
#===============================================================================
# Copyright 2020-2021 Intel Corporation
#
# 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.apa... | load('@onedal//dev/bazel:repos.bzl', 'repos')
micromkl_repo = repos.prebuilt_libs_repo_rule(includes=['include', '%{os}/include'], libs=['%{os}/lib/intel64/libdaal_mkl_thread.a', '%{os}/lib/intel64/libdaal_mkl_sequential.a', '%{os}/lib/intel64/libdaal_vmlipp_core.a'], build_template='@onedal//dev/bazel/deps:micromkl.tp... |
guests=int(input())
reservations=set([])
while guests!=0:
reservationCode=input()
reservations.add(reservationCode)
guests-=1
while True:
r=input()
if r!="END":
reservations.discard(r)
else:
print(len(reservations))
VIPS=[]; Regulars=[]
for e in reservations:
... | guests = int(input())
reservations = set([])
while guests != 0:
reservation_code = input()
reservations.add(reservationCode)
guests -= 1
while True:
r = input()
if r != 'END':
reservations.discard(r)
else:
print(len(reservations))
vips = []
regulars = []
f... |
class TestClass:
def __init__(self, list, name):
self.list = list
self.name = name
def func1():
print("func1 print something")
def func2():
print("func2 print something")
integer = 8
return integer
def func3():
print("func3 print something")
s = "func3"
return s
def f... | class Testclass:
def __init__(self, list, name):
self.list = list
self.name = name
def func1():
print('func1 print something')
def func2():
print('func2 print something')
integer = 8
return integer
def func3():
print('func3 print something')
s = 'func3'
return s
def ... |
# // ###########################################################################
# // Queries
# // ###########################################################################
# -> get a single cell of a df (use `iloc` with `row` + `col` as arguments)
df.iloc[0]['staticContextId']
# -> get one column as a list
allFunc... | df.iloc[0]['staticContextId']
all_function_names = staticContexts[['displayName']].to_numpy().flatten().tolist()
call_linked = staticTraces[~staticTraces['callId'].isin([0])]
df.drop(['A', 'B'], axis=1)
staticTraces.query(f'callId == {callId} or resultCallId == {callId}')
df.set_index('key').join(other.set_index('key')... |
"""Module to help guess whether a file is binary or text.
Requirements:
Python 2.7+
Recommended:
Python 3
"""
def is_binary_file(fname):
"""Attempt to guess if 'fname' is a binary file heuristically.
This algorithm has many flaws. Use with caution.
It assumes that if a part of the file has NUL b... | """Module to help guess whether a file is binary or text.
Requirements:
Python 2.7+
Recommended:
Python 3
"""
def is_binary_file(fname):
"""Attempt to guess if 'fname' is a binary file heuristically.
This algorithm has many flaws. Use with caution.
It assumes that if a part of the file has NUL b... |
def climbingLeaderboard(ranked, player):
ranked = sorted(list(set(ranked)), reverse=True)
ranks = []
# print(ranked)
for i in range(len(player)):
bi = 0
bs = len(ranked) - 1
index = 0
while (bi <= bs):
mid = (bi+bs) // 2
if (ranked[mid] > player... | def climbing_leaderboard(ranked, player):
ranked = sorted(list(set(ranked)), reverse=True)
ranks = []
for i in range(len(player)):
bi = 0
bs = len(ranked) - 1
index = 0
while bi <= bs:
mid = (bi + bs) // 2
if ranked[mid] > player[i]:
in... |
class Auth():
def __init__(self, client):
self.client = client
def get_profiles(self):
return self.client.get('/auth/api/profiles/', {'page_size': 10000})['results']
def get_groups(self):
return self.client.get('/auth/api/groups/')
def get_group_map(self):
return {gro... | class Auth:
def __init__(self, client):
self.client = client
def get_profiles(self):
return self.client.get('/auth/api/profiles/', {'page_size': 10000})['results']
def get_groups(self):
return self.client.get('/auth/api/groups/')
def get_group_map(self):
return {group... |
input = """
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in
"""
def validate(passpor... | input = '\necl:gry pid:860033327 eyr:2020 hcl:#fffffd\nbyr:1937 iyr:2017 cid:147 hgt:183cm\n\niyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884\nhcl:#cfa07d byr:1929\n\nhcl:#ae17e1 iyr:2013\neyr:2024\necl:brn pid:760753108 byr:1931\nhgt:179cm\n\nhcl:#cfa07d eyr:2025 pid:166559648\niyr:2011 ecl:brn hgt:59in\n'
def valida... |
class Solution:
def kthFactor(self, n: int, k: int) -> int:
s1 = set()
s2 = set()
for i in range(1,int(n**0.5)+1):
if n%i ==0:
s1.add(i)
s2.add(int(n/i))
l = list(s1|s2)
l.sort()
if k > len(l):
return -1
... | class Solution:
def kth_factor(self, n: int, k: int) -> int:
s1 = set()
s2 = set()
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
s1.add(i)
s2.add(int(n / i))
l = list(s1 | s2)
l.sort()
if k > len(l):
retu... |
class Node(object): # Similar to Linked List initial set-up
def __init__(self, value): # Constructor
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def print_tree(self, traversal_type):
... | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Binarytree(object):
def __init__(self, root):
self.root = node(root)
def print_tree(self, traversal_type):
if traversal_type == 'preorder':
retur... |
# _*_ coding: utf-8 _*_
"""
util_config.py by xianhu
"""
__all__ = [
"CONFIG_FETCH_MESSAGE",
"CONFIG_PARSE_MESSAGE",
"CONFIG_MESSAGE_PATTERN",
"CONFIG_URL_LEGAL_PATTERN",
"CONFIG_URL_ILLEGAL_PATTERN",
]
# define the structure of message, used in Fetcher and Parser
CONFIG_FETCH_MESSAGE = "priority... | """
util_config.py by xianhu
"""
__all__ = ['CONFIG_FETCH_MESSAGE', 'CONFIG_PARSE_MESSAGE', 'CONFIG_MESSAGE_PATTERN', 'CONFIG_URL_LEGAL_PATTERN', 'CONFIG_URL_ILLEGAL_PATTERN']
config_fetch_message = 'priority=%s, keys=%s, deep=%s, repeat=%s, url=%s'
config_parse_message = 'priority=%s, keys=%s, deep=%s, url=%s'
config_... |
__title__ = 'The Onion Box'
__description__ = 'Dashboard to monitor Tor node operations.'
__version__ = '20.2'
__stamp__ = '20200119|095654'
| __title__ = 'The Onion Box'
__description__ = 'Dashboard to monitor Tor node operations.'
__version__ = '20.2'
__stamp__ = '20200119|095654' |
# This is the word list from where the answers for the hangman game will come from.
word_list = [
2015,
"Fred Swaniker",
"Rwanda and Mauritius",
2,
"Dr, Gaidi Faraj",
"Sila Ogidi",
"Madagascar",
94,
8,
"Mauritius"
]
# Here we are defining the variables 'Right'(for ... | word_list = [2015, 'Fred Swaniker', 'Rwanda and Mauritius', 2, 'Dr, Gaidi Faraj', 'Sila Ogidi', 'Madagascar', 94, 8, 'Mauritius']
right = 0
tries = 0
def greet(name):
print('Hello ' + name + ' welcome to hangman and good luck!')
user_name = input('What is your name?')
greet(user_name)
def alu(guess):
if guess... |
OS_MA_NFVO_IP = '192.168.1.197'
OS_USER_DOMAIN_NAME = 'Default'
OS_USERNAME = 'admin'
OS_PASSWORD = '0000'
OS_PROJECT_DOMAIN_NAME = 'Default'
OS_PROJECT_NAME = 'admin' | os_ma_nfvo_ip = '192.168.1.197'
os_user_domain_name = 'Default'
os_username = 'admin'
os_password = '0000'
os_project_domain_name = 'Default'
os_project_name = 'admin' |
# Copyright 2016 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | _pub_uri = 'https://storage.googleapis.com/pub.dartlang.org/packages'
'A set of BUILD rules that facilitate using or building on "pub".'
def _pub_repository_impl(repository_ctx):
package = repository_ctx.attr.package
version = repository_ctx.attr.version
repository_ctx.download_and_extract('%s/%s-%s.tar.gz... |
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
if len(nums) < 1:
raise Exception("Invalid Array")
n = len(nums)
res = []
s = set()
for x in nums:
s.add(x)
for i in range(1, n + 1):
if i not in s:
... | class Solution:
def find_disappeared_numbers(self, nums: List[int]) -> List[int]:
if len(nums) < 1:
raise exception('Invalid Array')
n = len(nums)
res = []
s = set()
for x in nums:
s.add(x)
for i in range(1, n + 1):
if i not in s:
... |
'''
03 - Multiple arguments
In the previous exercise, the square brackets around imag in the documentation showed us that the
imag argument is optional. But Python also uses a different way to tell users about arguments being
optional.
Have a look at the documentation of sorted() by typing help(sorted) in the IPython... | """
03 - Multiple arguments
In the previous exercise, the square brackets around imag in the documentation showed us that the
imag argument is optional. But Python also uses a different way to tell users about arguments being
optional.
Have a look at the documentation of sorted() by typing help(sorted) in the IPython... |
parameters = {}
genome = {}
genome_stats = {}
genome_test_stats = []
brain = {}
cortical_list = []
cortical_map = {}
intercortical_mapping = []
block_dic = {}
upstream_neurons = {}
memory_list = {}
activity_stats = {}
temp_neuron_list = []
original_genome_id = []
fire_list = []
termination_flag = False
variation_counte... | parameters = {}
genome = {}
genome_stats = {}
genome_test_stats = []
brain = {}
cortical_list = []
cortical_map = {}
intercortical_mapping = []
block_dic = {}
upstream_neurons = {}
memory_list = {}
activity_stats = {}
temp_neuron_list = []
original_genome_id = []
fire_list = []
termination_flag = False
variation_counte... |
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton' , 'Andrew Ng' , 'Sebastian Raschka' , 'Yoshua Bengio']
class_2 = ['Hilary Mason' , 'Carla Gentry' , 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
del new_class[5]
print(new_class)
# Code... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
del new_class[5]
print(new_class)
courses = {'Math': 65, 'English': 70, 'History'... |
n = int(input().strip())
items = [
int(A_temp)
for A_temp
in input().strip().split(' ')
]
items_map = {}
result = None
for i, item in enumerate(items):
if item not in items_map:
items_map[item] = [i]
else:
items_map[item].append(i)
for _, item_indexes in items_map.items():
it... | n = int(input().strip())
items = [int(A_temp) for a_temp in input().strip().split(' ')]
items_map = {}
result = None
for (i, item) in enumerate(items):
if item not in items_map:
items_map[item] = [i]
else:
items_map[item].append(i)
for (_, item_indexes) in items_map.items():
items_indexes_le... |
"""A Queryset slicer for Django."""
def slice_queryset(queryset, chunk_size):
"""Slice a queryset into chunks."""
start_pk = 0
queryset = queryset.order_by('pk')
while True:
# No entry left
if not queryset.filter(pk__gt=start_pk).exists():
break
try:
#... | """A Queryset slicer for Django."""
def slice_queryset(queryset, chunk_size):
"""Slice a queryset into chunks."""
start_pk = 0
queryset = queryset.order_by('pk')
while True:
if not queryset.filter(pk__gt=start_pk).exists():
break
try:
end_pk = queryset.filter(pk_... |
def compareMetaboliteDicts(d1, d2):
sorted_d1_keys = sorted(d1.keys())
sorted_d2_keys = sorted(d2.keys())
for i in range(len(sorted_d1_keys)):
if not compareMetabolites(sorted_d1_keys[i], sorted_d2_keys[i], naive=True):
return False
elif not d1[sorted_d1_keys[i]] == d2[sorted_... | def compare_metabolite_dicts(d1, d2):
sorted_d1_keys = sorted(d1.keys())
sorted_d2_keys = sorted(d2.keys())
for i in range(len(sorted_d1_keys)):
if not compare_metabolites(sorted_d1_keys[i], sorted_d2_keys[i], naive=True):
return False
elif not d1[sorted_d1_keys[i]] == d2[sorted_... |
class Session(list):
"""Abstract Session class"""
def to_strings(self, user_id, session_id):
"""represent session as list of strings (one per event)"""
user_id, session_id = str(user_id), str(session_id)
session_type = self.get_type()
strings = []
for event, product in s... | class Session(list):
"""Abstract Session class"""
def to_strings(self, user_id, session_id):
"""represent session as list of strings (one per event)"""
(user_id, session_id) = (str(user_id), str(session_id))
session_type = self.get_type()
strings = []
for (event, product... |
"""Recursive implementations."""
def find_max(A):
"""invoke recursive function to find maximum value in A."""
def rmax(lo, hi):
"""Use recursion to find maximum value in A[lo:hi+1]."""
if lo == hi: return A[lo]
mid = (lo+hi) // 2
L = rmax(lo, mid)
R = rmax(mid+1, hi)
... | """Recursive implementations."""
def find_max(A):
"""invoke recursive function to find maximum value in A."""
def rmax(lo, hi):
"""Use recursion to find maximum value in A[lo:hi+1]."""
if lo == hi:
return A[lo]
mid = (lo + hi) // 2
l = rmax(lo, mid)
r = rmax... |
"""ssb-pseudonymization - Data pseudonymization functions used by SSB"""
__version__ = '0.0.2'
__author__ = 'Statistics Norway (ssb.no)'
__all__ = []
| """ssb-pseudonymization - Data pseudonymization functions used by SSB"""
__version__ = '0.0.2'
__author__ = 'Statistics Norway (ssb.no)'
__all__ = [] |
problem_type = "segmentation"
dataset_name = "synthia_rand_cityscapes"
dataset_name2 = None
perc_mb2 = None
model_name = "resnetFCN"
freeze_layers_from = None
show_model = False
load_imageNet = True
load_pretrained = False
weights_file = "weights.hdf5"
train_model = True
test_model = True
pred_model = False
debug = Tru... | problem_type = 'segmentation'
dataset_name = 'synthia_rand_cityscapes'
dataset_name2 = None
perc_mb2 = None
model_name = 'resnetFCN'
freeze_layers_from = None
show_model = False
load_image_net = True
load_pretrained = False
weights_file = 'weights.hdf5'
train_model = True
test_model = True
pred_model = False
debug = Tr... |
{
"targets": [
{
"target_name": "cclust",
"sources": [ "./src/heatmap_clustering_js_module.cpp" ],
'dependencies': ['bonsaiclust']
},
{
'target_name': 'bonsaiclust',
'type': 'static_library',
'sources': [ 'src/cluster.c' ],
'cflags': ['-fPIC', '-I', '-pedantic', '... | {'targets': [{'target_name': 'cclust', 'sources': ['./src/heatmap_clustering_js_module.cpp'], 'dependencies': ['bonsaiclust']}, {'target_name': 'bonsaiclust', 'type': 'static_library', 'sources': ['src/cluster.c'], 'cflags': ['-fPIC', '-I', '-pedantic', '-Wall']}]} |
#!/usr/bin/env python3.8
table="".maketrans("0123456789","\N{Devanagari digit zero}\N{Devanagari digit one}"
"\N{Devanagari digit two}\N{Devanagari digit three}"
"\N{Devanagari digit four}\N{Devanagari digit five}"
"\N{Devanagari digit six}\N{Devanagari digit seven}"
"\N{Devanagari digit eight}\N{Devanagari digit nine... | table = ''.maketrans('0123456789', '०१२३४५६७८९')
print('0123456789'.translate(table)) |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class AzureCloudCredentials(object):
"""Implementation of the 'AzureCloudCredentials' model.
Specifies the cloud credentials to connect to a Microsoft
Azure service account.
Attributes:
storage_access_key (string): Specifies the access ... | class Azurecloudcredentials(object):
"""Implementation of the 'AzureCloudCredentials' model.
Specifies the cloud credentials to connect to a Microsoft
Azure service account.
Attributes:
storage_access_key (string): Specifies the access key to use when
accessing a storage tier in a ... |
__author__ = 'Riccardo Frigerio'
'''
Oggetto HOST
Attributi:
- mac_address: indirizzo MAC
- port: porta a cui e' collegato
- dpid: switch a cui e' collegato
'''
class Host(object):
def __init__(self, mac_address, port, dpid):
self.mac_address = mac_address
self.port = port
self.dpid = dpi... | __author__ = 'Riccardo Frigerio'
"\nOggetto HOST\nAttributi:\n- mac_address: indirizzo MAC\n- port: porta a cui e' collegato\n- dpid: switch a cui e' collegato\n"
class Host(object):
def __init__(self, mac_address, port, dpid):
self.mac_address = mac_address
self.port = port
self.dpid = dp... |
"""
Write a function with a list of ints as a paramter. /
Return True if any two nums sum to 0. /
>>> add_to_zero([]) /
False /
>>> add_to_zero([1]) /
False /
>>> add_to_zero([1, 2, 3]) /
False /
>>> add_to_zero([1, 2, 3, -2]) /
True /
"""
| """
Write a function with a list of ints as a paramter. /
Return True if any two nums sum to 0. /
>>> add_to_zero([]) /
False /
>>> add_to_zero([1]) /
False /
>>> add_to_zero([1, 2, 3]) /
False /
>>> add_to_zero([1, 2, 3, -2]) /
True /
""" |
# nested loops = The "inner loop" will finish all of it's iterations before
# finishing one iteration of the "outer loop"
rows = int(input("How many rows?: "))
columns = int(input("How many columns?: "))
symbol = input("Enter a symbol to use: ")
#symbol = int(input("Enter a symbol to use: "))
for i in... | rows = int(input('How many rows?: '))
columns = int(input('How many columns?: '))
symbol = input('Enter a symbol to use: ')
for i in range(rows):
for j in range(columns):
print(symbol, end='')
print() |
# -*- coding: utf-8 -*-
"""Top-level package for Music Downloader Telegram Bot."""
# version as tuple for simple comparisons
VERSION = (0, 9, 16)
__author__ = """George Pchelkin"""
__email__ = 'george@pchelk.in'
# string created from tuple to avoid inconsistency
__version__ = ".".join([str(x) for x in VERSION])
| """Top-level package for Music Downloader Telegram Bot."""
version = (0, 9, 16)
__author__ = 'George Pchelkin'
__email__ = 'george@pchelk.in'
__version__ = '.'.join([str(x) for x in VERSION]) |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py'
]
cudnn_benchmark = True
norm_cfg = dict(type='BN', requires_grad=True)
checkpoint = 'https://download.openmmlab.com/mmclassification/v0/efficientnet/efficientnet-b3_3rdparty_8xb32-aa_in1k... | _base_ = ['../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py']
cudnn_benchmark = True
norm_cfg = dict(type='BN', requires_grad=True)
checkpoint = 'https://download.openmmlab.com/mmclassification/v0/efficientnet/efficientnet-b3_3rdparty_8xb32-aa_in1k_20220119-5... |
'''
1. Write a Python program to access a specific item in a singly linked list using index value.
2. Write a Python program to set a new value of an item in a singly linked list using index value.
3. Write a Python program to delete the first item from a singly linked list.
'''
| """
1. Write a Python program to access a specific item in a singly linked list using index value.
2. Write a Python program to set a new value of an item in a singly linked list using index value.
3. Write a Python program to delete the first item from a singly linked list.
""" |
"""
.. module:: aws_utilities_cli.iam
:platform: OS X
:synopsis: Small collection of utilities that
use the Amazon Web Services (AWS) SDK
.. moduleauthor:: dataday
"""
__all__ = ['generate_identity', 'generate_policy']
| """
.. module:: aws_utilities_cli.iam
:platform: OS X
:synopsis: Small collection of utilities that
use the Amazon Web Services (AWS) SDK
.. moduleauthor:: dataday
"""
__all__ = ['generate_identity', 'generate_policy'] |
class Node:
left = right = None
def __init__(self, data):
self.data = data
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, end=' ')
inorder(root.right)
def insert(root, key):
if root is None:
return Node(key)
if key < root.data:
... | class Node:
left = right = None
def __init__(self, data):
self.data = data
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, end=' ')
inorder(root.right)
def insert(root, key):
if root is None:
return node(key)
if key < root.data:
... |
class NoMessageRecipients(Exception):
"""
Raised when Message Recipients are not specified.
"""
pass
class InvalidAmount(Exception):
"""
Raised when an invalid currency amount is specified
"""
pass
| class Nomessagerecipients(Exception):
"""
Raised when Message Recipients are not specified.
"""
pass
class Invalidamount(Exception):
"""
Raised when an invalid currency amount is specified
"""
pass |
def something() -> None:
print("Andrew says: `something`.")
| def something() -> None:
print('Andrew says: `something`.') |
blacklist=set()
def get_blacklist():
return blacklist
def add_to_blacklist(jti):
return blacklist.add(jti)
| blacklist = set()
def get_blacklist():
return blacklist
def add_to_blacklist(jti):
return blacklist.add(jti) |
#unit
#mydict.py
class Dict(dict):
def __init__(self,**kw):
super(Dict,self).__init__(**kw)
def __getattr__(self,key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object han no attribute'%s'" %key)
def __setattr__(self,key,value):
self[key]=value
| class Dict(dict):
def __init__(self, **kw):
super(Dict, self).__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise attribute_error("'Dict' object han no attribute'%s'" % key)
def __setattr__(self, key, value):
self... |
"""Translates validation error messages for the response"""
messages = {
'accepted': 'The :field: must be accepted.',
'after': 'The :field: must be a date after :other:.',
'alpha': 'The :field: may contain only letters.',
'alpha_dash': 'The :field: may only contain letters, numbers, and dashes.',
... | """Translates validation error messages for the response"""
messages = {'accepted': 'The :field: must be accepted.', 'after': 'The :field: must be a date after :other:.', 'alpha': 'The :field: may contain only letters.', 'alpha_dash': 'The :field: may only contain letters, numbers, and dashes.', 'alpha_num': 'The :fiel... |
"""
Commom settings to all applications
"""
A = 40.3
TECU = 1.0e16
C = 299792458
F1 = 1.57542e9
F2 = 1.22760e9
factor_1 = (F1 - F2) / (F1 + F2) / C
factor_2 = (F1 * F2) / (F2 - F1) / C
DIFF_TEC_MAX = 0.05
LIMIT_STD = 7.5
plot_it = True
REQUIRED_VERSION = 3.01
CONSTELLATIONS = ['G', 'R']
COLUMNS_IN_RINEX = {'3.03': ... | """
Commom settings to all applications
"""
a = 40.3
tecu = 1e+16
c = 299792458
f1 = 1575420000.0
f2 = 1227600000.0
factor_1 = (F1 - F2) / (F1 + F2) / C
factor_2 = F1 * F2 / (F2 - F1) / C
diff_tec_max = 0.05
limit_std = 7.5
plot_it = True
required_version = 3.01
constellations = ['G', 'R']
columns_in_rinex = {'3.03': {... |
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dict_1 = {}
for i in s:
if i not in dict_1:
dict_1[i] = 1
else:
dict_1[i] += 1
print(dict_1)
... | class Solution(object):
def first_uniq_char(self, s):
"""
:type s: str
:rtype: int
"""
dict_1 = {}
for i in s:
if i not in dict_1:
dict_1[i] = 1
else:
dict_1[i] += 1
print(dict_1)
for (idx, val) ... |
#
# This is Seisflows
#
# See LICENCE file
#
###############################################################################
raise NotImplementedError
| raise NotImplementedError |
# -*- coding: utf-8 -*-
"""
awsecommerceservice
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class ItemLookupRequest(object):
"""Implementation of the 'ItemLookupRequest' model.
TODO: type model description here.
Attributes:
condition (ConditionE... | """
awsecommerceservice
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Itemlookuprequest(object):
"""Implementation of the 'ItemLookupRequest' model.
TODO: type model description here.
Attributes:
condition (ConditionEnum): TODO: type descriptio... |
#Integer division
#You have a shop selling buns for $2.40 each. A customer comes in with $15, and would like to buy as many buns as possible.
#Complete the code to calculate how many buns the customer can afford.
#Note: Your customer won't be happy if you try to sell them part of a bun.
#Print only the result, any o... | bun_price = 2.4
money = 15
print(money // bun_price) |
# An algorithm to reconstruct the queue.
# Suppose you have a random list of people standing in a queue.
# Each person is described by a pair of integers (h,k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h.
class Solution:
de... | class Solution:
def reconstruct_queue(self, people: List[List[int]]) -> List[List[int]]:
people = sorted(people, key=lambda x: (-x[0], x[1]))
ans = []
for pep in people:
ans.insert(pep[1], pep)
return ans |
# statements that used at the start of defenition or in statements without columns
defenition_statements = {
"DROP": "DROP",
"CREATE": "CREATE",
"TABLE": "TABLE",
"DATABASE": "DATABASE",
"SCHEMA": "SCHEMA",
"ALTER": "ALTER",
"TYPE": "TYPE",
"DOMAIN": "DOMAIN",
"REPLACE": "REPLACE",
... | defenition_statements = {'DROP': 'DROP', 'CREATE': 'CREATE', 'TABLE': 'TABLE', 'DATABASE': 'DATABASE', 'SCHEMA': 'SCHEMA', 'ALTER': 'ALTER', 'TYPE': 'TYPE', 'DOMAIN': 'DOMAIN', 'REPLACE': 'REPLACE', 'OR': 'OR', 'CLUSTERED': 'CLUSTERED', 'SEQUENCE': 'SEQUENCE', 'TABLESPACE': 'TABLESPACE'}
common_statements = {'INDEX': '... |
def kmp(P, T):
# Compute the start position (number of chars) of the longest suffix that matches a prefix,
# and store them into list K, the first element of K is set to be -1, the second
#
K = [] # K[t] store the value that when mismatch happens at t, should move Pattern P K[t] characters ahead
t ... | def kmp(P, T):
k = []
t = -1
K.append(t)
for k in range(1, len(P) + 1):
while t >= 0 and P[t] != P[k - 1]:
t = K[t]
t = t + 1
K.append(t)
print(K)
m = 0
for i in range(0, len(T)):
while m >= 0 and P[m] != T[i]:
m = K[m]
m = m + ... |
class _FuncStorage:
def __init__(self):
self._function_map = {}
def insert_function(self, name, function):
self._function_map[name] = function
def get_all_functions(self):
return self._function_map
| class _Funcstorage:
def __init__(self):
self._function_map = {}
def insert_function(self, name, function):
self._function_map[name] = function
def get_all_functions(self):
return self._function_map |
A=int(input("dame int"))
B=int(input("dame int"))
if(A>B):
print("A es mayor")
else:
print("B es mayor")
| a = int(input('dame int'))
b = int(input('dame int'))
if A > B:
print('A es mayor')
else:
print('B es mayor') |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-03-15 00:07:14
# Description:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = set()
for i in range(0, len(nums) - 1):
# Reduce the problem to two sum(0)
two_sum =... | class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
result = set()
for i in range(0, len(nums) - 1):
two_sum = -nums[i]
cache = set()
for num in nums[i + 1:]:
remaining = two_sum - num
if remaining in cache:
... |
bluelabs_format_hints = {
'field-delimiter': ',',
'record-terminator': "\n",
'compression': 'GZIP',
'quoting': None,
'quotechar': '"',
'doublequote': False,
'escape': '\\',
'encoding': 'UTF8',
'dateformat': 'YYYY-MM-DD',
'timeonlyformat': 'HH24:MI:SS',
'datetimeformattz': 'YY... | bluelabs_format_hints = {'field-delimiter': ',', 'record-terminator': '\n', 'compression': 'GZIP', 'quoting': None, 'quotechar': '"', 'doublequote': False, 'escape': '\\', 'encoding': 'UTF8', 'dateformat': 'YYYY-MM-DD', 'timeonlyformat': 'HH24:MI:SS', 'datetimeformattz': 'YYYY-MM-DD HH:MI:SSOF', 'datetimeformat': 'YYYY... |
# FROM THE OP PAPER-ISH
MINI_BATCH_SIZE = 32
MEMORY_SIZE = 10**6
BUFFER_SIZE = 100
LHIST = 4
GAMMA = 0.99
UPDATE_FREQ_ONlINE = 4
UPDATE_TARGET = 2500 # This was 10**4 but is measured in actor steps, so it's divided update_freq_online
TEST_FREQ = 5*10**4 # Measure in updates
TEST_STEPS = 10**4
LEARNING_RATE = 0.00025
G_... | mini_batch_size = 32
memory_size = 10 ** 6
buffer_size = 100
lhist = 4
gamma = 0.99
update_freq_o_nl_ine = 4
update_target = 2500
test_freq = 5 * 10 ** 4
test_steps = 10 ** 4
learning_rate = 0.00025
g_momentum = 0.95
epsilon_init = 1.0
epsilon_final = 0.1
epsilon_test = 0.05
epsilon_life = 10 ** 6
replay_start = 5 * 10... |
# author: jamie
# email: jinjiedeng.jjd@gmail.com
def Priority (c):
if c == '&': return 3
elif c == '|': return 2
elif c == '^': return 1
elif c == '(': return 0
def InfixToPostfix (infix, postfix):
stack = []
for c in infix:
if c == '(':
stack.append('(')
elif c =... | def priority(c):
if c == '&':
return 3
elif c == '|':
return 2
elif c == '^':
return 1
elif c == '(':
return 0
def infix_to_postfix(infix, postfix):
stack = []
for c in infix:
if c == '(':
stack.append('(')
elif c == ')':
w... |
__version__ = 'unknown'
try:
__version__ = __import__('pkg_resources').get_distribution('django_richenum').version
except Exception as e:
pass
| __version__ = 'unknown'
try:
__version__ = __import__('pkg_resources').get_distribution('django_richenum').version
except Exception as e:
pass |
CHARACTERS_PER_LINE = 39
def break_lines(text):
chars_in_line = 1
final_text = ''
skip = False
for char in text:
if chars_in_line >= CHARACTERS_PER_LINE:
if char == ' ':
# we happen to be on a space, se we can just break here
final_text += '\n'
... | characters_per_line = 39
def break_lines(text):
chars_in_line = 1
final_text = ''
skip = False
for char in text:
if chars_in_line >= CHARACTERS_PER_LINE:
if char == ' ':
final_text += '\n'
skip = True
else:
for i in range(l... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
nums = []
while head:
nums.append(head.val)
head = head.next
... | class Solution:
def next_larger_nodes(self, head: ListNode) -> List[int]:
nums = []
while head:
nums.append(head.val)
head = head.next
stack = []
res = [0] * len(nums)
for (i, n) in enumerate(nums):
while stack and nums[stack[-1]] < n:
... |
def is_field(token):
"""Checks if the token is a valid ogc type field
"""
return token in ["name", "description", "encodingType", "location", "properties", "metadata",
"definition", "phenomenonTime", "resultTime", "observedArea", "result", "id", "@iot.id",
"resultQ... | def is_field(token):
"""Checks if the token is a valid ogc type field
"""
return token in ['name', 'description', 'encodingType', 'location', 'properties', 'metadata', 'definition', 'phenomenonTime', 'resultTime', 'observedArea', 'result', 'id', '@iot.id', 'resultQuality', 'validTime', 'time', 'parameters',... |
"""Exception utilities."""
class ParsingException(Exception):
pass
class EnvVariableNotSet(Exception):
def __init__(self, varname: str) -> None:
super(EnvVariableNotSet, self).__init__(f"Env variable [{varname}] not set.")
class InvalidLineUp(Exception):
pass
class UnsupportedLineUp(Exceptio... | """Exception utilities."""
class Parsingexception(Exception):
pass
class Envvariablenotset(Exception):
def __init__(self, varname: str) -> None:
super(EnvVariableNotSet, self).__init__(f'Env variable [{varname}] not set.')
class Invalidlineup(Exception):
pass
class Unsupportedlineup(Exception):... |
# (major, minor, patch, prerelease)
VERSION = (0, 0, 6, "")
__shortversion__ = '.'.join(map(str, VERSION[:3]))
__version__ = '.'.join(map(str, VERSION[:3])) + "".join(VERSION[3:])
__package_name__ = 'pyqubo'
__contact_names__ = 'Recruit Communications Co., Ltd.'
__contact_emails__ = 'rco_pyqubo@ml.cocorou.jp'
__homep... | version = (0, 0, 6, '')
__shortversion__ = '.'.join(map(str, VERSION[:3]))
__version__ = '.'.join(map(str, VERSION[:3])) + ''.join(VERSION[3:])
__package_name__ = 'pyqubo'
__contact_names__ = 'Recruit Communications Co., Ltd.'
__contact_emails__ = 'rco_pyqubo@ml.cocorou.jp'
__homepage__ = 'https://pyqubo.readthedocs.io... |
#033: ler tres numeros e dizer qual o maior e qual o menor:
print("Digite 3 numeros:")
maiorn = 0
n = int(input("Numero 1: "))
if n > maiorn:
maiorn = n
menorn = n
n = int(input("Numero 2: "))
if n > maiorn:
maiorn = n
if n < menorn:
menorn = n
n = int(input("Numero 3: "))
if n > maiorn:
maiorn = n... | print('Digite 3 numeros:')
maiorn = 0
n = int(input('Numero 1: '))
if n > maiorn:
maiorn = n
menorn = n
n = int(input('Numero 2: '))
if n > maiorn:
maiorn = n
if n < menorn:
menorn = n
n = int(input('Numero 3: '))
if n > maiorn:
maiorn = n
if n < menorn:
menorn = n
print(f'o maior numero foi {ma... |
#!/usr/bin/python3
#coding=utf-8
def cc_debug():
print(__name__) | def cc_debug():
print(__name__) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-23
Last_modify: 2016-03-23
******************************************
'''
'''
Say you have an array for which the ith el... | """
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-23
Last_modify: 2016-03-23
******************************************
"""
'\nSay you have an array for which the ith element is\nthe price of a given stock on day i.\n... |
def drop(i_list: list,n:int) -> list:
"""
Drop at multiple of n from the list
:param n: Drop from the list i_list every N element
:param i_list: The source list
:return: The returned list
"""
assert(n>0)
_shallow_list = []
k=1
for element in i_list:
if k % n != 0:
... | def drop(i_list: list, n: int) -> list:
"""
Drop at multiple of n from the list
:param n: Drop from the list i_list every N element
:param i_list: The source list
:return: The returned list
"""
assert n > 0
_shallow_list = []
k = 1
for element in i_list:
if k % n != 0:
... |
#!/usr/bin/python3
"""
Given a binary tree, we install cameras on the nodes of the tree.
Each camera at a node can monitor its parent, itself, and its immediate children.
Calculate the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: [0,0,null,0,0]
Output: 1
Explanation: One c... | """
Given a binary tree, we install cameras on the nodes of the tree.
Each camera at a node can monitor its parent, itself, and its immediate children.
Calculate the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to ... |
# Copyright 2014 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.
DEPS = [
'adb',
'depot_tools/bot_update',
'depot_tools/gclient',
'goma',
'recipe_engine/context',
'recipe_engine/json',
'recipe_engine/path',
... | deps = ['adb', 'depot_tools/bot_update', 'depot_tools/gclient', 'goma', 'recipe_engine/context', 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/step', 'recipe_engine/url', 'depot_tools/tryserver']
def __checkout_steps(api, builde... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
##
# Copyright 2017 FIWARE Foundation, e.V.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... | __author__ = 'fla'
google_accounts_base_url = 'https://accounts.google.com'
application_name = 'TSC Enablers Dashboard'
credential_dir = '.credentials'
credential_file = 'sheets.googleapis.com.json'
db_name = 'enablers-dashboard.db'
db_folder = 'dbase'
log_file = 'tsc-dashboard.log'
fixed_rows = 16
initial_row = 2
fixe... |
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0: return []
rls = [[1]]
for i in range(2, numRows+1):
row = [1] * i
for j in range(1, i-1):
row[j] = rls[-1][... | class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
rls = [[1]]
for i in range(2, numRows + 1):
row = [1] * i
for j in range(1, i - 1):
... |
def maxProfitWithKTransactions(prices, k):
n = len(prices)
profit = [[0]*n for _ in range(k+1)]
"""
t := number of transactions
d := day at which either buy/sell stock
profit[t][d] = max ( previous day profit = profit[t][d-1] ,
profit sold at this day + max(buy for th... | def max_profit_with_k_transactions(prices, k):
n = len(prices)
profit = [[0] * n for _ in range(k + 1)]
'\n t := number of transactions\n d := day at which either buy/sell stock\n\n profit[t][d] = max ( previous day profit = profit[t][d-1] ,\n\n profit sold at this day + max... |
# 11. Replace tabs into spaces
# Replace every occurrence of a tab character into a space. Confirm the result by using sed, tr, or expand command.
with open('popular-names.txt') as f:
for line in f:
print(line.strip().replace("\t", " "))
| with open('popular-names.txt') as f:
for line in f:
print(line.strip().replace('\t', ' ')) |
""" Test data"""
stub_films = [{
"id": "12345",
"title": "This is film one",
},{
"id": "23456",
"title": "This is film two",
}]
stub_poeple = [{
"name": "person 1",
"films": ["url/12345", "url/23456"]
},{
"name": "person 2",
"films": ["url/23456"]
},{
"name": "person 3",
"film... | """ Test data"""
stub_films = [{'id': '12345', 'title': 'This is film one'}, {'id': '23456', 'title': 'This is film two'}]
stub_poeple = [{'name': 'person 1', 'films': ['url/12345', 'url/23456']}, {'name': 'person 2', 'films': ['url/23456']}, {'name': 'person 3', 'films': ['url/12345']}, {'name': 'person 4', 'films': [... |
s = input()
num = [0] * 26
for i in range(len(s)):
num[ord(s[i])-97] += 1
for i in num:
print(i, end = " ")
if i == len(num)-1:
print(i)
| s = input()
num = [0] * 26
for i in range(len(s)):
num[ord(s[i]) - 97] += 1
for i in num:
print(i, end=' ')
if i == len(num) - 1:
print(i) |
# Source : https://leetcode.com/problems/binary-tree-tilt/description/
# Date : 2017-12-26
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findTilt(self, root):
"""
... | class Solution:
def find_tilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
global ans
ans = 0
self.sumOfNode(root)
return ans
def sum_of_node(self, root):
if root == None:
return 0
left = self.sumOfNode(root.l... |
class Order():
def __init__(self, side, pair, size, price, stop_loss_price, id):
self.side = side
self.pair = pair
self.size = size
self.price = price
self.stop_loss_price = stop_loss_price
self.id = id
self.fills = []
def define_id(self, id):
se... | class Order:
def __init__(self, side, pair, size, price, stop_loss_price, id):
self.side = side
self.pair = pair
self.size = size
self.price = price
self.stop_loss_price = stop_loss_price
self.id = id
self.fills = []
def define_id(self, id):
self... |
word = input('Type a word: ')
while word != 'chupacabra':
word = input('Type a word: ')
if word == 'chupacabra':
print('You are out of the loop')
break | word = input('Type a word: ')
while word != 'chupacabra':
word = input('Type a word: ')
if word == 'chupacabra':
print('You are out of the loop')
break |
# Copyright 2021 The Pigweed 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | _rtos_none = '//pw_build/constraints/rtos:none'
target_compatible_with_host_select = {'@platforms//os:windows': [_RTOS_NONE], '@platforms//os:macos': [_RTOS_NONE], '@platforms//os:linux': [_RTOS_NONE], '//conditions:default': ['@platforms//:incompatible']} |
def factorial(n):
fact = 1
for i in range(2,n+1):
fact*= i
return fact
def main():
n = int(input("Enter a number: "))
if n >= 0:
print(f"Factorial: {factorial(n)}")
else:
print(f"Choose another number")
if __name__ == "__main__":
main()
| def factorial(n):
fact = 1
for i in range(2, n + 1):
fact *= i
return fact
def main():
n = int(input('Enter a number: '))
if n >= 0:
print(f'Factorial: {factorial(n)}')
else:
print(f'Choose another number')
if __name__ == '__main__':
main() |
users = []
class UserModel(object):
"""Class user models."""
def __init__(self):
self.db = users
def add_user(self, fname, lname, email, phone, password, confirm_password, city):
""" Method for saving user to the dictionary """
payload = {
"userId": len(self.db)+1,
... | users = []
class Usermodel(object):
"""Class user models."""
def __init__(self):
self.db = users
def add_user(self, fname, lname, email, phone, password, confirm_password, city):
""" Method for saving user to the dictionary """
payload = {'userId': len(self.db) + 1, 'fname': fname... |
"""
Entradas:
lectura actual--->float--->lect2
lectura anterior--->float--->lect1
valor kw--->float--->valorkw
Salidas:
consumo--->float--->consumo
total factura-->flotante--->total
"""
lect2 = float ( entrada ( "Digite lectura real:" ))
lect1 = float ( entrada ( "Digite lectura anterior:" ))
valorkw = float ( input ( ... | """
Entradas:
lectura actual--->float--->lect2
lectura anterior--->float--->lect1
valor kw--->float--->valorkw
Salidas:
consumo--->float--->consumo
total factura-->flotante--->total
"""
lect2 = float(entrada('Digite lectura real:'))
lect1 = float(entrada('Digite lectura anterior:'))
valorkw = float(input('Valor del kil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.