content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# OpenWeatherMap API Key
weather_api_key = "Insert your own key"
# Google API Key
g_key = "Insert your own key"
| weather_api_key = 'Insert your own key'
g_key = 'Insert your own key' |
"Tests for pug bzl definitions"
load("@bazel_tools//tools/build_rules:test_rules.bzl", "file_test", "rule_test")
def _pug_binary_test(package):
rule_test(
name = "hello_world_rule_test",
generates = ["main.html"],
rule = package + "/hello_world:hello_world"
)
file_test(
na... | """Tests for pug bzl definitions"""
load('@bazel_tools//tools/build_rules:test_rules.bzl', 'file_test', 'rule_test')
def _pug_binary_test(package):
rule_test(name='hello_world_rule_test', generates=['main.html'], rule=package + '/hello_world:hello_world')
file_test(name='hello_world_file_test', file=package + ... |
class Solution:
def countGoodSubstrings(self, s: str) -> int:
count, i, end = 0, 2, len(s)
while i < end:
a, b, c = s[i-2], s[i-1], s[i]
if a == b == c:
i += 2
continue
count += a != b and b != c and a != c
i += 1
... | class Solution:
def count_good_substrings(self, s: str) -> int:
(count, i, end) = (0, 2, len(s))
while i < end:
(a, b, c) = (s[i - 2], s[i - 1], s[i])
if a == b == c:
i += 2
continue
count += a != b and b != c and (a != c)
... |
(
XL_CELL_EMPTY, #0
XL_CELL_TEXT, #1
XL_CELL_NUMBER, #2
XL_CELl_DATE, #3
XL_CELL_BOOLEAN,#4
XL_CELL_ERROR, #5
XL_CELL_BLANK, #6
) = range(7)
ctype_text = {
XL_CELL_EMPTY: 'empty',
XL_CELL_TEXT:'text',
XL_CELL_NUMBER:'number',
XL_CELl_DATE:'date',
XL_CELL_BOOLEAN:'... | (xl_cell_empty, xl_cell_text, xl_cell_number, xl_ce_ll_date, xl_cell_boolean, xl_cell_error, xl_cell_blank) = range(7)
ctype_text = {XL_CELL_EMPTY: 'empty', XL_CELL_TEXT: 'text', XL_CELL_NUMBER: 'number', XL_CELl_DATE: 'date', XL_CELL_BOOLEAN: 'boolean', XL_CELL_ERROR: 'error', XL_CELL_BLANK: 'blank'} |
"""
Dictionary key must be immutable
"""
string_dict = dict({"1": "1st", "2": "2nd", "3": "3rd"})
def add_element_to_string_dict(key: str, value: str):
string_dict[key] = value
def delete_element_to_string_dict(key: str):
del string_dict[key]
def get_element_from_string_dict(key: str):
if key in strin... | """
Dictionary key must be immutable
"""
string_dict = dict({'1': '1st', '2': '2nd', '3': '3rd'})
def add_element_to_string_dict(key: str, value: str):
string_dict[key] = value
def delete_element_to_string_dict(key: str):
del string_dict[key]
def get_element_from_string_dict(key: str):
if key in string_d... |
def sum6(n):
nums = [i for i in range(1, n + 1)]
return sum(nums)
N = 10
S = sum6(N)
print(S)
| def sum6(n):
nums = [i for i in range(1, n + 1)]
return sum(nums)
n = 10
s = sum6(N)
print(S) |
class ValveStatus(object):
"""
An enumeration of possible valve states. OPEN_AND_DISABLED should never happen.
"""
OPEN_AND_ENABLED, CLOSED_AND_ENABLED, OPEN_AND_DISABLED, CLOSED_AND_DISABLED = (i for i in range(4))
| class Valvestatus(object):
"""
An enumeration of possible valve states. OPEN_AND_DISABLED should never happen.
"""
(open_and_enabled, closed_and_enabled, open_and_disabled, closed_and_disabled) = (i for i in range(4)) |
def solve():
s = sum((x ** x for x in range(1, 1001)))
print(str(s)[-10:])
if __name__ == '__main__':
solve()
| def solve():
s = sum((x ** x for x in range(1, 1001)))
print(str(s)[-10:])
if __name__ == '__main__':
solve() |
#!/usr/bin/env python
"""Contains extractor configuration information
"""
# Setup the name of our extractor.
EXTRACTOR_NAME = ""
# Name of scientific method for this extractor. Leave commented out if it's unknown
#METHOD_NAME = ""
# The version number of the extractor
VERSION = "1.0"
# The extractor description
DE... | """Contains extractor configuration information
"""
extractor_name = ''
version = '1.0'
description = ''
author_name = ''
author_email = ''
repository = ''
variable_names = '' |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
tmp = head
while tmp and tmp.next:... | class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def middle_node(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
tmp = head
while tmp and tmp.next:
head = head.next
... |
listaDePalavras = ('Aprender','Programar','Linguagem','Python','Curso','Gratis',
'Estudar','Praticar','Trabalhar','Mercado','Programador',
'Futuro')
for palavras in listaDePalavras:
print(f'\n A palavra {palavras} temos', end=' ')
for letras in palavras:
if letras.l... | lista_de_palavras = ('Aprender', 'Programar', 'Linguagem', 'Python', 'Curso', 'Gratis', 'Estudar', 'Praticar', 'Trabalhar', 'Mercado', 'Programador', 'Futuro')
for palavras in listaDePalavras:
print(f'\n A palavra {palavras} temos', end=' ')
for letras in palavras:
if letras.lower() in 'aeiou':
... |
x = 1
y = 'Hello'
z = 10.123
d = x + z
print(d)
print(type(x))
print(type(y))
print(y.upper())
print(y.lower())
print(type(z))
a = [1,2,3,4,5,6,6,7,8]
print(len(a))
print(a.count(6))
b = list(range(10,100,10))
print(b)
stud_marks = {"Madhan":90, "Raj":25,"Mani":80}
print(stud_marks.keys())
print(stud_marks.va... | x = 1
y = 'Hello'
z = 10.123
d = x + z
print(d)
print(type(x))
print(type(y))
print(y.upper())
print(y.lower())
print(type(z))
a = [1, 2, 3, 4, 5, 6, 6, 7, 8]
print(len(a))
print(a.count(6))
b = list(range(10, 100, 10))
print(b)
stud_marks = {'Madhan': 90, 'Raj': 25, 'Mani': 80}
print(stud_marks.keys())
print(stud_mark... |
# Generate .travis.yml automatically
# Configuration for Linux
configs = [
# OS, OS version, compiler, build type, task
("ubuntu", "18.04", "gcc", "DefaultDebug", "Test"),
("ubuntu", "18.04", "gcc", "DefaultRelease", "Test"),
("debian", "9", "gcc", "DefaultDebug", "Test"),
("debian", "9", "gcc", "D... | configs = [('ubuntu', '18.04', 'gcc', 'DefaultDebug', 'Test'), ('ubuntu', '18.04', 'gcc', 'DefaultRelease', 'Test'), ('debian', '9', 'gcc', 'DefaultDebug', 'Test'), ('debian', '9', 'gcc', 'DefaultRelease', 'Test'), ('debian', '10', 'gcc', 'DefaultDebug', 'Test'), ('debian', '10', 'gcc', 'DefaultRelease', 'Test'), ('ubu... |
#########################
# #
# Developer: Luis Regus #
# Date: 11/24/15 #
# #
#########################
NORTH = "north"
EAST = "east"
SOUTH = "south"
WEST = "west"
class Robot:
'''
Custom object used to represent a robot
'''
def __init__(self, ... | north = 'north'
east = 'east'
south = 'south'
west = 'west'
class Robot:
"""
Custom object used to represent a robot
"""
def __init__(self, direction=NORTH, x_coord=0, y_coord=0):
self.coordinates = (x_coord, y_coord)
self.bearing = direction
def turn_right(self):
dire... |
class ToolBoxBaseException(Exception):
status_code = 500
error_name = 'base_exception'
def __init__(self, message):
self.message = message
def to_dict(self):
return dict(error_name=self.error_name, message=self.message)
class UnknownError(ToolBoxBaseException):
status_code = 500
... | class Toolboxbaseexception(Exception):
status_code = 500
error_name = 'base_exception'
def __init__(self, message):
self.message = message
def to_dict(self):
return dict(error_name=self.error_name, message=self.message)
class Unknownerror(ToolBoxBaseException):
status_code = 500
... |
'''
lab 8 functions
'''
#3.1
def count_words(input_str):
return len(input_str.split())
#print(count_words('This is a string'))
#3.2
demo_str = 'Hello World!'
print(count_words(demo_str))
#3.3
def find_min(num_list):
min_item = num_list[0]
for num in num_list:
if type(num) is not str:
... | """
lab 8 functions
"""
def count_words(input_str):
return len(input_str.split())
demo_str = 'Hello World!'
print(count_words(demo_str))
def find_min(num_list):
min_item = num_list[0]
for num in num_list:
if type(num) is not str:
if min_item >= num:
min_item = num
r... |
users = {
'name': 'Elena',
'age': 100,
'town': 'Varna'
}
for key, value in users.items():
print(key, value)
for key in users.keys():
print(key)
for value in users.values():
print(value)
| users = {'name': 'Elena', 'age': 100, 'town': 'Varna'}
for (key, value) in users.items():
print(key, value)
for key in users.keys():
print(key)
for value in users.values():
print(value) |
class Solution:
def getSum(self, a: int, b: int) -> int:
# 32 bits integer max and min
MAX = 0x7FFFFFFF
MIN = 0x80000000
mask = 0xFFFFFFFF
while b != 0:
carry = a & b
a, b = (a ^ b) & mask, (carry << 1) & mask
ret... | class Solution:
def get_sum(self, a: int, b: int) -> int:
max = 2147483647
min = 2147483648
mask = 4294967295
while b != 0:
carry = a & b
(a, b) = ((a ^ b) & mask, carry << 1 & mask)
return a if a <= MAX else ~(a ^ mask) |
""" Compatibility related items. """
__author__ = "Brian Allen Vanderburg II"
__copyright__ = "Copyright (C) 2019 Brian Allen Vanderburg II"
__license__ = "Apache License 2.0"
| """ Compatibility related items. """
__author__ = 'Brian Allen Vanderburg II'
__copyright__ = 'Copyright (C) 2019 Brian Allen Vanderburg II'
__license__ = 'Apache License 2.0' |
CONFIG = {
"main_dir": "./tests/",
"results_dir": "results/",
"manips_dir": "manips/",
"parameters_dir": "parameters/",
"tikz_dir": "tikz/"
}
| config = {'main_dir': './tests/', 'results_dir': 'results/', 'manips_dir': 'manips/', 'parameters_dir': 'parameters/', 'tikz_dir': 'tikz/'} |
stack = []
while True:
print("1. Insert Element in the stack")
print("2. Remove element from stack")
print("3. Display elements in stack")
print("4. Exit")
choice = int(input("Enter your Choice: "))
if choice == 1:
if len(stack) == 5:
print("Sorry, stack is already full")... | stack = []
while True:
print('1. Insert Element in the stack')
print('2. Remove element from stack')
print('3. Display elements in stack')
print('4. Exit')
choice = int(input('Enter your Choice: '))
if choice == 1:
if len(stack) == 5:
print('Sorry, stack is already full')
... |
# Operations on Sets ?
# Consider the following set:
S = {1,8,2,3}
# Len(s) : Returns 4, the length of the set
S = {1,8,2,3}
print(len(S)) #Length of the Set
# remove(8) : Updates the set S and removes 8 from S
S = {1,8,2,3}
S.remove(8) #Remove of the Set
print(S)
# pop() : Removes an arbitrary element fro... | s = {1, 8, 2, 3}
s = {1, 8, 2, 3}
print(len(S))
s = {1, 8, 2, 3}
S.remove(8)
print(S)
s = {1, 8, 2, 3}
print(S.pop())
s = {1, 8, 2, 3}
print(S.clear())
s = {1, 8, 2, 3}
print(S.union())
s = {1, 8, 2, 3}
print(S.intersection()) |
idade = str(input("idade :"))
if not idade.isnumeric():
print("oi")
else:
print("passou") | idade = str(input('idade :'))
if not idade.isnumeric():
print('oi')
else:
print('passou') |
CHUNK_SIZE = 16
CHUNK_SIZE_PIXELS = 256
RATTLE_DELAY = 10
RATTLE_RANGE = 3 | chunk_size = 16
chunk_size_pixels = 256
rattle_delay = 10
rattle_range = 3 |
def is_std_ref(string):
"""
It finds whether the string has reference in itself.
"""
return 'Prop.' in string or 'C.N.' in string or 'Post.' in string or 'Def.' in string
def std_ref_form(ref_string):
"""
Deletes unnecessary chars from the string.
Seperates combined references.
return... | def is_std_ref(string):
"""
It finds whether the string has reference in itself.
"""
return 'Prop.' in string or 'C.N.' in string or 'Post.' in string or ('Def.' in string)
def std_ref_form(ref_string):
"""
Deletes unnecessary chars from the string.
Seperates combined references.
return... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast , slow = head, head
w... | class Solution(object):
def detect_cycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
(fast, slow) = (head, head)
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
s1 = ... |
def solution(string, markers):
string = string.split('\n')
result = ''
for line in string:
for character in line:
if character not in markers:
result += character
else:
result = result[:-1]
break
result += '\n'
... | def solution(string, markers):
string = string.split('\n')
result = ''
for line in string:
for character in line:
if character not in markers:
result += character
else:
result = result[:-1]
break
result += '\n'
retur... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
errno.py
Error Code Define
Copyright: All Rights Reserved 2019-2019
History:
1 2019-07-14 Liu Yu (source@liuyu.com) Initial Version
'''
SUCCESS = 'SUCC'
ERROR_SUCCESS = SUCCESS
FAIL = 'FAIL'
ERROR = FAIL
ERROR_INVALID = 'INVALID'
ERROR_UNSUPPORT = 'UNSU... | """
errno.py
Error Code Define
Copyright: All Rights Reserved 2019-2019
History:
1 2019-07-14 Liu Yu (source@liuyu.com) Initial Version
"""
success = 'SUCC'
error_success = SUCCESS
fail = 'FAIL'
error = FAIL
error_invalid = 'INVALID'
error_unsupport = 'UNSUPPORT' |
# Write a Python program to add leading zeroes to a string
String = 'hello'
print(String.rjust(9, '0'))
| string = 'hello'
print(String.rjust(9, '0')) |
RETENTION_SQL = """
SELECT
datediff(%(period)s, {trunc_func}(toDateTime(%(start_date)s)), reference_event.event_date) as base_interval,
datediff(%(period)s, reference_event.event_date, {trunc_func}(toDateTime(event_date))) as intervals_from_base,
COUNT(DISTINCT event.target) count
FROM (
{returning_even... | retention_sql = '\nSELECT\n datediff(%(period)s, {trunc_func}(toDateTime(%(start_date)s)), reference_event.event_date) as base_interval,\n datediff(%(period)s, reference_event.event_date, {trunc_func}(toDateTime(event_date))) as intervals_from_base,\n COUNT(DISTINCT event.target) count\nFROM (\n {returning_... |
def dos2unix(file_path):
"""This is copied from Stack Overflow pretty much as is
Opens a file, converts the line endings to unix, and
then overwrites the file.
"""
# replacement strings
WINDOWS_LINE_ENDING = b'\r\n'
UNIX_LINE_ENDING = b'\n'
with open(file_path, 'rb') as open_file:
... | def dos2unix(file_path):
"""This is copied from Stack Overflow pretty much as is
Opens a file, converts the line endings to unix, and
then overwrites the file.
"""
windows_line_ending = b'\r\n'
unix_line_ending = b'\n'
with open(file_path, 'rb') as open_file:
content = open_file.rea... |
class InputMode:
def __init__(self):
pass
def GetTitle(self):
return ""
def TitleHighlighted(self):
return True
def GetHelpText(self):
return None
def OnMouse(self, event):
pass
def OnKeyDown(self, event):
pass
def OnKe... | class Inputmode:
def __init__(self):
pass
def get_title(self):
return ''
def title_highlighted(self):
return True
def get_help_text(self):
return None
def on_mouse(self, event):
pass
def on_key_down(self, event):
pass
def on_key_up(self,... |
# -*- coding: utf-8 -*-
"""Generic errors for immutable data validation."""
class ImmutableDataValidationError(Exception):
def __init__(self, msg: str = None, append_text: str = None):
if append_text is not None:
msg = "%s %s" % (msg, append_text)
super().__init__(msg)
class Immutabl... | """Generic errors for immutable data validation."""
class Immutabledatavalidationerror(Exception):
def __init__(self, msg: str=None, append_text: str=None):
if append_text is not None:
msg = '%s %s' % (msg, append_text)
super().__init__(msg)
class Immutabledatavalidationvalueerror(Imm... |
#!/usr/bin/env python3
""" String Objects
"""
def get_str():
"""
Prompt user for a string
"""
valid_input = False
while not valid_input:
try:
sample_str = input('>>> ')
valid_input = True
return sample_str
except Exception as err:
r... | """ String Objects
"""
def get_str():
"""
Prompt user for a string
"""
valid_input = False
while not valid_input:
try:
sample_str = input('>>> ')
valid_input = True
return sample_str
except Exception as err:
return 'Expected String : ... |
src = Split('''
hal_test.c
''')
component = aos_component('hal_test', src)
component.add_cflags('-Wall')
component.add_cflags('-Werror')
| src = split('\n hal_test.c\n')
component = aos_component('hal_test', src)
component.add_cflags('-Wall')
component.add_cflags('-Werror') |
class resizable_array:
def __init__(self,arraysize):
self.arraysize = arraysize
self.array = [None for i in range(self.arraysize)]
self.temp =1
def __insert(self,value):
for i in range(len(self.array)):
if self.array[i] == None:
self.array[i] = valu... | class Resizable_Array:
def __init__(self, arraysize):
self.arraysize = arraysize
self.array = [None for i in range(self.arraysize)]
self.temp = 1
def __insert(self, value):
for i in range(len(self.array)):
if self.array[i] == None:
self.array[i] = va... |
qt=int(input())
for i in range(qt):
jogadores=input().split()
nome1=str(jogadores[0])
escolha1=str(jogadores[1])
nome2 = str(jogadores[2])
escolha2 = str(jogadores[3])
numeros=input().split()
numerosJ1=int(numeros[0])
numerosJ2=int(numeros[1])
if escolha1=="PAR" and escolha2=="IMP... | qt = int(input())
for i in range(qt):
jogadores = input().split()
nome1 = str(jogadores[0])
escolha1 = str(jogadores[1])
nome2 = str(jogadores[2])
escolha2 = str(jogadores[3])
numeros = input().split()
numeros_j1 = int(numeros[0])
numeros_j2 = int(numeros[1])
if escolha1 == 'PAR' and... |
"""
Aliyun API
==========
The Aliyun API is well-documented at `dev.aliyun.com <http://dev.aliyun.com/thread.php?spm=0.0.0.0.MqTmNj&fid=8>`_.
Each service's API is very similar: There are regions, actions, and each action has many parameters.
It is an OAuth2 API, so you need to have an ID and a secret. You can get the... | """
Aliyun API
==========
The Aliyun API is well-documented at `dev.aliyun.com <http://dev.aliyun.com/thread.php?spm=0.0.0.0.MqTmNj&fid=8>`_.
Each service's API is very similar: There are regions, actions, and each action has many parameters.
It is an OAuth2 API, so you need to have an ID and a secret. You can get the... |
class VertexPaint:
use_group_restrict = None
use_normal = None
use_spray = None
| class Vertexpaint:
use_group_restrict = None
use_normal = None
use_spray = None |
@app.post('/login')
def login(response: Response):
...
token = manager.create_access_token(
data=dict(sub=user.email)
)
manager.set_cookie(response, token)
return response | @app.post('/login')
def login(response: Response):
...
token = manager.create_access_token(data=dict(sub=user.email))
manager.set_cookie(response, token)
return response |
print("Pass statement in Python");
for i in range (1,11,1):
if(i==3):
i = i + 1;
pass;
else:
print(i);
i = i + 1;
| print('Pass statement in Python')
for i in range(1, 11, 1):
if i == 3:
i = i + 1
pass
else:
print(i)
i = i + 1 |
# Runtime error
N = int(input())
X = list(map(int, input().split())) # Memory problem
tot = sum(X)
visited = [False for k in range(N)]
currentStar = 0
while True:
if currentStar < 0 or currentStar > N-1:
break
else:
visited[currentStar] = True
if X[currentStar] >= 1:
if X[... | n = int(input())
x = list(map(int, input().split()))
tot = sum(X)
visited = [False for k in range(N)]
current_star = 0
while True:
if currentStar < 0 or currentStar > N - 1:
break
else:
visited[currentStar] = True
if X[currentStar] >= 1:
if X[currentStar] % 2 == 0:
... |
n = int(input())
for i in range(n):
dieta = list(input())
cafe = list(input())
almoco = list(input())
todos = cafe + almoco
cheat = False
for comido in todos:
if comido in dieta:
dieta.remove(comido)
else:
cheat = True
if not cheat:
print("".join(sorted(dieta)))
else:
print("CHEATER")
| n = int(input())
for i in range(n):
dieta = list(input())
cafe = list(input())
almoco = list(input())
todos = cafe + almoco
cheat = False
for comido in todos:
if comido in dieta:
dieta.remove(comido)
else:
cheat = True
if not cheat:
print(''.jo... |
first_name = input("Enter you name")
last_name = input("Enter you surname")
past_year = input("MS program start year?")
a = 2 + int(past_year)
print(f"{first_name} {last_name} {past_year} you are graduate in {a}") | first_name = input('Enter you name')
last_name = input('Enter you surname')
past_year = input('MS program start year?')
a = 2 + int(past_year)
print(f'{first_name} {last_name} {past_year} you are graduate in {a}') |
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton','Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
#print(class_1)
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
#print(class_2)
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
courses = {'Math': 65, 'English... |
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
if not pushed and not popped:
return True
aux = []
idx = 0
for _ in pushed:
aux.append(_)
while aux and aux[-1] == popped[idx]:
aux.pop(... | class Solution:
def validate_stack_sequences(self, pushed: List[int], popped: List[int]) -> bool:
if not pushed and (not popped):
return True
aux = []
idx = 0
for _ in pushed:
aux.append(_)
while aux and aux[-1] == popped[idx]:
aux... |
widget = WidgetDefault()
widget.border = "None"
commonDefaults["GroupBoxWidget"] = widget
def generateGroupBoxWidget(file, screen, box, parentName):
name = box.getName()
file.write(" %s = leGroupBoxWidget_New();" % (name))
generateBaseWidget(file, screen, box)
writeSetStringAssetName(file, name,... | widget = widget_default()
widget.border = 'None'
commonDefaults['GroupBoxWidget'] = widget
def generate_group_box_widget(file, screen, box, parentName):
name = box.getName()
file.write(' %s = leGroupBoxWidget_New();' % name)
generate_base_widget(file, screen, box)
write_set_string_asset_name(file, n... |
# Problem Statement Link: https://www.hackerrank.com/challenges/the-minion-game/problem
def minion_game(w):
s = k = 0
v = ['A', 'E', 'I', 'O', 'U']
for x in range( len(w) ):
if w[x] in v:
k += (len(w)-x)
else:
s += (len(w)-x)
if s == k: print("Draw")
el... | def minion_game(w):
s = k = 0
v = ['A', 'E', 'I', 'O', 'U']
for x in range(len(w)):
if w[x] in v:
k += len(w) - x
else:
s += len(w) - x
if s == k:
print('Draw')
elif s > k:
print('Stuart', s)
else:
print('Kevin', k)
if __name__ == '... |
a = 10
print(a)
| a = 10
print(a) |
def stations_level_over_threshold(stations, tol): #2B part 2
stationList = []
for station in stations:
if station.typical_range_consistent() and station.latest_level != None:
if station.relative_water_level() > tol:
stationList.append((station, station.relative_water_level()... | def stations_level_over_threshold(stations, tol):
station_list = []
for station in stations:
if station.typical_range_consistent() and station.latest_level != None:
if station.relative_water_level() > tol:
stationList.append((station, station.relative_water_level()))
sort... |
lanches = ['X-Bacon','X-Tudo','X-Calabresa', 'CalaFrango','X-Salada','CalaFrango','X-Bacon','CalaFrango']
lanches_finais = []
print('Estamos sem CalaFrango')
while 'CalaFrango' in lanches:
lanches.remove('CalaFrango')
while lanches:
preparo = lanches.pop()
print('Preparei seu lanche de {}'.format(preparo)... | lanches = ['X-Bacon', 'X-Tudo', 'X-Calabresa', 'CalaFrango', 'X-Salada', 'CalaFrango', 'X-Bacon', 'CalaFrango']
lanches_finais = []
print('Estamos sem CalaFrango')
while 'CalaFrango' in lanches:
lanches.remove('CalaFrango')
while lanches:
preparo = lanches.pop()
print('Preparei seu lanche de {}'.format(prep... |
# -*- coding: utf-8 -*-
# list of system groups ordered descending by rights in application
groups = ['wheel', 'sudo', 'users']
| groups = ['wheel', 'sudo', 'users'] |
def escreva(frase):
a = len(frase)+2
print('~'*(a+2))
print(f' {frase}')
print('~' * (a + 2))
escreva('Gustavo Guanabara')
escreva('Curso de Python no YouTube')
escreva('CeV')
| def escreva(frase):
a = len(frase) + 2
print('~' * (a + 2))
print(f' {frase}')
print('~' * (a + 2))
escreva('Gustavo Guanabara')
escreva('Curso de Python no YouTube')
escreva('CeV') |
# Find the set of maximums and minimums in a series,
# with some tolerance for multiple max or minimums
# if some highest or lowest values in a series are
# tolerance_threshold away
def find_maxs_or_mins_in_series(series, kind, tolerance_threshold):
isolated_globals = []
if kind == "max":
global_max_or_min = s... | def find_maxs_or_mins_in_series(series, kind, tolerance_threshold):
isolated_globals = []
if kind == 'max':
global_max_or_min = series.max()
else:
global_max_or_min = series.min()
for (idx, val) in series.items():
if val == global_max_or_min or abs(global_max_or_min - val) < tole... |
load("//cipd/internal:cipd_client.bzl", "cipd_client_deps")
def cipd_deps():
cipd_client_deps()
| load('//cipd/internal:cipd_client.bzl', 'cipd_client_deps')
def cipd_deps():
cipd_client_deps() |
class Holding:
"""A single holding in a fund. Subclasses of Holding include Equity, Bond, and Cash."""
def __init__(self, name):
self.name = name
"""The name of the security."""
self.identifier_cusip = None
"""The CUSIP identifier for the security, if available and applica... | class Holding:
"""A single holding in a fund. Subclasses of Holding include Equity, Bond, and Cash."""
def __init__(self, name):
self.name = name
'The name of the security.'
self.identifier_cusip = None
'The CUSIP identifier for the security, if available and applicable.'
... |
'''
Detect Cantor set membership
Status: Accepted
'''
###############################################################################
def main():
"""Read input and print output"""
while True:
value = input()
if value == 'END':
break
value = float(value)
lhs, rhs,... | """
Detect Cantor set membership
Status: Accepted
"""
def main():
"""Read input and print output"""
while True:
value = input()
if value == 'END':
break
value = float(value)
(lhs, rhs, ternary) = (0.0, 1.0, '')
for _ in range(12):
third = (rhs - ... |
class State:
def __init__(self):
self.pixel = None
self.keyboard = None
self.keyboard_layout = None
pass
def start(self):
pass
def end(self):
pass
def onTick(self):
pass
def onButtonPress(self):
pass
def onButtonRelease(self):
... | class State:
def __init__(self):
self.pixel = None
self.keyboard = None
self.keyboard_layout = None
pass
def start(self):
pass
def end(self):
pass
def on_tick(self):
pass
def on_button_press(self):
pass
def on_button_release(s... |
def convert( s: str, numRows: int) -> str:
print('hi')
# Algorithm:
# Output: Linearize the zig zagged string matrix
# input: string and number of rows in which to make the string zag zag
# Algorithm steps:
# d and nd list /diagonal and nondiagonal lists
#remove all prints if pasting in leetc... | def convert(s: str, numRows: int) -> str:
print('hi')
if numRows == 1:
return s
step = 1
pos = 1
lines = {}
for c in s:
if pos not in lines:
print(pos, 'im pos', 'and im step', step)
lines[pos] = c
print(lines, 'when pos not in lines')
... |
class Node:
"""create a Node"""
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def __repr__(self):
return 'Node Val: {}'.format(self.val)
def __str__(self):
return str(self.val)
| class Node:
"""create a Node"""
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def __repr__(self):
return 'Node Val: {}'.format(self.val)
def __str__(self):
return str(self.val) |
class Solution:
def reconstructQueue(self, people: list) -> list:
if not people:
return []
def func(x):
return -x[0], x[1]
people.sort(key=func)
new_people = [people[0]]
for i in people[1:]:
new_people.insert(i[1], i)
return new_p... | class Solution:
def reconstruct_queue(self, people: list) -> list:
if not people:
return []
def func(x):
return (-x[0], x[1])
people.sort(key=func)
new_people = [people[0]]
for i in people[1:]:
new_people.insert(i[1], i)
return ne... |
# -*- coding: utf-8 -*-
"""
equip.visitors.classes
~~~~~~~~~~~~~~~~~~~~~~
Callback the visit method for each encountered class in the program.
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
class ClassVisitor(object):
"""
A class visitor that ... | """
equip.visitors.classes
~~~~~~~~~~~~~~~~~~~~~~
Callback the visit method for each encountered class in the program.
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
class Classvisitor(object):
"""
A class visitor that is triggered for all e... |
class Post():
def __init__(self, userIden, content, timestamp, image=None, score='0', replies=None):
self.userIden = userIden
self.content = content
self.timestamp = timestamp
self.image = image
self.score = score
self.replies = [] if not replies else replies
| class Post:
def __init__(self, userIden, content, timestamp, image=None, score='0', replies=None):
self.userIden = userIden
self.content = content
self.timestamp = timestamp
self.image = image
self.score = score
self.replies = [] if not replies else replies |
def radix_sort(alist, base=10):
if alist == []:
return
def key_factory(digit, base):
def key(alist, index):
return ((alist[index]//(base**digit)) % base)
return key
largest = max(alist)
exp = 0
while base**exp <= largest:
alist = counting_sort(alist, bas... | def radix_sort(alist, base=10):
if alist == []:
return
def key_factory(digit, base):
def key(alist, index):
return alist[index] // base ** digit % base
return key
largest = max(alist)
exp = 0
while base ** exp <= largest:
alist = counting_sort(alist, bas... |
N, *A = map(int, open(0).read().split())
result = 0
for i in range(2, 1000):
t = 0
for a in A:
if a % i == 0:
t += 1
result = max(result, t)
print(result)
| (n, *a) = map(int, open(0).read().split())
result = 0
for i in range(2, 1000):
t = 0
for a in A:
if a % i == 0:
t += 1
result = max(result, t)
print(result) |
#{
#Driver Code Starts
#Initial Template for Python 3
# } Driver Code Ends
#User function Template for python3
# Function to calculate average
def calc_average(nums):
# Your code here
mini = min(nums)
maxi = max(nums)
n = len(nums)
s = sum(nums)-mini-maxi
s = s//(n-2)
return s
#{ ... | def calc_average(nums):
mini = min(nums)
maxi = max(nums)
n = len(nums)
s = sum(nums) - mini - maxi
s = s // (n - 2)
return s
def main():
testcases = int(input())
while testcases > 0:
size_arr = int(input())
a = input().split()
arr = list()
for i in range... |
# in file: models/db_custom.py
db.define_table('company', Field('name', notnull = True, unique = True), format = '%(name)s')
db.define_table(
'contact',
Field('name', notnull = True),
Field('company', 'reference company'),
Field('picture', 'upload'),
Field('email', requires = IS_EMAIL()),
Field('phone... | db.define_table('company', field('name', notnull=True, unique=True), format='%(name)s')
db.define_table('contact', field('name', notnull=True), field('company', 'reference company'), field('picture', 'upload'), field('email', requires=is_email()), field('phone_number', requires=is_match('[\\d\\-\\(\\) ]+')), field('add... |
def main():
i = 0
while True:
print(i)
i += 1
if i > 5:
break
j = 10
while j < 100:
print(j)
j += 10
while 1:
print(j + i)
break
while 0.1:
print(j + i)
break
while 0:
print("This never executes")... | def main():
i = 0
while True:
print(i)
i += 1
if i > 5:
break
j = 10
while j < 100:
print(j)
j += 10
while 1:
print(j + i)
break
while 0.1:
print(j + i)
break
while 0:
print('This never executes')
... |
example = """
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#"""
example_list = [list(x) for x in example.split()]
with open('test.in', mode='r') as f:
puzzle_input = [list(x.strip()) for x in f.readlines()]
def tree_hitting_fun... | example = '\n..##.......\n#...#...#..\n.#....#..#.\n..#.#...#.#\n.#...##..#.\n..#.##.....\n.#.#.#....#\n.#........#\n#.##...#...\n#...##....#\n.#..#...#.#'
example_list = [list(x) for x in example.split()]
with open('test.in', mode='r') as f:
puzzle_input = [list(x.strip()) for x in f.readlines()]
def tree_hitting... |
'''
Synchronization phenomena in networked dynamics
'''
def kuramoto(G, k: float, w: Callable):
'''
Kuramoto lattice
k: coupling gain
w: intrinsic frequency
'''
phase = gds.node_gds(G)
w_vec = np.array([w(x) for x in phase.X])
phase.set_evolution(dydt=lambda t, y: w_vec + k * phase.div(np.sin(phase.grad())))
... | """
Synchronization phenomena in networked dynamics
"""
def kuramoto(G, k: float, w: Callable):
"""
Kuramoto lattice
k: coupling gain
w: intrinsic frequency
"""
phase = gds.node_gds(G)
w_vec = np.array([w(x) for x in phase.X])
phase.set_evolution(dydt=lambda t, y: w_vec + k * phase.div(np.sin(phase... |
'''
Determine sum of integer digits between two inclusive limits
Status: Accepted
'''
###############################################################################
def digit_sum(value):
"""Return the sum of all digits between 0 and input value"""
result = 0
if value > 0:
magnitude = value // 1... | """
Determine sum of integer digits between two inclusive limits
Status: Accepted
"""
def digit_sum(value):
"""Return the sum of all digits between 0 and input value"""
result = 0
if value > 0:
magnitude = value // 10
magnitude_sum = sum([int(i) for i in list(str(magnitude))])
resu... |
def Markov1_3D_BC_taper_init(particle, fieldset, time):
# Initialize random velocity magnitudes in the isopycnal plane
u_iso_prime_abs = ParcelsRandom.normalvariate(0, math.sqrt(fieldset.nusquared))
v_iso_prime_abs = ParcelsRandom.normalvariate(0, math.sqrt(fieldset.nusquared))
# (double) derivativ... | def markov1_3_d_bc_taper_init(particle, fieldset, time):
u_iso_prime_abs = ParcelsRandom.normalvariate(0, math.sqrt(fieldset.nusquared))
v_iso_prime_abs = ParcelsRandom.normalvariate(0, math.sqrt(fieldset.nusquared))
sx = -drhodx / drhodz
sy = -drhody / drhodz
sabs = math.sqrt(Sx ** 2 + Sy ** 2)
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalTraversalRec(self, root, row, col, columns):
if not root:
return
co... | class Solution:
def vertical_traversal_rec(self, root, row, col, columns):
if not root:
return
columns[col].append((row, root.val))
self.verticalTraversalRec(root.left, row + 1, col - 1, columns)
self.verticalTraversalRec(root.right, row + 1, col + 1, columns)
def v... |
'''
Author: Shuailin Chen
Created Date: 2021-09-14
Last Modified: 2021-09-25
content:
'''
_base_ = [
'../_base_/models/deeplabv3_r50a-d8.py',
'../_base_/datasets/sn6_sar_pro.py', '../_base_/default_runtime.py',
'../_base_/schedules/schedule_20k.py'
]
model = dict(
decode_head=dict(num_classes=2), auxi... | """
Author: Shuailin Chen
Created Date: 2021-09-14
Last Modified: 2021-09-25
content:
"""
_base_ = ['../_base_/models/deeplabv3_r50a-d8.py', '../_base_/datasets/sn6_sar_pro.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_20k.py']
model = dict(decode_head=dict(num_classes=2), auxiliary_head=dict(num... |
"""
Module provides state and state history for agent.
"""
class AgentState(object):
"""
AgentState class.
Agent state is a class that specifies current agent behaviour. It
provides methods that describe the way agent cooperate with
percepted stimulus coming from environment.
@attention: You ... | """
Module provides state and state history for agent.
"""
class Agentstate(object):
"""
AgentState class.
Agent state is a class that specifies current agent behaviour. It
provides methods that describe the way agent cooperate with
percepted stimulus coming from environment.
@attention: You ... |
# encoding=utf-8
d = dict(one=1, two=2)
d1 = {'one': 1, "two": 2}
d2 = dict()
d2['one'] = 1
d2['two'] = 2
# [(key,value), (key, value)]
my_dict = {}.setdefault().append(1)
print(my_dict[1]) | d = dict(one=1, two=2)
d1 = {'one': 1, 'two': 2}
d2 = dict()
d2['one'] = 1
d2['two'] = 2
my_dict = {}.setdefault().append(1)
print(my_dict[1]) |
# Matrix Ops some helper functions for matrix operations
#
# Legal:
# ==============
# Copyright 2021 lukasjoc<jochamlu@gmail.com>
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Softw... | def get_rows(arr):
""" return the rows for a given matrix """
return [arr[row] for row in range(len(arr))]
def get_cols(arr):
""" returns the cols for a given matrix """
cols = []
for row in range(len(arr)):
for col in range(len(arr[0])):
cols.append(arr[col][row])
return co... |
"""Problem 001
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
ans = sum(n for n in range(1000) if n % 3 == 0 or n % 5 == 0)
print(ans)
| """Problem 001
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
ans = sum((n for n in range(1000) if n % 3 == 0 or n % 5 == 0))
print(ans) |
@app.route('/home')
def home():
return redirect(url_for('about', name='World'))
@app.route('/about/<name>')
def about(name):
return f'Hello {name}' | @app.route('/home')
def home():
return redirect(url_for('about', name='World'))
@app.route('/about/<name>')
def about(name):
return f'Hello {name}' |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... | class Panosestrokevariation(object):
"""
Const Class
See Also:
`API PanoseStrokeVariation <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1rendering_1_1PanoseStrokeVariation.html>`_
"""
__ooo_ns__: str = 'com.sun.star.rendering'
__ooo_full_ns__: str = 'com.sun.s... |
def Naturals(n):
yield n
yield from Naturals(n+1)
s = Naturals(1)
print("Natural #s", next(s), next(s), next(s), next(s))
def sieve(s):
n = next(s)
yield n
yield from sieve(i for i in s if i%n != 0)
p = sieve(Naturals(2))
print("Prime #s", next(p), next(p), next(p), \
next(p), next(p), next(p)... | def naturals(n):
yield n
yield from naturals(n + 1)
s = naturals(1)
print('Natural #s', next(s), next(s), next(s), next(s))
def sieve(s):
n = next(s)
yield n
yield from sieve((i for i in s if i % n != 0))
p = sieve(naturals(2))
print('Prime #s', next(p), next(p), next(p), next(p), next(p), next(p),... |
"""
Storage for script settings and parameter grids
Authors: Vincent Yu
Date: 12/03/2020
"""
# GENERAL SETTINGS
# Set to true to re-read the latest version of the dataset csv files
update_dset = False
# Set the rescale factor to inflate the dataset
rescale = 1000
# FINE TUNING RELATED
# Set the random grid search st... | """
Storage for script settings and parameter grids
Authors: Vincent Yu
Date: 12/03/2020
"""
update_dset = False
rescale = 1000
random = True
random_size_lstm = 50
random_size_arimax = 1
params_arimax = {'num_extra_states': [i for i in range(6)], 'p': [i for i in range(5, 10)], 'd': [i for i in range(2)], 'q': [i for i... |
##
## parse argument
##
## written by @ciku370
##
def toxic(wibu_bau,bawang):
shit = bawang.split(',')
dan_buriq = 0
result = {}
for i in wibu_bau:
if i in shit:
try:
result.update({wibu_bau[dan_buriq]:wibu_bau[dan_buriq+1]})
except IndexError:
... | def toxic(wibu_bau, bawang):
shit = bawang.split(',')
dan_buriq = 0
result = {}
for i in wibu_bau:
if i in shit:
try:
result.update({wibu_bau[dan_buriq]: wibu_bau[dan_buriq + 1]})
except IndexError:
continue
dan_buriq += 1
retur... |
raise NotImplementedError("'str' object has no attribute named '__getitem__' looks like I can't index a string?")
def countGroups(related):
groups = 0
def follow_subusers(matrix_lookup, user_id, users_in_group):
"""
Recursive helper to follow users across matrix that have associations possibl... | raise not_implemented_error("'str' object has no attribute named '__getitem__' looks like I can't index a string?")
def count_groups(related):
groups = 0
def follow_subusers(matrix_lookup, user_id, users_in_group):
"""
Recursive helper to follow users across matrix that have associations possi... |
for linha in range(5):
for coluna in range(3):
if (linha == 0 and coluna == 0) or (linha == 4 and coluna == 0):
print(' ', end='')
elif linha == 0 or linha == 4 or coluna == 0:
print('*', end='')
else:
print(' ', end='')
print()
| for linha in range(5):
for coluna in range(3):
if linha == 0 and coluna == 0 or (linha == 4 and coluna == 0):
print(' ', end='')
elif linha == 0 or linha == 4 or coluna == 0:
print('*', end='')
else:
print(' ', end='')
print() |
IV = bytearray.fromhex("391e95a15847cfd95ecee8f7fe7efd66")
CT = bytearray.fromhex("8473dcb86bc12c6b6087619c00b6657e")
# Hashes from the description of challenge
ORIGINAL_MESSAGE = bytearray.fromhex(
"464952455f4e554b45535f4d454c4121") # FIRE_NUKES_MELA!
ALTERED_MESSAGE = bytearray.fromhex(
"53454e445f4e55444... | iv = bytearray.fromhex('391e95a15847cfd95ecee8f7fe7efd66')
ct = bytearray.fromhex('8473dcb86bc12c6b6087619c00b6657e')
original_message = bytearray.fromhex('464952455f4e554b45535f4d454c4121')
altered_message = bytearray.fromhex('53454e445f4e554445535f4d454c4121')
altered_iv = bytearray()
for i in range(16):
ALTERED_... |
def draw(stick: int, cx: str):
"""Function to draw of the board.
Args:
stick: nb of sticks left
cx: past
"""
if stick == 11:
print(
"#######################\n | | | | | | | | | | | \n#######################"
)
if stick == 10:
print(
"#... | def draw(stick: int, cx: str):
"""Function to draw of the board.
Args:
stick: nb of sticks left
cx: past
"""
if stick == 11:
print('#######################\n | | | | | | | | | | | \n#######################')
if stick == 10:
print('#######################\n | | | | | |... |
#Check String
'''To check if a certain phrase or character is present in a string, we can use the keyword in.'''
#Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
txt = "Hello buddie owo!"
if "owo" in txt:
print("Yes, 'owo' is present.")
'''
Terminal... | """To check if a certain phrase or character is present in a string, we can use the keyword in."""
txt = 'The best things in life are free!'
print('free' in txt)
txt = 'Hello buddie owo!'
if 'owo' in txt:
print("Yes, 'owo' is present.")
"\nTerminal:\nTrue\nYes, 'owo' is present.\n" |
testes = int(input())
casos = []
for x in range(testes):
casos_ = input().split()
casos.append(casos_)
for x in range(testes):
a = int(casos[x][0])
b = int(casos[x][1])
print(a+b)
| testes = int(input())
casos = []
for x in range(testes):
casos_ = input().split()
casos.append(casos_)
for x in range(testes):
a = int(casos[x][0])
b = int(casos[x][1])
print(a + b) |
# led-control WS2812B LED Controller Server
# Copyright 2021 jackw01. Released under the MIT License (see LICENSE for details).
default = {
0: {
'name': 'Sunset Light',
'mode': 0,
'colors': [
[
0.11311430089613972,
1,
1
... | default = {0: {'name': 'Sunset Light', 'mode': 0, 'colors': [[0.11311430089613972, 1, 1], [0.9936081381405101, 0.6497928024431981, 1], [0.9222222222222223, 0.9460097254004577, 1], [0.7439005234662223, 0.7002515180395283, 1], [0.6175635842715993, 0.6474992244615467, 1]]}, 10: {'name': 'Sunset Dark', 'mode': 0, 'colors':... |
class Solution:
def myAtoi(self, s: str) -> int:
s = s.strip(' ')
s = s.rstrip('.')
lens = len(s)
if (not s) or s[0].isalpha() or (lens == 1 and not s[0].isdecimal()):
return 0
string, i = '', 0
if s[0] in {'-', '+'}:
i = 1
string... | class Solution:
def my_atoi(self, s: str) -> int:
s = s.strip(' ')
s = s.rstrip('.')
lens = len(s)
if not s or s[0].isalpha() or (lens == 1 and (not s[0].isdecimal())):
return 0
(string, i) = ('', 0)
if s[0] in {'-', '+'}:
i = 1
st... |
while(True):
try:
n,k=map(int,input().split())
text=input()
except EOFError:
break
p=0
for i in range(1,n):
if text[0:i]==text[n-i:n]:
p=i
#print(p)
s=text+text[p:]*(k-1)
print(s) | while True:
try:
(n, k) = map(int, input().split())
text = input()
except EOFError:
break
p = 0
for i in range(1, n):
if text[0:i] == text[n - i:n]:
p = i
s = text + text[p:] * (k - 1)
print(s) |
class ExileError(Exception):
pass
class SCardError(ExileError):
pass
class YKOATHError(ExileError):
pass
| class Exileerror(Exception):
pass
class Scarderror(ExileError):
pass
class Ykoatherror(ExileError):
pass |
class Team:
def __init__(self, client):
self.client = client
async def info(self):
result = await self.client.api_call('GET', 'team.info')
return result['team']
| class Team:
def __init__(self, client):
self.client = client
async def info(self):
result = await self.client.api_call('GET', 'team.info')
return result['team'] |
def chunk_string(string, chunk_size=450):
# Limit = 462, cutting off at 450 to be safe.
string_chunks = []
while len(string) != 0:
current_chunk = string[0:chunk_size]
string_chunks.append(current_chunk)
string = string[len(current_chunk):]
return string_chunks
| def chunk_string(string, chunk_size=450):
string_chunks = []
while len(string) != 0:
current_chunk = string[0:chunk_size]
string_chunks.append(current_chunk)
string = string[len(current_chunk):]
return string_chunks |
class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
l, r = 0, len(numbers) - 1
while numbers[l] + numbers[r] != target:
if numbers[l] + numbers[r] < target:
l += 1
... | class Solution:
def two_sum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
(l, r) = (0, len(numbers) - 1)
while numbers[l] + numbers[r] != target:
if numbers[l] + numbers[r] < target:
l... |
def maiusculas(frase):
palavra = ''
for letra in frase:
if ord(letra) >= 65 and ord(letra) <= 90:
palavra += letra
return palavra
def maiusculas2(frase):
palavra = ''
for letra in frase:
if letra.isupper():
palavra += letra
return palavra
| def maiusculas(frase):
palavra = ''
for letra in frase:
if ord(letra) >= 65 and ord(letra) <= 90:
palavra += letra
return palavra
def maiusculas2(frase):
palavra = ''
for letra in frase:
if letra.isupper():
palavra += letra
return palavra |
# SQRT(X) LEETCODE SOLUTION:
# creating a class.
class Solution(object):
# creating a function to solve the problem.
def mySqrt(self, x):
# declaring a variable to track the output.
i = 0
# creating a while-loop to run while the output variable squared is less than or equa... | class Solution(object):
def my_sqrt(self, x):
i = 0
while i * i <= x:
i += 1
return i - 1 |
with open("input_blocks.txt") as file:
content = file.read()
for idx, block in enumerate(content.strip().split("---\n")):
with open(f"blocks/{idx+1}.txt", "w") as file:
print(block.rstrip(), file=file) | with open('input_blocks.txt') as file:
content = file.read()
for (idx, block) in enumerate(content.strip().split('---\n')):
with open(f'blocks/{idx + 1}.txt', 'w') as file:
print(block.rstrip(), file=file) |
# Defining a Function
def iterPower(base, exp):
# Making an Iterative Call
result = 1
while exp > 0:
result *= base
exp -= 1
return result
| def iter_power(base, exp):
result = 1
while exp > 0:
result *= base
exp -= 1
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.