content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
vals = ... | """
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
vals =... |
# Copyright (c) Nikita Sychev, 29.04.2017
# Licensed by MIT
a = input()
b = input()
c = input()
n = len(a)
a_new = ""
b_new = ""
c_new = ""
for i in range(n):
unused = chr(ord('A') + ord('B') + ord('C') + ord('?')
- ord(a[i]) - ord(b[i]) - ord(c[i]))
if a[i] == '?':
a_new += u... | a = input()
b = input()
c = input()
n = len(a)
a_new = ''
b_new = ''
c_new = ''
for i in range(n):
unused = chr(ord('A') + ord('B') + ord('C') + ord('?') - ord(a[i]) - ord(b[i]) - ord(c[i]))
if a[i] == '?':
a_new += unused
else:
a_new += a[i]
if b[i] == '?':
b_new += unused
e... |
def sum(x,y):
print("sum"," =",(x+y))
def subtract(x,y):
print("difference"," =",(x-y))
def divide(x,y):
print("division"," =",(x/y))
def multiply(x,y):
print("multiplication"," =",(x/y))
| def sum(x, y):
print('sum', ' =', x + y)
def subtract(x, y):
print('difference', ' =', x - y)
def divide(x, y):
print('division', ' =', x / y)
def multiply(x, y):
print('multiplication', ' =', x / y) |
def plug_in(symbol_values):
s = symbol_values['s']
p = len(s.sites) / s.volume
rho = float(s.density)
mbar = rho / p
v_a = 1 / p
return {'p': len(s.sites) / s.volume,
'rho': float(s.density),
'v_a': v_a,
'mbar': mbar}
DESCRIPTION = """
Model calculating the ... | def plug_in(symbol_values):
s = symbol_values['s']
p = len(s.sites) / s.volume
rho = float(s.density)
mbar = rho / p
v_a = 1 / p
return {'p': len(s.sites) / s.volume, 'rho': float(s.density), 'v_a': v_a, 'mbar': mbar}
description = '\nModel calculating the atomic density from the corresponding \... |
# 110. Balanced Binary Tree
# Runtime: 3232 ms, faster than 5.10% of Python3 online submissions for Balanced Binary Tree.
# Memory Usage: 17.6 MB, less than 100.00% of Python3 online submissions for Balanced Binary Tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=Non... | class Solution:
def is_balanced(self, root: TreeNode) -> bool:
if not root:
return True
else:
def get_depth(node: TreeNode) -> int:
if not node:
return 0
else:
return max(get_depth(node.left), get_depth... |
# Link: https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/
# Time: O(N)
# Space: O(N)
def reverse_parentheses(s):
stack, queue = [], []
for char in s:
if char == ")":
while stack[-1] != "(":
queue.append(stack.pop())
stack.pop() ... | def reverse_parentheses(s):
(stack, queue) = ([], [])
for char in s:
if char == ')':
while stack[-1] != '(':
queue.append(stack.pop())
stack.pop()
while queue:
stack.append(queue.pop(0))
else:
stack.append(char)
... |
x = input("Enter a string")
y = input("Enter a string")
z = input("Enter a string")
for i in range(10):
print("This is some output from the lab ",i)
print("Your input was " + x)
print("Your input was " + y)
print("Your input was " + z) | x = input('Enter a string')
y = input('Enter a string')
z = input('Enter a string')
for i in range(10):
print('This is some output from the lab ', i)
print('Your input was ' + x)
print('Your input was ' + y)
print('Your input was ' + z) |
"""Load dependencies needed to compile CLIF as a 3rd-party consumer."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
LLVM_COMMIT = "1f21de535d37997c41b9b1ecb2f7ca0e472e9f77" # 2021-01-15
LLVM_BAZEL_TAG = "llvm-project-%s" % (LLVM_COMMIT,)
LLVM_BAZEL_SHA256 = "f2fd051574fdddae8f8fff81f986d1165... | """Load dependencies needed to compile CLIF as a 3rd-party consumer."""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
llvm_commit = '1f21de535d37997c41b9b1ecb2f7ca0e472e9f77'
llvm_bazel_tag = 'llvm-project-%s' % (LLVM_COMMIT,)
llvm_bazel_sha256 = 'f2fd051574fdddae8f8fff81f986d1165b51dc0b62b70d9d4... |
class Solution:
def reverseBits(self, n):
result = 0
for i in range(32):
result <<= 1
if n & 1 > 0:
result += 1
n >>= 1
return result
| class Solution:
def reverse_bits(self, n):
result = 0
for i in range(32):
result <<= 1
if n & 1 > 0:
result += 1
n >>= 1
return result |
i = 1
n = 1
S = int(0)
while i <= 39:
somar = i/n
S = S + somar
n = n*2
i = i + 2
print('%.2f'%S)
| i = 1
n = 1
s = int(0)
while i <= 39:
somar = i / n
s = S + somar
n = n * 2
i = i + 2
print('%.2f' % S) |
'''
Class to define a LIFO Stack
'''
class UnderflowException(Exception):
'''
Raised when any element access operation is attempted on
an empty stack.
'''
pass
class Stack(object):
'''
Implements a Stack or a LIFO-style collection of elements.
'''
def __init__(self):
self.... | """
Class to define a LIFO Stack
"""
class Underflowexception(Exception):
"""
Raised when any element access operation is attempted on
an empty stack.
"""
pass
class Stack(object):
"""
Implements a Stack or a LIFO-style collection of elements.
"""
def __init__(self):
self.... |
#!/usr/bin/env python3
def eval_jumps1(jumps):
cloned = list(jumps)
pc = 0
i = 0
while 0 <= pc < len(cloned):
old_pc = cloned[pc]
cloned[pc] += 1
pc += old_pc
i += 1
return i
def eval_jumps2(jumps):
cloned = list(jumps)
pc = 0
i = 0
while 0 <= pc <... | def eval_jumps1(jumps):
cloned = list(jumps)
pc = 0
i = 0
while 0 <= pc < len(cloned):
old_pc = cloned[pc]
cloned[pc] += 1
pc += old_pc
i += 1
return i
def eval_jumps2(jumps):
cloned = list(jumps)
pc = 0
i = 0
while 0 <= pc < len(cloned):
old_... |
class Solution:
def solve(self, n, k):
ans = []
for i in range(k):
ans.append(x := max(1,n-26*(k-i-1)))
n -= x
return "".join(chr(ord('a')+x-1) for x in ans)
| class Solution:
def solve(self, n, k):
ans = []
for i in range(k):
ans.append((x := max(1, n - 26 * (k - i - 1))))
n -= x
return ''.join((chr(ord('a') + x - 1) for x in ans)) |
load("@build_bazel_rules_nodejs//:index.bzl", "pkg_web")
load(":tools/ngsw_config.bzl", _ngsw_config = "ngsw_config")
def pkg_pwa(
name,
srcs,
index_html,
ngsw_config,
additional_root_paths = []):
pkg_web(
name = "%s_web" % name,
srcs = srcs + ["@npm//:node_m... | load('@build_bazel_rules_nodejs//:index.bzl', 'pkg_web')
load(':tools/ngsw_config.bzl', _ngsw_config='ngsw_config')
def pkg_pwa(name, srcs, index_html, ngsw_config, additional_root_paths=[]):
pkg_web(name='%s_web' % name, srcs=srcs + ['@npm//:node_modules/@angular/service-worker/ngsw-worker.js', '@npm//:node_modul... |
def calculate_amstrong_numbers_3_digits():
result = []
for item in range(100, 1000):
sum = 0
for number in str(item):
sum += int(number) ** 3
if sum == item:
result.append(item)
return result
print("3-digit Amstrong Numbers:")
print(calculate_amstrong_numb... | def calculate_amstrong_numbers_3_digits():
result = []
for item in range(100, 1000):
sum = 0
for number in str(item):
sum += int(number) ** 3
if sum == item:
result.append(item)
return result
print('3-digit Amstrong Numbers:')
print(calculate_amstrong_numbers_... |
def int_to_Roman(num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i = 0
while num > 0:
for _ in range(num... | def int_to__roman(num):
val = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
syb = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
roman_num = ''
i = 0
while num > 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 5 19:33:09 2019
@author: sodatab
MITx: 6.00.1x
"""
"""
Midterm-03 Closest Power
-------------------------
Implement a function called closest_power that meets the specifications below.
def closest_power(base, num):
'''
base: base of the ... | """
Created on Sat Oct 5 19:33:09 2019
@author: sodatab
MITx: 6.00.1x
"""
"\nMidterm-03 Closest Power\n-------------------------\nImplement a function called closest_power that meets the specifications below.\n\ndef closest_power(base, num):\n '''\n base: base of the exponential, integer > 1\n num: number y... |
class A:
def f(self):
return B()
a = A()
a.f() # NameError: name 'B' is not defined
b = B() # NameError: name 'B' is not defined
def f():
b = B()
f() # NameError: name 'B' is not defined
class B:
pass
| class A:
def f(self):
return b()
a = a()
a.f()
b = b()
def f():
b = b()
f()
class B:
pass |
def reverse_list(items):
start = 0
end = len(items) - 1
while start < end:
items[start], items[end] = items[end], items[start]
start += 1
end -= 1
return items
if __name__ == '__main__':
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(reverse_list(items))
| def reverse_list(items):
start = 0
end = len(items) - 1
while start < end:
(items[start], items[end]) = (items[end], items[start])
start += 1
end -= 1
return items
if __name__ == '__main__':
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(reverse_list(items)) |
#!/usr/bin/python3
#
#
MAGIC_SEED = 1956
#PATH
TRAIN_PATH = 'train'
PREDICT_PATH = 'predict'
# Dataset properties
CSV_PATH="C:\\Users\\dmitr_000\\.keras\\datasets\\Imbalance_data.csv"
# Header names
DT_DSET ="Date Time"
RCPOWER_DSET= "Imbalance"
DISCRET =10
# The time cutoffs for the formation of the validation ... | magic_seed = 1956
train_path = 'train'
predict_path = 'predict'
csv_path = 'C:\\Users\\dmitr_000\\.keras\\datasets\\Imbalance_data.csv'
dt_dset = 'Date Time'
rcpower_dset = 'Imbalance'
discret = 10
test_cut_off = 60
val_cut_off = 360
log_file_name = 'Imbalance'
epochs = 10
n_steps = 32
n_features = 1
lstm_possible_type... |
def unsupervised_distr(distr):
variables = {k: k + '_u' for k in distr.var + distr.cond_var if k != 'z'}
distr_unsupervised = distr.replace_var(**variables)
return distr_unsupervised, variables
def unsupervised_distr_no_var(distr):
variables = {k: k + '_u' for k in distr.var + distr.cond_var if k != '... | def unsupervised_distr(distr):
variables = {k: k + '_u' for k in distr.var + distr.cond_var if k != 'z'}
distr_unsupervised = distr.replace_var(**variables)
return (distr_unsupervised, variables)
def unsupervised_distr_no_var(distr):
variables = {k: k + '_u' for k in distr.var + distr.cond_var if k != ... |
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
table = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
return len({''.join(table[ord(c) - ord('a')] for c ... | class Solution:
def unique_morse_representations(self, words: List[str]) -> int:
table = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..']
return len({''.join((ta... |
#!/bin/python3
"""
Recommender algorithm
Weight sum of similarity vector
"""
WEIGHTS = [1, 1, 1, 1]
# rank, bgg_url, game_id, names, min_players, max_players, avg_time, min_time,
# max_time, year, avg_rating, geek_rating, num_votes, image_url, age, mechanic,
# owned, category, designer, weight
def recommend_simil... | """
Recommender algorithm
Weight sum of similarity vector
"""
weights = [1, 1, 1, 1]
def recommend_similar(data, row, vectors, names, weights=None, count=20):
"""Recommend similar items to one that is provided as 1st argument
weights is ordered list of weights given to each component in vector.
v(geek_ra... |
expected_output = {
"list_of_neighbors": ["192.168.197.254"],
"vrf": {
"default": {
"neighbor": {
"192.168.197.254": {
"address_family": {
"ipv4 unicast": {
"advertise_bit": 0,
... | expected_output = {'list_of_neighbors': ['192.168.197.254'], 'vrf': {'default': {'neighbor': {'192.168.197.254': {'address_family': {'ipv4 unicast': {'advertise_bit': 0, 'bgp_table_version': 1, 'dynamic_slow_peer_recovered': 'never', 'index': 0, 'last_detected_dynamic_slow_peer': 'never', 'last_received_refresh_end_of_... |
class RepositoryTests(TestCase):
"""Unit tests for Repository operations."""
fixtures = ["test_scmtools"]
def setUp(self):
super(RepositoryTests, self).setUp()
self.local_repo_path = os.path.join(os.path.dirname(__file__), "..", "testdata", "git_repo")
self.repository = Repository.objects.create(name="Git test... | class Repositorytests(TestCase):
"""Unit tests for Repository operations."""
fixtures = ['test_scmtools']
def set_up(self):
super(RepositoryTests, self).setUp()
self.local_repo_path = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'git_repo')
self.repository = Repository.... |
def check_paranthesis(inp):
stack = []
c = 1
for i in inp:
if i in ['(','[','{']:
stack.append(i)
c += 1
else:
if len(stack) == 0:
return c
elif (i == ')' and stack[-1] == '(') or (i == ']' and stack[-1] == '[') or (i == '}' and... | def check_paranthesis(inp):
stack = []
c = 1
for i in inp:
if i in ['(', '[', '{']:
stack.append(i)
c += 1
elif len(stack) == 0:
return c
elif i == ')' and stack[-1] == '(' or (i == ']' and stack[-1] == '[') or (i == '}' and stack[-1] == '{'):
... |
# Bazel macro that instantiates a native cc_test rule for an S2 test.
def s2test(name, deps = [], size = "small"):
native.cc_test(
name = name,
srcs = ["%s.cc" % (name)],
copts = [
"-Iexternal/gtest/include",
"-DS2_TEST_DEGENERACIES",
"-DS2_USE_GFLAGS",
... | def s2test(name, deps=[], size='small'):
native.cc_test(name=name, srcs=['%s.cc' % name], copts=['-Iexternal/gtest/include', '-DS2_TEST_DEGENERACIES', '-DS2_USE_GFLAGS', '-DS2_USE_GLOG', '-DHASH_NAMESPACE=std', '-Wno-deprecated-declarations', '-Wno-format', '-Wno-non-virtual-dtor', '-Wno-parentheses', '-Wno-sign-co... |
#
# PySNMP MIB module CT-DAWANDEVCONN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CT-DAWANDEVCONN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:28:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
class Node(object):
def __init__(self, item):
self.item = item
self.next = None
def get_item(self):
return self.item
def get_next(self):
return self.next
def set_item(self, new_item):
self.item = new_item
def set_next(self, new_next):
self.next = n... | class Node(object):
def __init__(self, item):
self.item = item
self.next = None
def get_item(self):
return self.item
def get_next(self):
return self.next
def set_item(self, new_item):
self.item = new_item
def set_next(self, new_next):
self.next = ... |
class Solution(object):
# # Backtracking Approach - TLE
# def canJump(self, nums):
# """
# :type nums: List[int]
# :rtype: bool
# """
# return self.canJumpHelper(nums, 0)
#
# def canJumpHelper(self, nums, currentIdx):
# if currentIdx == len(nums) - 1:
... | class Solution(object):
def can_jump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
last_position = len(nums) - 1
for i in range(len(nums) - 1, -1, -1):
next_max_jump = i + nums[i]
if nextMaxJump >= lastPosition:
last_... |
# The major optimization is to do arithmetic in base 10 in the main loop, avoiding division and modulo
def compute():
# Initialize
n = 1000000000 # The pattern is greater than 10^18, so start searching at 10^9
ndigits = [0] * 10 # In base 10, little-endian
temp = n
for i in range(len(ndigits)):
ndigits[i] = ... | def compute():
n = 1000000000
ndigits = [0] * 10
temp = n
for i in range(len(ndigits)):
ndigits[i] = temp % 10
temp //= 10
n2digits = [0] * 19
temp = n * n
for i in range(len(n2digits)):
n2digits[i] = temp % 10
temp //= 10
while not is_concealed_square(n2d... |
def parse_string_time(input_time: str) -> float:
total_amount = 0
times = _slice_input_times(input_time)
for _amount, duration_type in times:
amount = _to_float(_amount)
multiplier = _parse_multiplier(duration_type)
total_amount += amount * multiplier
return total_amount
def... | def parse_string_time(input_time: str) -> float:
total_amount = 0
times = _slice_input_times(input_time)
for (_amount, duration_type) in times:
amount = _to_float(_amount)
multiplier = _parse_multiplier(duration_type)
total_amount += amount * multiplier
return total_amount
def _... |
"""This module contains j2cl_js_provider helpers."""
load(
"@io_bazel_rules_closure//closure:defs.bzl",
"CLOSURE_JS_TOOLCHAIN_ATTRS",
"closure_js_binary",
"create_closure_js_library",
"web_library",
)
def create_js_lib_struct(j2cl_info, extra_providers = []):
return struct(
providers =... | """This module contains j2cl_js_provider helpers."""
load('@io_bazel_rules_closure//closure:defs.bzl', 'CLOSURE_JS_TOOLCHAIN_ATTRS', 'closure_js_binary', 'create_closure_js_library', 'web_library')
def create_js_lib_struct(j2cl_info, extra_providers=[]):
return struct(providers=[j2cl_info] + extra_providers, closu... |
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
MAX, MASK = 0x7FFFFFFF, 0xFFFFFFFF
while b != 0:
a, b = (a ^ b) & MASK, ((a & b) << 1) & MASK
return a if a <= MAX else ~(a ^ MASK)
| class Solution(object):
def get_sum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
(max, mask) = (2147483647, 4294967295)
while b != 0:
(a, b) = ((a ^ b) & MASK, (a & b) << 1 & MASK)
return a if a <= MAX else ~(a ^ MASK) |
HITBOX_OCTANE = 0
HITBOX_DOMINUS = 1
HITBOX_PLANK = 2
HITBOX_BREAKOUT = 3
HITBOX_HYBRID = 4
HITBOX_BATMOBILE = 5
| hitbox_octane = 0
hitbox_dominus = 1
hitbox_plank = 2
hitbox_breakout = 3
hitbox_hybrid = 4
hitbox_batmobile = 5 |
N, M = map(int, input().split())
A = list(map(int, input().split()))
threshold = sum(A) / (4 * M)
if len([a for a in A if a >= threshold]) >= M:
print('Yes')
else:
print('No')
| (n, m) = map(int, input().split())
a = list(map(int, input().split()))
threshold = sum(A) / (4 * M)
if len([a for a in A if a >= threshold]) >= M:
print('Yes')
else:
print('No') |
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
# exception
if len(strs) == 0:
return ""
# sort first!
strs.sort()
# strategy
# compare first and last string in sorted strings!
# pick first element ... | class Solution:
def longest_common_prefix(self, strs: List[str]) -> str:
if len(strs) == 0:
return ''
strs.sort()
pick = strs[0]
prefix = ''
for i in range(len(pick)):
if strs[len(strs) - 1][i] == pick[i]:
prefix += strs[len(strs) - 1]... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def _add(self, node, data):
if data <= node.data:
if node.left:
self._add(node.left, data)
... | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Bst:
def __init__(self):
self.root = None
def _add(self, node, data):
if data <= node.data:
if node.left:
self._add(node.left, data)
... |
class SymbolMapper(object):
def __init__(self):
self.symbolmap = {0: '0', 1: '+', -1: '-'}
@staticmethod
def normalize(value):
return 0 if value == 0 else value / abs(value)
def inputs2symbols(self, inputs):
return map(
lambda value: self.symbolmap[SymbolMapper.nor... | class Symbolmapper(object):
def __init__(self):
self.symbolmap = {0: '0', 1: '+', -1: '-'}
@staticmethod
def normalize(value):
return 0 if value == 0 else value / abs(value)
def inputs2symbols(self, inputs):
return map(lambda value: self.symbolmap[SymbolMapper.normalize(value)... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# (c)2021 .direwolf <kururinmiracle@outlook.com>
# Licensed under the MIT License.
class AffNoteTypeError(Exception):
pass
class AffNoteIndexError(Exception):
pass
class AffNoteValueError(Exception):
pass
class AffSceneTypeError(Exception):
pass
cl... | class Affnotetypeerror(Exception):
pass
class Affnoteindexerror(Exception):
pass
class Affnotevalueerror(Exception):
pass
class Affscenetypeerror(Exception):
pass
class Affreaderror(Exception):
pass |
class RC4 :
def __init__(self):
self.S = []
def preprocess_hex_chars(self, text) :
"""
Preprocess text by decoding hex characters into ASCII characters
"""
preprocessed_text = ''
i = 0
while i < len(text) :
if '\\x' == text[i:i+2] :
... | class Rc4:
def __init__(self):
self.S = []
def preprocess_hex_chars(self, text):
"""
Preprocess text by decoding hex characters into ASCII characters
"""
preprocessed_text = ''
i = 0
while i < len(text):
if '\\x' == text[i:i + 2]:
... |
# Ignore file list
ignore_filelist = [
'teslagun.activeitem',
'teslagun2.activeitem',
]
ignore_filelist_patch = [
]
| ignore_filelist = ['teslagun.activeitem', 'teslagun2.activeitem']
ignore_filelist_patch = [] |
# This is input for <FileUploadToCommons.py> that actually writes the content to Wikimedia commons using the API
#See https://pypi.org/project/mwtemplates/
# ===============BEGIN TEMPLETE======================
# Lets use a minimally filled {{Infomormation}} template - https://commons.wikimedia.org/wiki/Template:In... | file_template = '\n=={{{{int:filedesc}}}}==\n{{{{Information\n |author = {author}\n |description = {{{{en|1=Page {page} of the Album amicorum Jacob Heyblocq KB131H26}}}} \n |source = https://resolver.kb.nl/resolve?urn=EuropeanaTravel:131H26:{page}\n}}}}\n\n=={{{{int:license-header}}}}==\n... |
# funcao como parametro de funcao
# so imprime se o numero estiver correto
def imprime_com_condicao(num, fcond):
if fcond(num):
print(num)
def par(x):
return x % 2 == 0
def impar(x):
return not par(x)
# Programa Principal
# neste caso nao imprimira
imprime_com_condicao(5, par)
| def imprime_com_condicao(num, fcond):
if fcond(num):
print(num)
def par(x):
return x % 2 == 0
def impar(x):
return not par(x)
imprime_com_condicao(5, par) |
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
swaps = 0
for i in range(n):
temp=0
for j in range(n-1):
if a[j] > a[j+1]:
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
swaps+=1
if swaps==0:
print("Array is sorted in", swaps, "swaps."... | n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
swaps = 0
for i in range(n):
temp = 0
for j in range(n - 1):
if a[j] > a[j + 1]:
temp = a[j]
a[j] = a[j + 1]
a[j + 1] = temp
swaps += 1
if swaps == 0:
print('Array is sorted in', s... |
t = int(input())
for i in range(t):
r = int(input())
length = r*5
width = length*0.6
left = -1*length*0.45
right = length*0.55
w = width/2
# print coordinates
print('Case '+str(i+1)+':')
# upper left
print("%.0f %.0f" % (left, w))
# upper right
print("%.0f %.0f" % (right,... | t = int(input())
for i in range(t):
r = int(input())
length = r * 5
width = length * 0.6
left = -1 * length * 0.45
right = length * 0.55
w = width / 2
print('Case ' + str(i + 1) + ':')
print('%.0f %.0f' % (left, w))
print('%.0f %.0f' % (right, w))
print('%.0f %.0f' % (right, -1 *... |
myString = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
inTab = "yzabcdefghijklmnopqrstuvwx"
outTab = "abcdefghijklmnopqrstuvwxyz"
transTab = str.maketrans(i... | my_string = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
in_tab = 'yzabcdefghijklmnopqrstuvwx'
out_tab = 'abcdefghijklmnopqrstuvwxyz'
trans_tab = str.maketrans... |
def sortByHeight(a):
heights = []
# Store all the heights in a list
for i in range(len(a)):
if a[i] != -1:
heights.append(a[i])
# Sort the heights
heights = sorted(heights)
# Replace the heights in the original list
j = 0
for i in range(len(a)):
if a[i] != ... | def sort_by_height(a):
heights = []
for i in range(len(a)):
if a[i] != -1:
heights.append(a[i])
heights = sorted(heights)
j = 0
for i in range(len(a)):
if a[i] != -1:
a[i] = heights[j]
j += 1
return a |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 09:54:51 2020
@author: bruger
"""
| """
Created on Sat Feb 29 09:54:51 2020
@author: bruger
""" |
class Solution:
def reverseWords(self, set):
return ' '.join(set.split()[::-1])
if __name__ == "__main__":
solution = Solution()
print(solution.reverseWords("the sky is blue"))
print(solution.reverseWords(" hello world! "))
| class Solution:
def reverse_words(self, set):
return ' '.join(set.split()[::-1])
if __name__ == '__main__':
solution = solution()
print(solution.reverseWords('the sky is blue'))
print(solution.reverseWords(' hello world! ')) |
class SleuthError(Exception):
pass
class SleuthNotFoundError(SleuthError):
pass
| class Sleutherror(Exception):
pass
class Sleuthnotfounderror(SleuthError):
pass |
def insertion_sort(nums: list[float]) -> list[float]:
for start in range(1, len(nums)):
index = start
while nums[index] < nums[index - 1] and index > 0:
nums[index], nums[index - 1] = nums[index - 1], nums[index]
index -= 1
return nums
| def insertion_sort(nums: list[float]) -> list[float]:
for start in range(1, len(nums)):
index = start
while nums[index] < nums[index - 1] and index > 0:
(nums[index], nums[index - 1]) = (nums[index - 1], nums[index])
index -= 1
return nums |
# coding:utf-8
class FakeBot(object):
"""Fake Bot object """
def __init__(self):
self.msg = ''
def send_message(self, text='', **kwargs):
self.msg = text
class FakeUpdate(object):
def __init__(self):
self.message = FakeMessage()
class FakeMessage(object):
"""Docstri... | class Fakebot(object):
"""Fake Bot object """
def __init__(self):
self.msg = ''
def send_message(self, text='', **kwargs):
self.msg = text
class Fakeupdate(object):
def __init__(self):
self.message = fake_message()
class Fakemessage(object):
"""Docstring for FakeMessage.... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | bing_edge = {'color': {'color': '#228372'}, 'title': 'Bing-related Parsing Functions', 'label': 'B'}
def run(unfurl, node):
if node.data_type == 'url.query.pair':
if 'bing' in unfurl.find_preceding_domain(node):
if node.key == 'pq':
unfurl.add_to_queue(data_type='descriptor', ke... |
"""Module for user fixtures"""
USER = {
'email': 'test_user@example.com',
'password': 'Password@1234',
}
USER_INVALID = {'email': '', 'password': ''}
SUPERUSER = {
'email': 'test_userII@example.com',
'password': 'password1234',
}
UNREGISTERED_USER = {
'email': 'unregistered@example1.com',
'p... | """Module for user fixtures"""
user = {'email': 'test_user@example.com', 'password': 'Password@1234'}
user_invalid = {'email': '', 'password': ''}
superuser = {'email': 'test_userII@example.com', 'password': 'password1234'}
unregistered_user = {'email': 'unregistered@example1.com', 'password': 'Password@1234'}
test_aut... |
class Term(str):
@property
def is_variable(self):
return self[0] == "?"
@property
def is_constant(self):
return self[0] != "?"
@property
def arity(self):
return 0
class ListTerm(tuple):
def __init__(self, *args):
self.is_function = None
tuple.__ini... | class Term(str):
@property
def is_variable(self):
return self[0] == '?'
@property
def is_constant(self):
return self[0] != '?'
@property
def arity(self):
return 0
class Listterm(tuple):
def __init__(self, *args):
self.is_function = None
tuple.__in... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( a , b , k ) :
c1 = ( b - a ) - 1
c2 = ( k - b ) + ( a - 1 )
if ( c1 == c2 ) :
return 0
retu... | def f_gold(a, b, k):
c1 = b - a - 1
c2 = k - b + (a - 1)
if c1 == c2:
return 0
return min(c1, c2)
if __name__ == '__main__':
param = [(83, 98, 86), (3, 39, 87), (11, 96, 30), (50, 67, 48), (40, 16, 32), (62, 86, 76), (40, 78, 71), (66, 11, 74), (6, 9, 19), (25, 5, 5)]
n_success = 0
f... |
"""Exceptions of the pygmx package."""
class InvalidMagicException(Exception): pass
class InvalidIndexException(Exception): pass
class UnknownLenError(Exception): pass
class FileTypeError(Exception): pass
class XTCError(Exception): pass
| """Exceptions of the pygmx package."""
class Invalidmagicexception(Exception):
pass
class Invalidindexexception(Exception):
pass
class Unknownlenerror(Exception):
pass
class Filetypeerror(Exception):
pass
class Xtcerror(Exception):
pass |
def get_locale_name(something, lang):
if type(something) == str:
pass
if type(something) == list:
pass
if type(something) == dict:
pass
| def get_locale_name(something, lang):
if type(something) == str:
pass
if type(something) == list:
pass
if type(something) == dict:
pass |
phoneNumber = {}
x = int(input())
for i in range(x):
name, number = input().split()
phoneNumber[name] = number
for i in range(x):
query_name = input()
if query_name in phoneNumber.keys():
print(query_name + "=" + phoneNumber[query_name])
else:
print("Not found")
| phone_number = {}
x = int(input())
for i in range(x):
(name, number) = input().split()
phoneNumber[name] = number
for i in range(x):
query_name = input()
if query_name in phoneNumber.keys():
print(query_name + '=' + phoneNumber[query_name])
else:
print('Not found') |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Control.py
#
class Control:
def __init__(self, TagName):
self._hosted = False # Is added to Form
self._script = '' # Javascript code (Used before added to Form)
self._id = '' # Used By Form to identify control Dont change
self._... | class Control:
def __init__(self, TagName):
self._hosted = False
self._script = ''
self._id = ''
self._script += 'var Control = document.createElement("' + TagName + '");'
self.events = {}
self.Controls = []
pass
def initialize(self, Id, parent):
... |
AVAILABLE = [
{
'account_name': 'ExampleTwitterMarkovBot', # derived from https://twitter.com/ExampleTwitterMarkovBot
'corpora': ('example_corpus1', 'example_corpus2'),
'description': 'An example configuration for a bot instance',
'twitter_key': '', # twitter app API key
'twi... | available = [{'account_name': 'ExampleTwitterMarkovBot', 'corpora': ('example_corpus1', 'example_corpus2'), 'description': 'An example configuration for a bot instance', 'twitter_key': '', 'twitter_secret': ''}] |
if __name__ == "__main__":
with open("input.txt", "r") as f:
input_list = f.readlines()
x = 0
y = 0
for input in input_list:
command, string_val = input.split(" ")
val = int(string_val)
if command == "forward":
x += val
... | if __name__ == '__main__':
with open('input.txt', 'r') as f:
input_list = f.readlines()
x = 0
y = 0
for input in input_list:
(command, string_val) = input.split(' ')
val = int(string_val)
if command == 'forward':
x += val
... |
class TransactionError(Exception):
pass
class TransactionTimeoutError(Exception):
pass
class TransactionFinished(Exception):
pass
| class Transactionerror(Exception):
pass
class Transactiontimeouterror(Exception):
pass
class Transactionfinished(Exception):
pass |
class AdvancedArithmetic(object):
def divisorSum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def divisorSum(self, n):
divisor_sum = 0
for divisor in range(2, n):
if n % divisor == 0:
divisor_sum += divisor
return divisor_sum +... | class Advancedarithmetic(object):
def divisor_sum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def divisor_sum(self, n):
divisor_sum = 0
for divisor in range(2, n):
if n % divisor == 0:
divisor_sum += divisor
return divisor_su... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | """Implementation of resource bundle/importing rules."""
load('@bazel_skylib//lib:partial.bzl', 'partial')
load('@build_bazel_rules_apple//apple:providers.bzl', 'AppleResourceBundleInfo')
load('@build_bazel_rules_apple//apple:utils.bzl', 'group_files_by_directory')
load('@build_bazel_rules_apple//apple/internal:resourc... |
def gcd(a: int, b: int) -> int:
# supposed a >= b
if b > a:
return gcd(b, a)
elif a % b == 0:
return b
return gcd(b, a % b)
| def gcd(a: int, b: int) -> int:
if b > a:
return gcd(b, a)
elif a % b == 0:
return b
return gcd(b, a % b) |
def data_loader(f_name, l_name):
with open(f_name, mode='r', encoding='utf-8') as f:
data = list(set(f.readlines()))
label = [l_name for i in range(len(data))]
return data, label
| def data_loader(f_name, l_name):
with open(f_name, mode='r', encoding='utf-8') as f:
data = list(set(f.readlines()))
label = [l_name for i in range(len(data))]
return (data, label) |
# TODO: maybe store them .sql files and read them as string
# example: https://cloud.google.com/blog/products/application-development/how-to-schedule-a-recurring-python-script-on-gcp
# def file_to_string(sql_path):
# """Converts a SQL file holding a SQL query to a string.
# Args:
# sql_path: String cont... | sample_events_query = '\nSELECT \nCONCAT(stream_id, "_" , user_pseudo_id, "_" , event_name, "_" , event_timestamp) AS event_id,\n\nevent_date AS event_date,\nevent_timestamp AS event_timestamp,\nevent_name AS event_name,\nevent_previous_timestamp AS event_previous_timestamp,\nevent_value_in_usd AS event_value_in_usd,... |
def in_order_traversal(node, visit_func):
if node is not None:
in_order_traversal(node.left, visit_func)
visit_func(node.data)
in_order_traversal(node.right, visit_func)
def pre_order_traversal(node, visit_func):
if node is not None:
visit_func(node.data)
pre_order_trave... | def in_order_traversal(node, visit_func):
if node is not None:
in_order_traversal(node.left, visit_func)
visit_func(node.data)
in_order_traversal(node.right, visit_func)
def pre_order_traversal(node, visit_func):
if node is not None:
visit_func(node.data)
pre_order_trave... |
'''
Desenvolva um algoritmo que solicite seu ano de nacimento e o ano anoAtual
Calcule a idade e apresente na tela.
Para fins de simplificacao, despreze o dia e mes do ano. Apos o calculo
verifique se a idade e maior ou igual a 18 anos e apresente na tela a mensagen
informando que ja e possivel tirar a carteira de mot... | """
Desenvolva um algoritmo que solicite seu ano de nacimento e o ano anoAtual
Calcule a idade e apresente na tela.
Para fins de simplificacao, despreze o dia e mes do ano. Apos o calculo
verifique se a idade e maior ou igual a 18 anos e apresente na tela a mensagen
informando que ja e possivel tirar a carteira de mot... |
class Feature:
def __init__(self, name, selector, data_type, number_of_values, patterns):
self.name = name
self.selector = selector
self.pattern = patterns[data_type]
self.multiple_values = number_of_values != 'single' | class Feature:
def __init__(self, name, selector, data_type, number_of_values, patterns):
self.name = name
self.selector = selector
self.pattern = patterns[data_type]
self.multiple_values = number_of_values != 'single' |
## rolling mean & variance
class OnlineStats:
def __init__(self):
self.reset()
def reset(self) -> None:
self.n = 0
self.mean = 0.0
self.m2 = 0.0
def update(self, x: float) -> None:
"""Update stats for new observation."""
self.n += 1
new_mean = self... | class Onlinestats:
def __init__(self):
self.reset()
def reset(self) -> None:
self.n = 0
self.mean = 0.0
self.m2 = 0.0
def update(self, x: float) -> None:
"""Update stats for new observation."""
self.n += 1
new_mean = self.mean + (x - self.mean) / se... |
def get_multiples(num=1,c=10):
# if n > 0: (what about negative multiples?)
a = 0
num2 = num
while a < c:
if num2%num == 0:
yield num2
num2 += 1
a += 1
else:
num2 += 1
multiples_two = get_multiples(2,3)
for i in multiples_two:
print(i)
default_multiples = get_multiples()
multiples_5 = g... | def get_multiples(num=1, c=10):
a = 0
num2 = num
while a < c:
if num2 % num == 0:
yield num2
num2 += 1
a += 1
else:
num2 += 1
multiples_two = get_multiples(2, 3)
for i in multiples_two:
print(i)
default_multiples = get_multiples()
multiples... |
# Copyright 2010-2011, RTLCores. All rights reserved.
# http://rtlcores.com
# See LICENSE.txt
class CmdArgs(list):
def __init__(self, value=[], cmd=None):
list.__init__(self, value)
self.cmd = cmd
def conv(self):
if(self.cmd == None):
return self
else:
r... | class Cmdargs(list):
def __init__(self, value=[], cmd=None):
list.__init__(self, value)
self.cmd = cmd
def conv(self):
if self.cmd == None:
return self
else:
return self.cmd(self) |
def main() -> None:
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
INF = 1 << 60
min_length = [INF] * (1 << n)
remain = 1 << n
mi... | def main() -> None:
(n, m) = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
(u, v) = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
inf = 1 << 60
min_length = [INF] * (1 << n)
remain = 1 << n
min_length[0... |
"""A rich command line interface for PyPI."""
__name__ = "pypi-command-line"
__title__ = __name__
__license__ = "MIT"
__version__ = "0.4.0"
__author__ = "Arian Mollik Wasi"
__github__ = "https://github.com/wasi-master/pypi-cli"
| """A rich command line interface for PyPI."""
__name__ = 'pypi-command-line'
__title__ = __name__
__license__ = 'MIT'
__version__ = '0.4.0'
__author__ = 'Arian Mollik Wasi'
__github__ = 'https://github.com/wasi-master/pypi-cli' |
"""
Name: MultiSURF.py
Authors: Gediminas Bertasius and Ryan Urbanowicz - Written at Dartmouth College, Hanover, NH, USA
Contact: ryan.j.urbanowicz@darmouth.edu
Created: December 4, 2013
Modified: August 25,2014
Description:
----------------------------------------------------------... | """
Name: MultiSURF.py
Authors: Gediminas Bertasius and Ryan Urbanowicz - Written at Dartmouth College, Hanover, NH, USA
Contact: ryan.j.urbanowicz@darmouth.edu
Created: December 4, 2013
Modified: August 25,2014
Description:
----------------------------------------------------------... |
# import libraries and modules
# provide a class storing the configuration of the back-end engine
class LXMconfig:
# constructor of the class
def __init__(self):
self.idb_c1 = None
self.idb_c2 = None
self.idb_c3 = None
self.lxm_conf = {}
self.program_name = "lx_allocator... | class Lxmconfig:
def __init__(self):
self.idb_c1 = None
self.idb_c2 = None
self.idb_c3 = None
self.lxm_conf = {}
self.program_name = 'lx_allocator'
self.lxm_conf['header_request_id'] = 0
self.lxm_conf['header_forwarded_for'] = 1
self.lxm_conf['service... |
{
"targets": [
{
"target_name": "priorityqueue_native",
"sources": [ "src/priorityqueue_native.cpp", "src/ObjectHolder.cpp", "src/index.d.ts"],
"cflags": ["-Wall", "-std=c++11"],
'xcode_settings': {
'OTHER_CFLAGS': [
'-std=c++11'
],
},
"conditions": [
... | {'targets': [{'target_name': 'priorityqueue_native', 'sources': ['src/priorityqueue_native.cpp', 'src/ObjectHolder.cpp', 'src/index.d.ts'], 'cflags': ['-Wall', '-std=c++11'], 'xcode_settings': {'OTHER_CFLAGS': ['-std=c++11']}, 'conditions': [['OS=="mac"', {'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'OTHER_C... |
class User:
"""
User class for creating password locker account and logging in
"""
user_credentials = []
def __init__(self, fullname, username, password):
self.fullname = fullname
self.username = username
self.password = password
def save_user(self):
"""
... | class User:
"""
User class for creating password locker account and logging in
"""
user_credentials = []
def __init__(self, fullname, username, password):
self.fullname = fullname
self.username = username
self.password = password
def save_user(self):
"""
... |
"""Breadth-first search shortest path implementations."""
def bfs_shortest_path(graph, x, y):
"""Find shortest number of edges between nodes x and y.
:x: a node
:y: a node
:Returns: shortest number of edges from node x to y or -1 if none exists
"""
if x == y:
return 0
v... | """Breadth-first search shortest path implementations."""
def bfs_shortest_path(graph, x, y):
"""Find shortest number of edges between nodes x and y.
:x: a node
:y: a node
:Returns: shortest number of edges from node x to y or -1 if none exists
"""
if x == y:
return 0
v... |
'''
'''
print('\nNested Function\n')
def function_1(text):
text = text
def function_2():
print(text)
function_2()
if __name__ == '__main__':
function_1('Welcome')
print('\n closure Function \n')
def function_1(text):
text = text
def function_2():
print(text)
return function_2
if __name__ == '__main__... | """
"""
print('\nNested Function\n')
def function_1(text):
text = text
def function_2():
print(text)
function_2()
if __name__ == '__main__':
function_1('Welcome')
print('\n closure Function \n')
def function_1(text):
text = text
def function_2():
print(text)
return funct... |
# def mul(a=1,b=3):
# c=a*b
# return c
# def add(a=1,b=2):
# c=a+b
# return c
class Student:
def __init__(self,first,last,kid):
self.fname = first
self.lname = last
self.kid = kid
self.email = first + '.' + last +'@tamuk.edu'
def firstname(self):
retur... | class Student:
def __init__(self, first, last, kid):
self.fname = first
self.lname = last
self.kid = kid
self.email = first + '.' + last + '@tamuk.edu'
def firstname(self):
return self.fname
stu_1 = student('ashwitha', 'devireddy', 'k00442409')
stu_2 = student('santosh'... |
def get_initial(name):
initial = name[0:1].upper()
return initial
first_name = input('Enter your first name: ')
first_name_initial = get_initial (first_name)
middle_name = input('Enter your middle name: ')
middle_name_initial = get_initial (middle_name)
last_name = input('Enter your last name: ')
last_name_... | def get_initial(name):
initial = name[0:1].upper()
return initial
first_name = input('Enter your first name: ')
first_name_initial = get_initial(first_name)
middle_name = input('Enter your middle name: ')
middle_name_initial = get_initial(middle_name)
last_name = input('Enter your last name: ')
last_name_initia... |
class Password:
'''
class of the password file
'''
def __init__(self, page, password):
self.page = page
self.password = password
'''
function for class properties
'''
'''
user properties
'''
user_password = []
def save_page(self):
Password.user_passwords.append(self)
'''
save pas... | class Password:
"""
class of the password file
"""
def __init__(self, page, password):
self.page = page
self.password = password
'\nfunction for class properties\n'
'\nuser properties\n'
user_password = []
def save_page(self):
Password.user_passwords.append(self)
'\n save password creat... |
# This is the main settings file for package setup and PyPi deployment.
# Sphinx configuration is in the docsrc folder
# Main package name
PACKAGE_NAME = 'dstream_excel'
# Package version in the format (major, minor, release)
PACKAGE_VERSION_TUPLE = (0, 4, 6)
# Short description of the package
PACKAGE_SHORT_DESCRIPT... | package_name = 'dstream_excel'
package_version_tuple = (0, 4, 6)
package_short_description = 'Automate data collection from Thompson Reuters Datastream using the excel plugin'
package_description = '\nUse this tool to drive Excel using the Thompson Reuters Eikon plugin to download Datastream data.\nSee more at the repo... |
while True:
try:
e = str(input()).strip()
c = e.replace('.', '').replace('-', '')
s = 0
for i in range(9):
s += int(c[i]) * (i + 1)
b1 = s % 11
b1 = 0 if b1 == 10 else b1
s = 0
if b1 == int(e[-2]):
for i in range(9):
... | while True:
try:
e = str(input()).strip()
c = e.replace('.', '').replace('-', '')
s = 0
for i in range(9):
s += int(c[i]) * (i + 1)
b1 = s % 11
b1 = 0 if b1 == 10 else b1
s = 0
if b1 == int(e[-2]):
for i in range(9):
... |
# Intersection of 2 arrays
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
counter = None
result = []
if len(nums1) < len(nums2):
counter = collections.Counter(nums1)
for n in nums2:
... | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
counter = None
result = []
if len(nums1) < len(nums2):
counter = collections.Counter(nums1)
for n in nums2:
if n in counter and counter[n] > 0:
c... |
class propertyDecorator(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
pd = propertyDecorator(100)
print(pd.x)
pd.x = 10
print(pd.x)
| class Propertydecorator(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
pd = property_decorator(100)
print(pd.x)
pd.x = 10
print(pd.x) |
countries = ["USA", "Spain", "France", "Canada"]
for country in countries:
print(country)
data = "Hello from python"
for out in data:
print(out)
for numero in range(8):
print(numero) | countries = ['USA', 'Spain', 'France', 'Canada']
for country in countries:
print(country)
data = 'Hello from python'
for out in data:
print(out)
for numero in range(8):
print(numero) |
# X = {
# "0xFF": {
# "id": 255,
# "name": "meta",
# "0x00": {
# "type_id": 0,
# "type_name": "sequence_number",
# "length": 2,
# "params": [
# "nmsb",
# "nlsb"
# ],
# "dtype": "int",
# ... | x = {255: {0: {'dtype': 'int', 'length': 2, 'mask': (255, 255), 'params': ('nmsb', 'nlsb'), 'type_id': 0, 'type_name': 'sequence_number', 'default': [0, 0]}, 1: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 1, 'type_name': 'text_event', 'default': 'Enter the Text'}, 2: {'dtype': 'str', 'lengt... |
def make_car(car_manufacturer,car_model,**Other_attributes):
Other_attributes['car_model']=car_model
Other_attributes['car_manufacturer']=car_manufacturer
return Other_attributes
print(make_car('Toyota','Rav 4',color='blue')) | def make_car(car_manufacturer, car_model, **Other_attributes):
Other_attributes['car_model'] = car_model
Other_attributes['car_manufacturer'] = car_manufacturer
return Other_attributes
print(make_car('Toyota', 'Rav 4', color='blue')) |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 22 16:21:21 2019
@author: x
"""
| """
Created on Fri Feb 22 16:21:21 2019
@author: x
""" |
def find_largest_palindrome(range_start: int, range_end: int) -> int:
largest: int = 0
product: int
i: int
for i in range(range_start, range_end):
j: int
for j in range(range_start, range_end):
product = i * j
if is_palindrome(str(product)) and product > largest... | def find_largest_palindrome(range_start: int, range_end: int) -> int:
largest: int = 0
product: int
i: int
for i in range(range_start, range_end):
j: int
for j in range(range_start, range_end):
product = i * j
if is_palindrome(str(product)) and product > largest:
... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2020 Akumatic
#
# https://adventofcode.com/2020/day/18
def read_file() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return [line.strip() for line in f.readlines()]
def evaluate(values: list, operators: list, precedence: bool) -> int... | def read_file() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", 'r') as f:
return [line.strip() for line in f.readlines()]
def evaluate(values: list, operators: list, precedence: bool) -> int:
if not precedence:
result = int(values[0])
for i in range(len(operators)):
... |
class AuthenticationError(Exception):
pass
class MarketClosedError(Exception):
pass
class MarketEmptyError(Exception):
pass
class InternalStateBotError(Exception):
pass
| class Authenticationerror(Exception):
pass
class Marketclosederror(Exception):
pass
class Marketemptyerror(Exception):
pass
class Internalstateboterror(Exception):
pass |
class Database:
def __init__(self):
self.stuff = {}
def cleanup(self):
self.stuff = {}
def save(self, id, timestamp, count):
self.stuff[id] = {
'timestamp': timestamp,
'count': count
}
def find_all(self, id):
return [self.stuff[id]]
... | class Database:
def __init__(self):
self.stuff = {}
def cleanup(self):
self.stuff = {}
def save(self, id, timestamp, count):
self.stuff[id] = {'timestamp': timestamp, 'count': count}
def find_all(self, id):
return [self.stuff[id]]
def count(self):
return ... |
def assemble_message(message: str, error: bool = False) -> str:
print("Assembling Message")
if error:
message = "-ERR {0}".format(message)
else:
message = "+OK {0}".format(message)
return message
| def assemble_message(message: str, error: bool=False) -> str:
print('Assembling Message')
if error:
message = '-ERR {0}'.format(message)
else:
message = '+OK {0}'.format(message)
return message |
def longest_special_subseq(_n, dist, chars):
chars = tuple(ord(char) - ord("a") for char in chars)
print(chars)
lengths = [0] * 26
# print(lengths)
for char in chars:
c_from = max(char - dist, 0)
c_to = min(char + dist, 25)
longest = max(lengths[c_from: c_to+1])
print... | def longest_special_subseq(_n, dist, chars):
chars = tuple((ord(char) - ord('a') for char in chars))
print(chars)
lengths = [0] * 26
for char in chars:
c_from = max(char - dist, 0)
c_to = min(char + dist, 25)
longest = max(lengths[c_from:c_to + 1])
print(longest)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.