content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
b=int(input())
x_1=b
i=0
while True:
a=b//10+(b%10)
b=(b%10)*10+a%10
i+=1
x=b
if x==x_1:
break
print(i)
| b = int(input())
x_1 = b
i = 0
while True:
a = b // 10 + b % 10
b = b % 10 * 10 + a % 10
i += 1
x = b
if x == x_1:
break
print(i) |
class Stack:
def __init__ (self):
self.elements = []
def is_empty(self):
return self.elements == []
def push(self, item):
self.elements.append(item)
def pop(self):
return self.elements.pop()
def peek(self):
return self.elements[-1]
def size(self):
... | class Stack:
def __init__(self):
self.elements = []
def is_empty(self):
return self.elements == []
def push(self, item):
self.elements.append(item)
def pop(self):
return self.elements.pop()
def peek(self):
return self.elements[-1]
def size(self):
... |
# -*- coding: utf-8 -*-
# open repositories
"""Todo: move src for acquiring data"""
'http://www.opendoar.org/countrylist.php'
better = 'http://oaister.worldcat.org/'
# Should access Terms and Conditions all the time.
| """Todo: move src for acquiring data"""
'http://www.opendoar.org/countrylist.php'
better = 'http://oaister.worldcat.org/' |
n = int(input())
l = []
for i in range(1, n):
if (i < 3):
l.append(1)
else:
l.append(l[len(l) - 1] + l[len(l) -2])
print(i, ": ", l[i-1])
| n = int(input())
l = []
for i in range(1, n):
if i < 3:
l.append(1)
else:
l.append(l[len(l) - 1] + l[len(l) - 2])
print(i, ': ', l[i - 1]) |
python = Runtime.createAndStart("python","Python")
mouth = Runtime.createAndStart("Mouth","MouthControl")
arduino = mouth.getArduino()
arduino.connect('COM11')
jaw = mouth.getJaw()
jaw.detach()
jaw.attach(arduino,11)
mouth.setmouth(110,120)
mouth.autoAttach = False
speech = Runtime.createAndStart("Speech","AcapelaSpeec... | python = Runtime.createAndStart('python', 'Python')
mouth = Runtime.createAndStart('Mouth', 'MouthControl')
arduino = mouth.getArduino()
arduino.connect('COM11')
jaw = mouth.getJaw()
jaw.detach()
jaw.attach(arduino, 11)
mouth.setmouth(110, 120)
mouth.autoAttach = False
speech = Runtime.createAndStart('Speech', 'Acapela... |
"""
Counting power sets
http://www.codewars.com/kata/54381f0b6f032f933c000108/train/python
"""
def powers(lst):
return 2 ** len(lst) | """
Counting power sets
http://www.codewars.com/kata/54381f0b6f032f933c000108/train/python
"""
def powers(lst):
return 2 ** len(lst) |
# -*- coding: utf-8 -*-
if __name__ == '__main__':
s = input()
t = input()
mod_s = s
for i in range(len(s)):
mod_s = mod_s[1:] + mod_s[0]
if mod_s == t:
print('Yes')
exit()
print('No')
| if __name__ == '__main__':
s = input()
t = input()
mod_s = s
for i in range(len(s)):
mod_s = mod_s[1:] + mod_s[0]
if mod_s == t:
print('Yes')
exit()
print('No') |
def test_cep_match(correios):
matches = correios.match_cep(cep="28620000", cod="QC067757494BR")
assert matches
def test_cep_not_match_wrong_digit(correios):
matches = correios.match_cep(cep="28620000", cod="QC067757490BR")
assert not matches
def test_cep_not_match(correios):
matches = correios... | def test_cep_match(correios):
matches = correios.match_cep(cep='28620000', cod='QC067757494BR')
assert matches
def test_cep_not_match_wrong_digit(correios):
matches = correios.match_cep(cep='28620000', cod='QC067757490BR')
assert not matches
def test_cep_not_match(correios):
matches = correios.mat... |
# This problem was recently asked by Apple:
# You are given an array. Each element represents the price of a stock on that particular day.
# Calculate and return the maximum profit you can make from buying and selling that stock only once.
def buy_and_sell(arr):
# Fill this in.
maxP = -1
buy = 0
sell... | def buy_and_sell(arr):
max_p = -1
buy = 0
sell = 0
change = True
for i in range(0, len(arr) - 1):
sell = arr[i + 1]
if change:
buy = arr[i]
if sell < buy:
change = True
continue
else:
temp = sell - buy
if tem... |
#reference_number = 9
text = ' is a prime number '
print('................................')
#print('This are numbers which can be divided into ' + str(reference_number))
for i in range(1, 100):
first = i / i
second = i/1
# print('Residual value of dividing ' + str(i) + ' / ' + str(reference_number) + ' = '... | text = ' is a prime number '
print('................................')
for i in range(1, 100):
first = i / i
second = i / 1
if first == 1:
if second == i:
print(str(i) + text) |
def test_a():
x = "this"
assert "h" in x
def test_b():
x = "hello"
assert "h" in x
def test_c():
x = "world"
assert "w" in x | def test_a():
x = 'this'
assert 'h' in x
def test_b():
x = 'hello'
assert 'h' in x
def test_c():
x = 'world'
assert 'w' in x |
#
# PySNMP MIB module AIPPP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AIPPP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:00:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
class S:
"""
Gets all keys from a dict and adds them
as attribute to a class (also works with nested dicts)
Parameters
----------
data : ``dict`
The dict you want to convert
"""
def __init__(self, data: dict) -> None:
self.__raw = data
class _(dict):
... | class S:
"""
Gets all keys from a dict and adds them
as attribute to a class (also works with nested dicts)
Parameters
----------
data : ``dict`
The dict you want to convert
"""
def __init__(self, data: dict) -> None:
self.__raw = data
class _(dict):
... |
#350111
#a3_p10.py
#Alexandru Sasu
#a.sasu@jacobs-university.de
def printframe(n, m, c):
for j in range(0,m):
print(c,end="")
print()
for i in range (1,n-1):
print(c,end="")
for j in range(1,m-1):
print(" ",end="")
print(c)
for j in range(0,m):
print(c,end="")
print()
n=int(input())
m=int(input())
c=i... | def printframe(n, m, c):
for j in range(0, m):
print(c, end='')
print()
for i in range(1, n - 1):
print(c, end='')
for j in range(1, m - 1):
print(' ', end='')
print(c)
for j in range(0, m):
print(c, end='')
print()
n = int(input())
m = int(input()... |
x = True
y=False
print(x,y)
num1=1
num2=2
resultado=num1<num2
print(resultado)
if(num1 < num2):
print("el valor num1 es menor que num2")
else:
print("el valor de num1 No es menor que num2") | x = True
y = False
print(x, y)
num1 = 1
num2 = 2
resultado = num1 < num2
print(resultado)
if num1 < num2:
print('el valor num1 es menor que num2')
else:
print('el valor de num1 No es menor que num2') |
class Solution:
def isMirrorImage(self, left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
if left.val != right.val:
return False
return self.isMirrorImage(left.left, right.right) a... | class Solution:
def is_mirror_image(self, left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
if left.val != right.val:
return False
return self.isMirrorImage(left.left, right.right) and self... |
# -*- coding: utf-8 -*-
#
# DVR-Scan: Find & Export Motion Events in Video Footage
# --------------------------------------------------------------
# [ Site: https://github.com/Breakthrough/DVR-Scan/ ]
# [ Documentation: http://dvr-scan.readthedocs.org/ ]
#
# This file contains all code for the ma... | """ DVR-Scan Unit Test Suite
To run all available tests run `pytest -v` from the parent directory
(i.e. the root project folder of DVR-Scan containing the scenedetect/
and tests/ folders). This will automatically find and run all of the
test cases in the tests/ folder and display the results.
""" |
# flake8: noqa
def test_variable_substitution(variable_transform):
text = "cd $HOME"
assert variable_transform(text) == "cd %s" % HOME
def test_variable_substitution_inverse(variable_transform):
text = "cd %s" % HOME
assert variable_transform(text, inverse=True) == "cd $HOME"
def test_variable_sub... | def test_variable_substitution(variable_transform):
text = 'cd $HOME'
assert variable_transform(text) == 'cd %s' % HOME
def test_variable_substitution_inverse(variable_transform):
text = 'cd %s' % HOME
assert variable_transform(text, inverse=True) == 'cd $HOME'
def test_variable_substitution_only_at_s... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or head.next == None:
return head
temp_dict = dict()
pre = head
... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def delete_duplicates(self, head: ListNode) -> ListNode:
if not head or head.next == None:
return head
temp_dict = dict()
pre = head
while pre:
if pre.v... |
def binary_search(data, value):
min = 0
max = len(data) - 1
while min <= max:
mid = (min + max) // 2
if data[mid] == value:
return mid
elif data[mid] < value:
min = mid + 1
else:
max = mid - 1
return -1
if __name__ == '__main__':
d... | def binary_search(data, value):
min = 0
max = len(data) - 1
while min <= max:
mid = (min + max) // 2
if data[mid] == value:
return mid
elif data[mid] < value:
min = mid + 1
else:
max = mid - 1
return -1
if __name__ == '__main__':
da... |
def jac_uniform(mesh, mask):
# create Jacobian
cv = mesh.get_control_volumes(cell_mask=mask)
cvc = mesh.get_control_volume_centroids(cell_mask=mask)
return 2 * (mesh.node_coords - cvc) * cv[:, None]
| def jac_uniform(mesh, mask):
cv = mesh.get_control_volumes(cell_mask=mask)
cvc = mesh.get_control_volume_centroids(cell_mask=mask)
return 2 * (mesh.node_coords - cvc) * cv[:, None] |
def pig_it(text):
l=text.split()
count=0
for i in l:
if i.isalpha():
tmp=list(i)
tmp.append(tmp[0])
tmp.pop(0)
tmp.extend(list('ay'))
l[count]=''.join(tmp)
count+=1
return ' '.join(l)
'''
def pig_it(text):
lst = text.split... | def pig_it(text):
l = text.split()
count = 0
for i in l:
if i.isalpha():
tmp = list(i)
tmp.append(tmp[0])
tmp.pop(0)
tmp.extend(list('ay'))
l[count] = ''.join(tmp)
count += 1
return ' '.join(l)
"\ndef pig_it(text):\n lst = te... |
{
"targets": [
{
"target_name": "glfw",
"sources": [
"src/native/glfw.cc",
"src/native/glad.c"
],
"include_dirs": [
"src/native/deps/include",
"<!@(pkg-config glfw3 --cflags-only-I | sed s/-I//g)"... | {'targets': [{'target_name': 'glfw', 'sources': ['src/native/glfw.cc', 'src/native/glad.c'], 'include_dirs': ['src/native/deps/include', '<!@(pkg-config glfw3 --cflags-only-I | sed s/-I//g)'], 'libraries': ['<!@(pkg-config --libs glfw3)'], 'library_dirs': ['/usr/local/lib']}, {'target_name': 'gles', 'sources': ['src/na... |
def foo():
return 'bar'
COMMAND = foo
| def foo():
return 'bar'
command = foo |
class HomeEventManager:
def __init__(self, model):
self._model = model
def handle_mouse_event(self, event):
for button in self.model.buttons:
if button.rect.collidepoint(event.pos):
return button
return None
@property
def model(self):
return... | class Homeeventmanager:
def __init__(self, model):
self._model = model
def handle_mouse_event(self, event):
for button in self.model.buttons:
if button.rect.collidepoint(event.pos):
return button
return None
@property
def model(self):
return... |
class HashMap:
def __init__(self, size):
self.size = size
self.map = [None] * self.size
self.index = -1
def __str__(self):
"""
Method from HashMap that prints indices, keys, and values in map
In: None
Out: string
"""
if self.map is not N... | class Hashmap:
def __init__(self, size):
self.size = size
self.map = [None] * self.size
self.index = -1
def __str__(self):
"""
Method from HashMap that prints indices, keys, and values in map
In: None
Out: string
"""
if self.map is not No... |
errors = {
"BadRequest": {"message": "Bad Request", "status": 400},
"Forbidden": {"message": "Forbidden", "status": 403},
"NotFound": {"message": "Resource Not Found", "status": 404},
"MethodNotAllowed": {"message": "Method Not allowed", "status": 405},
"Conflict": {
"message": "You can not ... | errors = {'BadRequest': {'message': 'Bad Request', 'status': 400}, 'Forbidden': {'message': 'Forbidden', 'status': 403}, 'NotFound': {'message': 'Resource Not Found', 'status': 404}, 'MethodNotAllowed': {'message': 'Method Not allowed', 'status': 405}, 'Conflict': {'message': 'You can not add a duplicate resource.', 's... |
class Node:
def __init__(self, data, depth):
children_count = int(data.pop(0))
metadata_count = int(data.pop(0))
self.children = []
self.metadata = []
self.depth = depth
for i in range(children_count):
self.children.append(Node(data, depth + 1))
... | class Node:
def __init__(self, data, depth):
children_count = int(data.pop(0))
metadata_count = int(data.pop(0))
self.children = []
self.metadata = []
self.depth = depth
for i in range(children_count):
self.children.append(node(data, depth + 1))
f... |
"""
Tuples:
1. immutable
2. heterogeneous data structures (i.e., their entries have different meanings)
3. ordered data structure that can be indexed and sliced like a list.
4. defined by listing a sequence of elements separated by commas, optionally contained within parentheses: ()
ex:
my_... | """
Tuples:
1. immutable
2. heterogeneous data structures (i.e., their entries have different meanings)
3. ordered data structure that can be indexed and sliced like a list.
4. defined by listing a sequence of elements separated by commas, optionally contained within parentheses: ()
ex:
my_... |
#WAP to print the grade
s1 = float(input("Enter marks for subject 1 :"))
s2 = float(input("Enter marks for subject 2 :"))
s3 = float(input("Enter marks for subject 3 :"))
s4 = float(input("Enter marks for subject 4 :"))
total = s1 + s2 + s3 + s4
avg = total / 4
print('Average marks:',avg)
if avg >= 90:
... | s1 = float(input('Enter marks for subject 1 :'))
s2 = float(input('Enter marks for subject 2 :'))
s3 = float(input('Enter marks for subject 3 :'))
s4 = float(input('Enter marks for subject 4 :'))
total = s1 + s2 + s3 + s4
avg = total / 4
print('Average marks:', avg)
if avg >= 90:
print('O')
elif avg >= 80:
prin... |
SAMPLEEXECUTION_TYPE_URI = "https://w3id.org/okn/o/sd#SampleExecution"
SAMPLEEXECUTION_TYPE_NAME = "SampleExecution"
GRID_TYPE_URI = "https://w3id.org/okn/o/sdm#Grid"
GRID_TYPE_NAME = "Grid"
DATASETSPECIFICATION_TYPE_URI = "https://w3id.org/okn/o/sd#DatasetSpecification"
DATASETSPECIFICATION_TYPE_NAME = "DatasetSpecifi... | sampleexecution_type_uri = 'https://w3id.org/okn/o/sd#SampleExecution'
sampleexecution_type_name = 'SampleExecution'
grid_type_uri = 'https://w3id.org/okn/o/sdm#Grid'
grid_type_name = 'Grid'
datasetspecification_type_uri = 'https://w3id.org/okn/o/sd#DatasetSpecification'
datasetspecification_type_name = 'DatasetSpecifi... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
total = 0
n = int(input(''))
size = list(map(int, input().split()))
m = int(input(''))
for i in range(m):
order = list(map(int, input().split()))
if order[0] in size:
total = total + order[1]
size.remove(order[0])
print(total)... | total = 0
n = int(input(''))
size = list(map(int, input().split()))
m = int(input(''))
for i in range(m):
order = list(map(int, input().split()))
if order[0] in size:
total = total + order[1]
size.remove(order[0])
print(total) |
def missingTwo(nums: [int]) -> [int]:
ret = 0
for i, num in enumerate(nums):
ret ^= (i + 1)
ret ^= num
ret ^= len(nums) + 1
ret ^= len(nums) + 2
mask = 1
while mask & ret == 0:
mask <<= 1
a, b = 0, 0
for i in range(1, len(nums) + 3):
if i & mask:
... | def missing_two(nums: [int]) -> [int]:
ret = 0
for (i, num) in enumerate(nums):
ret ^= i + 1
ret ^= num
ret ^= len(nums) + 1
ret ^= len(nums) + 2
mask = 1
while mask & ret == 0:
mask <<= 1
(a, b) = (0, 0)
for i in range(1, len(nums) + 3):
if i & mask:
... |
def diff_records(left, right):
'''
Given lists of [year, value] pairs, return list of [year, difference] pairs.
Fails if the inputs are not for exactly corresponding years.
'''
assert len(left) == len(right), \
'Inputs have different lengths.'
num_years = len(left)
results = []
... | def diff_records(left, right):
"""
Given lists of [year, value] pairs, return list of [year, difference] pairs.
Fails if the inputs are not for exactly corresponding years.
"""
assert len(left) == len(right), 'Inputs have different lengths.'
num_years = len(left)
results = []
for i in ra... |
#!/usr/bin/python3
# -*- encoding="UTF-8" -*-
#parameters
listR = [] #
listC = []
listL = []
listM = []
listE = []
listF = []
listG = []
listH = []
listD = []
listDCV = []
listSinV = []
listPulseV = []
listACV = []
listDCI = []
listSinI = []
listDCParam = []
listACParam = []
listTranParam = []
listPlotDC = []
list... | list_r = []
list_c = []
list_l = []
list_m = []
list_e = []
list_f = []
list_g = []
list_h = []
list_d = []
list_dcv = []
list_sin_v = []
list_pulse_v = []
list_acv = []
list_dci = []
list_sin_i = []
list_dc_param = []
list_ac_param = []
list_tran_param = []
list_plot_dc = []
list_plot_ac = []
list_plot_tran = []
op_ex... |
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
The symmetry package implements symmetry tools, e.g., spacegroup determination,
etc.
"""
| """
The symmetry package implements symmetry tools, e.g., spacegroup determination,
etc.
""" |
def math():
while True:
i_put = int(input())
if i_put == 0:
break
else:
for i in range(1, i_put+1):
for j in range(1, i_put+1):
print(i, end=' ')
j += 1
print()
if __name__ == '__main__':
m... | def math():
while True:
i_put = int(input())
if i_put == 0:
break
else:
for i in range(1, i_put + 1):
for j in range(1, i_put + 1):
print(i, end=' ')
j += 1
print()
if __name__ == '__main__':
... |
PLUGIN_NAME = 'plugin'
PACKAGE_NAME = 'mock-plugin'
PACKAGE_VERSION = '1.0'
def create_plugin_url(plugin_tar_name, file_server):
return '{0}/{1}'.format(file_server.url, plugin_tar_name)
def plugin_struct(file_server, source=None, args=None, name=PLUGIN_NAME,
executor=None, package_name=PACKAG... | plugin_name = 'plugin'
package_name = 'mock-plugin'
package_version = '1.0'
def create_plugin_url(plugin_tar_name, file_server):
return '{0}/{1}'.format(file_server.url, plugin_tar_name)
def plugin_struct(file_server, source=None, args=None, name=PLUGIN_NAME, executor=None, package_name=PACKAGE_NAME):
return ... |
"""
Author Samuel Souik
License MIT
endswith.py
"""
def endswith(string, target):
"""
Description
----------
Check to see if the target string is the end of the string.
Parameters
----------
string : str - string to check end of\n
target : str - string to search for
Returns
... | """
Author Samuel Souik
License MIT
endswith.py
"""
def endswith(string, target):
"""
Description
----------
Check to see if the target string is the end of the string.
Parameters
----------
string : str - string to check end of
target : str - string to search for
Returns
-... |
# Title: Reverse Linked List II
# Link: https://leetcode.com/problems/reverse-linked-list-ii/
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Problem:
def reverse_between(self, head: ListNode, m: int, n: int) -> ListNode:
cur = head
... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Problem:
def reverse_between(self, head: ListNode, m: int, n: int) -> ListNode:
cur = head
part = None
n = n - m
(head_end, tail_head) = (None, None)
m -= 1
... |
# -*- coding: utf-8 -*-
"""Collection of exceptions raised by requests-toolbelt."""
class StreamingError(Exception):
"""Used in :mod:`requests_toolbelt.downloadutils.stream`."""
pass
| """Collection of exceptions raised by requests-toolbelt."""
class Streamingerror(Exception):
"""Used in :mod:`requests_toolbelt.downloadutils.stream`."""
pass |
class TestImporter:
domain_file = "test/data/domain-woz.xml"
dialogue_file = "test/data/woz-dialogue.xml"
domain_file2 = "test/data/example-domain-params.xml"
dialogue_file2 = "test/data/dialogue.xml"
# def test_importer(self):
# system = DialogueSystem(XMLDomainReader.extract_domain(self.d... | class Testimporter:
domain_file = 'test/data/domain-woz.xml'
dialogue_file = 'test/data/woz-dialogue.xml'
domain_file2 = 'test/data/example-domain-params.xml'
dialogue_file2 = 'test/data/dialogue.xml' |
# define a function that:
# has one parameter, a number, and returns that number tripled.
# Q1: What do you name the function?
# A: number_tripled
# Q2: What are the parameters, and what types of information do they refer to?
# A: one parameter of type number
# Q2: What calculations are you doing with that informat... | def number_tripled(num: int) -> int:
"""
precondition: number is a number
take as input a number and multiply the number 3 times
>>> number_tripled(5)
125
>>> number_tripled(2.2)
6
"""
return num * 3 |
def factorial(x):
if x <= 0:
return x+1
else:
return x * factorial(x-1)
result = []
while True:
try:
n = input().split()
a = int(n[0])
b = int(n[1])
result.append(factorial(a) + factorial(b))
except EOFError:
break
for i in range(0,len(result)):
print(r... | def factorial(x):
if x <= 0:
return x + 1
else:
return x * factorial(x - 1)
result = []
while True:
try:
n = input().split()
a = int(n[0])
b = int(n[1])
result.append(factorial(a) + factorial(b))
except EOFError:
break
for i in range(0, len(result)... |
# OUT OF PLACE retuns new different dictionary
def replace_dict_value(d, bad_val, good_val):
new_dict = {}
for key, value in d.items():
if bad_val == value:
new_dict[key] = good_val
else:
new_dict[key] = value
return new_dict
og_dict = {'a':5,'b':6,'c':5}
print(og_d... | def replace_dict_value(d, bad_val, good_val):
new_dict = {}
for (key, value) in d.items():
if bad_val == value:
new_dict[key] = good_val
else:
new_dict[key] = value
return new_dict
og_dict = {'a': 5, 'b': 6, 'c': 5}
print(og_dict)
fresh_dict = replace_dict_value(og_di... |
Dict = {1:'Amrik', 2: 'Abhi'}
print (Dict)
##call
print(Dict[1])
print(Dict.get(2)) | dict = {1: 'Amrik', 2: 'Abhi'}
print(Dict)
print(Dict[1])
print(Dict.get(2)) |
##HEADING: Primality algorithm
#PROBLEM STATEMENT:
"""
TO CHECK WHETHER AN INTEGER IS PRIME OR NOT.
IF THE INTEGER IS PRIME RETURN TRUE.
ELSE RETURN FALSE.
"""
#SOLUTION-1: (BRUTE_FORCE) --> O(n)
def isPrime1(n: int) -> bool:
if(n<=1):
return False
elif(n==2):
return True
else:... | """
TO CHECK WHETHER AN INTEGER IS PRIME OR NOT.
IF THE INTEGER IS PRIME RETURN TRUE.
ELSE RETURN FALSE.
"""
def is_prime1(n: int) -> bool:
if n <= 1:
return False
elif n == 2:
return True
else:
for i in range(2, n):
if n % i == 0:
return Fals... |
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
... | """
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
... |
# Copyright (c) 2016-2017 Dustin Doloff
# Licensed under Apache License v2.0
load(
"@bazel_toolbox//labels:labels.bzl",
"executable_label",
)
load(
":internal.bzl",
"web_internal_generate_variables",
)
generate_variables = rule(
attrs = {
"config": attr.label(
mandatory = True,... | load('@bazel_toolbox//labels:labels.bzl', 'executable_label')
load(':internal.bzl', 'web_internal_generate_variables')
generate_variables = rule(attrs={'config': attr.label(mandatory=True, allow_single_file=True), 'out_js': attr.output(), 'out_css': attr.output(), 'out_scss': attr.output(), '_generate_variables_script'... |
"""title
https://adventofcode.com/2021/day/1
"""
def solve(data):
return data
def solve2(data):
return data
if __name__ == '__main__':
input_data = open('input_data.txt').read()
result = solve(input_data)
print(f'Example 1: {result}')
result = solve2(input_data)
print(f'Example 2: {re... | """title
https://adventofcode.com/2021/day/1
"""
def solve(data):
return data
def solve2(data):
return data
if __name__ == '__main__':
input_data = open('input_data.txt').read()
result = solve(input_data)
print(f'Example 1: {result}')
result = solve2(input_data)
print(f'Example 2: {resul... |
#!/usr/bin/env python
# encoding: utf-8
class Insertion(object):
"""Insertions do affect an applied sequence and do not store a sequence
themselves. They are a skip if the length is less than 0
Args:
index (int): the index into the `StrandSet` the `Insertion` occurs at
length (int): leng... | class Insertion(object):
"""Insertions do affect an applied sequence and do not store a sequence
themselves. They are a skip if the length is less than 0
Args:
index (int): the index into the `StrandSet` the `Insertion` occurs at
length (int): length of `Insertion`
"""
__slots__ = ... |
#https://www.codechef.com/problems/CHEFEZQ
for _ in range(int(input())):
q,k=map(int,input().split())
l=list(map(int,input().split()))
rem=0
c=0
f=0
for i in range(q):
rem+=l[i]
if(rem-k<0):
f=1
break
c+=1
rem-=k
print(c+1) if f else p... | for _ in range(int(input())):
(q, k) = map(int, input().split())
l = list(map(int, input().split()))
rem = 0
c = 0
f = 0
for i in range(q):
rem += l[i]
if rem - k < 0:
f = 1
break
c += 1
rem -= k
print(c + 1) if f else print(int(sum(l) ... |
# python_version >= '3.8'
#: Okay
class C:
def __init__(self, a, /, b=None):
pass
#: N805:2:18
class C:
def __init__(this, a, /, b=None):
pass
| class C:
def __init__(self, a, /, b=None):
pass
class C:
def __init__(this, a, /, b=None):
pass |
# Write your solution here
def count_matching_elements(my_matrix: list, element: int):
count = 0
for row in my_matrix:
for item in row:
if item == element:
count += 1
return count
if __name__ == "__main__":
m = [[1, 2, 1], [0, 3, 4], [1, 0, 0]]
print(count_matchin... | def count_matching_elements(my_matrix: list, element: int):
count = 0
for row in my_matrix:
for item in row:
if item == element:
count += 1
return count
if __name__ == '__main__':
m = [[1, 2, 1], [0, 3, 4], [1, 0, 0]]
print(count_matching_elements(m, 1)) |
{
"version": "eosio::abi/1.0",
"types": [],
"structs": [
{
"name": "newaccount",
"base": "",
"fields": [
{"name":"account", "type":"name"},
{"name":"pub_key", "type":"public_key"}
]
}
],
"actions": [{
... | {'version': 'eosio::abi/1.0', 'types': [], 'structs': [{'name': 'newaccount', 'base': '', 'fields': [{'name': 'account', 'type': 'name'}, {'name': 'pub_key', 'type': 'public_key'}]}], 'actions': [{'name': 'newaccount', 'type': 'newaccount', 'ricardian_contract': ''}], 'tables': [], 'ricardian_clauses': [], 'error_messa... |
iput = input('Multiphy number')
divi = input ('Multiply By?')
try:
put = int(iput)
di = int(divi)
ans = put * di
except:
print('Invalid Value')
quit()
print(ans)
| iput = input('Multiphy number')
divi = input('Multiply By?')
try:
put = int(iput)
di = int(divi)
ans = put * di
except:
print('Invalid Value')
quit()
print(ans) |
# Python3 program to find the
# max LRproduct[i] among all i
# Method to find the next greater
# value in left side
def nextGreaterInLeft(a):
left_index = [0] * len(a)
s = []
for i in range(len(a)):
# Checking if current
# element is greater than top
... | def next_greater_in_left(a):
left_index = [0] * len(a)
s = []
for i in range(len(a)):
while len(s) != 0 and a[i] >= a[s[-1]]:
s.pop()
if len(s) != 0:
left_index[i] = s[-1]
else:
left_index[i] = 0
s.append(i)
return left_index
def next_... |
"""
We can set t equal to the exponent:
t = a^4 + 1
r(t) = e^t
Then:
dt/da = 4a^3
dr/dt = e^t
Now we can use the chain rule:
dr/da = dr/dt * dt/da
= e^t(4a^3)
= 4a^3e^{a^4 + 1}
""" | """
We can set t equal to the exponent:
t = a^4 + 1
r(t) = e^t
Then:
dt/da = 4a^3
dr/dt = e^t
Now we can use the chain rule:
dr/da = dr/dt * dt/da
= e^t(4a^3)
= 4a^3e^{a^4 + 1}
""" |
CALENDAR_CACHE_TIME = 5*60 # seconds
CALENDAR_COLORS = ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854']
CALENDARS = [
{
'name': 'ATP Tennis 2018',
'color': CALENDAR_COLORS[0],
'url': '''https://p23-calendars.icloud.com/published/2/PMXFAiuTnEBHpFCFP8YdjnQt3zIkrpTgDwH58V9EWgy0_sZKiUMsrUl_DTyynnz5iCTEdu-h3ojPtsT... | calendar_cache_time = 5 * 60
calendar_colors = ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854']
calendars = [{'name': 'ATP Tennis 2018', 'color': CALENDAR_COLORS[0], 'url': 'https://p23-calendars.icloud.com/published/2/PMXFAiuTnEBHpFCFP8YdjnQt3zIkrpTgDwH58V9EWgy0_sZKiUMsrUl_DTyynnz5iCTEdu-h3ojPtsTwhzz59tWWK3zayh... |
class AbstractNotification(object):
def show_message(self, title, message):
"""
Show message in the notification system of the OS.
Parameters:
title: The title of the notification.
message: The notification message.
"""
raise NotImplementedError()
| class Abstractnotification(object):
def show_message(self, title, message):
"""
Show message in the notification system of the OS.
Parameters:
title: The title of the notification.
message: The notification message.
"""
raise not_implemented_error() |
"""
File with rsa test keys.
CAUTION:
DO NOT USE THEM IN YOUR PRODUCTION
CODE!
"""
private = '-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC7VJTUt9Us8cKj\nMzEfYyjiWA4R4/M2bS1GB4t7NXp98C3SC6dVMvDuictGeurT8jNbvJZHtCSuYEvu\nNMoSfm76oqFvAp8Gy0iz5sxjZmSnXyCdPEovGhLa0VzMaQ8s+CLOyS56YyCFGe... | """
File with rsa test keys.
CAUTION:
DO NOT USE THEM IN YOUR PRODUCTION
CODE!
"""
private = '-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC7VJTUt9Us8cKj\nMzEfYyjiWA4R4/M2bS1GB4t7NXp98C3SC6dVMvDuictGeurT8jNbvJZHtCSuYEvu\nNMoSfm76oqFvAp8Gy0iz5sxjZmSnXyCdPEovGhLa0VzMaQ8s+CLOyS56YyCFGeJ... |
#
# PySNMP MIB module ZYXEL-CFM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-CFM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:43:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
N,M=map(int,input().split())
if M == 1 or M == 2:
print("NEWBIE!")
elif M<=N:
print("OLDBIE!")
else:
print("TLE!") | (n, m) = map(int, input().split())
if M == 1 or M == 2:
print('NEWBIE!')
elif M <= N:
print('OLDBIE!')
else:
print('TLE!') |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 22 17:55:16 2019
@author: penko
Return team information for the current set of OWL teams.
Elements such as team colors, which may change from season to season, only
return their current values. For example, the Florida Mayhem colors return
Black and Pink instead of their... | """
Created on Sun Dec 22 17:55:16 2019
@author: penko
Return team information for the current set of OWL teams.
Elements such as team colors, which may change from season to season, only
return their current values. For example, the Florida Mayhem colors return
Black and Pink instead of their old Yellow and Red
"""... |
class AccountSetting:
"""Class for several configs"""
username = 'loodahu' # Set username here
password = '123456' # Set password here
def get_username(self):
return self.username
def get_password(self):
return self.password
| class Accountsetting:
"""Class for several configs"""
username = 'loodahu'
password = '123456'
def get_username(self):
return self.username
def get_password(self):
return self.password |
class MetricObjective:
def __init__(self, task):
self.task = task
self.clear()
def clear(self):
self.total = 0
self.iter = 0
def step(self):
self.total = 0
self.iter += 1
def update(self, logits, targets, args, metadata={}):
self.total += args[... | class Metricobjective:
def __init__(self, task):
self.task = task
self.clear()
def clear(self):
self.total = 0
self.iter = 0
def step(self):
self.total = 0
self.iter += 1
def update(self, logits, targets, args, metadata={}):
self.total += args[... |
a = input("give numbers ")#1
while a.isdigit() != True:
a = input("give numbers ")#1
b = input("give numbers ")
while b == 0 or b.isdigit() != True:
b = input("give numbers ")
a = int(a)
b = int(b)
if str(a)[-1] in [0,2,4,6,8]:
print("even")
else:
print("odd")
print(int(a)/int(b))#2
x = 0#3
b = 0
whi... | a = input('give numbers ')
while a.isdigit() != True:
a = input('give numbers ')
b = input('give numbers ')
while b == 0 or b.isdigit() != True:
b = input('give numbers ')
a = int(a)
b = int(b)
if str(a)[-1] in [0, 2, 4, 6, 8]:
print('even')
else:
print('odd')
print(int(a) / int(b))
x = 0
b = 0
while x ... |
def setup():
size(500,500);
background(0);
smooth();
noLoop();
def draw():
strokeWeight(10);
stroke(200);
line(10, 10, 400, 400)
| def setup():
size(500, 500)
background(0)
smooth()
no_loop()
def draw():
stroke_weight(10)
stroke(200)
line(10, 10, 400, 400) |
def lower(o):
t = type(o)
if t == str:
return o.lower()
elif t in (list, tuple, set):
return t(lower(i) for i in o)
elif t == dict:
return dict((lower(k), lower(v)) for k, v in o.items())
raise TypeError('Unable to lower %s (%s)' % (o, repr(o)))
| def lower(o):
t = type(o)
if t == str:
return o.lower()
elif t in (list, tuple, set):
return t((lower(i) for i in o))
elif t == dict:
return dict(((lower(k), lower(v)) for (k, v) in o.items()))
raise type_error('Unable to lower %s (%s)' % (o, repr(o))) |
def extractAlbedo404BlogspotCom(item):
'''
Parser for 'albedo404.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterou... | def extract_albedo404_blogspot_com(item):
"""
Parser for 'albedo404.blogspot.com'
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Lo... |
class FeatureDataResponseDto:
def __init__(self,
value = None,
iterationCount = None,
featureKey = None,
sampleKey = None
):
self.value = value
self.iterationCount = iterationCount
self.featureKey = featureKey
self.sampleKey = sampleKey
class Feat... | class Featuredataresponsedto:
def __init__(self, value=None, iterationCount=None, featureKey=None, sampleKey=None):
self.value = value
self.iterationCount = iterationCount
self.featureKey = featureKey
self.sampleKey = sampleKey
class Featuredatarequestdto:
def __init__(self, f... |
#zero
if n == 0:
yield []
return
#modify
for ig in partitions(n-1):
yield [1] + ig
if ig and (len(ig) < 2 or ig[1] > ig[0]):
yield [ig[0] + 1] + ig[1:]
| if n == 0:
yield []
return
for ig in partitions(n - 1):
yield ([1] + ig)
if ig and (len(ig) < 2 or ig[1] > ig[0]):
yield ([ig[0] + 1] + ig[1:]) |
N = int(input())
for i in range(N):
S = input().split()
print(S)
# ......
for string in S:
if string.upper() == "THE":
count += 1
| n = int(input())
for i in range(N):
s = input().split()
print(S)
for string in S:
if string.upper() == 'THE':
count += 1 |
print("BMI Calculator\n")
weight = float(input("Input your weight (kg.) : "))
height = float(input("Input your height (cm.) : ")) / 100
bmi = weight / height ** 2
print("\nYour BMI = {:15,.2f}".format(bmi))
# print("\nYour BMI = {0:.2f}".format(float(input("Input your weight (kg.) : ")) / ((float(input("In... | print('BMI Calculator\n')
weight = float(input('Input your weight (kg.) : '))
height = float(input('Input your height (cm.) : ')) / 100
bmi = weight / height ** 2
print('\nYour BMI = {:15,.2f}'.format(bmi)) |
"""
* User: lotus_zero
* Date: 11/17/18
* Time: 16:25 PM
* Brief: A program to calculate Multiple Circle Area with Check
"""
PI = 3.14159
def process (radius):
return PI * radius * radius
def main ():
radius = 0.0
area = 0.0
n = int(input("# of Circles? \n"))
for i in range (0,n):
ra... | """
* User: lotus_zero
* Date: 11/17/18
* Time: 16:25 PM
* Brief: A program to calculate Multiple Circle Area with Check
"""
pi = 3.14159
def process(radius):
return PI * radius * radius
def main():
radius = 0.0
area = 0.0
n = int(input('# of Circles? \n'))
for i in range(0, n):
radius... |
# O(N) Solution:
def leftIndex(n,arr,x):
for i in range(n):
if arr[i] == x:
return i
return -1
#______________________________________________________________________________________
# O(logN) Solution: Using Binary Search to find the first occurence of the element
def leftI... | def left_index(n, arr, x):
for i in range(n):
if arr[i] == x:
return i
return -1
def left_index(N, A, x):
lo = 0
hi = N - 1
mid = lo + (hi - lo) // 2
while lo <= hi:
mid = lo + (hi - lo) // 2
if A[mid] == x and mid == 0 or (A[mid] == x and A[mid - 1] < x):
... |
'''
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow... | """
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow... |
class Try(object):
@staticmethod
def print_hi():
print('hi')
| class Try(object):
@staticmethod
def print_hi():
print('hi') |
class Endpoint:
def __init__(self, ID, data_center_latency):
self.ID = ID
self.data_center_latency = data_center_latency
self.cache_server_connections = []
# def get_connection(self, cs):
# if(cs in self.cache_server_connections_hash.keys()):
# return self.cache_serv... | class Endpoint:
def __init__(self, ID, data_center_latency):
self.ID = ID
self.data_center_latency = data_center_latency
self.cache_server_connections = [] |
# 1038
code, quantity = input().split(" ")
code = int(code)
quantity = int(quantity)
if code == 1:
print("Total: R$ {0:.2f}".format(quantity * 4.00))
elif code == 2:
print("Total: R$ {0:.2f}".format(quantity * 4.50))
elif code == 3:
print("Total: R$ {0:.2f}".format(quantity * 5.00))
elif code == 4:
prin... | (code, quantity) = input().split(' ')
code = int(code)
quantity = int(quantity)
if code == 1:
print('Total: R$ {0:.2f}'.format(quantity * 4.0))
elif code == 2:
print('Total: R$ {0:.2f}'.format(quantity * 4.5))
elif code == 3:
print('Total: R$ {0:.2f}'.format(quantity * 5.0))
elif code == 4:
print('Total... |
expected_output = {
"route-information": {
"route-table": {
"active-route-count": "929",
"destination-count": "929",
"hidden-route-count": "0",
"holddown-route-count": "0",
"rt": [
{
"rt-destination": "10.220.0.0... | expected_output = {'route-information': {'route-table': {'active-route-count': '929', 'destination-count': '929', 'hidden-route-count': '0', 'holddown-route-count': '0', 'rt': [{'rt-destination': '10.220.0.0/16', 'rt-entry': {'active-tag': '*', 'as-path': '(65151 65000) I', 'bgp-metric-flags': 'Nexthop Change', 'local-... |
# -*- coding: utf-8 -*-
class Incrementor:
def __init__(self, inf_bound, increment, sup_bound, step_duration):
"""Build a new Incrementor.
Args:
inf_bound (int or float): The inf bound (included).
increment (int or float): The step increment.
sup_bound (int or f... | class Incrementor:
def __init__(self, inf_bound, increment, sup_bound, step_duration):
"""Build a new Incrementor.
Args:
inf_bound (int or float): The inf bound (included).
increment (int or float): The step increment.
sup_bound (int or float): The sup bound (e... |
# Modulo
for i in range(0, 101):
if i % 2 == 0:
print (str(i) + " is even")
else:
print (str(i) + " is odd")
print ("----------------------")
# Without modulo
for i in range (0,101):
num = int(i/2)
if (num * 2 == i):
print (str(i) + " is even")
else:
print (str(i) + " is odd")
| for i in range(0, 101):
if i % 2 == 0:
print(str(i) + ' is even')
else:
print(str(i) + ' is odd')
print('----------------------')
for i in range(0, 101):
num = int(i / 2)
if num * 2 == i:
print(str(i) + ' is even')
else:
print(str(i) + ' is odd') |
# csamiselo@github.com 15.10.2019
print("This is how i count my livestock")
print("Goats",12 + 30 + 60)
print("Cows", 13 + 15 + 10)
print ("Layers" ,1000 + 250 + 503 )
print ("Are the layers more than the goats")
print (12 + 30 + 60 < 1000 + 250 +503 )
| print('This is how i count my livestock')
print('Goats', 12 + 30 + 60)
print('Cows', 13 + 15 + 10)
print('Layers', 1000 + 250 + 503)
print('Are the layers more than the goats')
print(12 + 30 + 60 < 1000 + 250 + 503) |
class CeleryConfig:
# List of modules to import when the Celery worker starts.
imports = ('apps.tasks',)
## Broker settings.
broker_url = 'amqp://'
## Disable result backent and also ignore results.
task_ignore_result = True
| class Celeryconfig:
imports = ('apps.tasks',)
broker_url = 'amqp://'
task_ignore_result = True |
def if_pycaffe(if_true, if_false = []):
return select({
"@caffe_tools//:caffe_python_layer": if_true,
"//conditions:default": if_false
})
def caffe_pkg(label):
return select({
"//conditions:default": ["@caffe//" + label],
"@caffe_tools//:use_caffe_rcnn": ["@caffe_rcnn//" + label],
"... | def if_pycaffe(if_true, if_false=[]):
return select({'@caffe_tools//:caffe_python_layer': if_true, '//conditions:default': if_false})
def caffe_pkg(label):
return select({'//conditions:default': ['@caffe//' + label], '@caffe_tools//:use_caffe_rcnn': ['@caffe_rcnn//' + label], '@caffe_tools//:use_caffe_ssd': ['... |
frase = "Nos estamos procurando o rubi na floresta"
rubi = frase[24:29]
print (rubi) | frase = 'Nos estamos procurando o rubi na floresta'
rubi = frase[24:29]
print(rubi) |
def spiralTraverse(array):
num_elements = len(array) * len(array[0])
n = len(array)
m = len(array[0])
it = 0
result = []
while num_elements > 0:
# Up side
for j in range(it, m - it):
result.append(array[it][j])
num_elements -= 1
if num_elemen... | def spiral_traverse(array):
num_elements = len(array) * len(array[0])
n = len(array)
m = len(array[0])
it = 0
result = []
while num_elements > 0:
for j in range(it, m - it):
result.append(array[it][j])
num_elements -= 1
if num_elements == 0:
... |
"""
This is the base class for any AI component. All AIs inherit from this module, and
implement the getMove() function, which takes a Grid object as a parameter and
returns a move.
"""
class BaseAI:
def getMove(self,grid):
pass | """
This is the base class for any AI component. All AIs inherit from this module, and
implement the getMove() function, which takes a Grid object as a parameter and
returns a move.
"""
class Baseai:
def get_move(self, grid):
pass |
"""
The Ceasar cipher is one of the simplest and one of the earliest known ciphers.
It is a type of substitution cipher that 'shifts' a letter by a fixed amount in the alphabet.
For example with a shift = 3:
a -> d
b -> e
.
.
.
z -> c
Programmed by Aladdin Persson <aladdin.persson at hotmail dot com>
* 2019-11-07 I... | """
The Ceasar cipher is one of the simplest and one of the earliest known ciphers.
It is a type of substitution cipher that 'shifts' a letter by a fixed amount in the alphabet.
For example with a shift = 3:
a -> d
b -> e
.
.
.
z -> c
Programmed by Aladdin Persson <aladdin.persson at hotmail dot com>
* 2019-11-07 I... |
class PantryModel:
def get_ingredients(self, user_id):
"""Get all ingredients from in pantry and return a list of instances
of the ingredient class.
"""
pass
| class Pantrymodel:
def get_ingredients(self, user_id):
"""Get all ingredients from in pantry and return a list of instances
of the ingredient class.
"""
pass |
#
# @lc app=leetcode id=2 lang=python3
#
# [2] Add Two Numbers
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
... | class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
"""
time: O(len(n)) n : max(len(l1), len(l2))
space: O(len(n))
"""
total = cur = list_node(0)
carry = 0
while l1 or l2 or carry:
sum_digit = carry
if l... |
{
PDBConst.Name: "paymentmode",
PDBConst.Columns: [
{
PDBConst.Name: "ID",
PDBConst.Attributes: ["tinyint", "not null", "primary key"]
},
{
PDBConst.Name: "Name",
PDBConst.Attributes: ["varchar(128)", "not null"]
},
{
PDBConst.Name: "SID",
PDBC... | {PDBConst.Name: 'paymentmode', PDBConst.Columns: [{PDBConst.Name: 'ID', PDBConst.Attributes: ['tinyint', 'not null', 'primary key']}, {PDBConst.Name: 'Name', PDBConst.Attributes: ['varchar(128)', 'not null']}, {PDBConst.Name: 'SID', PDBConst.Attributes: ['varchar(128)', 'not null']}], PDBConst.Initials: [{'Name': "'Cre... |
class Graph(object):
def __init__(self, graph_dict=None):
if graph_dict == None:
graph_dict = {}
self.__graph_dict = graph_dict
| class Graph(object):
def __init__(self, graph_dict=None):
if graph_dict == None:
graph_dict = {}
self.__graph_dict = graph_dict |
def add_reporter_email_recipients(client=None,
project_key=None,
scenario_id=None,
recipients=[]):
"""Append additional recipients to a scenario email reporter.
"""
prj = client.get_project(project_key)
... | def add_reporter_email_recipients(client=None, project_key=None, scenario_id=None, recipients=[]):
"""Append additional recipients to a scenario email reporter.
"""
prj = client.get_project(project_key)
scn_settings = prj.get_scenario(scenario_id).get_settings()
reporters = scn_settings.raw_reporter... |
main = {
'General': {
'Prop': {
'Labels': 'rw',
'AlarmStatus': 'r-'
}
}
}
cfgm = {
'General': {
'Prop': {
'Blacklist': 'rw'
}
}
}
fm = {
'Status': {
'Prop': {
'AlarmStatus': 'r-'
},
'Cmd': (
... | main = {'General': {'Prop': {'Labels': 'rw', 'AlarmStatus': 'r-'}}}
cfgm = {'General': {'Prop': {'Blacklist': 'rw'}}}
fm = {'Status': {'Prop': {'AlarmStatus': 'r-'}, 'Cmd': ('Acknowledge',)}, 'Configuration': {'Prop': {'AlarmConfiguration': 'rw'}}, 'DuplicatedMac': {'Prop': {'DuplicatedMacAccessList': 'r-'}, 'Cmd': ('F... |
tiles = [
# Riker's Island - https://www.openstreetmap.org/relation/3955540
(10, 301, 384, 'Rikers Island'),
# SF County Jail - https://www.openstreetmap.org/way/103383866
(14, 2621, 6332, 'SF County Jail')
]
for z, x, y, name in tiles:
assert_has_feature(
z, x, y, 'pois',
{ 'kind':... | tiles = [(10, 301, 384, 'Rikers Island'), (14, 2621, 6332, 'SF County Jail')]
for (z, x, y, name) in tiles:
assert_has_feature(z, x, y, 'pois', {'kind': 'prison', 'name': name})
assert_has_feature(10, 301, 384, 'landuse', {'kind': 'prison'}) |
def median(x):
sorted_x = sorted(x)
midpoint = len(x) // 2
if len(x) % 2:
return sorted_x[midpoint]
else:
return (sorted_x[midpoint]+sorted_x[midpoint-1])/2
assert median([1]) == 1
assert median([1, 2]) == 1.5
assert median([1, 2, 3]) == 2
assert median([3,1,2]) == 2
assert medi... | def median(x):
sorted_x = sorted(x)
midpoint = len(x) // 2
if len(x) % 2:
return sorted_x[midpoint]
else:
return (sorted_x[midpoint] + sorted_x[midpoint - 1]) / 2
assert median([1]) == 1
assert median([1, 2]) == 1.5
assert median([1, 2, 3]) == 2
assert median([3, 1, 2]) == 2
assert media... |
#!/usr/bin/python3
#https://codeforces.com/contest/1426/problem/F
def f(s):
_,a,ab,abc = 1,0,0,0
for c in s:
if c=='a':
a += _
elif c=='b':
ab += a
elif c=='c':
abc += ab
else:
abc *= 3
abc += ab
ab *=... | def f(s):
(_, a, ab, abc) = (1, 0, 0, 0)
for c in s:
if c == 'a':
a += _
elif c == 'b':
ab += a
elif c == 'c':
abc += ab
else:
abc *= 3
abc += ab
ab *= 3
ab += a
a *= 3
a +... |
DEBUG = True
INSTAGRAM_CLIENT_ID = ''
INSTAGRAM_CLIENT_SECRET = ''
INSTAGRAM_CALLBACK = 'http://cameo.gala-isen.fr/api/instagram/hub'
MONGODB_NAME = 'cameo'
MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
REDIS_HOST = 'localhost'
REDIS_PORT = 6379 | debug = True
instagram_client_id = ''
instagram_client_secret = ''
instagram_callback = 'http://cameo.gala-isen.fr/api/instagram/hub'
mongodb_name = 'cameo'
mongodb_host = 'localhost'
mongodb_port = 27017
redis_host = 'localhost'
redis_port = 6379 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.