content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
a = int(input())
if a % 7 == 0 :
print("multiple")
else :
print("not multiple")
| a = int(input())
if a % 7 == 0:
print('multiple')
else:
print('not multiple') |
#Tuplas
a = 10
b = 5
print(a)
(a,b) = (b,a)
print(a) #Cambio los valores con las tuplas | a = 10
b = 5
print(a)
(a, b) = (b, a)
print(a) |
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
degree = [0]*numCourses
courseDic = [[] for i in range(numCourses)]
for i, j in prerequisites:
courseDic[j].append(i)
degree[i] += 1
dfs = [i for i in range(numCourse... | class Solution:
def can_finish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
degree = [0] * numCourses
course_dic = [[] for i in range(numCourses)]
for (i, j) in prerequisites:
courseDic[j].append(i)
degree[i] += 1
dfs = [i for i in range(nu... |
class RetsError(RuntimeError):
pass
class RetsClientError(RetsError):
pass
class RetsParseError(RetsClientError):
pass
class RetsResponseError(RetsClientError):
def __init__(self, content: str, headers: dict):
super().__init__('Unexpected response from RETS')
self.content = conte... | class Retserror(RuntimeError):
pass
class Retsclienterror(RetsError):
pass
class Retsparseerror(RetsClientError):
pass
class Retsresponseerror(RetsClientError):
def __init__(self, content: str, headers: dict):
super().__init__('Unexpected response from RETS')
self.content = content
... |
n,l,r,x=map(int,input().split())
num=list(map(int,input().split()))
ans=0
for i in range(2**n):
st=bin(i)[2:]
st='0'*(n-len(st))+st
if st.count('1')>=2:
pt=[]
for i in range(len(st)):
if st[i]=='1':
pt.append(num[i])
if sum(pt)<=r and sum(pt)>=l and max(pt... | (n, l, r, x) = map(int, input().split())
num = list(map(int, input().split()))
ans = 0
for i in range(2 ** n):
st = bin(i)[2:]
st = '0' * (n - len(st)) + st
if st.count('1') >= 2:
pt = []
for i in range(len(st)):
if st[i] == '1':
pt.append(num[i])
if sum(p... |
RUTA_CANCIONES = "D:/proyectos/cocid/cocid_practica_semanal/semana3/canciones/"
CANCIONES = {
1: "Get_Back.txt",
2: "Hey_Jude.txt",
3: "Let_It_Be.txt",
4: "She _Loves_You.txt"
}
| ruta_canciones = 'D:/proyectos/cocid/cocid_practica_semanal/semana3/canciones/'
canciones = {1: 'Get_Back.txt', 2: 'Hey_Jude.txt', 3: 'Let_It_Be.txt', 4: 'She _Loves_You.txt'} |
kitReportMQHost = '***'
kitReportMQPort = 5672
kitReportMQUsername = '***'
kitReportMQPassword = '***'
kitReportMQQueueName = '***'
kitReportMQHeartBeat = 20
kitGitHost = '***'
kitGitUser = '***'
kitDBPort = 3306
kitDBHost = "***"
kitDBName = "***"
kitDBUsername = "***"
kitDBPassword = "***" | kit_report_mq_host = '***'
kit_report_mq_port = 5672
kit_report_mq_username = '***'
kit_report_mq_password = '***'
kit_report_mq_queue_name = '***'
kit_report_mq_heart_beat = 20
kit_git_host = '***'
kit_git_user = '***'
kit_db_port = 3306
kit_db_host = '***'
kit_db_name = '***'
kit_db_username = '***'
kit_db_password =... |
"""
This module lets you practice the ACCUMULATOR pattern
in its simplest classic forms:
SUMMING: total = total + number
Authors: David Mutchler, Vibha Alangar, Dave Fisher, Matt Boutell, Mark Hays,
Mohammed Noureddine, Sana Ebrahimi, Sriram Mohan, their colleagues and
PUT_YOUR_NAME_HERE.
""... | """
This module lets you practice the ACCUMULATOR pattern
in its simplest classic forms:
SUMMING: total = total + number
Authors: David Mutchler, Vibha Alangar, Dave Fisher, Matt Boutell, Mark Hays,
Mohammed Noureddine, Sana Ebrahimi, Sriram Mohan, their colleagues and
PUT_YOUR_NAME_HERE.
""... |
def validate_fit_event_struct(fitEvent, tester):
tester.assertTrue(hasattr(fitEvent, 'df'))
tester.assertTrue(hasattr(fitEvent, 'spec'))
tester.assertTrue(hasattr(fitEvent, 'model'))
tester.assertTrue(hasattr(fitEvent, 'featureColumns'))
tester.assertTrue(hasattr(fitEvent, 'predictionColumns'))
... | def validate_fit_event_struct(fitEvent, tester):
tester.assertTrue(hasattr(fitEvent, 'df'))
tester.assertTrue(hasattr(fitEvent, 'spec'))
tester.assertTrue(hasattr(fitEvent, 'model'))
tester.assertTrue(hasattr(fitEvent, 'featureColumns'))
tester.assertTrue(hasattr(fitEvent, 'predictionColumns'))
... |
class JumpHistory(object):
def __init__(self):
self._history = [ ]
self._pos = 0
def __len__(self):
return len(self._history)
def jump_to(self, addr):
if self._pos != len(self._history) - 1:
self.trim()
if not self._history or self._history[-1] != ad... | class Jumphistory(object):
def __init__(self):
self._history = []
self._pos = 0
def __len__(self):
return len(self._history)
def jump_to(self, addr):
if self._pos != len(self._history) - 1:
self.trim()
if not self._history or self._history[-1] != addr:
... |
# Given a string s, find the longest palindromic substring in s
# --- Example
# Input: "babad"
# Output: "bab"
# Note: "aba" is also a valid answer.
# Time: O(n^2) | Space: O(1)
# Time complexity: O(n^2) Since expanding a palindrome around its center could take up to O(n), and we do this for each character.
class Sol... | class Solution:
def longest_palindrome(self, s):
res = ''
for i in range(len(s)):
current = self.expand_around_middle(s, i - 1, i + 1)
in_between = self.expand_around_middle(s, i, i + 1)
res = max(res, current, in_between, key=len)
return res
def exp... |
"""
AOC2020 - day3
"""
FILEPATH = "./day3.txt"
MAP = []
ROWLEN = 0
def doFall(down, right):
cnt = 0
myRight = 0
for ind in range(down, len(MAP), down):
myRight += right
if myRight >= ROWLEN:
myRight -= ROWLEN
if MAP[ind][myRight] == '#':
... | """
AOC2020 - day3
"""
filepath = './day3.txt'
map = []
rowlen = 0
def do_fall(down, right):
cnt = 0
my_right = 0
for ind in range(down, len(MAP), down):
my_right += right
if myRight >= ROWLEN:
my_right -= ROWLEN
if MAP[ind][myRight] == '#':
cnt += 1
retu... |
#!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
# return linear_search_iterative(array,... | def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
return linear_search_recursive(array, item)
def linear_search_iterative(array, item):
for (index, value) in enumerate(array):
if item == value:
return index
return None
def li... |
def res(x):
a=[]
i=1
for c in x:
a.append(c+i)
i+=1
return a
n=int(input())
x=list(map(int,input().split()))
x.sort(reverse=True)
a=res(x)
print(max(a)+1)
| def res(x):
a = []
i = 1
for c in x:
a.append(c + i)
i += 1
return a
n = int(input())
x = list(map(int, input().split()))
x.sort(reverse=True)
a = res(x)
print(max(a) + 1) |
"""
Copyright (C) 2017 Open Source Robotics Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to... | """
Copyright (C) 2017 Open Source Robotics Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to... |
# B_R_R
# M_S_A_W
def fibonacci(num):
if num==0:
return 0
elif num==1:
return 1
else:
return fibonacci(num-1)+fibonacci(num-2)
inp_val=int(input("How many numbers: "))
i=1
while i<inp_val:
fibValue=fibonacci(i)
print(fibValue)
i+=1
print("All Done")
| def fibonacci(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
return fibonacci(num - 1) + fibonacci(num - 2)
inp_val = int(input('How many numbers: '))
i = 1
while i < inp_val:
fib_value = fibonacci(i)
print(fibValue)
i += 1
print('All Done') |
"""
PASSENGERS
"""
numPassengers = 34399
passenger_arriving = (
(9, 4, 8, 11, 5, 1, 5, 5, 2, 3, 3, 0, 0, 7, 4, 8, 4, 6, 2, 8, 4, 2, 2, 1, 1, 0), # 0
(6, 9, 9, 6, 5, 1, 3, 5, 3, 1, 3, 0, 0, 9, 7, 4, 4, 7, 4, 3, 5, 5, 2, 2, 0, 0), # 1
(11, 13, 5, 10, 9, 2, 5, 2, 3, 1, 4, 1, 0, 14, 7, 7, 6, 15, 4, 3, 6, 3, 1, 2, 1... | """
PASSENGERS
"""
num_passengers = 34399
passenger_arriving = ((9, 4, 8, 11, 5, 1, 5, 5, 2, 3, 3, 0, 0, 7, 4, 8, 4, 6, 2, 8, 4, 2, 2, 1, 1, 0), (6, 9, 9, 6, 5, 1, 3, 5, 3, 1, 3, 0, 0, 9, 7, 4, 4, 7, 4, 3, 5, 5, 2, 2, 0, 0), (11, 13, 5, 10, 9, 2, 5, 2, 3, 1, 4, 1, 0, 14, 7, 7, 6, 15, 4, 3, 6, 3, 1, 2, 1, 0), (14, 17, 9... |
num = [0 for n in range(4)]
for i in range(4):
num[i] = int(input(""))
failed = False
if (num[0] == 8 or num[0] == 9) and (num[3] == 8 or num[3] == 9) and (num[1] == num[2]):
print("ignore")
else:
print("answer") | num = [0 for n in range(4)]
for i in range(4):
num[i] = int(input(''))
failed = False
if (num[0] == 8 or num[0] == 9) and (num[3] == 8 or num[3] == 9) and (num[1] == num[2]):
print('ignore')
else:
print('answer') |
'''
05 - Regression plot parameters
Seaborn's regression plot supports several parameters that can be
used to configure the plots and drive more insight into the data.
For the next exercise, we can look at the relationship between tuition
and the percent of students that receive Pell grants. A Pell grant is
... | """
05 - Regression plot parameters
Seaborn's regression plot supports several parameters that can be
used to configure the plots and drive more insight into the data.
For the next exercise, we can look at the relationship between tuition
and the percent of students that receive Pell grants. A Pell grant is
... |
# coding: utf-8
class Confirm(object):
def __init__(self, assume_yes=False):
self.assume_yes = assume_yes
def ask(self):
if self.assume_yes:
return True
message = '\n==> Press "Y" to confirm, or anything else to abort: '
confirmation = input(message)
retur... | class Confirm(object):
def __init__(self, assume_yes=False):
self.assume_yes = assume_yes
def ask(self):
if self.assume_yes:
return True
message = '\n==> Press "Y" to confirm, or anything else to abort: '
confirmation = input(message)
return True if str(conf... |
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next = next_node
def add_node(self, node):
self.next = node
def remove_next_node(self):
self.next = None
def add_value(self, value):
self.value = value
| class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next = next_node
def add_node(self, node):
self.next = node
def remove_next_node(self):
self.next = None
def add_value(self, value):
self.value = value |
class Attribute(object):
"""
Args:
target (str): the attribute name in the batch
source (str): the key in the example dict
field (:class:`Field`): the field for target attribute
include_valid (bool): if True, the validation
dataset vocab will be included.
include_test (bool): if True, t... | class Attribute(object):
"""
Args:
target (str): the attribute name in the batch
source (str): the key in the example dict
field (:class:`Field`): the field for target attribute
include_valid (bool): if True, the validation
dataset vocab will be included.
include_test (bool): if True,... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( num ) :
length = len ( num )
if ( length == 1 and num [ 0 ] == '0' ) :
return True
if ( length ... | def f_gold(num):
length = len(num)
if length == 1 and num[0] == '0':
return True
if length % 3 == 1:
num = str(num) + '00'
length += 2
elif length % 3 == 2:
num = str(num) + '0'
length += 1
sum = 0
p = 1
for i in range(length - 1, -1, -1):
grou... |
s = 0
f1 = 1
f2 = 2
f_old = f1
f_new = f1
while f_new < 4000000:
if f_new % 2 == 0:
s += f_new
f_new_temp = f_new
f_new = f_new_temp + f_old
f_old = f_new_temp
print(s) | s = 0
f1 = 1
f2 = 2
f_old = f1
f_new = f1
while f_new < 4000000:
if f_new % 2 == 0:
s += f_new
f_new_temp = f_new
f_new = f_new_temp + f_old
f_old = f_new_temp
print(s) |
# https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/445769/merge-sort-CLEAR-simple-EXPLANATION-with-EXAMPLES-O(n-lg-n)
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
def mergeAndCount(arr, start, end, result):
if start >= end:
re... | class Solution:
def count_smaller(self, nums: List[int]) -> List[int]:
def merge_and_count(arr, start, end, result):
if start >= end:
return
mid = (start + end) // 2
merge_and_count(arr, start, mid, result)
merge_and_count(arr, mid + 1, end, ... |
class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
gaps = defaultdict(int)
for row in wall:
position = 0
for brick in row[:-1]:
position += brick
gaps[position] += 1
fewestCrossings = len(wall)
if len(gaps) > 0... | class Solution:
def least_bricks(self, wall: List[List[int]]) -> int:
gaps = defaultdict(int)
for row in wall:
position = 0
for brick in row[:-1]:
position += brick
gaps[position] += 1
fewest_crossings = len(wall)
if len(gaps) ... |
# python3
n, m = map(int, input().split())
edges = [ list(map(int, input().split())) for i in range(m) ]
# This solution prints a simple satisfiable formula
# and passes about half of the tests.
# Change this function to solve the problem.
def printEquisatisfiableSatFormula():
print("3 2")
print("1 2 0")
p... | (n, m) = map(int, input().split())
edges = [list(map(int, input().split())) for i in range(m)]
def print_equisatisfiable_sat_formula():
print('3 2')
print('1 2 0')
print('-1 -2 0')
print('1 -2 0')
print_equisatisfiable_sat_formula() |
SINE = 0
SQUARE = 1
TRI = 2
UP = 3
DOWN = 4
ARB0 = 100
ARB1 = 101
ARB2 = 102
ARB3 = 103
ARB4 = 104
ARB5 = 105
ARB6 = 106
ARB7 = 107
ARB8 = 108
ARB9 = 109
ARB10 = 110
ARB11 = 111
ARB12 = 112
ARB13 = 113
ARB14 = 114
ARB15 = 115
| sine = 0
square = 1
tri = 2
up = 3
down = 4
arb0 = 100
arb1 = 101
arb2 = 102
arb3 = 103
arb4 = 104
arb5 = 105
arb6 = 106
arb7 = 107
arb8 = 108
arb9 = 109
arb10 = 110
arb11 = 111
arb12 = 112
arb13 = 113
arb14 = 114
arb15 = 115 |
N = int(input())
if N <= 999:
print('ABC')
else:
print('ABD')
| n = int(input())
if N <= 999:
print('ABC')
else:
print('ABD') |
class DtoObject(dict):
@property
def __dict__(self):
return {k: v for k, v in self.items()}
| class Dtoobject(dict):
@property
def __dict__(self):
return {k: v for (k, v) in self.items()} |
"""
Calculate different thread patterns
"""
tx = list(range(0, 256))
#print("sAtx", map(lambda x: (x%2) * 512 + x/2, tx))
print("gmStoreCtx", map(lambda x: (x%16)*2 + (x/16)*16*8, tx))
print("", map(lambda x: (x%16)*2 + (x/16)*16*8 + 32 + 1, tx))
| """
Calculate different thread patterns
"""
tx = list(range(0, 256))
print('gmStoreCtx', map(lambda x: x % 16 * 2 + x / 16 * 16 * 8, tx))
print('', map(lambda x: x % 16 * 2 + x / 16 * 16 * 8 + 32 + 1, tx)) |
expected_output = {
"TenGigabitEthernet1/0/2":{
"port_channel":{
"port_channel_member": False
},
"enabled": True,
"line_protocol":"up",
"oper_status":"up",
"connected": True,
"suspended": False,
"err_disabled": False,
"type":"Ten Gigabit Ethernet",
... | expected_output = {'TenGigabitEthernet1/0/2': {'port_channel': {'port_channel_member': False}, 'enabled': True, 'line_protocol': 'up', 'oper_status': 'up', 'connected': True, 'suspended': False, 'err_disabled': False, 'type': 'Ten Gigabit Ethernet', 'mac_address': '682c.7b3f.f002', 'phys_address': '682c.7b3f.f002', 'de... |
#!/usr/bin/env python
names = ('ff','ff','sfs','fdfs')
for name in names:
print(name)
lll = list(range(5))
print(lll)
sum =0
for l in lll:
sum+=l
print(sum)
| names = ('ff', 'ff', 'sfs', 'fdfs')
for name in names:
print(name)
lll = list(range(5))
print(lll)
sum = 0
for l in lll:
sum += l
print(sum) |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
class Aluno:
estuda = "digita os codigos"
boceja = "aaaaahhhh"
def estuda(self):
print(self.estuda)
def boceja(self):
print(self.boceja)
def main():
joao = Aluno()
joao.estuda()
joao.bocej... | class Aluno:
estuda = 'digita os codigos'
boceja = 'aaaaahhhh'
def estuda(self):
print(self.estuda)
def boceja(self):
print(self.boceja)
def main():
joao = aluno()
joao.estuda()
joao.boceja()
if __name__ == '__main__':
main() |
__project__ = 'Synerty Peek'
__copyright__ = '2016, Synerty'
__author__ = 'Synerty'
__version__ = '1.0.0'
| __project__ = 'Synerty Peek'
__copyright__ = '2016, Synerty'
__author__ = 'Synerty'
__version__ = '1.0.0' |
def primesieve(a,n):
global m
N=n
n+=5
prime=[0 for i in range(n+1)]
p=2
while(p*p<=n):
if(prime[p]==0):
for i in range(p*p,n,p):
prime[i]=1
p+=1
c=0
for i in range(a,N+1):
if prime[i]==0:
m.append(i)
c+=1
re... | def primesieve(a, n):
global m
n = n
n += 5
prime = [0 for i in range(n + 1)]
p = 2
while p * p <= n:
if prime[p] == 0:
for i in range(p * p, n, p):
prime[i] = 1
p += 1
c = 0
for i in range(a, N + 1):
if prime[i] == 0:
m.app... |
#
# PySNMP MIB module HIRSCHMANN-DVMRP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HIRSCHMANN-DVMRP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:30:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint) ... |
r = int(input())
pi = 3.14159
v = (4/3) *pi * (r ** 3)
print("VOLUME = {0:.3f}".format(v))
| r = int(input())
pi = 3.14159
v = 4 / 3 * pi * r ** 3
print('VOLUME = {0:.3f}'.format(v)) |
expected_output = {
"interfaces": {
"Port-channel1": {
"name": "Port-channel1",
"protocol": "lacp",
"members": {
"GigabitEthernet2": {
"interface": "GigabitEthernet2",
"counters": {
"lacp_in_p... | expected_output = {'interfaces': {'Port-channel1': {'name': 'Port-channel1', 'protocol': 'lacp', 'members': {'GigabitEthernet2': {'interface': 'GigabitEthernet2', 'counters': {'lacp_in_pkts': 22, 'lacp_out_pkts': 27, 'marker_in_pkts': 0, 'marker_out_pkts': 0, 'lacp_pkts': 0, 'marker_response_in_pkts': 0, 'marker_respon... |
#
# ***** ALERTA SERVER DEFAULT SETTINGS -- DO NOT MODIFY THIS FILE *****
#
# To override these settings use /etc/alertad.conf or the contents of the
# configuration file set by the environment variable ALERTA_SVR_CONF_FILE.
#
# Further information on settings can be found at http://docs.alerta.io
DEBUG = False
LOGGE... | debug = False
logger_name = 'alerta'
log_file = None
secret_key = 'changeme'
query_limit = 10000
history_limit = 1000
mongo_host = 'localhost'
mongo_port = 27017
mongo_database = 'monitoring'
mongo_replset = None
mongo_username = 'alerta'
mongo_password = None
auth_required = False
admin_users = []
customer_views = Fal... |
c_player_version_path = '/v1/player/versionInfo'
c_casino_version_path = '/v1/casino/versionInfo'
c_not_ready = 'not_ready_0'
# frontend
c_frontend_src_em = 'EM_FE'
c_frontend_src_operator = 'operator_FE'
# update time
c_job_interval_minutes = 30
c_json_key_operator_group = 'Operator Group'
c_redis_key_operator_g... | c_player_version_path = '/v1/player/versionInfo'
c_casino_version_path = '/v1/casino/versionInfo'
c_not_ready = 'not_ready_0'
c_frontend_src_em = 'EM_FE'
c_frontend_src_operator = 'operator_FE'
c_job_interval_minutes = 30
c_json_key_operator_group = 'Operator Group'
c_redis_key_operator_group = 'operatorGroup'
c_json_k... |
'''A program to distribute candy to boys with array rating
each boy will get one more candy than the boy with less rating than him
example:[0,1,6] will return
1+2+3=6
[1,1,1,2,3,2+10]
=>1+1+1+2+2+3+4
'''
def distr(A:list):
A= sorted(A)
no_candy=1
the_boy=0
total_candy=0
for boy in A:
... | """A program to distribute candy to boys with array rating
each boy will get one more candy than the boy with less rating than him
example:[0,1,6] will return
1+2+3=6
[1,1,1,2,3,2+10]
=>1+1+1+2+2+3+4
"""
def distr(A: list):
a = sorted(A)
no_candy = 1
the_boy = 0
total_candy = 0
for boy in A:
... |
# Definition for a Node.
class Node:
def __init__(self, x: int, next: "Node" = None, random: "Node" = None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def copyRandomList(self, head: "Node") -> "Node":
if not head:
return None
no... | class Node:
def __init__(self, x: int, next: 'Node'=None, random: 'Node'=None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def copy_random_list(self, head: 'Node') -> 'Node':
if not head:
return None
node = head
d = {}
... |
# All things for a HAP characteristic.
class HAP_FORMAT:
BOOL = 'bool'
INT = 'int'
FLOAT = 'float'
STRING = 'string'
ARRAY = 'array'
DICTIONARY = 'dictionary'
UINT8 = 'uint8'
UINT16 = 'uint16'
UINT32 = 'uint32'
UINT64 = 'uint64'
DATA = 'data'
TLV8 = 'tlv8'
NUMERIC = (INT, FLOAT,... | class Hap_Format:
bool = 'bool'
int = 'int'
float = 'float'
string = 'string'
array = 'array'
dictionary = 'dictionary'
uint8 = 'uint8'
uint16 = 'uint16'
uint32 = 'uint32'
uint64 = 'uint64'
data = 'data'
tlv8 = 'tlv8'
numeric = (INT, FLOAT, UINT8, UINT16, UINT32, UINT... |
# encoding: utf-8
_default_allow_actions = (
'site_read',
'user_create',
'sysadmin', # pseudo-action that CKAN calls check_access for
'dashboard_new_activities_count',
'dashboard_activity_list',
'package_search',
'organization_list_for_user',
'organization_list',
'group_list',
... | _default_allow_actions = ('site_read', 'user_create', 'sysadmin', 'dashboard_new_activities_count', 'dashboard_activity_list', 'package_search', 'organization_list_for_user', 'organization_list', 'group_list', 'group_edit_permissions')
def is_action_allowed_by_default(action_name):
"""
Indicates whether the gi... |
""" Dont duplicate errors same type. """
DUPLICATES = (
# multiple statements on one line
[('pep8', 'E701'), ('pylint', 'C0321')],
# missing whitespace around operator
[('pep8', 'E225'), ('pylint', 'C0326')],
# unused variable
[('pylint', 'W0612'), ('pyflakes', 'W0612')],
# undefined va... | """ Dont duplicate errors same type. """
duplicates = ([('pep8', 'E701'), ('pylint', 'C0321')], [('pep8', 'E225'), ('pylint', 'C0326')], [('pylint', 'W0612'), ('pyflakes', 'W0612')], [('pylint', 'E0602'), ('pyflakes', 'E0602')], [('pylint', 'W0611'), ('pyflakes', 'W0611')], [('pylint', 'C0326'), ('pep8', 'E251')], [('p... |
'''from rasa.core.agent import Agent
from rasa.utils.endpoints import EndpointConfig
import asyncio
import logging
logger = logging.getLogger("app.main")
class RasaAgent():
def __init__(self, **kwargs):
self.model_name = kwargs.get('model')
self.response = None
self.message = None
... | """from rasa.core.agent import Agent
from rasa.utils.endpoints import EndpointConfig
import asyncio
import logging
logger = logging.getLogger("app.main")
class RasaAgent():
def __init__(self, **kwargs):
self.model_name = kwargs.get('model')
self.response = None
self.message = None
... |
# https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/train/python
#Take each letters index
#Add to string each letters multiplied by its index (first letter must be uppercase and others lowercase)
#Add - between each set
def accum(s):
accummedStr=s[0].upper()
for i in range(1,len(s)): accummedStr+="-"+s[i... | def accum(s):
accummed_str = s[0].upper()
for i in range(1, len(s)):
accummed_str += '-' + s[i].upper() + s[i].lower() * i
return accummedStr |
with open('test.txt', 'r+') as f:
f.seek(15)
print(f.readline())
with open('test.txt') as f:
data = []
for d in f:
data.append(d)
print(data) | with open('test.txt', 'r+') as f:
f.seek(15)
print(f.readline())
with open('test.txt') as f:
data = []
for d in f:
data.append(d)
print(data) |
def figure_layout(annotations=None, title_text=None, x_label=None, y_label=None, show_legend=False):
"""Customize plotly figures
Parameters
----------
annotations: a list of dictionaries informing the values of parameters
to format annotations.
x_label: str. Title ... | def figure_layout(annotations=None, title_text=None, x_label=None, y_label=None, show_legend=False):
"""Customize plotly figures
Parameters
----------
annotations: a list of dictionaries informing the values of parameters
to format annotations.
x_label: str. Title for... |
def move_zeros_to_left(A):
if len(A) < 1: return
lengthA = len(A)
write_index = lengthA - 1
read_index = lengthA - 1
while(read_index >= 0):
if A[read_index] != 0:
A[write_index] = A[read_index]
write_index -= 1
read_index -= 1
while (write_index >= 0)... | def move_zeros_to_left(A):
if len(A) < 1:
return
length_a = len(A)
write_index = lengthA - 1
read_index = lengthA - 1
while read_index >= 0:
if A[read_index] != 0:
A[write_index] = A[read_index]
write_index -= 1
read_index -= 1
while write_index >=... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS=[
'tests',
]
DEBUG = False
SITE_ID = 1 | databases = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
installed_apps = ['tests']
debug = False
site_id = 1 |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 30 18:07:30 2020
@author: user
"""
| """
Created on Sun Aug 30 18:07:30 2020
@author: user
""" |
n = int(input())
a = list(map(int, input().split()))
a = sorted(a)
c = 0
for i in range(0,n,2):
c = c + a[i+1]-a[i]
print(c)
| n = int(input())
a = list(map(int, input().split()))
a = sorted(a)
c = 0
for i in range(0, n, 2):
c = c + a[i + 1] - a[i]
print(c) |
# Do not edit the class below except
# for the breadthFirstSearch method.
# Feel free to add new properties
# and methods to the class.
class Node:
def __init__(self, name):
self.children = []
self.name = name
def addChild(self, name):
self.children.append(Node(name))
return sel... | class Node:
def __init__(self, name):
self.children = []
self.name = name
def add_child(self, name):
self.children.append(node(name))
return self
def breadth_first_search(self, array):
queue = [self]
while len(queue) > 0:
cur_node = queue.pop(0)... |
confThreshold= 0.5
nmsThreshold = 0.4
inpWidth = 416
inpHeight = 416
classesFile = "coco.names"
classes = None
with open(classesFile,"rt") as f:
classes = f.read().rstrip("\n").split("\n")
print(classes) | conf_threshold = 0.5
nms_threshold = 0.4
inp_width = 416
inp_height = 416
classes_file = 'coco.names'
classes = None
with open(classesFile, 'rt') as f:
classes = f.read().rstrip('\n').split('\n')
print(classes) |
#!/usr/bin/python
# height2.py
print ('Height: %.2f %s' % (172.3, 'cm'))
print ('Height: {0:.2f} {1:s}'.format(172.3, 'cm'))
| print('Height: %.2f %s' % (172.3, 'cm'))
print('Height: {0:.2f} {1:s}'.format(172.3, 'cm')) |
#
# PySNMP MIB module EFM-CU-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/EFM-CU-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:11:39 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( OctetS... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ... |
# (c) 2021 Leon Luithlen
# This code is licensed under MIT license
def strongly_typed(*args, **kwargs):
stargs = args
stkwargs = kwargs
def type_strongly(func):
def wrapper(*args, **kwargs):
for arg, type_ in zip(args, stargs):
assert isinstance(arg,type_), f"{arg} should be of type {type_}"
for kw, a... | def strongly_typed(*args, **kwargs):
stargs = args
stkwargs = kwargs
def type_strongly(func):
def wrapper(*args, **kwargs):
for (arg, type_) in zip(args, stargs):
assert isinstance(arg, type_), f'{arg} should be of type {type_}'
for (kw, arg) in kwargs.items... |
# ==== Start of helper classes to be used by TriggerExtractorResultCollection ====
class DocumentPrediction(object):
def __init__(self, docid):
self.docid = docid
self.sentences = dict()
""":type: dict[str, SentencePrediction]"""
def to_json(self):
d = dict()
d['docid'] ... | class Documentprediction(object):
def __init__(self, docid):
self.docid = docid
self.sentences = dict()
':type: dict[str, SentencePrediction]'
def to_json(self):
d = dict()
d['docid'] = self.docid
sentences = []
for sentence in self.sentences.values():
... |
"""
https://leetcode.com/problems/reshape-the-matrix/
566. Reshape the Matrix (Easy)
"""
class Solution:
def matrixReshape(self, mat, r, c):
m = len(mat)
n = len(mat[0])
if m*n != r*c:
return mat
rLoc = 0
cLoc = 0
result = []
row = []
... | """
https://leetcode.com/problems/reshape-the-matrix/
566. Reshape the Matrix (Easy)
"""
class Solution:
def matrix_reshape(self, mat, r, c):
m = len(mat)
n = len(mat[0])
if m * n != r * c:
return mat
r_loc = 0
c_loc = 0
result = []
row =... |
'''
A string with parentheses is well bracketed if all parentheses are matched: every opening bracket has a matching closing bracket and vice versa.
Write a Python function wellbracketed(s) that takes a string s containing parentheses and returns True if s is well bracketed and False otherwise.
Hint: Keep track of the ... | """
A string with parentheses is well bracketed if all parentheses are matched: every opening bracket has a matching closing bracket and vice versa.
Write a Python function wellbracketed(s) that takes a string s containing parentheses and returns True if s is well bracketed and False otherwise.
Hint: Keep track of the ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 29 16:51:16 2019
@author: linyizi
"""
| """
Created on Mon Apr 29 16:51:16 2019
@author: linyizi
""" |
# Models are decision tree
# Batandwa Mgutsi
# 12/03/2020
class DecisionCase:
"""A Decision case has a sentence and a set of two other decision cases to execute on yes and on no"""
"""answers by the user in case the DecisonCase requires input"""
sentence = None
requiresAnswer = True
yesCase = No... | class Decisioncase:
"""A Decision case has a sentence and a set of two other decision cases to execute on yes and on no"""
'answers by the user in case the DecisonCase requires input'
sentence = None
requires_answer = True
yes_case = None
no_case = None
def __init__(self, sentence, requires... |
class Solution:
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
length = len(cost)
dp = [0 for x in range(0, length)]
dp[0] = cost[0]
dp[1] = cost[1]
for i in range(2, length):
# Remember to divided ... | class Solution:
def min_cost_climbing_stairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
length = len(cost)
dp = [0 for x in range(0, length)]
dp[0] = cost[0]
dp[1] = cost[1]
for i in range(2, length):
if i == length - 1... |
PLURAL_KEYS = (
"view",
"measure",
"dimension",
"dimension_group",
"filter",
"access_filter",
"bind_filters",
"map_layer",
"parameter",
"set",
"column",
"derived_column",
"include",
"explore",
"link",
"when",
"allowed_value",
"named_value_format",
... | plural_keys = ('view', 'measure', 'dimension', 'dimension_group', 'filter', 'access_filter', 'bind_filters', 'map_layer', 'parameter', 'set', 'column', 'derived_column', 'include', 'explore', 'link', 'when', 'allowed_value', 'named_value_format', 'join', 'datagroup', 'access_grant', 'sql_step', 'sql_where', 'action', '... |
A = 26
MOD = 1_000_000_007
def shortPalindrome(s):
c1 = [0] * A
c2 = [[0] * A for _ in range(A)]
c3 = [0] * A
res = 0
for i in (ord(c) - 97 for c in s):
res = (res + c3[i]) % MOD
for j in range(A):
c3[j] += c2[j][i]
for j in range(A):
c2[... | a = 26
mod = 1000000007
def short_palindrome(s):
c1 = [0] * A
c2 = [[0] * A for _ in range(A)]
c3 = [0] * A
res = 0
for i in (ord(c) - 97 for c in s):
res = (res + c3[i]) % MOD
for j in range(A):
c3[j] += c2[j][i]
for j in range(A):
c2[j][i] += c1[j]
... |
"""Exceptions for downtoearth.
These are helpers provided so that you can raise proper HTTP code errors from your API.
Usage:
from downtoearth.exceptions import NotFoundException
raise NotFoundException('your princess is in another castle')
"""
class BadRequestException(Exception):
def __init__(self, ms... | """Exceptions for downtoearth.
These are helpers provided so that you can raise proper HTTP code errors from your API.
Usage:
from downtoearth.exceptions import NotFoundException
raise NotFoundException('your princess is in another castle')
"""
class Badrequestexception(Exception):
def __init__(self, ms... |
class Solution:
def isPalindrome(self, x: int) -> bool:
i = 0
str_x = str(x)
n = len(str_x)
while i < n-i-1:
if str_x[i] != str_x[n-i-1]:
return False
i += 1
return True | class Solution:
def is_palindrome(self, x: int) -> bool:
i = 0
str_x = str(x)
n = len(str_x)
while i < n - i - 1:
if str_x[i] != str_x[n - i - 1]:
return False
i += 1
return True |
"""2017 Advent of Code, Day 2"""
with open("input", "r+") as file:
puzzle_input = file.readlines()
SPREADSHEET = []
CHECKSUM = 0
CHECKSUM_2 = 0
for row in puzzle_input:
SPREADSHEET.append([int(value) for value in row.strip().split()])
for row in SPREADSHEET:
row.sort()
CHECKSUM += row[-1] - row[0]
f... | """2017 Advent of Code, Day 2"""
with open('input', 'r+') as file:
puzzle_input = file.readlines()
spreadsheet = []
checksum = 0
checksum_2 = 0
for row in puzzle_input:
SPREADSHEET.append([int(value) for value in row.strip().split()])
for row in SPREADSHEET:
row.sort()
checksum += row[-1] - row[0]
f... |
class Solution:
def getSkyline(self, buildings: [[int]]) -> [[int]]:
if not buildings:
return []
if len(buildings) == 1:
return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]]
mid = len(buildings) // 2
left = self.getSkyline(buildings[:mid])
... | class Solution:
def get_skyline(self, buildings: [[int]]) -> [[int]]:
if not buildings:
return []
if len(buildings) == 1:
return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]]
mid = len(buildings) // 2
left = self.getSkyline(buildings[:mid])
... |
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
def valid(sub):
nums = [item for item in sub if item.isdigit()]
return len(set(nums)) == len(nums)
def check_row():
return al... | class Solution:
def is_valid_sudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
def valid(sub):
nums = [item for item in sub if item.isdigit()]
return len(set(nums)) == len(nums)
def check_row():
return all((v... |
class Node (object):
def __init__(self, leaf, num_spaces=4):
self.name = leaf[0]
self.num_spaces = num_spaces
leaves = leaf[1:]
if len(leaves):
self.leaves = [Node(leaves, num_spaces)]
else:
self.leaves = None
# Returns true when the leaves are a... | class Node(object):
def __init__(self, leaf, num_spaces=4):
self.name = leaf[0]
self.num_spaces = num_spaces
leaves = leaf[1:]
if len(leaves):
self.leaves = [node(leaves, num_spaces)]
else:
self.leaves = None
def add(self, leaves):
if lea... |
# isr1.py - Timer to activate units in a cycle
# The 7-segment units are controlled one-by one in a cycle, using a timer interrupt for consistent light output.
# Model 1: every timer interrupt, the control switches from one unit to the next.
# User configuration
framebuf = "ABCD" # User configuration: desir... | framebuf = 'ABCD'
timer_ms = 5
unitcount = 4
assert TIMER_MS >= 1
assert TIMER_MS * UNITCOUNT <= 20
assert UNITCOUNT == len(framebuf)
_unit = UNITCOUNT - 1
_rows = '?'
_column = '?'
_unitlog = ''
_rowslog = ''
_columnlog = ''
def log(sep=None):
global _unitlog, _rowslog, _columnlog
global _slot, _unit, _rows, ... |
letters = {}
for c in input():
if c in letters:
letters[c] += 1
else:
letters[c] = 1
max_double = max(letters.values())
if max_double == 1:
print(len(letters))
for l in letters:
print(l)
exit(0)
if list(letters.values()).count(max_double) == 1:
print(1)
for l, k in... | letters = {}
for c in input():
if c in letters:
letters[c] += 1
else:
letters[c] = 1
max_double = max(letters.values())
if max_double == 1:
print(len(letters))
for l in letters:
print(l)
exit(0)
if list(letters.values()).count(max_double) == 1:
print(1)
for (l, k) in ... |
#Generate Christmas Tree Pattern
# Generating Triangle Shape
def triangleShape(n):
for i in range(n):
for j in range(n-i):
print(' ', end=' ')
for k in range(2*i+1):
print('*',end=' ')
print()
# Generating Pole Shape
def poleShape(n):
for i in range(n):
... | def triangle_shape(n):
for i in range(n):
for j in range(n - i):
print(' ', end=' ')
for k in range(2 * i + 1):
print('*', end=' ')
print()
def pole_shape(n):
for i in range(n):
for j in range(n - 1):
print(' ', end=' ')
print('* * *')... |
"""A set of function(s) that are used for estimating frame per second (fps).
These function(s) often receive an inference time, perform some calculation on it.
The function(s) do return a fps value.
"""
def convert_infr_time_to_fps(infr_time: float) -> int:
# Gets the time of inference (infr_time) and returns F... | """A set of function(s) that are used for estimating frame per second (fps).
These function(s) often receive an inference time, perform some calculation on it.
The function(s) do return a fps value.
"""
def convert_infr_time_to_fps(infr_time: float) -> int:
fps = int(1.0 / infr_time)
return fps |
class Node():
"""Building Block of Linked List."""
def __init__(self, data):
"""Initialize Node.
Args:
data: The data to be stored.
"""
self.data = data
self.next = None
def __str__(self):
"""String representation of Node."""
return "(... | class Node:
"""Building Block of Linked List."""
def __init__(self, data):
"""Initialize Node.
Args:
data: The data to be stored.
"""
self.data = data
self.next = None
def __str__(self):
"""String representation of Node."""
return '({},... |
# check if a number is odd or even
num = int(input("Enter a number: "))
if num%2: # note that it is not checked with ==; result of %2 is 0 or 1 which can be translated as False or True
print("The number is odd")
else:
print("The number is even") | num = int(input('Enter a number: '))
if num % 2:
print('The number is odd')
else:
print('The number is even') |
# zwei 06/16/2014
# inspired by sympy.utilities.iterables.kbins.partition()
def partition(lista, bins):
# EnricoGiampieri's partition generator from
# http://stackoverflow.com/questions/13131491/
# partition-n-items-into-k-bins-in-python-lazily
if len(lista) == 1 or bins == 1:
yield [lista]
... | def partition(lista, bins):
if len(lista) == 1 or bins == 1:
yield [lista]
elif len(lista) > 1 and bins > 1:
for i in range(1, len(lista)):
for part in partition(lista[i:], bins - 1):
if len([lista[:i]] + part) == bins:
yield ([lista[:i]] + part)
f... |
"""
Writing a Function that accepts 2 parameters.
Draws a playing board based on the rows and columns input
GitHub : @ChaitanyaJoshiX
"""
def DrawingBoard(rows, columns):
for i in range(rows):
if i%2 == 0:
for j in range(columns):
if j%2 == 0:
if j!=... | """
Writing a Function that accepts 2 parameters.
Draws a playing board based on the rows and columns input
GitHub : @ChaitanyaJoshiX
"""
def drawing_board(rows, columns):
for i in range(rows):
if i % 2 == 0:
for j in range(columns):
if j % 2 == 0:
if j != co... |
class Solution:
def romanToInt(self, s: str) -> int:
roman = {'I': 1,'V': 5,'X': 10, 'L': 50,'C': 100,'D': 500,'M': 1000}
exception = {'IV': 4,'IX': 9,'XL': 40,'XC': 90,'CD': 400,'CM': 900}
intnum = 0
for exc in exception:
if exc in s:
intnum = intnum + e... | class Solution:
def roman_to_int(self, s: str) -> int:
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
exception = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
intnum = 0
for exc in exception:
if exc in s:
intnum ... |
class Simbolo:
def __init__(self,tipo,nombre,posicion,ambito,dimensiones=0):
self.tipo=tipo
self.nombre=nombre
self.posicion=posicion
self.ambito=ambito
self.dimensiones=dimensiones | class Simbolo:
def __init__(self, tipo, nombre, posicion, ambito, dimensiones=0):
self.tipo = tipo
self.nombre = nombre
self.posicion = posicion
self.ambito = ambito
self.dimensiones = dimensiones |
pytest_plugins = [
'aioclustermanager.tests.fixtures'
]
| pytest_plugins = ['aioclustermanager.tests.fixtures'] |
class Result(dict):
"""Result dict. Behaves 'immutable' to the Feature.process method.
Just a simple dict to hold the results from features.
"""
__slots__ = ()
def __setitem__(self, *args):
raise TypeError('`Result` object does not support item assignment.')
def _setitem(self, key, v... | class Result(dict):
"""Result dict. Behaves 'immutable' to the Feature.process method.
Just a simple dict to hold the results from features.
"""
__slots__ = ()
def __setitem__(self, *args):
raise type_error('`Result` object does not support item assignment.')
def _setitem(self, key, ... |
"""
Simple dependencies between tests.
"""
def test_no_skip(ctestdir):
"""One test is skipped, but no other test depends on it,
so all other tests pass.
"""
ctestdir.makepyfile("""
import pytest
@pytest.mark.dependency()
def test_a():
pytest.skip("explicit skip")
... | """
Simple dependencies between tests.
"""
def test_no_skip(ctestdir):
"""One test is skipped, but no other test depends on it,
so all other tests pass.
"""
ctestdir.makepyfile('\n import pytest\n\n @pytest.mark.dependency()\n def test_a():\n pytest.skip("explicit skip")... |
# URI Online Judge 1117
nota1, nota2 = -1, -1
continuar = 1
while continuar == 1:
nota1, nota2 = -1, -1
while nota1 < 0 or nota1 > 10:
nota1 = float(input())
if nota1 < 0 or nota1 > 10:
print("nota invalida")
while nota2 < 0 or nota2 > 10:
nota2 = float(input())
... | (nota1, nota2) = (-1, -1)
continuar = 1
while continuar == 1:
(nota1, nota2) = (-1, -1)
while nota1 < 0 or nota1 > 10:
nota1 = float(input())
if nota1 < 0 or nota1 > 10:
print('nota invalida')
while nota2 < 0 or nota2 > 10:
nota2 = float(input())
if nota2 < 0 or n... |
result = set()
for *features, label in DATA[1:]:
species = label.pop()
if species.endswith(SUFFIXES):
result.add(species)
| result = set()
for (*features, label) in DATA[1:]:
species = label.pop()
if species.endswith(SUFFIXES):
result.add(species) |
# Work out the first ten digits of the sum of
# the following one-hundred 50-digit numbers.
num_str = "37107287533902102798797998220837590246510135740250\
46376937677490009712648124896970078050417018260538\
74324986199524741059474233309513058123726617309629\
91942213363574161572522430563301811072406154908250\
23067588... | num_str = '371072875339021027987979982208375902465101357402504637693767749000971264812489697007805041701826053874324986199524741059474233309513058123726617309629919422133635741615725224305633018110724061549082502306758820753934617117198031042104751377806324667689261670696623633820136378418383684178734361726757281128798... |
class Out():
def __init__(self):
self.log_level = 0
def print(self, msg):
print(msg)
def log(self, level, msg):
if level >= self.log_level:
return
else:
output = ""
if level == 1:
output = "[VERBOSE] "
elif le... | class Out:
def __init__(self):
self.log_level = 0
def print(self, msg):
print(msg)
def log(self, level, msg):
if level >= self.log_level:
return
else:
output = ''
if level == 1:
output = '[VERBOSE] '
elif leve... |
number_of_test_cases = int(input().strip())
for _ in range(number_of_test_cases):
try:
a, b = map(int, input().strip().split(" "))
print(a // b)
except Exception as e:
print("Error Code:", e)
| number_of_test_cases = int(input().strip())
for _ in range(number_of_test_cases):
try:
(a, b) = map(int, input().strip().split(' '))
print(a // b)
except Exception as e:
print('Error Code:', e) |
def printArray(array):
print(" ")
for itemNum in range(0, len(array)):
print("#" + str(itemNum) + ": " + str(array[itemNum]))
def linearSearch(array, find):
foundInd = -1
found = False
time = 0
while time < len(array) and not found:
if array[time] == find:
print... | def print_array(array):
print(' ')
for item_num in range(0, len(array)):
print('#' + str(itemNum) + ': ' + str(array[itemNum]))
def linear_search(array, find):
found_ind = -1
found = False
time = 0
while time < len(array) and (not found):
if array[time] == find:
prin... |
# TODO
# Have not even started one bit but easy once get the other part done
# https://bsmg.wiki/mapping/map-format.html#events-2
# Get the Melograph
# Translate the graph to the events
# Write the results to the file
# Onset Can create a idea of where to put the beats
# https://librosa.org/doc/latest/generated/lib... | """
You may be wondering, how do we manage to incentivize more creative mapping? Rather than just placing events based on time and location, we run a multitude of different checks to decide on where to place our events.
Beats with a high pace (more than 1 block per beat) receive a red center light, beats with a medium... |
class GroupHelper:
def __init__(self,app):
self.app = app
def return_to_group_page(self):
wd = self.app.wd
wd.find_element_by_link_text("group page").click()
def creator(self, group):
wd = self.app.wd
# open_gp
wd.find_element_by_link_text("groups").click()
# init_group_creator
wd.find_element_by_... | class Grouphelper:
def __init__(self, app):
self.app = app
def return_to_group_page(self):
wd = self.app.wd
wd.find_element_by_link_text('group page').click()
def creator(self, group):
wd = self.app.wd
wd.find_element_by_link_text('groups').click()
wd.find_... |
class category(object):
def __init__(self, id=None, account=None, name=None,
description=None, parent=None,
selectable=True, active=True):
self.id = id
self.account = account
self.name = name
self.description = description
self.parent = parent
self.selectable = s... | class Category(object):
def __init__(self, id=None, account=None, name=None, description=None, parent=None, selectable=True, active=True):
self.id = id
self.account = account
self.name = name
self.description = description
self.parent = parent
self.selectable = selec... |
"""
Fixed and improved version based on "extracting from C++ doxygen documented file Author G.D." and py++ code.
Distributed under the Boost Software License, Version 1.0. (See
accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
"""
class doxygen_doc_extractor:
"""
Extracts Doxyg... | """
Fixed and improved version based on "extracting from C++ doxygen documented file Author G.D." and py++ code.
Distributed under the Boost Software License, Version 1.0. (See
accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
"""
class Doxygen_Doc_Extractor:
"""
Extracts Doxyg... |
#Project Euler Problem-52
#Author Tushar Gayan
def f(num_1,num_2): #Checks same digit
num_list_1 = [int(i) for i in str(num_1)]
num_list_2 = [int(i) for i in str(num_2)]
num_list_1.sort();num_list_2.sort()
if num_list_1 == num_list_2:
return True
else:
return False
n = 1
while f(n... | def f(num_1, num_2):
num_list_1 = [int(i) for i in str(num_1)]
num_list_2 = [int(i) for i in str(num_2)]
num_list_1.sort()
num_list_2.sort()
if num_list_1 == num_list_2:
return True
else:
return False
n = 1
while f(n, 2 * n) != True or f(2 * n, 3 * n) != True or f(3 * n, 4 * n) !... |
"""
breadcrumbs.namedobject
~~~~~~~~~~~~~~~~~~~~~~~
Sentinels with good representation.
:copyright: 2021 by breadcrumbs Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
class NamedObject(object):
"""A class to construct named sentinels."""
def __in... | """
breadcrumbs.namedobject
~~~~~~~~~~~~~~~~~~~~~~~
Sentinels with good representation.
:copyright: 2021 by breadcrumbs Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
class Namedobject(object):
"""A class to construct named sentinels."""
def __ini... |
# problem : https://leetcode.com/problems/coin-change-2/
# time complexity : O(NM)
# algorithm : DP
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
if amount == 0 and len(coins) == 0:
return 1
dp = [[0] * (amount + 1)] * (len(coins) + 1)
for coinInd in ra... | class Solution:
def change(self, amount: int, coins: List[int]) -> int:
if amount == 0 and len(coins) == 0:
return 1
dp = [[0] * (amount + 1)] * (len(coins) + 1)
for coin_ind in range(len(coins)):
coin = coins[coinInd]
prev = dp[coinInd]
now =... |
def main():
with open("day1/input.dat") as f:
expenses = [int(n) for n in f.readlines()]
result = None
for a in expenses:
for b in expenses:
if a + b == 2020:
result = a*b
break
return result
if __name__ == "__main__":
print(main()) | def main():
with open('day1/input.dat') as f:
expenses = [int(n) for n in f.readlines()]
result = None
for a in expenses:
for b in expenses:
if a + b == 2020:
result = a * b
break
return result
if __name__ == '__main__':
print(main()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.