content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Employee:
def __init__(self, id: int, importance: int, subordinates: list[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
class Solution:
def getImportance(self, employees: list['Employee'], id: int) -> int:
total_importance = 0
emp... | class Employee:
def __init__(self, id: int, importance: int, subordinates: list[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
class Solution:
def get_importance(self, employees: list['Employee'], id: int) -> int:
total_importance = 0
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
_SNAKE_TO_CAMEL_CASE_TABLE = {
"access_methods": "accessMethods",
"admin_groups": "adminGroups",
"allow_transfers": "allowT... | _snake_to_camel_case_table = {'access_methods': 'accessMethods', 'admin_groups': 'adminGroups', 'allow_transfers': 'allowTransfers', 'allow_unverified_ssl': 'allowUnverifiedSsl', 'allow_updates': 'allowUpdates', 'auto_create_reversezone': 'autoCreateReversezone', 'client_debug': 'clientDebug', 'copy_xfer_to_notify': 'c... |
AUTHORITY_RESPONSE_OK = "ok"
AUTHORITY_RESPONSE_UPDATE = "update"
AUTHORITY_RESPONSE_DOES_NOT_EXIST = "does_not_exist"
AUTHORITY_RESPONSE_INSTANCE_ID_MISMATCH = "instance_id_mismatch"
AUTHORITY_RESPONSE_INVALID = "invalid"
| authority_response_ok = 'ok'
authority_response_update = 'update'
authority_response_does_not_exist = 'does_not_exist'
authority_response_instance_id_mismatch = 'instance_id_mismatch'
authority_response_invalid = 'invalid' |
# ------------------------------------------------------------------------
# Helper file for 100 Days of Code
#
# My first 'libaray' code
#
# Brent Gawryluik
# 2018-07-09
# ------------------------------------------------------------------------
def print_header(title):
border_length = len(title) + 12
print... | def print_header(title):
border_length = len(title) + 12
print()
print_border(border_length)
print_title(title)
print_border(border_length)
print()
def print_border(length):
for _ in range(length):
print('-', end='', flush=True)
print()
def print_title(title):
print(' ... |
'''
Have the function ArrayRotation(arr) take the arr parameter being passed which will be an array of non-negative integers and
circularly rotate the array starting from the Nth element where N is equal to the first integer in the array.
For example: if arr is [2, 3, 4, 1, 6, 10] then your program should rotate t... | """
Have the function ArrayRotation(arr) take the arr parameter being passed which will be an array of non-negative integers and
circularly rotate the array starting from the Nth element where N is equal to the first integer in the array.
For example: if arr is [2, 3, 4, 1, 6, 10] then your program should rotate the ... |
# Fiona Nealon, 2018-04-07
# A program that finds the smallest positive number that is evenly divisible by all of the numbers from 1 to 20
def factorial(upto):
# Create a variable that will become the answer
multupto = 1
# Loop through numbers i from 1 to upto
for i in range (1, upto):
# # Adapted from: ht... | def factorial(upto):
multupto = 1
for i in range(1, upto):
if multupto % i > 0:
for k in range(1, upto):
if multupto * k % i == 0:
multupto = multupto * k
break
return multupto
print('The smallest positive number that is evenly divi... |
############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | source('../../shared/qtcreator.py')
def main():
path_creator = srcPath + '/creator/qtcreator.pro'
path_speedcrunch = srcPath + '/creator-test-data/speedcrunch/src/speedcrunch.pro'
if not needed_file_present(pathCreator) or not needed_file_present(pathSpeedcrunch):
return
start_application('qtcr... |
def how_sum(target_sum, numbers, memo={}):
if target_sum in memo.keys():
return memo[target_sum]
if target_sum == 0: return []
if target_sum < 0: return None
for num in numbers:
remainder = target_sum - num
rem_result = how_sum(remainder, numbers, memo)
if rem_result is not None:
memo[target_sum] = rem_... | def how_sum(target_sum, numbers, memo={}):
if target_sum in memo.keys():
return memo[target_sum]
if target_sum == 0:
return []
if target_sum < 0:
return None
for num in numbers:
remainder = target_sum - num
rem_result = how_sum(remainder, numbers, memo)
if... |
# ================================================================
g_eps_adam = 10**(-8)
g_beta = 0.9
g_beta2 = 0.999
g_rhomin = 0.015
g_rhomax = 0.15
#for 2Dshell
#g_ymin_2Dshell = None
#g_ymax_2Dshell = None
g_ymin_2Dshell = -7.9
g_ymax_2Dshell = 4.0
g_alpha_Neo_init = 0.01
# ========================... | g_eps_adam = 10 ** (-8)
g_beta = 0.9
g_beta2 = 0.999
g_rhomin = 0.015
g_rhomax = 0.15
g_ymin_2_dshell = -7.9
g_ymax_2_dshell = 4.0
g_alpha__neo_init = 0.01
def get_alpha_num(name, type_opt):
if name == 'x^2':
if type_opt == 'dp_GD_basic':
alpha = 0.5
num = 100
elif type_opt ... |
orbit_map = {}
with open('input.txt') as f:
for line in f:
vk = line.strip().split(')')
orbit_map[vk[1]] = vk[0]
def orbiters(omap, x):
return { i[0] for i in omap.items() if i[1] == x }
def count_direct_indirect_orbits(orbit_map):
count = 0
visit = [('COM', 1)]
while len(visit):
... | orbit_map = {}
with open('input.txt') as f:
for line in f:
vk = line.strip().split(')')
orbit_map[vk[1]] = vk[0]
def orbiters(omap, x):
return {i[0] for i in omap.items() if i[1] == x}
def count_direct_indirect_orbits(orbit_map):
count = 0
visit = [('COM', 1)]
while len(visit):
... |
#!/usr/bin/env python
s1 = 'china'
s2 = 'czech'
ch = 'ch'
def total_occurrences(s1: str, s2: str, ch:str):
return s1.count(ch) + s2.count(ch)
print(total_occurrences( s1, s2, ch))
| s1 = 'china'
s2 = 'czech'
ch = 'ch'
def total_occurrences(s1: str, s2: str, ch: str):
return s1.count(ch) + s2.count(ch)
print(total_occurrences(s1, s2, ch)) |
class Solution:
def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
St = []
remove = len(nums) - k
for num in nums:
while St and num < St[-1] and remove > 0:
St.pop()
remove -= 1
St.append(num)
return St[:len(St) - ... | class Solution:
def most_competitive(self, nums: List[int], k: int) -> List[int]:
st = []
remove = len(nums) - k
for num in nums:
while St and num < St[-1] and (remove > 0):
St.pop()
remove -= 1
St.append(num)
return St[:len(St... |
def f(a):
a = []
for i in range(5):
i = i ** 3
a.append(i)
yield a
# return a
def main():
for x in f(5):
print(x,)
if __name__ == '__main__':
main()
| def f(a):
a = []
for i in range(5):
i = i ** 3
a.append(i)
yield a
def main():
for x in f(5):
print(x)
if __name__ == '__main__':
main() |
nums = [int(i) for i in input().split()]
prefixsum = [0] * (len(nums) + 1)
mi = prefixsum[0]
ma = -100000
msum = nums[0]
for i in range(1, len(nums) + 1):
prefixsum[i] = prefixsum[i-1] + nums[i-1]
if prefixsum[i-1] < mi:
mi = prefixsum[i-1]
if prefixsum[i] - mi > msum:
msum = prefixsum[i... | nums = [int(i) for i in input().split()]
prefixsum = [0] * (len(nums) + 1)
mi = prefixsum[0]
ma = -100000
msum = nums[0]
for i in range(1, len(nums) + 1):
prefixsum[i] = prefixsum[i - 1] + nums[i - 1]
if prefixsum[i - 1] < mi:
mi = prefixsum[i - 1]
if prefixsum[i] - mi > msum:
msum = prefixs... |
#Copyright (C) 2008 Codethink Ltd
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU Lesser General Public
#License version 2 as published by the Free Software Foundation.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; with... | __all__ = ['Enum']
class Enum(int):
def __str__(self):
return self._enum_lookup[int(self)]
def __eq__(self, other):
if other is None:
return False
try:
if int(self) == int(other):
return True
else:
return False
... |
class LaMarkArgumentError(Exception):
def __init__(self, msg, lineno):
self.msg = msg
self.lineno = lineno
def __str__(self):
return "Argument error in tag beginning on line %d: %s" % (
self.lineno, self.msg)
| class Lamarkargumenterror(Exception):
def __init__(self, msg, lineno):
self.msg = msg
self.lineno = lineno
def __str__(self):
return 'Argument error in tag beginning on line %d: %s' % (self.lineno, self.msg) |
class QuantumCircuit:
I=[[1,0],[0,1]]
zero_vector=[[1],[0]]
job=[]
def __init__(self,no_of_qubits):
self.no_of_qubits=no_of_qubits
basis=[]
mat= [[1]]
state_vect... | class Quantumcircuit:
i = [[1, 0], [0, 1]]
zero_vector = [[1], [0]]
job = []
def __init__(self, no_of_qubits):
self.no_of_qubits = no_of_qubits
basis = []
mat = [[1]]
state_vector = [[1]]
for i in range(self.no_of_qubits):
mat = self.Tensor_matrix(mat... |
class Solution:
# @param {integer[]} nums
# @return {boolean}
def containsDuplicate(self, nums):
dict = {}
for i in nums:
if i in dict:
return True
else:
dict[i] = True
return False
| class Solution:
def contains_duplicate(self, nums):
dict = {}
for i in nums:
if i in dict:
return True
else:
dict[i] = True
return False |
# create a list of variable x of the even numbers from range 1 to 100
even_numbers = [x for x in range(1,101) if x % 2 == 0]
print(even_numbers)
odd_numbers = [x for x in range(1,101) if x % 2 != 0]
print(odd_numbers)
words = ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
answer = [... | even_numbers = [x for x in range(1, 101) if x % 2 == 0]
print(even_numbers)
odd_numbers = [x for x in range(1, 101) if x % 2 != 0]
print(odd_numbers)
words = ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
answer = [[w.upper(), w.lower(), len(w)] for w in words]
print(answer) |
# coding=utf-8
class DefaultTimeouts(object):
SHORT_TIMEOUT = 1
DEFAULT_TIMEOUT = 5
LARGE_TIMEOUT = 10
VLARGE_TIMEOUT = 30
PAGE_LOAD_TIMEOUT = 15
| class Defaulttimeouts(object):
short_timeout = 1
default_timeout = 5
large_timeout = 10
vlarge_timeout = 30
page_load_timeout = 15 |
#Test class
class Person:
#Weak Private
_name = 'No Name'
def setName(self,name):
self._name = name
print(f'Name set to {self._name}')
#String Private
def __think(self):
print('Thinking to my self')
def work(self):
self.__think()
#Before and After
def ... | class Person:
_name = 'No Name'
def set_name(self, name):
self._name = name
print(f'Name set to {self._name}')
def __think(self):
print('Thinking to my self')
def work(self):
self.__think()
def __init__(self):
print('Constructor')
def __call__(self):
... |
def is_prime(number):
if number<=1:
return False
if number==2:
return True
for i in range(2,number):
if number%i==0:
return False
return True
def get_primes(numbers):
for number in numbers:
if is_prime(number):
yield number
print(list(get_pr... | def is_prime(number):
if number <= 1:
return False
if number == 2:
return True
for i in range(2, number):
if number % i == 0:
return False
return True
def get_primes(numbers):
for number in numbers:
if is_prime(number):
yield number
print(list... |
class AppError(Exception):
@property
def default_message(self):
raise NotImplementedError
def __init__(self, message: str = '') -> None:
super(AppError, self).__init__(message)
self._message = message
def __str__(self):
message = self.default_message
if self._me... | class Apperror(Exception):
@property
def default_message(self):
raise NotImplementedError
def __init__(self, message: str='') -> None:
super(AppError, self).__init__(message)
self._message = message
def __str__(self):
message = self.default_message
if self._mes... |
#simple function
def Welcome():
print("Welcome to 2019")
#Main function defintion
def main():
print("Main would be printed first")
Welcome()
main()
| def welcome():
print('Welcome to 2019')
def main():
print('Main would be printed first')
welcome()
main() |
SYNTH_PORTS = {'rf':10050, 'demod':10051}
COMMAND_INDEX = 0
RF_CAL = 2
LO_CAL = 3
FILT_CMD = 'f'
WAIT_CMD = 'w'
LMX_POW_CMD = 'p'
DBM_CMD = 'b'
FREQ_CMD = 'r'
DAC_POW_CMD = 'a'
CMD_ERR = 'E'
| synth_ports = {'rf': 10050, 'demod': 10051}
command_index = 0
rf_cal = 2
lo_cal = 3
filt_cmd = 'f'
wait_cmd = 'w'
lmx_pow_cmd = 'p'
dbm_cmd = 'b'
freq_cmd = 'r'
dac_pow_cmd = 'a'
cmd_err = 'E' |
# Problem Set 2, Question 2
# These hold the values of the balance.
balance = 1000
origBalance = balance
# These hold the values of the annual and monthly interest rates.
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12.0
lowestPayment = 0
# This goes through all the possibilites.
while (balan... | balance = 1000
orig_balance = balance
annual_interest_rate = 0.2
monthly_interest_rate = annualInterestRate / 12.0
lowest_payment = 0
while balance > 0:
lowest_payment += 10
balance = origBalance
for month in range(12):
balance = (balance - lowestPayment) * (1 + monthlyInterestRate)
print('Lowest Pa... |
API_MAIN_SEC = "YOUR SEC"
API_MAIN_KEY ="YOUR KEY"
PASSPHRASE_TV = "q4511678"
PERP = {
"KEY" : "YOUR SUBACCOUNT KEY",
"SECRET" : "YOUR SECRET KEY",
"SUBACCOUNT" : "PERP",
}
SPOT = {
"KEY" : "YOUR SUBACCOUNT KEY",
"SECRET" : "YOUR SECRET KEY",
"SUBACCOUNT" : "SPOT",
}
G_API = "GoogleAPI"
G_bucke... | api_main_sec = 'YOUR SEC'
api_main_key = 'YOUR KEY'
passphrase_tv = 'q4511678'
perp = {'KEY': 'YOUR SUBACCOUNT KEY', 'SECRET': 'YOUR SECRET KEY', 'SUBACCOUNT': 'PERP'}
spot = {'KEY': 'YOUR SUBACCOUNT KEY', 'SECRET': 'YOUR SECRET KEY', 'SUBACCOUNT': 'SPOT'}
g_api = 'GoogleAPI'
g_bucket_name = 'GoogleBucketName' |
#!/usr/bin/env python3
class rec:
pass
rec.name = "Bob"
rec.age = 40
print(rec.name)
print(rec.age)
x = rec()
y = rec()
x.name = "Sue"
print(rec.name, x.name, y.name)
l = list(rec.__dict__.keys())
print(l)
l = list(name for name in rec.__dict__.keys() if not name.startswith('__'))
print(l)
l = list(x.__dict__... | class Rec:
pass
rec.name = 'Bob'
rec.age = 40
print(rec.name)
print(rec.age)
x = rec()
y = rec()
x.name = 'Sue'
print(rec.name, x.name, y.name)
l = list(rec.__dict__.keys())
print(l)
l = list((name for name in rec.__dict__.keys() if not name.startswith('__')))
print(l)
l = list(x.__dict__.keys())
print(l)
l = list(... |
N = int(input())
A = [int(input()) for _ in range(N)]
dic = {}
ans = 0
for a in A:
if dic.get(a, 0) > 0:
ans += 1
else:
dic[a] = 1
print(ans)
| n = int(input())
a = [int(input()) for _ in range(N)]
dic = {}
ans = 0
for a in A:
if dic.get(a, 0) > 0:
ans += 1
else:
dic[a] = 1
print(ans) |
#!/usr/local/anaconda3/bin/python
def read_data_from_file():
with open("test.txt") as f:
lineno = 0
for line in f:
lineno = (lineno + 1)
print('Line: {0}, String: {1}'.format(lineno, line))
if __name__ == '__main__':
print('Nice! I still remember this piece!');
read... | def read_data_from_file():
with open('test.txt') as f:
lineno = 0
for line in f:
lineno = lineno + 1
print('Line: {0}, String: {1}'.format(lineno, line))
if __name__ == '__main__':
print('Nice! I still remember this piece!')
read_data_from_file() |
a=input()
a=int(a)
b=input()
b=int(b)
add=a+b
print(add) | a = input()
a = int(a)
b = input()
b = int(b)
add = a + b
print(add) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
g = (str(i) for i in range(3))
assert next(g) == '0'
assert list(g) == ['1', '2']
g = ((x * y) for x in range(3) for y in range(4))
assert list(g) == [0, 0, 0, 0, 0, 1, 2, 3, 0, 2, 4, 6]
g = (i for i in range(8) if i % 3 == 0)
assert list(g) == [0, 3, 6]
assert [i for ... | g = (str(i) for i in range(3))
assert next(g) == '0'
assert list(g) == ['1', '2']
g = (x * y for x in range(3) for y in range(4))
assert list(g) == [0, 0, 0, 0, 0, 1, 2, 3, 0, 2, 4, 6]
g = (i for i in range(8) if i % 3 == 0)
assert list(g) == [0, 3, 6]
assert [i for i in range(3)] == [0, 1, 2] |
# Complete the function below.
def find_next_pos(arr, l, x):
while arr[x] < 0 and x < l - 1:
x += 1
return x
def find_next_neg(arr, l, x):
while arr[x] >= 0 and x < l - 1:
x += 1
return x
def alternating_positives_and_negatives(arr):
l = len(arr)
n = find_next_neg(arr, l, ... | def find_next_pos(arr, l, x):
while arr[x] < 0 and x < l - 1:
x += 1
return x
def find_next_neg(arr, l, x):
while arr[x] >= 0 and x < l - 1:
x += 1
return x
def alternating_positives_and_negatives(arr):
l = len(arr)
n = find_next_neg(arr, l, 0)
p = find_next_pos(arr, l, 0)
... |
# Copyright (c) 2014 Alexander Bredo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions ... | information_elements = dict()
information_elements[1] = 'octetDeltaCount'
information_elements[2] = 'packetDeltaCount'
information_elements[3] = 'deltaFlowCount'
information_elements[4] = 'protocolIdentifier'
information_elements[5] = 'ipClassOfService'
information_elements[6] = 'tcpControlBits'
information_elements[7]... |
VERSION = (0, 11, 4)
__version__ = ".".join(map(str, VERSION))
default_app_config = "cabinet.apps.CabinetConfig"
| version = (0, 11, 4)
__version__ = '.'.join(map(str, VERSION))
default_app_config = 'cabinet.apps.CabinetConfig' |
def median(x):
sorted_x = sorted(x)
midpoint = len(x) // 2
if len(x) % 2:
return sorted_x[midpoint]
else:
return (sorted_x[midpoint]+sorted_x[midpoint-1])/2
def split_half(li):
sorted_li = sorted(li)
midpoint = len(li) // 2
if len(li) % 2:
return (sorted_li[:m... | def median(x):
sorted_x = sorted(x)
midpoint = len(x) // 2
if len(x) % 2:
return sorted_x[midpoint]
else:
return (sorted_x[midpoint] + sorted_x[midpoint - 1]) / 2
def split_half(li):
sorted_li = sorted(li)
midpoint = len(li) // 2
if len(li) % 2:
return (sorted_li[:mi... |
'''
Kattis - cantiaofbabel
The tricky part of this question is not really the SCC part as it is quite standard but rather constructing the directed graph.
Good thing tho, n <= 100 so our O(n^2 * 20) relatively naive method will work. If we need to be more efficient,
we can construct a set of language listeners for eac... | """
Kattis - cantiaofbabel
The tricky part of this question is not really the SCC part as it is quite standard but rather constructing the directed graph.
Good thing tho, n <= 100 so our O(n^2 * 20) relatively naive method will work. If we need to be more efficient,
we can construct a set of language listeners for eac... |
# A function to list the n terms of the Fibonacci sequence.
# Save file as fibonacci.py.
# Run the Module (or type F5).
def fibonacci(n):
a, b = 0, 1
print(a)
print(b)
print(a+b)
for i in range(n-3):
a, b = b, a+b
print(a+b)
| def fibonacci(n):
(a, b) = (0, 1)
print(a)
print(b)
print(a + b)
for i in range(n - 3):
(a, b) = (b, a + b)
print(a + b) |
PERSISTNET
DATA: {'AnalysedTiles': [{'State': 'UNANALYSED', 'Subject': None}, {'State': 'ANALYSED', 'Subject': 'diamond head'},
{'State': 'ANALYSED', 'Subject': 'dog'}, {'State': 'ANALYSED', 'Subject': 'yulong river'},
{'State': 'ANALYSED', 'Subject': 'kangaroo'}, {'Sta... | PERSISTNET
data: {'AnalysedTiles': [{'State': 'UNANALYSED', 'Subject': None}, {'State': 'ANALYSED', 'Subject': 'diamond head'}, {'State': 'ANALYSED', 'Subject': 'dog'}, {'State': 'ANALYSED', 'Subject': 'yulong river'}, {'State': 'ANALYSED', 'Subject': 'kangaroo'}, {'State': 'UNANALYSED', 'Subject': None}, {'State': 'UN... |
"helpers for test assertions"
load("@bazel_skylib//rules:diff_test.bzl", "diff_test")
load("@bazel_skylib//rules:write_file.bzl", "write_file")
load("@build_bazel_rules_nodejs//:index.bzl", "npm_package_bin")
def assert_program_produces_stdout(name, tool, stdout, tags = []):
write_file(
name = "_write_exp... | """helpers for test assertions"""
load('@bazel_skylib//rules:diff_test.bzl', 'diff_test')
load('@bazel_skylib//rules:write_file.bzl', 'write_file')
load('@build_bazel_rules_nodejs//:index.bzl', 'npm_package_bin')
def assert_program_produces_stdout(name, tool, stdout, tags=[]):
write_file(name='_write_expected_' + ... |
an_letters = "aefhilmnorsxAEFHILMNORSX"
word = input("I will cheer for you! Enter a word:\n")
times = int(input("Enthusiasm level (1-10):\n"))
i = 0
while i < len(word):
char = word[i]
if char in an_letters:
print("Give me an", char, "!", char)
else:
print("Give me a", char, "!", char)
i += 1
print("What does... | an_letters = 'aefhilmnorsxAEFHILMNORSX'
word = input('I will cheer for you! Enter a word:\n')
times = int(input('Enthusiasm level (1-10):\n'))
i = 0
while i < len(word):
char = word[i]
if char in an_letters:
print('Give me an', char, '!', char)
else:
print('Give me a', char, '!', char)
i... |
def make_scene_name(type, num):
if type == "":
return "FloorPlan" + str(num)
elif num < 10:
return "FloorPlan" + type + "0" + str(num)
else:
return "FloorPlan" + type + str(num)
def get_scenes(scene_str):
scene_str_split = scene_str.split("+")
if len(scene_str_split) == 1:
... | def make_scene_name(type, num):
if type == '':
return 'FloorPlan' + str(num)
elif num < 10:
return 'FloorPlan' + type + '0' + str(num)
else:
return 'FloorPlan' + type + str(num)
def get_scenes(scene_str):
scene_str_split = scene_str.split('+')
if len(scene_str_split) == 1:
... |
p= int(input("Enter starting principal please"))
n= int(input("Enter number of compounding periods per year"))
r= float(input("Enter annual rate. e.g 15 for 15%"))
y= int(input("Enter amount of years."))
FV = p * (((1 + ((r/100.0)/n)) ** (n*y)))
print("The final amount after ", y, "years is", FV) | p = int(input('Enter starting principal please'))
n = int(input('Enter number of compounding periods per year'))
r = float(input('Enter annual rate. e.g 15 for 15%'))
y = int(input('Enter amount of years.'))
fv = p * (1 + r / 100.0 / n) ** (n * y)
print('The final amount after ', y, 'years is', FV) |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root):
if not root: return None
left = self.solve(root.left)
right = self.solve(root.right)
if not le... | class Solution:
def solve(self, root):
if not root:
return None
left = self.solve(root.left)
right = self.solve(root.right)
if not left and (not right) and (root.val % 2 == 0):
return None
root.left = left
root.right = right
return roo... |
# https://leetcode.com/problems/toeplitz-matrix/
class Solution:
def isToeplitzMatrix(self, arr: List[List[int]]) -> bool:
N = len(arr)
if N == 0:
return True
M = len(arr[0])
if M == 0:
return True
for j in range(M):
row, col = 0, j
... | class Solution:
def is_toeplitz_matrix(self, arr: List[List[int]]) -> bool:
n = len(arr)
if N == 0:
return True
m = len(arr[0])
if M == 0:
return True
for j in range(M):
(row, col) = (0, j)
diagonal_element = arr[0][j]
... |
# Python - 3.6.0
def sexy_prime(x, y):
def isPrime(n):
if n in [2, 3, 5, 7]:
return True
if (n < 2) or (n & 1) == 0:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
return (abs(x -... | def sexy_prime(x, y):
def is_prime(n):
if n in [2, 3, 5, 7]:
return True
if n < 2 or n & 1 == 0:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
return abs(x - y) == 6 and is_prime(... |
class DnD:
'''
Python wrapper for the tkDnD tk extension.
source: https://mail.python.org/pipermail/tkinter-discuss/2005-July/000476.html
'''
_subst_format = ('%A', '%a', '%T', '%W', '%X', '%Y', '%x', '%y','%D')
_subst_format_str = " ".join(_subst_format)
def __init__(self, tkroot):
... | class Dnd:
"""
Python wrapper for the tkDnD tk extension.
source: https://mail.python.org/pipermail/tkinter-discuss/2005-July/000476.html
"""
_subst_format = ('%A', '%a', '%T', '%W', '%X', '%Y', '%x', '%y', '%D')
_subst_format_str = ' '.join(_subst_format)
def __init__(self, tkroot):
... |
class Prehensor:
def __init__(self, charge: float) -> None:
self._charge = charge
@property
def charge(self) -> float:
return self._charge
| class Prehensor:
def __init__(self, charge: float) -> None:
self._charge = charge
@property
def charge(self) -> float:
return self._charge |
def save_model(MainModel, network_filepath, weight_filepath, dump_filepath):
model = MainModel.RefactorModel()
model = MainModel.deploy_weight(model, weight_filepath)
model.save_checkpoint(dump_filepath, 0)
print('MXNet checkpoint file is saved with prefix [{}] and iteration 0, generated by [{}.py] and ... | def save_model(MainModel, network_filepath, weight_filepath, dump_filepath):
model = MainModel.RefactorModel()
model = MainModel.deploy_weight(model, weight_filepath)
model.save_checkpoint(dump_filepath, 0)
print('MXNet checkpoint file is saved with prefix [{}] and iteration 0, generated by [{}.py] and ... |
class SbrickProtocol(object):
def __init__(self):
self.module = 'sbrick'
self.version = '01'
def gen_sp_topic(self, action):
return "{module}/{version}/sp/{action}".format(action=action, **(self.__dict__))
def gen_rr_topic(self, action):
return "{module}/{version}/rr/... | class Sbrickprotocol(object):
def __init__(self):
self.module = 'sbrick'
self.version = '01'
def gen_sp_topic(self, action):
return '{module}/{version}/sp/{action}'.format(action=action, **self.__dict__)
def gen_rr_topic(self, action):
return '{module}/{version}/rr/{action... |
# This program calculates the gross pay for
# each of Megan's baristas.
# NUM_EMPLOYEES is used as a constant for the
# size of the list.
NUM_EMPLOYEES = 6
def main():
# Create a list to hold employee hours.
hours = [0] * NUM_EMPLOYEES
# Get each employee's hours worked.
for index in rang... | num_employees = 6
def main():
hours = [0] * NUM_EMPLOYEES
for index in range(NUM_EMPLOYEES):
print('Enter the hours worked by employee ', index + 1, ': ', sep='', end='')
hours[index] = float(input())
pay_rate = float(input('Enter the hourly pay rate: '))
for index in range(NUM_EMPLOYEE... |
x = [True, True, False]
if any(x):
print("At least one True")
if all(x):
print("No one False")
if any(x) and not all(x):
print("At least one True and one False")
| x = [True, True, False]
if any(x):
print('At least one True')
if all(x):
print('No one False')
if any(x) and (not all(x)):
print('At least one True and one False') |
# Hyperparameters
learning_rate = 0.001
weight_decay = 0.0001
batch_size = 256
num_epochs = 256
img_size = 72 #images will be resized to this size
patch_size = 6
num_patches = (img_size//patch_size) ** 2
projection_dim = 3
num_heads = 4
transformer_units = [projection_dim*2, projection_dim]
mlp_head_units = [2048,1024... | learning_rate = 0.001
weight_decay = 0.0001
batch_size = 256
num_epochs = 256
img_size = 72
patch_size = 6
num_patches = (img_size // patch_size) ** 2
projection_dim = 3
num_heads = 4
transformer_units = [projection_dim * 2, projection_dim]
mlp_head_units = [2048, 1024]
transformer_layers = 8 |
ENGLISH = 0
GERMAN = 1
FRENCH = 2
MAX_PADDING = 140
MAX_WORDS = 20
# frontend
LANG_DICT = {'English': ENGLISH, 'German': GERMAN, 'French': FRENCH}
LANG = ['en', 'de', 'fr']
TARGET_IMAGE_SIZE = [448, 448]
CHANNEL_MEAN = [0.485, 0.456, 0.406]
CHANNEL_STD = [0.229, 0.224, 0.225]
WAVEGLOW_PATH = "tacotron2/waveglow2/"
T... | english = 0
german = 1
french = 2
max_padding = 140
max_words = 20
lang_dict = {'English': ENGLISH, 'German': GERMAN, 'French': FRENCH}
lang = ['en', 'de', 'fr']
target_image_size = [448, 448]
channel_mean = [0.485, 0.456, 0.406]
channel_std = [0.229, 0.224, 0.225]
waveglow_path = 'tacotron2/waveglow2/'
tacotron_path =... |
GITHUB_WEBHOOK_SECRET="nothing to see here"
GITHUB_OAUTH_CLIENT_ID="nothing to see here"
GITHUB_OAUTH_CLIENT_SECRET="nothing to see here"
GITHUB_STATUS_OAUTH_TOKEN="nothing to see here"
COVERALLS_REPO_TOKEN="nothing to see here"
CODECOV_REPO_TOKEN="nothing to see here"
FREEBSDCI_OAUTH_TOKEN="nothing to see here"
SLACK_... | github_webhook_secret = 'nothing to see here'
github_oauth_client_id = 'nothing to see here'
github_oauth_client_secret = 'nothing to see here'
github_status_oauth_token = 'nothing to see here'
coveralls_repo_token = 'nothing to see here'
codecov_repo_token = 'nothing to see here'
freebsdci_oauth_token = 'nothing to se... |
# Given a string, return a string where for every char in the original, there
# are two chars.
# double_char('The') --> 'TThhee'
# double_char('AAbb') --> 'AAAAbbbb'
# double_char('Hi-There') --> 'HHii--TThheerree'
def double_char(str):
result = ''
for c in str:
result += c*2
return result
print(double_c... | def double_char(str):
result = ''
for c in str:
result += c * 2
return result
print(double_char('The'))
print(double_char('AAbb'))
print(double_char('Hi-There')) |
# https://app.codesignal.com/arcade/code-arcade/well-of-integration/kvGfZZxGyjNbD7yxv
def integerToStringOfFixedWidth(number, width):
# Given a number and a width, either crop it or expand it.
# Expansion is adding 0s, cropping is removing left-to-right digits.
str_num = str(number)
# "0" times a negati... | def integer_to_string_of_fixed_width(number, width):
str_num = str(number)
str_num = '0' * (width - len(str_num)) + str_num
return str_num[-width:] |
class Rectangle:
def __init__(self, startCoordinates, endCoordinates):
self.startCoordinates = startCoordinates
self.endCoordinates = endCoordinates
self.x = self.startCoordinates[0]
self.y = self.startCoordinates[1]
self.width = self.endCoordinates[0] - self.x
self.height = self.endCoordinates[1]... | class Rectangle:
def __init__(self, startCoordinates, endCoordinates):
self.startCoordinates = startCoordinates
self.endCoordinates = endCoordinates
self.x = self.startCoordinates[0]
self.y = self.startCoordinates[1]
self.width = self.endCoordinates[0] - self.x
self.... |
class MyClass:
def __init__(self, i):
self.i = i
def get(self):
func_name = 'function'+str(self.i)
self.func_name()
def function1(self):
print("Hello")
def function2(self):
print("There")
obj = MyClass(1)
obj.get() | class Myclass:
def __init__(self, i):
self.i = i
def get(self):
func_name = 'function' + str(self.i)
self.func_name()
def function1(self):
print('Hello')
def function2(self):
print('There')
obj = my_class(1)
obj.get() |
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config_type='sweetberry'
inas = [
('sweetberry', (1,3), 'ppvar_kb_bl', 7.6, 0.100, 'j2', True), # D36
('sweetberry', (2,4), 'pp3300_a_mic... | config_type = 'sweetberry'
inas = [('sweetberry', (1, 3), 'ppvar_kb_bl', 7.6, 0.1, 'j2', True), ('sweetberry', (2, 4), 'pp3300_a_micvdd', 3.3, 0.01, 'j2', True), ('sweetberry', (1, 3), 'battery', 7.6, 0.05, 'j3', True), ('sweetberry', (1, 3), 'pp3300_g', 3.3, 0.1, 'j4', True), ('sweetberry', (2, 4), 'pp3300_h1', 3.3, 0... |
#
# PySNMP MIB module KERNEL-READER-SUNMANAGEMENTCENTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/KERNEL-READER-SUNMANAGEMENTCENTER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:54:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
#... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, single_value_constraint, value_size_constraint) ... |
def create_field(size):
return [[0] * size for _ in range(size)]
def check_cell(size, row, col):
return 0 <= row < size and 0 <= col < size
def increase_neighbouring_cells(matrix, size):
rows = [-1, -1, -1, 0, 1, 1, 1, 0]
cols = [-1, 0, 1, 1, 1, 0, -1, -1]
for row in range(size):
for col... | def create_field(size):
return [[0] * size for _ in range(size)]
def check_cell(size, row, col):
return 0 <= row < size and 0 <= col < size
def increase_neighbouring_cells(matrix, size):
rows = [-1, -1, -1, 0, 1, 1, 1, 0]
cols = [-1, 0, 1, 1, 1, 0, -1, -1]
for row in range(size):
for col i... |
self.description = "transferred file with glob characters that match a removed file"
lp = pmpkg("foo")
lp.files = ["foo/b*r", "foo/bar"]
self.addpkg2db("local", lp)
sp1 = pmpkg("foo", "1.0-2")
self.addpkg(sp1)
sp2 = pmpkg("bar", "1.0-2")
sp2.files = ["foo/b*r"]
self.addpkg(sp2)
self.args = "-U %s %s" % (sp1.filenam... | self.description = 'transferred file with glob characters that match a removed file'
lp = pmpkg('foo')
lp.files = ['foo/b*r', 'foo/bar']
self.addpkg2db('local', lp)
sp1 = pmpkg('foo', '1.0-2')
self.addpkg(sp1)
sp2 = pmpkg('bar', '1.0-2')
sp2.files = ['foo/b*r']
self.addpkg(sp2)
self.args = '-U %s %s' % (sp1.filename(),... |
# Leetcode Problem
# - id: 91
# - title: Decode Ways
# - url: https://leetcode.com/problems/decode-ways/
# - difficulty: medium
class Solution:
def numDecodings(self, s: str) -> int:
cache = [None] * len(s)
return self.num_decodings(s, 0, cache)
def is_valid(self, s: str) -> bool:
... | class Solution:
def num_decodings(self, s: str) -> int:
cache = [None] * len(s)
return self.num_decodings(s, 0, cache)
def is_valid(self, s: str) -> bool:
if not s:
return False
if s[0] == '0':
return False
code = int(s)
if code < 1 or co... |
'''
https://leetcode.com/problems/merge-k-sorted-lists/
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
vals=[]
for hea... | """
https://leetcode.com/problems/merge-k-sorted-lists/
"""
class Solution:
def merge_k_lists(self, lists: List[ListNode]) -> ListNode:
vals = []
for head in lists:
while head is not None:
vals.append(head.val)
head = head.next
vals.sort()
... |
class Haromszog(object):
def __init__(self, a = 1, b = 1, c = 1):
self.setA(a)
self.setB(b)
self.setC(c)
def setA(self, a):
self._a = a
def setB(self, b):
self._b = b
def setC(self, c):
self._c = c
def __str__(s... | class Haromszog(object):
def __init__(self, a=1, b=1, c=1):
self.setA(a)
self.setB(b)
self.setC(c)
def set_a(self, a):
self._a = a
def set_b(self, b):
self._b = b
def set_c(self, c):
self._c = c
def __str__(self):
return '(a: %f, b: %f, c:... |
expected_output = {
"files": {
1: {
"file_length": 4096,
"file_date": "Nov 09 2020 01:44:00.0000000000 +00:00",
"file_name": "/bootflash/"
},
2: {
"file_length": 16384,
"file_date": "Apr 20 2017 23:21:13.0000000000 +00:00",
"file_name": "/bootflash/lost+found"
},
... | expected_output = {'files': {1: {'file_length': 4096, 'file_date': 'Nov 09 2020 01:44:00.0000000000 +00:00', 'file_name': '/bootflash/'}, 2: {'file_length': 16384, 'file_date': 'Apr 20 2017 23:21:13.0000000000 +00:00', 'file_name': '/bootflash/lost+found'}, 3: {'file_length': 4096, 'file_date': 'May 01 2018 04:41:34.00... |
weather = input("What is the weather today?")
if weather == "It is sunny":
print ("It is sunny outside")
print ("I won't need my umbrella")
elif weather == "It is raining":
print ("I will take my umbrella to work today")
print ("It is rainy")
else:
print ("Ok, thank you for telling me.")
| weather = input('What is the weather today?')
if weather == 'It is sunny':
print('It is sunny outside')
print("I won't need my umbrella")
elif weather == 'It is raining':
print('I will take my umbrella to work today')
print('It is rainy')
else:
print('Ok, thank you for telling me.') |
#@title Reset session { form-width: "30%" }
# This cell resets the Tensorflow session, but keeps the same computational
# graph.
try:
sess.close()
except NameError:
pass
sess = tf.Session()
sess.run(tf.global_variables_initializer())
last_iteration = 0
logged_iterations = []
losses_tr = []
losses_4_ge = []
loss... | try:
sess.close()
except NameError:
pass
sess = tf.Session()
sess.run(tf.global_variables_initializer())
last_iteration = 0
logged_iterations = []
losses_tr = []
losses_4_ge = []
losses_9_ge = []
log_every_seconds = 20
print('# (iteration number), T (elapsed seconds), Ltr (training 1-step loss), Lge4 (test/gene... |
def largest_product(a,n):
output = 0
for i in range(len(str(a))-n):
product = 1
for j in range(n):
product *= int(str(a)[i+j])
if product > output:
output = product
return output
a = 731671765313306249192251196744265747423553491949349698352031277450632623... | def largest_product(a, n):
output = 0
for i in range(len(str(a)) - n):
product = 1
for j in range(n):
product *= int(str(a)[i + j])
if product > output:
output = product
return output
a = 731671765313306249192251196744265747423553491949349698352031277450632623... |
class Solution:
def __init__(self):
self.cache = {}
def climbStairs(self, n: int) -> int:
if (n == 0):
self.cache[0] = 0
if (n == 1):
self.cache[1] = 1
if (n == 2):
self.cache[2] = 2
return self.climb(n)
def climb(self, n: int) -... | class Solution:
def __init__(self):
self.cache = {}
def climb_stairs(self, n: int) -> int:
if n == 0:
self.cache[0] = 0
if n == 1:
self.cache[1] = 1
if n == 2:
self.cache[2] = 2
return self.climb(n)
def climb(self, n: int) -> int... |
def run_policy_on_env(policy_fn, env, truncate_episode_at=None, first_obs=None):
if first_obs is None:
obs = env.reset()
else:
obs = first_obs
trajectory = []
step_num = 0
while True:
act = policy_fn(obs)
next_obs, rew, done, _ = env.step(act)
trajectory.appe... | def run_policy_on_env(policy_fn, env, truncate_episode_at=None, first_obs=None):
if first_obs is None:
obs = env.reset()
else:
obs = first_obs
trajectory = []
step_num = 0
while True:
act = policy_fn(obs)
(next_obs, rew, done, _) = env.step(act)
trajectory.app... |
a = sorted([*map(int, input().split())])
b = sorted([*map(int, input().split())])
print("YES" if a == b and a[0] * a[0] + a[1] * a[1] == a[2] * a[2] else "NO")
| a = sorted([*map(int, input().split())])
b = sorted([*map(int, input().split())])
print('YES' if a == b and a[0] * a[0] + a[1] * a[1] == a[2] * a[2] else 'NO') |
#
# PySNMP MIB module CXLlcLanConv-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXLlcLanConv-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:17:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, value_size_constraint, single_value_constraint) ... |
print("step: 1")
print("x: 1")
print("step: 2")
print("x: 2")
print("step: 3")
print("x: 3")
print("x: 4")
| print('step: 1')
print('x: 1')
print('step: 2')
print('x: 2')
print('step: 3')
print('x: 3')
print('x: 4') |
class Math:
@staticmethod
def add(x, y):
addition = x + y
return addition
@staticmethod
def pr():
print("run")
print(Math.add(4, 5))
# calling method without passing any argument
Math.pr() | class Math:
@staticmethod
def add(x, y):
addition = x + y
return addition
@staticmethod
def pr():
print('run')
print(Math.add(4, 5))
Math.pr() |
# https://atcoder.jp/contests/abc209/tasks/abc209_b
N, X = map(int, input().split())
a_arr = list(map(int, input().split()))
total = 0
for i, a in enumerate(a_arr):
if i % 2 == 1:
total += (a - 1)
continue
total += a
ans = 'Yes' if total <= X else 'No'
print(ans)
| (n, x) = map(int, input().split())
a_arr = list(map(int, input().split()))
total = 0
for (i, a) in enumerate(a_arr):
if i % 2 == 1:
total += a - 1
continue
total += a
ans = 'Yes' if total <= X else 'No'
print(ans) |
# TODO:
def test_authorization_url():
pass
def test_decode_and_validate():
pass
def test_build_user_creds_jwt_grant():
pass | def test_authorization_url():
pass
def test_decode_and_validate():
pass
def test_build_user_creds_jwt_grant():
pass |
SORT_CREATED = "created"
SORT_FINISHED = "finished"
SORT_STATUS = "status"
SORT_PROCESS = "process"
SORT_SERVICE = "service"
SORT_USER = "user"
SORT_QUOTE = "quote"
SORT_PRICE = "price"
SORT_ID = "id"
SORT_ID_LONG = "identifier" # long form employed by Processes in DB representation
PROCESS_SORT_VALUES = frozenset([
... | sort_created = 'created'
sort_finished = 'finished'
sort_status = 'status'
sort_process = 'process'
sort_service = 'service'
sort_user = 'user'
sort_quote = 'quote'
sort_price = 'price'
sort_id = 'id'
sort_id_long = 'identifier'
process_sort_values = frozenset([SORT_ID, SORT_ID_LONG, SORT_PROCESS, SORT_CREATED])
job_so... |
# See: https://www.codewars.com/kata/557592fcdfc2220bed000042
def pattern(n):
return '\n'.join(''.join(map(str, range(1,n+1)[i:n]+range(1,n+1)[:i])) for i in range(n))
| def pattern(n):
return '\n'.join((''.join(map(str, range(1, n + 1)[i:n] + range(1, n + 1)[:i])) for i in range(n))) |
keywords : dict = {
"print" : 'print',
"comment":'#',
"variable":'=',
"start":'start',
"start_db" : 'database',
"init_table" : 'table',
"add_toTable" : 'add',
"add_Unique" : 'uadd',
"remove_fromTable" : 'remove',
"local_db" : 'local',
"update" : 'update',
}
def get_tokens():
wi... | keywords: dict = {'print': 'print', 'comment': '#', 'variable': '=', 'start': 'start', 'start_db': 'database', 'init_table': 'table', 'add_toTable': 'add', 'add_Unique': 'uadd', 'remove_fromTable': 'remove', 'local_db': 'local', 'update': 'update'}
def get_tokens():
with open('Basic_tests.arql', 'r') as f:
... |
file = open("Street_Centrelines.csv","r")
def list_tuple(): #here we get tuple names
for line in file:
line=line.split(',')
res=(line[2],line[4],line[6],line[7])
print(res)
list_tuple()
'''Here getting the result as a dictonary
were key as maintainence and values no.of streets.'''
def maintain_hist():
file =... | file = open('Street_Centrelines.csv', 'r')
def list_tuple():
for line in file:
line = line.split(',')
res = (line[2], line[4], line[6], line[7])
print(res)
list_tuple()
'Here getting the result as a dictonary\n were key as maintainence and values no.of streets.'
def maintain_hist():
fi... |
# 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 ( arr , N ) :
lis = [ 0 ] * N
for i in range ( N ) :
lis [ i ] = 1
for i in range ( 1 , N ) :
... | def f_gold(arr, N):
lis = [0] * N
for i in range(N):
lis[i] = 1
for i in range(1, N):
for j in range(i):
if arr[i] >= arr[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
max = 0
for i in range(N):
if max < lis[i]:
max = lis[i]
retur... |
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
sumdiag, sumdiaginv, min, max = 0, 0, 0, len(arr)-1
for i in range(0, len(arr)):
for j in range(0, len(arr)):
... | def diagonal_difference(arr):
(sumdiag, sumdiaginv, min, max) = (0, 0, 0, len(arr) - 1)
for i in range(0, len(arr)):
for j in range(0, len(arr)):
if i == j:
sumdiag += arr[i][j]
if min == i and max == j:
sumdiaginv += arr[i][j]
min ... |
"Unit tests for //internal/common:preserve_legacy_templated_args.bzl"
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
load("//internal/common:preserve_legacy_templated_args.bzl", "preserve_legacy_templated_args")
def _impl(ctx):
env = unittest.begin(ctx)
conversions = {
"$": "$$",
... | """Unit tests for //internal/common:preserve_legacy_templated_args.bzl"""
load('@bazel_skylib//lib:unittest.bzl', 'asserts', 'unittest')
load('//internal/common:preserve_legacy_templated_args.bzl', 'preserve_legacy_templated_args')
def _impl(ctx):
env = unittest.begin(ctx)
conversions = {'$': '$$', '$$': '$$',... |
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
bfs = deque([[sr,sc]])
visited = {(sr,sc)}
replace_color = image[sr][sc]
while bfs:
y,x = bfs.popleft()
image[y][x] = newColor
... | class Solution:
def flood_fill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
bfs = deque([[sr, sc]])
visited = {(sr, sc)}
replace_color = image[sr][sc]
while bfs:
(y, x) = bfs.popleft()
image[y][x] = newColor
f... |
CIPHER = {'A': '11', 'B': '12', 'C': '13', 'D': '14',
'E': '15', 'F': '21', 'G': '22', 'H': '23',
'I': '24', 'J': '24', 'K': '25', 'L': '31',
'M': '32', 'N': '33', 'O': '34', 'P': '35',
'Q': '41', 'R': '42', 'S': '43', 'T': '44',
'U': '45', 'V': '51', 'W': '52', 'X': '5... | cipher = {'A': '11', 'B': '12', 'C': '13', 'D': '14', 'E': '15', 'F': '21', 'G': '22', 'H': '23', 'I': '24', 'J': '24', 'K': '25', 'L': '31', 'M': '32', 'N': '33', 'O': '34', 'P': '35', 'Q': '41', 'R': '42', 'S': '43', 'T': '44', 'U': '45', 'V': '51', 'W': '52', 'X': '53', 'Y': '54', 'Z': '55'}
def polybius(text):
... |
class ErrorMessageDisplayed(BaseException):
def __init__(self, m):
self.message = m
def __str__(self):
return self.message
class WarningMessageDisplayed(BaseException):
def __init__(self, m):
self.message = m
def __str__(self):
return self.message
| class Errormessagedisplayed(BaseException):
def __init__(self, m):
self.message = m
def __str__(self):
return self.message
class Warningmessagedisplayed(BaseException):
def __init__(self, m):
self.message = m
def __str__(self):
return self.message |
start, end, nimages = map(int, input().split())
images = []
for i in range(nimages):
timestamp, rows, cols = map(int, input().split())
image = []
for j in range(rows):
image += map(int, input().split())
if start <= timestamp <= end:
if any(image):
print(timestamp)
| (start, end, nimages) = map(int, input().split())
images = []
for i in range(nimages):
(timestamp, rows, cols) = map(int, input().split())
image = []
for j in range(rows):
image += map(int, input().split())
if start <= timestamp <= end:
if any(image):
print(timestamp) |
precio_lote = float(input("precio del lote de naranjas: "))
precio_docena = float(input("precio de la docena: "))
num_ventas = int(input("numero de ventas: "))
porcentaje_lote = precio_lote / precio_docena
ganancia_naranjas = porcentaje_lote + precio_lote
porcentaje_ganancias = round(num_ventas / ganancia_naranjas, 2)
... | precio_lote = float(input('precio del lote de naranjas: '))
precio_docena = float(input('precio de la docena: '))
num_ventas = int(input('numero de ventas: '))
porcentaje_lote = precio_lote / precio_docena
ganancia_naranjas = porcentaje_lote + precio_lote
porcentaje_ganancias = round(num_ventas / ganancia_naranjas, 2)
... |
class CH:
def __init__(self):
pass
def attach(self,C):
for f in C.frame:
for x in f:
if x.__class__==self.__class__.__burst__:
x.attach(self)
def deattach(self,C):
for f in C.frame:
for x in f:
if x.__class__==self.__class__.__burst__:
x.deattach()
def compress_bits(self,sbuf):
dbuf... | class Ch:
def __init__(self):
pass
def attach(self, C):
for f in C.frame:
for x in f:
if x.__class__ == self.__class__.__burst__:
x.attach(self)
def deattach(self, C):
for f in C.frame:
for x in f:
if x.__... |
class Solution:
def numPrimeArrangements(self, n: int) -> int:
kMod = int(1e9) + 7
def countPrimes(n: int) -> int:
isPrime = [False] * 2 + [True] * (n - 1)
for i in range(2, int(n**0.5) + 1):
if isPrime[i]:
for j in range(i * i, n + 1, i):
isPrime[j] = False
... | class Solution:
def num_prime_arrangements(self, n: int) -> int:
k_mod = int(1000000000.0) + 7
def count_primes(n: int) -> int:
is_prime = [False] * 2 + [True] * (n - 1)
for i in range(2, int(n ** 0.5) + 1):
if isPrime[i]:
for j in range(... |
class Node:
def __init__(self, id, x, y, z):
self.id = int(id) - 1
self.x = x
self.y = y
self.z = z
self.is_noslip = False
self.is_input = False
self.is_output = False
def get_position(self):
return [self.x, self.y, self.z]
def __eq__(self, o... | class Node:
def __init__(self, id, x, y, z):
self.id = int(id) - 1
self.x = x
self.y = y
self.z = z
self.is_noslip = False
self.is_input = False
self.is_output = False
def get_position(self):
return [self.x, self.y, self.z]
def __eq__(self, ... |
# -*- coding: utf-8 -*-
# Scrapy settings for segurarse_com_ar project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/... | bot_name = 'segurarse_com_ar'
spider_modules = ['segurarse_com_ar.spiders']
newspider_module = 'segurarse_com_ar.spiders'
user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'
cookies_enabled = False
phantomjs_path = './../phantomjs.exe' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def partition(arr, low, high):
pivot = arr[low]
(i, j) = (low-1, high+1)
while True:
while True:
i += 1
if arr[i] >= pivot:
break
... | def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def partition(arr, low, high):
pivot = arr[low]
(i, j) = (low - 1, high + 1)
while True:
while True:
i += 1
if arr[i] >= pivot:
break
while True:
j -= 1
... |
class ClientConfig(object):
PUBLIC_KEY = '7fqG6ZDxHhGKxY+501J0J6MgAgnTdTcHSkvd78Ww740'
APP_NAME = 'ThunderTac'
COMPANY_NAME = 'ThunderApps'
HTTP_TIMEOUT = 30
MAX_DOWNLOAD_RETRIES = 3
UPDATE_URLS = ['https://raw.githubusercontent.com/diVineProportion/thundertacupdates/main/']
| class Clientconfig(object):
public_key = '7fqG6ZDxHhGKxY+501J0J6MgAgnTdTcHSkvd78Ww740'
app_name = 'ThunderTac'
company_name = 'ThunderApps'
http_timeout = 30
max_download_retries = 3
update_urls = ['https://raw.githubusercontent.com/diVineProportion/thundertacupdates/main/'] |
class Solution:
# O(n) time | O(1) space
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
for i in range(len(flowerbed)):
prev = 0 if i == 0 else flowerbed[i - 1]
nex = 0 if i == len(flowerbed) - 1 else flowerbed[i + 1]
if flowerbed[i] == 0 and prev =... | class Solution:
def can_place_flowers(self, flowerbed: List[int], n: int) -> bool:
for i in range(len(flowerbed)):
prev = 0 if i == 0 else flowerbed[i - 1]
nex = 0 if i == len(flowerbed) - 1 else flowerbed[i + 1]
if flowerbed[i] == 0 and prev == 0 and (nex == 0):
... |
T = int(input())
for _ in range(T):
n, x = map(int,input().split())
print(2*x)
| t = int(input())
for _ in range(T):
(n, x) = map(int, input().split())
print(2 * x) |
# -*- coding:utf-8 -*-
# DT Colors
def distrotube():
colors = [
["#2a2a2a", "#2a2a2a"], # panel background
["#3d3f4b", "#434758"], # background for current screen tab
["#ffffff", "#ffffff"], # font color for group names
["#ff5555", "#ff5555"], # border line color for current tab... | def distrotube():
colors = [['#2a2a2a', '#2a2a2a'], ['#3d3f4b', '#434758'], ['#ffffff', '#ffffff'], ['#ff5555', '#ff5555'], ['#74438f', '#74438f'], ['#4f76c7', '#4f76c7'], ['#e1acff', '#e1acff'], ['#ecbbfb', '#ecbbfb']]
return colors
def hollowknight():
colors = [['#06090A', '#06090A'], ['#06090A', '#111b1... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class FindElements:
def __init__(self, root: TreeNode):
self.table = set()
def dfs(root, curr):
if root is None:
retur... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Findelements:
def __init__(self, root: TreeNode):
self.table = set()
def dfs(root, curr):
if root is None:
return
root.val = curr
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.