content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def calculation(filepath,down,across):
with open(filepath) as file:
rows = [x.strip() for x in file.readlines()]
end = len(rows)
currentrow = 0
currentcolumn = 0
count = 0
while currentrow < (end-1):
currentrow = currentrow+down
currentcolumn = (currentcolumn+acr... | def calculation(filepath, down, across):
with open(filepath) as file:
rows = [x.strip() for x in file.readlines()]
end = len(rows)
currentrow = 0
currentcolumn = 0
count = 0
while currentrow < end - 1:
currentrow = currentrow + down
currentcolumn = (currentcolumn + across... |
class Student:
def __init__(self, firstname, lastname, major, gpa):
self.firstname = firstname
self.lastname = lastname
self.major = major
self.gpa = gpa
@property # property decorator # access this method as an attribute
def fullname(self):
return f'{self.firstname} {self.lastname}'
@fullname.setter # ... | class Student:
def __init__(self, firstname, lastname, major, gpa):
self.firstname = firstname
self.lastname = lastname
self.major = major
self.gpa = gpa
@property
def fullname(self):
return f'{self.firstname} {self.lastname}'
@fullname.setter
def fullname(... |
{
"targets": [
{
"target_name": "simpleTest",
"sources": [ "simpleTest.cc" ]
},
{
"target_name": "simpleTest2",
"sources": [ "simpleTest.cc" ]
},
{
"target_name": "simpleTest3",
"sources": [ "simpleTest.cc" ]
}
]
} | {'targets': [{'target_name': 'simpleTest', 'sources': ['simpleTest.cc']}, {'target_name': 'simpleTest2', 'sources': ['simpleTest.cc']}, {'target_name': 'simpleTest3', 'sources': ['simpleTest.cc']}]} |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 12700.py
# Description: UVa Online Judge - 12700
# =============================================================================
def run():... | def run():
n = int(input())
line = input()
count_b = sum(map(lambda x: x == 'B', line))
count_w = sum(map(lambda x: x == 'W', line))
count_t = sum(map(lambda x: x == 'T', line))
if countT == 0 and countW == 0 and (countB == 0):
print('ABANDONED')
elif countT == 0 and countW == 0 and ... |
DEBUG = True
PORT = 5000
UPLOAD_FOLDER = 'sacapp/static/tmp'
MODEL_FOLDER = 'model/'
DRUG2ID_FILE = 'model/drug2id.txt'
GENE2ID_FILE = 'model/gene2idx.txt'
IC50_DRUGS_FILE = 'model/ic50_drugid.txt'
IC50_DRUG2ID_FILE = 'model/ic50_drug2idx.txt'
IC50_GENES_FILE = 'model/ic50_genes.txt'
PERT_DRUGS_FILE = 'model/pert_drugi... | debug = True
port = 5000
upload_folder = 'sacapp/static/tmp'
model_folder = 'model/'
drug2_id_file = 'model/drug2id.txt'
gene2_id_file = 'model/gene2idx.txt'
ic50_drugs_file = 'model/ic50_drugid.txt'
ic50_drug2_id_file = 'model/ic50_drug2idx.txt'
ic50_genes_file = 'model/ic50_genes.txt'
pert_drugs_file = 'model/pert_dr... |
"""Advent of Code 2019 Day 1."""
def main(file_input='input.txt'):
masses = [int(num.strip()) for num in get_file_contents(file_input)]
needed_fuel = get_needed_fuel(masses, module_fuel)
print(f'Fuel requirement: {needed_fuel}')
needed_fuel_with_fuel_mass = get_needed_fuel(masses, module_fuel_with_fue... | """Advent of Code 2019 Day 1."""
def main(file_input='input.txt'):
masses = [int(num.strip()) for num in get_file_contents(file_input)]
needed_fuel = get_needed_fuel(masses, module_fuel)
print(f'Fuel requirement: {needed_fuel}')
needed_fuel_with_fuel_mass = get_needed_fuel(masses, module_fuel_with_fuel... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Point of Sale',
'version': '1.0.1',
'category': 'Sales/Point of Sale',
'sequence': 40,
'summary': 'User-friendly PoS interface for shops and restaurants',
'description': "",
'depend... | {'name': 'Point of Sale', 'version': '1.0.1', 'category': 'Sales/Point of Sale', 'sequence': 40, 'summary': 'User-friendly PoS interface for shops and restaurants', 'description': '', 'depends': ['stock_account', 'barcodes', 'web_editor', 'digest'], 'data': ['security/point_of_sale_security.xml', 'security/ir.model.acc... |
BASE_URL = 'https://www.instagram.com/'
LOGIN_URL = BASE_URL + 'accounts/login/ajax/'
LOGOUT_URL = BASE_URL + 'accounts/logout/'
MEDIA_URL = BASE_URL + '{0}/media'
STORIES_URL = 'https://i.instagram.com/api/v1/feed/user/{0}/reel_media/'
STORIES_UA = 'Instagram 9.5.2 (iPhone7,2; iPhone OS 9_3_3; en_US; en-US; scale=2.0... | base_url = 'https://www.instagram.com/'
login_url = BASE_URL + 'accounts/login/ajax/'
logout_url = BASE_URL + 'accounts/logout/'
media_url = BASE_URL + '{0}/media'
stories_url = 'https://i.instagram.com/api/v1/feed/user/{0}/reel_media/'
stories_ua = 'Instagram 9.5.2 (iPhone7,2; iPhone OS 9_3_3; en_US; en-US; scale=2.00... |
class Problem(Exception):
"""
User-visible exception
"""
def __init__(self, message, code=None, icon=':exclamation:'):
"""
:param message: The error message
:type message: str
:param code: An internal error code, for ease of testing
:type code: str|None
:... | class Problem(Exception):
"""
User-visible exception
"""
def __init__(self, message, code=None, icon=':exclamation:'):
"""
:param message: The error message
:type message: str
:param code: An internal error code, for ease of testing
:type code: str|None
:... |
"""
Binary search in list.
List must be sorted.
speed - O(log2N)
"""
def binary_search(a, key):
"""
a - sorted list
key - value for search
returs: index or None
"""
left = 0
right = len(a)
while left < right:
middle = (left + right) // 2
if key < a[middle]:
... | """
Binary search in list.
List must be sorted.
speed - O(log2N)
"""
def binary_search(a, key):
"""
a - sorted list
key - value for search
returs: index or None
"""
left = 0
right = len(a)
while left < right:
middle = (left + right) // 2
if key < a[middle]:
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Dexter Scott Belmont"
__credits__ = [ "Dexter Scott Belmont" ]
__tags__ = [ "Maya", "Virus", "Removal" ]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Dexter Scott Belmont"
__email__ = "dexter@kerneloid.com"
__status__ = "alpha"
#jobs = cmds.sc... | __author__ = 'Dexter Scott Belmont'
__credits__ = ['Dexter Scott Belmont']
__tags__ = ['Maya', 'Virus', 'Removal']
__license__ = 'MIT'
__version__ = '0.1'
__maintainer__ = 'Dexter Scott Belmont'
__email__ = 'dexter@kerneloid.com'
__status__ = 'alpha'
found = False
for job in cmds.scriptJob(lj=True):
if 'leukocyte.a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 17:21:13 2018
@author: gykovacs
"""
__version__= '0.3.0' | """
Created on Fri Dec 28 17:21:13 2018
@author: gykovacs
"""
__version__ = '0.3.0' |
__all__ = ['Mine']
class Mine(object):
'''A mine object.
Attributes:
x (int): the mine position in X.
y (int): the mine position in Y.
owner (int): the hero's id that owns this mine.
'''
def __init__(self, x, y):
'''Constructor.
Args:
x (in... | __all__ = ['Mine']
class Mine(object):
"""A mine object.
Attributes:
x (int): the mine position in X.
y (int): the mine position in Y.
owner (int): the hero's id that owns this mine.
"""
def __init__(self, x, y):
"""Constructor.
Args:
x (int): ... |
INVALID_EMAIL = "invalid_email"
INVALID_EMAIL_CHANGE = "invalid_email_change"
MISSING_EMAIL = "missing_email"
MISSING_NATIONALITY = "missing_nationality"
DUPLICATE_EMAIL = "unique"
REQUIRED = "required"
INVALID_SUBSCRIBE_TO_EMPTY_EMAIL = "invalid_subscribe_to_empty_email"
| invalid_email = 'invalid_email'
invalid_email_change = 'invalid_email_change'
missing_email = 'missing_email'
missing_nationality = 'missing_nationality'
duplicate_email = 'unique'
required = 'required'
invalid_subscribe_to_empty_email = 'invalid_subscribe_to_empty_email' |
min_temp = None
max_temp = None
# factor = 2.25
factor = 0
HUE_MAX = 240 / 360
HUE_MIN = 0
HUE_GOOD = 120 / 360
HUE_WARNING = 50/360
HUE_DANGER = 0
#comfort ranges
TEMP_LOW = 16
TEMP_HIGH = 24
HUMIDITY_LOW = 30
HUMIDITY_HIGHT = 60 | min_temp = None
max_temp = None
factor = 0
hue_max = 240 / 360
hue_min = 0
hue_good = 120 / 360
hue_warning = 50 / 360
hue_danger = 0
temp_low = 16
temp_high = 24
humidity_low = 30
humidity_hight = 60 |
# C100--- python classes
class Student(object):
"""
blueprint for Student
"""
def __init__(self, nameInput, ageInput, genderInput, levelInput, gradesInput):
self.name = nameInput
self.age = ageInput
self.gender = genderInput
self.level = levelInput
self.grade... | class Student(object):
"""
blueprint for Student
"""
def __init__(self, nameInput, ageInput, genderInput, levelInput, gradesInput):
self.name = nameInput
self.age = ageInput
self.gender = genderInput
self.level = levelInput
self.grades = gradesInput or {}
... |
"""Constants for terminal formatting"""
colors = 'dark', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'gray'
FG_COLORS = dict(list(zip(colors, list(range(30, 38)))))
BG_COLORS = dict(list(zip(colors, list(range(40, 48)))))
STYLES = dict(list(zip(('bold', 'dark', 'underline', 'blink', 'invert'), [1,2,4,5,7])))
... | """Constants for terminal formatting"""
colors = ('dark', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'gray')
fg_colors = dict(list(zip(colors, list(range(30, 38)))))
bg_colors = dict(list(zip(colors, list(range(40, 48)))))
styles = dict(list(zip(('bold', 'dark', 'underline', 'blink', 'invert'), [1, 2, 4, 5, 7... |
MAX_PIXEL_VALUE = 255
LAPLAS_FACTOR = 0.5
LAPLAS_1 = [[0,1,0],[1,-4,1],[0,1,0]]
LAPLAS_2 = [[1,1,1],[1,-8,1],[1,1,1]]
LAPLAS_3 = [[0,-1,0],[-1,4,-1],[0,-1,0]]
LAPLAS_4 = [[-1,-1,-1],[-1,8,-1],[-1,-1,-1]]
LAPLAS_5 = [[0,-1,0],[-1,5,-1],[0,-1,0]]
LAPLAS_6 = [[-1,-1,-1],[-1,9,-1],[-1,-1,-1]]
LAPLAS_7 = [[0,-1,0],[-1,LAPL... | max_pixel_value = 255
laplas_factor = 0.5
laplas_1 = [[0, 1, 0], [1, -4, 1], [0, 1, 0]]
laplas_2 = [[1, 1, 1], [1, -8, 1], [1, 1, 1]]
laplas_3 = [[0, -1, 0], [-1, 4, -1], [0, -1, 0]]
laplas_4 = [[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]
laplas_5 = [[0, -1, 0], [-1, 5, -1], [0, -1, 0]]
laplas_6 = [[-1, -1, -1], [-1, 9, -... |
class ListExtension(object):
@staticmethod
def split_list_in_n_parts(my_list, number_chunks):
k, m = len(my_list) / number_chunks, len(my_list) % number_chunks
return list(my_list[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in xrange(number_chunks))
@staticmethod
def convert_l... | class Listextension(object):
@staticmethod
def split_list_in_n_parts(my_list, number_chunks):
(k, m) = (len(my_list) / number_chunks, len(my_list) % number_chunks)
return list((my_list[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in xrange(number_chunks)))
@staticmethod
def con... |
# Violet Cube Fragment
FRAGMENT = 2434125
REWARD1 = 5062009 # red cube
REWARD2 = 5062010 # black cube
q = sm.getQuantityOfItem(FRAGMENT)
if q >= 10:
if sm.canHold(REWARD2):
sm.giveItem(REWARD2)
sm.consumeItem(FRAGMENT, 10)
else:
sm.systemMessage("Make sure you have enough space in your inventory..")
elif q >... | fragment = 2434125
reward1 = 5062009
reward2 = 5062010
q = sm.getQuantityOfItem(FRAGMENT)
if q >= 10:
if sm.canHold(REWARD2):
sm.giveItem(REWARD2)
sm.consumeItem(FRAGMENT, 10)
else:
sm.systemMessage('Make sure you have enough space in your inventory..')
elif q >= 5:
if sm.canHold(REW... |
num = {}
for i in range(97,123):
num[chr(i)] = i-96
L = int(input())
data = list(input().rstrip())
res = 0
M = 1234567891
for idx,val in enumerate(data):
res += (31**idx)*num[val]
res %= M
print(res) | num = {}
for i in range(97, 123):
num[chr(i)] = i - 96
l = int(input())
data = list(input().rstrip())
res = 0
m = 1234567891
for (idx, val) in enumerate(data):
res += 31 ** idx * num[val]
res %= M
print(res) |
class f:
def __init__(self,s,i):
self.s=s;self.i=i
r=""
for _ in range(int(__import__('sys').stdin.readline())):
n=int(__import__('sys').stdin.readline())
a=__import__('sys').stdin.readline().split()
b=__import__('sys').stdin.readline().split()
o=[-1]*n
for i in range(n):
for j i... | class F:
def __init__(self, s, i):
self.s = s
self.i = i
r = ''
for _ in range(int(__import__('sys').stdin.readline())):
n = int(__import__('sys').stdin.readline())
a = __import__('sys').stdin.readline().split()
b = __import__('sys').stdin.readline().split()
o = [-1] * n
for i i... |
n = int(input())
even = 0
odd = 0
for i in range(1, n + 1):
number = int(input())
if i % 2 == 0:
even += number
else:
odd += number
if even == odd:
print(f"Yes\nSum = {even}")
else:
print(f"No\nDiff = {abs(even - odd)}")
| n = int(input())
even = 0
odd = 0
for i in range(1, n + 1):
number = int(input())
if i % 2 == 0:
even += number
else:
odd += number
if even == odd:
print(f'Yes\nSum = {even}')
else:
print(f'No\nDiff = {abs(even - odd)}') |
def diff():
print("Diff Diff")
def patch():
print("Patch")
| def diff():
print('Diff Diff')
def patch():
print('Patch') |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS = [
'userprofile',
]
USER_PROFILE_MODULE = 'userprofile.Profile'
| databases = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
installed_apps = ['userprofile']
user_profile_module = 'userprofile.Profile' |
class Solution:
def equalSubstring(self, s: str, t: str, mx: int) -> int:
i = 0
for j in range(len(s)):
mx -= abs(ord(s[j]) - ord(t[j]))
if mx < 0:
mx += abs(ord(s[i]) - ord(t[i]))
i += 1
return j - i + 1 | class Solution:
def equal_substring(self, s: str, t: str, mx: int) -> int:
i = 0
for j in range(len(s)):
mx -= abs(ord(s[j]) - ord(t[j]))
if mx < 0:
mx += abs(ord(s[i]) - ord(t[i]))
i += 1
return j - i + 1 |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CompressionPolicyVaultEnum(object):
"""Implementation of the 'CompressionPolicy_Vault' enum.
Specifies whether to send data to the Vault in a
compressed format.
'kCompressionNone' indicates that data is not compressed.
'kCompressionLow'... | class Compressionpolicyvaultenum(object):
"""Implementation of the 'CompressionPolicy_Vault' enum.
Specifies whether to send data to the Vault in a
compressed format.
'kCompressionNone' indicates that data is not compressed.
'kCompressionLow' indicates that data is compressed using LZ4 or Snappy.
... |
'''
Problem:
Given an array A of n integers, in sorted order, and an integer x,
design an O(n)-time complexity algorithm to determine whether there
are 2 integers in A whose sum is exactly x.
'''
def sum(target, x):
lookup = set()
# Build a lookup table.
for item in target:
lookup.add(x - item)
... | """
Problem:
Given an array A of n integers, in sorted order, and an integer x,
design an O(n)-time complexity algorithm to determine whether there
are 2 integers in A whose sum is exactly x.
"""
def sum(target, x):
lookup = set()
for item in target:
lookup.add(x - item)
for item in target:
... |
class Televisao():
def __init__(self, c):
self.ligada = False
self.canal = c
self.marca = 'SAMSUNG'
self.tamanho = '43'
def muda_canal_cima(self):
if self.canal < 50:
self.canal += 1
else:
self.canal = 1
def muda_canal_baixo(self):
... | class Televisao:
def __init__(self, c):
self.ligada = False
self.canal = c
self.marca = 'SAMSUNG'
self.tamanho = '43'
def muda_canal_cima(self):
if self.canal < 50:
self.canal += 1
else:
self.canal = 1
def muda_canal_baixo(self):
... |
def test_numbers():
assert 1234 == 1234
def test_hello_world():
assert "hello" + "world" == "helloworld"
def test_foobar():
assert True
| def test_numbers():
assert 1234 == 1234
def test_hello_world():
assert 'hello' + 'world' == 'helloworld'
def test_foobar():
assert True |
'''
SPDX-License-Identifier: Apache-2.0
Copyright 2021 Keylime Authors
'''
async def execute(revocation):
try:
value = revocation['hello']
print(value)
except Exception as e:
raise Exception(
"The provided dictionary does not contain the 'hello' key")
| """
SPDX-License-Identifier: Apache-2.0
Copyright 2021 Keylime Authors
"""
async def execute(revocation):
try:
value = revocation['hello']
print(value)
except Exception as e:
raise exception("The provided dictionary does not contain the 'hello' key") |
# local scope
def my_func():
x = 300
print(x)
def my_inner_func():
print(x)
my_inner_func()
my_func()
| def my_func():
x = 300
print(x)
def my_inner_func():
print(x)
my_inner_func()
my_func() |
# OpenWeatherMap API Key
weather_api_key = "8915eee544f1c9b3ef5fa102f5edeb66"
# Google API Key
g_key = "AIzaSyDgD7ZgpyA4MuuVfr3Ep8G2-uCEx37joSE"
| weather_api_key = '8915eee544f1c9b3ef5fa102f5edeb66'
g_key = 'AIzaSyDgD7ZgpyA4MuuVfr3Ep8G2-uCEx37joSE' |
"""
Entradas
valor_mercancia-->float-->valor_mercancia
Salidas
cantidad_extraida_de_fondos-->float-->cantidad_fondos
cantidad_credito-->float-->cantidad_credito
banco_prestamo-->float-->banco_prestamo
"""
valor_mercancia=float(input("Digite el costo de los insumos "))
if(valor_mercancia>=5000001):
cantidad_fondos=val... | """
Entradas
valor_mercancia-->float-->valor_mercancia
Salidas
cantidad_extraida_de_fondos-->float-->cantidad_fondos
cantidad_credito-->float-->cantidad_credito
banco_prestamo-->float-->banco_prestamo
"""
valor_mercancia = float(input('Digite el costo de los insumos '))
if valor_mercancia >= 5000001:
cantidad_fondo... |
def to_polar(x, y):
'Rectangular to polar conversion using ints scaled by 100000. Angle in degrees.'
theta = 0
for i, adj in enumerate((4500000, 2656505, 1403624, 712502, 357633, 178991, 89517, 44761)):
sign = 1 if y < 0 else -1
x, y, theta = x - sign*(y >> i) , y + sign*(x >> i), theta - si... | def to_polar(x, y):
"""Rectangular to polar conversion using ints scaled by 100000. Angle in degrees."""
theta = 0
for (i, adj) in enumerate((4500000, 2656505, 1403624, 712502, 357633, 178991, 89517, 44761)):
sign = 1 if y < 0 else -1
(x, y, theta) = (x - sign * (y >> i), y + sign * (x >> i)... |
# -*- coding: utf-8 -*-
description = 'common detector devices provided by QMesyDAQ'
group = 'lowlevel'
devices = dict(
timer = device('nicos.devices.generic.VirtualTimer',
description = 'QMesyDAQ timer',
lowlevel = True,
unit = 's',
fmtstr = '%.1f',
),
mon1 = device('nic... | description = 'common detector devices provided by QMesyDAQ'
group = 'lowlevel'
devices = dict(timer=device('nicos.devices.generic.VirtualTimer', description='QMesyDAQ timer', lowlevel=True, unit='s', fmtstr='%.1f'), mon1=device('nicos.devices.generic.VirtualCounter', description='QMesyDAQ monitor 1', type='monitor', l... |
def arrayMap(f):
def app(arr):
return tuple(f(e) for e in arr)
return app
| def array_map(f):
def app(arr):
return tuple((f(e) for e in arr))
return app |
"""
LeetCode 163. Missing Ranges
# https://www.goodtecher.com/leetcode-163-missing-ranges/
Description
https://leetcode.com/problems/missing-ranges/
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.
A number x is considered missin... | """
LeetCode 163. Missing Ranges
# https://www.goodtecher.com/leetcode-163-missing-ranges/
Description
https://leetcode.com/problems/missing-ranges/
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.
A number x is considered missin... |
n = int(input())
arr = [int(e) for e in input().split()]
for inicio in range(1, n):
i = inicio
while i >= 1 and arr[i] < arr[i-1]:
arr[i], arr[i-1] = arr[i-1], arr[i]
i -= 1
for i in range(8):
print(arr[i], end=" ")
print()
| n = int(input())
arr = [int(e) for e in input().split()]
for inicio in range(1, n):
i = inicio
while i >= 1 and arr[i] < arr[i - 1]:
(arr[i], arr[i - 1]) = (arr[i - 1], arr[i])
i -= 1
for i in range(8):
print(arr[i], end=' ')
print() |
def area_for_polygon(polygon):
result = 0
imax = len(polygon) - 1
for i in range(0, imax):
result += (polygon[i][1] * polygon[i + 1][0]) - (polygon[i + 1][1] * polygon[i][0])
result += (polygon[imax][1] * polygon[0][0]) - (polygon[0][1] * polygon[imax][0])
return result / 2.
def centroid_f... | def area_for_polygon(polygon):
result = 0
imax = len(polygon) - 1
for i in range(0, imax):
result += polygon[i][1] * polygon[i + 1][0] - polygon[i + 1][1] * polygon[i][0]
result += polygon[imax][1] * polygon[0][0] - polygon[0][1] * polygon[imax][0]
return result / 2.0
def centroid_for_polyg... |
def square(): # function header
new_value=4 ** 2 # function body
print(new_value)
square()
| def square():
new_value = 4 ** 2
print(new_value)
square() |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 2 00:25:26 2017
@author: Roberto Piga
"""
# Paste your code into this box
# define variables like in the example, below
balance = 3329; annualInterestRate = 0.2
minimumFixed = 0
f = True
initialBalance = balance
while balance > 0:
balance = initialBa... | """
Created on Thu Feb 2 00:25:26 2017
@author: Roberto Piga
"""
balance = 3329
annual_interest_rate = 0.2
minimum_fixed = 0
f = True
initial_balance = balance
while balance > 0:
balance = initialBalance
minimum_fixed += 10
for month in range(1, 13):
unpaid_balance = balance - minimumFixed
... |
class MockDbQuery(object):
def __init__(self, responses):
self.responses = responses
def get(self, method, **kws):
resp = None
if method in self.responses:
resp = self.responses[method].pop(0)
if 'validate' in resp:
checks = resp['validate']['che... | class Mockdbquery(object):
def __init__(self, responses):
self.responses = responses
def get(self, method, **kws):
resp = None
if method in self.responses:
resp = self.responses[method].pop(0)
if 'validate' in resp:
checks = resp['validate']['che... |
_tol = 1e-5
def sim(a,b):
if (a==b):
return True
elif a == 0 or b == 0:
return False
if (a<b):
return (1-a/b)<=_tol
else:
return (1-b/a)<=_tol
def nsim(a,b):
if (a==b):
return False
elif a == 0 or b == 0:
return True
if (a<b):
return (1-a/b)>_tol
else:
return (1-b/a)>_tol
def gsim(a,b):
if ... | _tol = 1e-05
def sim(a, b):
if a == b:
return True
elif a == 0 or b == 0:
return False
if a < b:
return 1 - a / b <= _tol
else:
return 1 - b / a <= _tol
def nsim(a, b):
if a == b:
return False
elif a == 0 or b == 0:
return True
if a < b:
... |
class ContextMixin(object):
"""Defines a ``GET`` method that invokes :meth:`get_rendering_context()`
and returns its result to the client.
"""
def get_rendering_context(self, *args, **kwargs):
raise NotImplementedError("Subclasses must override this method.")
| class Contextmixin(object):
"""Defines a ``GET`` method that invokes :meth:`get_rendering_context()`
and returns its result to the client.
"""
def get_rendering_context(self, *args, **kwargs):
raise not_implemented_error('Subclasses must override this method.') |
class BaseModel:
def __init__(self):
pass
def predict(self, data):
"""
Get prediction on the data.
Parameters
----------
data : optional
Data on which prediction should be done.
Returns
-------
None
"""
pass
... | class Basemodel:
def __init__(self):
pass
def predict(self, data):
"""
Get prediction on the data.
Parameters
----------
data : optional
Data on which prediction should be done.
Returns
-------
None
"""
pass... |
'''
Globals that are used throughout CheckAPI
'''
# Whether to output debugging statements
debug = False
# The model's current working directory
workingdir = "/"
| """
Globals that are used throughout CheckAPI
"""
debug = False
workingdir = '/' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four mill... | """
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
"""... |
class SuperPalmTree:
def __init__(self, a: int, b: int, c: float):
self.a = a
self.b = b
self.c = c
def __call__(self, x):
return (self.a + self.b) * x / self.c
def unpack(self):
yield self.a
yield self.b
yield self.c
def param_tuple(self):
... | class Superpalmtree:
def __init__(self, a: int, b: int, c: float):
self.a = a
self.b = b
self.c = c
def __call__(self, x):
return (self.a + self.b) * x / self.c
def unpack(self):
yield self.a
yield self.b
yield self.c
def param_tuple(self):
... |
# functions
def yes_or_no(): # Returns 'yes' or 'no' based on first letter of user input.
while True:
item = input()
if not item or item[0] not in ['y', 'n']:
print('(y)es or (n)o are valid answers')
continue
elif item[0].lower() == 'y':
return 'yes'
... | def yes_or_no():
while True:
item = input()
if not item or item[0] not in ['y', 'n']:
print('(y)es or (n)o are valid answers')
continue
elif item[0].lower() == 'y':
return 'yes'
elif item[0].lower() == 'n':
return 'no' |
'''
Author : MiKueen
Level : Medium
Problem Statement : Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"... | """
Author : MiKueen
Level : Medium
Problem Statement : Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"... |
# flake8: noqa
RESPONSE_NO_DEPS = """
{
"category": "storage",
"changelog": "created",
"created_at": "2019-05-31T20:06:53.963000Z",
"description": "Extra slots in inventory.",
"downloads_count": 4110,
"homepage": "",
"license": {
"description": "A permissive license that is short a... | response_no_deps = '\n{\n\n "category": "storage",\n "changelog": "created",\n "created_at": "2019-05-31T20:06:53.963000Z",\n "description": "Extra slots in inventory.",\n "downloads_count": 4110,\n "homepage": "",\n "license": {\n "description": "A permissive license that is short and to th... |
class BinaryTreeNode:
"""
This class represents a node which can be used to create a Binary Tree.
:Authors: pranaychandekar
"""
def __init__(self, data, left=None, right=None, parent=None):
"""
This method initializes a node for Binary Tree.
:param data: The data to be sto... | class Binarytreenode:
"""
This class represents a node which can be used to create a Binary Tree.
:Authors: pranaychandekar
"""
def __init__(self, data, left=None, right=None, parent=None):
"""
This method initializes a node for Binary Tree.
:param data: The data to be sto... |
# selection sorting is an in-place comparison sort
# O(N^2) time, inefficient for large datasets
# best when memory is limited
def selection_sort(lst):
''' Implementation of selection sort. Efficient with space but not time. Finds the smallest unsorted index (index 0 in the first run) and compares it to all other... | def selection_sort(lst):
""" Implementation of selection sort. Efficient with space but not time. Finds the smallest unsorted index (index 0 in the first run) and compares it to all other items in the list. if an item has a smaller numeric value than the smallest unsorted index, it swaps with the smallest of all th... |
def list_to_string(lst):
string = ''
for item in lst:
string = string + item
return string
def find_rc(rc):
rc = rc[:: -1]
replacements = {"A": "T",
"T": "A",
"G": "C",
"C": "G"}
rc = "".join([replacements.get(c, c) for c in r... | def list_to_string(lst):
string = ''
for item in lst:
string = string + item
return string
def find_rc(rc):
rc = rc[::-1]
replacements = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
rc = ''.join([replacements.get(c, c) for c in rc])
return rc
def find_palindromes(x):
sequence = lis... |
"""
==============
Output Metrics
==============
Currently, ``vivarium`` uses the :ref:`values pipeline system <values_concept>`
to produce the results, or output metrics, from a simulation. The metrics
The component here is a normal ``vivarium`` component whose only purpose is
to provide an empty :class:`dict` as th... | """
==============
Output Metrics
==============
Currently, ``vivarium`` uses the :ref:`values pipeline system <values_concept>`
to produce the results, or output metrics, from a simulation. The metrics
The component here is a normal ``vivarium`` component whose only purpose is
to provide an empty :class:`dict` as th... |
t = int(input())
for _ in range(t):
s = input()
c = 0
for i in range(len(s)-1):
if abs(ord(s[i]) - ord(s[i+1])) != 1:
c += 1
print (c)
| t = int(input())
for _ in range(t):
s = input()
c = 0
for i in range(len(s) - 1):
if abs(ord(s[i]) - ord(s[i + 1])) != 1:
c += 1
print(c) |
# -*- coding: utf-8 -*-
""" Collection of validator methods """
def validate_required(value):
"""
Method to raise error if a required parameter is not passed in.
:param value: value to check to make sure it is not None
:returns: True or ValueError
"""
if value is None:
raise ValueErr... | """ Collection of validator methods """
def validate_required(value):
"""
Method to raise error if a required parameter is not passed in.
:param value: value to check to make sure it is not None
:returns: True or ValueError
"""
if value is None:
raise value_error('Missing value for arg... |
class CheckResult:
msg: str = ""
def __init__(self, msg) -> None:
self.msg = msg
class Ok(CheckResult):
pass
class Warn(CheckResult):
pass
class Err(CheckResult):
pass
class Unk(CheckResult):
pass
class Probe:
def __init__(self, **kwargs):
for k, v in kwargs.items(... | class Checkresult:
msg: str = ''
def __init__(self, msg) -> None:
self.msg = msg
class Ok(CheckResult):
pass
class Warn(CheckResult):
pass
class Err(CheckResult):
pass
class Unk(CheckResult):
pass
class Probe:
def __init__(self, **kwargs):
for (k, v) in kwargs.items():... |
load(":testing.bzl", "asserts", "test_suite")
load("//maven:sets.bzl", "sets")
def new_test(env):
set = sets.new()
asserts.equals(env, 0, len(set))
set = sets.new("a", "b", "c")
asserts.equals(env, 3, len(set))
asserts.equals(env, ["a", "b", "c"], list(set))
def equality_test(env):
a = sets.ne... | load(':testing.bzl', 'asserts', 'test_suite')
load('//maven:sets.bzl', 'sets')
def new_test(env):
set = sets.new()
asserts.equals(env, 0, len(set))
set = sets.new('a', 'b', 'c')
asserts.equals(env, 3, len(set))
asserts.equals(env, ['a', 'b', 'c'], list(set))
def equality_test(env):
a = sets.ne... |
#Write a function that accepts a filename as input argument and reads the file and saves each line of the file as an element
#in a list (without the new line ("\n")character) and returns the list. Each line of the file has comma separated values
# Type your code here
def list_from_file(file_name):
# Make a connec... | def list_from_file(file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
final_list = []
for x in data:
final_list.append(x.strip('\n'))
return final_list
file_pointer.close()
print(list_from_file('file_name.txt')) |
# Instruction opcodes
_CHAR = 0
_NEWLINE = 1
_FONT = 2
_COLOR = 3
_SHAKE = 4
_WAIT = 5
_CUSTOM = 6
class Graph:
def __init__(self, default_font):
self.instructions = []
self.default_font = default_font
def string(self, s):
'''Adds a string of characters to the passage.'''... | _char = 0
_newline = 1
_font = 2
_color = 3
_shake = 4
_wait = 5
_custom = 6
class Graph:
def __init__(self, default_font):
self.instructions = []
self.default_font = default_font
def string(self, s):
"""Adds a string of characters to the passage."""
for c in s:
se... |
class DummyField(object):
def __init__(self, value, **kwargs):
self.value = value
for k_, v_ in kwargs.items():
setattr(self, k_, v_)
| class Dummyfield(object):
def __init__(self, value, **kwargs):
self.value = value
for (k_, v_) in kwargs.items():
setattr(self, k_, v_) |
class TempProps:
def __init__(self, start_temperature, grad_temperature, temperature_coefficient):
self.start_temp = start_temperature
self.grad_temp = grad_temperature
self.temp_coeff = temperature_coefficient
def __str__(self):
out_str = ""
out_str += "start temp: " +... | class Tempprops:
def __init__(self, start_temperature, grad_temperature, temperature_coefficient):
self.start_temp = start_temperature
self.grad_temp = grad_temperature
self.temp_coeff = temperature_coefficient
def __str__(self):
out_str = ''
out_str += 'start temp: ' +... |
def loss_gen(disc, x_fake):
"""Compute the generator loss for `x_fake` given `disc`
Args:
disc: The generator
x_fake (ndarray): An array of shape (N,) that contains the fake samples
Returns:
ndarray: The generator loss
"""
# Loss for fake data
label_fake = 1
loss_fake = label_fake * torch.l... | def loss_gen(disc, x_fake):
"""Compute the generator loss for `x_fake` given `disc`
Args:
disc: The generator
x_fake (ndarray): An array of shape (N,) that contains the fake samples
Returns:
ndarray: The generator loss
"""
label_fake = 1
loss_fake = label_fake * torch.log(disc.classify(x... |
"""
2104. Sum of Subarray Ranges
Medium
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.
Return the sum of all subarray ranges of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Examp... | """
2104. Sum of Subarray Ranges
Medium
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.
Return the sum of all subarray ranges of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Examp... |
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/armor"
# docs_base_url = "https://[org_name].github.io/armor"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "Armor"
| """
Configuration for docs
"""
def get_context(context):
context.brand_html = 'Armor' |
class SmallArray():
def __init__(self) -> None:
self.clusters = 0
self.cluster_size = 0 | class Smallarray:
def __init__(self) -> None:
self.clusters = 0
self.cluster_size = 0 |
class ValidationError(Exception):
pass
class empty(Exception):
pass
| class Validationerror(Exception):
pass
class Empty(Exception):
pass |
# 1 and 9
TERMINAL_INDICES = [0, 8, 9, 17, 18, 26]
# dragons and winds
EAST = 27
SOUTH = 28
WEST = 29
NORTH = 30
HAKU = 31
HATSU = 32
CHUN = 33
WINDS = [EAST, SOUTH, WEST, NORTH]
HONOR_INDICES = WINDS + [HAKU, HATSU, CHUN]
FIVE_RED_MAN = 16
FIVE_RED_PIN = 52
FIVE_RED_SOU = 88
AKA_DORA_LIST = [FIVE_RED_MAN, FIVE_RED... | terminal_indices = [0, 8, 9, 17, 18, 26]
east = 27
south = 28
west = 29
north = 30
haku = 31
hatsu = 32
chun = 33
winds = [EAST, SOUTH, WEST, NORTH]
honor_indices = WINDS + [HAKU, HATSU, CHUN]
five_red_man = 16
five_red_pin = 52
five_red_sou = 88
aka_dora_list = [FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU]
display_winds ... |
# #class
class user:
def __init__(self,first_name,last_name,birth,sex): # this is the main class's (attribute)function , self is the main v
self.first_name=first_name
self.last_name=last_name
self.birth=birth
self.sex=sex
def grit(self):
print (f"name: {self.first_name}... | class User:
def __init__(self, first_name, last_name, birth, sex):
self.first_name = first_name
self.last_name = last_name
self.birth = birth
self.sex = sex
def grit(self):
print(f'name: {self.first_name},{self.last_name}, year: {self.birth}')
def calc_age(self, c... |
class BaseCSSIException(Exception):
"""The base of all CSSI library exceptions."""
pass
class CSSIException(BaseCSSIException):
"""An exception specific to CSSI library"""
pass
| class Basecssiexception(Exception):
"""The base of all CSSI library exceptions."""
pass
class Cssiexception(BaseCSSIException):
"""An exception specific to CSSI library"""
pass |
#$Id$
class ExchangeRate:
"""This class is used to create object for Exchange rate."""
def __init__(self):
"""Initialize parameters for exchange rate."""
self.exchange_rate_id = ''
self.currency_id = ''
self.currency_code = ''
self.effective_date = ''
self.rate =... | class Exchangerate:
"""This class is used to create object for Exchange rate."""
def __init__(self):
"""Initialize parameters for exchange rate."""
self.exchange_rate_id = ''
self.currency_id = ''
self.currency_code = ''
self.effective_date = ''
self.rate = 0.0
... |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
STATIC_DEBUG = DEBUG
CRISPY_FAIL_SILENTLY = not DEBUG
ADMINS = (
('Dummy', 'dummy@example.org'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'NAME': 'sdemo.db',
'ENGINE': 'django.db.backends.sqlite3',
'USER': '',
'PASSWORD': ''
}
}
#... | debug = True
template_debug = DEBUG
static_debug = DEBUG
crispy_fail_silently = not DEBUG
admins = (('Dummy', 'dummy@example.org'),)
managers = ADMINS
databases = {'default': {'NAME': 'sdemo.db', 'ENGINE': 'django.db.backends.sqlite3', 'USER': '', 'PASSWORD': ''}}
media_root = ''
media_url = ''
static_root = ''
static_... |
"""
Reference values for the nwchem test calculations within ExPrESS
All nwchem output values are in hartrees. ExPrESS converts units to eV.
All reference energies are in eV.
"""
TOTAL_ENERGY = -2079.18666382721904
TOTAL_ENERGY_CONTRIBUTION = {
"one_electron": {
"name": "one_electron",
"value": -33... | """
Reference values for the nwchem test calculations within ExPrESS
All nwchem output values are in hartrees. ExPrESS converts units to eV.
All reference energies are in eV.
"""
total_energy = -2079.186663827219
total_energy_contribution = {'one_electron': {'name': 'one_electron', 'value': -3350.5317140676307}, 'coulo... |
# -*- coding: utf-8 -*-
"""
Python implementation of Karatsuba's multiplication algorithm
"""
def karatsuba_mutiplication(x, y):
xstr = str(x)
ystr = str(y)
length = max(len(xstr), len(ystr))
if length > 1:
xstr = "0" * (length - len(xstr)) + xstr
ystr = "0" * (length - len(ystr)) +... | """
Python implementation of Karatsuba's multiplication algorithm
"""
def karatsuba_mutiplication(x, y):
xstr = str(x)
ystr = str(y)
length = max(len(xstr), len(ystr))
if length > 1:
xstr = '0' * (length - len(xstr)) + xstr
ystr = '0' * (length - len(ystr)) + ystr
xh = int(xstr[... |
def path(current, visited_small_caves, cmap):
if current == 'end':
return [[current]]
next_caves = cmap[current]
paths = []
for next_cave in next_caves:
if next_cave in visited_small_caves:
continue
if next_cave.islower():
next_visited_small_caves = visite... | def path(current, visited_small_caves, cmap):
if current == 'end':
return [[current]]
next_caves = cmap[current]
paths = []
for next_cave in next_caves:
if next_cave in visited_small_caves:
continue
if next_cave.islower():
next_visited_small_caves = visite... |
# -*- coding: utf-8 -*-
"""
Package Description.
"""
__version__ = "0.0.1"
__short_description__ = "Numpy/Pandas based module make faster data analysis"
__license__ = "MIT"
__author__ = "fuwiak"
__author_email__ = "poczta130@gmail.com"
__maintainer__ = "unknown maintainer"
__maintainer_email__ = "maintainer@example.c... | """
Package Description.
"""
__version__ = '0.0.1'
__short_description__ = 'Numpy/Pandas based module make faster data analysis'
__license__ = 'MIT'
__author__ = 'fuwiak'
__author_email__ = 'poczta130@gmail.com'
__maintainer__ = 'unknown maintainer'
__maintainer_email__ = 'maintainer@example.com'
__github_username__ = ... |
def func1(a):
a += 1
def funct2(b):
val = 1+b
return val
return funct2(a)
print(func1(5)) | def func1(a):
a += 1
def funct2(b):
val = 1 + b
return val
return funct2(a)
print(func1(5)) |
# You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
# The letters in J are guaranteed distinct, and all characters in J and S are letters. ... | class Solution:
def num_jewels_in_stones(self, J, S):
count = 0
if J.isalpha() and S.isalpha() and (len(J) <= 50) and (len(S) <= 50):
for stones in S:
if stones in J:
count += 1
return count
if __name__ == '__main__':
j = 'aA'
s = ... |
#identify cycles in a linked list
def has_cycle(head):
taboo_list = list()
temp = head
while temp:
if temp not in taboo_list:
taboo_list.append(temp)
temp = temp.next
else:
return 1
return 0
| def has_cycle(head):
taboo_list = list()
temp = head
while temp:
if temp not in taboo_list:
taboo_list.append(temp)
temp = temp.next
else:
return 1
return 0 |
# CAN controls for MQB platform Volkswagen, Audi, Skoda and SEAT.
# PQ35/PQ46/NMS, and any future MLB, to come later.
def create_mqb_steering_control(packer, bus, apply_steer, idx, lkas_enabled):
values = {
"SET_ME_0X3": 0x3,
"Assist_Torque": abs(apply_steer),
"Assist_Requested": lkas_enabled,
"Assis... | def create_mqb_steering_control(packer, bus, apply_steer, idx, lkas_enabled):
values = {'SET_ME_0X3': 3, 'Assist_Torque': abs(apply_steer), 'Assist_Requested': lkas_enabled, 'Assist_VZ': 1 if apply_steer < 0 else 0, 'HCA_Available': 1, 'HCA_Standby': not lkas_enabled, 'HCA_Active': lkas_enabled, 'SET_ME_0XFE': 254,... |
#
# gambit
#
# Configuration file for gravity inversion for use by planeGravInv.py
# mesh has been made with mkGeoWithData2D.py
#
# Inversion constants:
#
# scale between misfit and regularization
mu = 1.e-14
#
# used to scale computed density. kg/m^3
rho_0 = 1.
#
# IPCG tolerance *|r| <= atol+rtol*|r0|*... | mu = 1e-14
rho_0 = 1.0
atol = 0.0
rtol = 0.001
pdetol = 1e-10
iter_max = 500
data_scale = 1e-06
mesh_name = 'G_201x338test.fly'
data_file = 'Gravity_201x338.nc'
output_name = 'G_test_201x338_rho0_{0:1.3e}_mu_{1:1.3e}'.format(rho_0, mu)
verbose_level = 'low' |
def countWaysToChangeDigit(value):
result = 0
for i in str(value):
result += 9 - int(i)
return result
| def count_ways_to_change_digit(value):
result = 0
for i in str(value):
result += 9 - int(i)
return result |
def product(x):
t = 1
for n in x:
t *= n
return t
| def product(x):
t = 1
for n in x:
t *= n
return t |
"""
Medium puzzle
Algorithm to find scores while climbing the leaderboard
Given 2 sorted lists:
- Scoreboard: [100, 100, 80, 60]
- Alice: [50, 60, 75, 105]
Find the scores of alice
Ans: [3, 2, 2, 1]
"""
def countRankings(arr):
# Gets initial rankings
count = 1
if len(arr) == 1:
return count
... | """
Medium puzzle
Algorithm to find scores while climbing the leaderboard
Given 2 sorted lists:
- Scoreboard: [100, 100, 80, 60]
- Alice: [50, 60, 75, 105]
Find the scores of alice
Ans: [3, 2, 2, 1]
"""
def count_rankings(arr):
count = 1
if len(arr) == 1:
return count
for i in range(1, len(arr), ... |
# Note: The schema is stored in a .py file in order to take advantage of the
# int() and float() type coercion functions. Otherwise it could easily stored as
# as JSON or another serialized format.
'''This schema has been changed compared to the Udacity schema,
due to missing values for attributes 'user' and 'uid'.
... | """This schema has been changed compared to the Udacity schema,
due to missing values for attributes 'user' and 'uid'.
It makes sense to keep them in the schema for use of other OSM data."""
schema = {'node': {'type': 'dict', 'schema': {'id': {'required': True, 'type': 'integer', 'coerce': int}, 'lat': {'required': T... |
class Port:
def __init__(self, mac_address, ip_address, mtu):
self.mac_address = mac_address
self.ip_address = ip_address
self.mtu = mtu
def __str__(self):
return '(%s - %s - %d)' % (self.mac_address, self.ip_address, self.mtu)
| class Port:
def __init__(self, mac_address, ip_address, mtu):
self.mac_address = mac_address
self.ip_address = ip_address
self.mtu = mtu
def __str__(self):
return '(%s - %s - %d)' % (self.mac_address, self.ip_address, self.mtu) |
class Context:
def __init__(self, **kwargs):
self.message = kwargs.get("message")
self.command = kwargs.get("command")
def print(self, content, *, indent=0, **kwargs):
if indent > 0:
lines = content.split("\n")
for line in lines:
prefix =... | class Context:
def __init__(self, **kwargs):
self.message = kwargs.get('message')
self.command = kwargs.get('command')
def print(self, content, *, indent=0, **kwargs):
if indent > 0:
lines = content.split('\n')
for line in lines:
prefix = '| ' * ... |
'''
Config! Change as needed.
NOTE: Please make sure that all information (except for authentication keys)
are passed in lower-case!
'''
# Your twitter access tokens. These are your accounts that you will enter giveaways from.
# Add as many users as you want, and please make sure to enter your username in lower case!... | """
Config! Change as needed.
NOTE: Please make sure that all information (except for authentication keys)
are passed in lower-case!
"""
access_tokens = {'user1': {'consumer_key': '', 'consumer_secret': '', 'access_token': '', 'access_token_secret': ''}, 'user2': {'consumer_key': '', 'consumer_secret': '', 'access_tok... |
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for token in tokens:
if token not in "+-*/":
stack.append(int(token))
else:
b = stack.pop()
... | class Solution(object):
def eval_rpn(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for token in tokens:
if token not in '+-*/':
stack.append(int(token))
else:
b = stack.pop()
... |
n, m = [int(x) for x in input().split()]
edges = [[int(x) for x in input().split()] for _ in range(m)]
if m < n - 1:
print(0)
exit()
paths = []
start = 1
still_possible = True
while still_possible:
passed = [1]
current = start
for i in range(1, n):
for e in edges:
... | (n, m) = [int(x) for x in input().split()]
edges = [[int(x) for x in input().split()] for _ in range(m)]
if m < n - 1:
print(0)
exit()
paths = []
start = 1
still_possible = True
while still_possible:
passed = [1]
current = start
for i in range(1, n):
for e in edges:
if e[0] == cu... |
def is_unique_points(points=None):
if points is None:
points = {}
points_dict = {}
for key, values in points.items():
new_key = '%s:%s' % tuple(values)
is_exists = points_dict.get(new_key, None)
if is_exists:
return False
else:
points_dict[new... | def is_unique_points(points=None):
if points is None:
points = {}
points_dict = {}
for (key, values) in points.items():
new_key = '%s:%s' % tuple(values)
is_exists = points_dict.get(new_key, None)
if is_exists:
return False
else:
points_dict[ne... |
"""
Conditionally Yours
Pseudocode:
"""
# Increase = Current Price - Original Price
# Percent Increase = Increase / Original x 100
# Create integer variable for original_price
# Create integer variable for current_price
# Create float for threshold_to_buy
# Create float for threshold_to_sell
# Create float... | """
Conditionally Yours
Pseudocode:
"""
recommendation = 'buy'
print(f"Netflix's original stock price was ${original_price}")
print('Recommendation: ' + recommendation)
print()
print('But wait a minute... lets check your excess equity first.')
balance_check = balance * 5
print(f'You currently have ${balance} in exce... |
def containsDuplicate(nums):
sorted = sorted(nums)
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False | def contains_duplicate(nums):
sorted = sorted(nums)
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
return True
return False |
def find_max(root):
if not root:
return 0
if not root.left and not root.right:
return root.val
m = [0]
helper(root, m)
return m[0]
def helper(n, m):
if n.val > m[0]:
m[0] = n.val
if n.left:
helper(n.left, m)
if n.right:
helper(n.right, m)
| def find_max(root):
if not root:
return 0
if not root.left and (not root.right):
return root.val
m = [0]
helper(root, m)
return m[0]
def helper(n, m):
if n.val > m[0]:
m[0] = n.val
if n.left:
helper(n.left, m)
if n.right:
helper(n.right, m) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# ... | class Solution:
def sorted_list_to_bst(self, head: ListNode) -> TreeNode:
def get_median(left: ListNode, right: ListNode) -> ListNode:
fast = slow = left
while fast != right and fast.next != right:
fast = fast.next.next
slow = slow.next
r... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 11:06:08 2017
@author: James Jiang
"""
def position(range_firewall, time):
offset = time % (2 * (range_firewall - 1))
if offset > range_firewall - 1:
return(2 * (range_firewall - 1) - offset)
else:
return(offset)
all_lines = [line.rstrip... | """
Created on Wed Dec 13 11:06:08 2017
@author: James Jiang
"""
def position(range_firewall, time):
offset = time % (2 * (range_firewall - 1))
if offset > range_firewall - 1:
return 2 * (range_firewall - 1) - offset
else:
return offset
all_lines = [line.rstrip('\n') for line in open('Data... |
#!/usr/bin/env python3
def chdir(path, folder):
return path+"/"+folder
def previous(path):
temp = ""
for i in path.split("/")[1:-1]:
temp += "/"+i
return temp
| def chdir(path, folder):
return path + '/' + folder
def previous(path):
temp = ''
for i in path.split('/')[1:-1]:
temp += '/' + i
return temp |
# Bradley Grose
data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is $%s"
print(format_string % data) | data = ('John', 'Doe', 53.44)
format_string = 'Hello %s %s. Your current balance is $%s'
print(format_string % data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.