content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
load("//bazel/macros:toolchains.bzl", "parse_toolchain_file")
def _archive_rule(provider):
additional = ""
if provider.archive_opts != None:
additional = "\n strip_prefix = \"%s\"," % (provider.archive_opts)
return """
http_archive(
name = "{name}",
url = "{url}",
... | load('//bazel/macros:toolchains.bzl', 'parse_toolchain_file')
def _archive_rule(provider):
additional = ''
if provider.archive_opts != None:
additional = '\n strip_prefix = "%s",' % provider.archive_opts
return '\n http_archive(\n name = "{name}",\n url = "{url}",\n s... |
print('Hello my dear') #comments are essential but I am always to lazy
print ('what is your name?')
myName = input()
print('it is nice to meet you,' + myName)
print('the length of you name is :')
print(len(myName))
print ('what is your age?')
myAge = input ()
print('you will be ' + str(int(myAge) +1) +' in a year')
| print('Hello my dear')
print('what is your name?')
my_name = input()
print('it is nice to meet you,' + myName)
print('the length of you name is :')
print(len(myName))
print('what is your age?')
my_age = input()
print('you will be ' + str(int(myAge) + 1) + ' in a year') |
#encoding:utf-8
subreddit = 'HermitCraft'
t_channel = '@r_HermitCraft'
def send_post(submission, r2t):
return r2t.send_simple(submission, min_upvotes_limit=100)
| subreddit = 'HermitCraft'
t_channel = '@r_HermitCraft'
def send_post(submission, r2t):
return r2t.send_simple(submission, min_upvotes_limit=100) |
# exc. 7.1.4
def squared_numbers(start, stop):
while start <= stop:
print(start**2)
start += 1
def main():
start = -3
stop = 3
squared_numbers(start, stop)
if __name__ == "__main__":
main() | def squared_numbers(start, stop):
while start <= stop:
print(start ** 2)
start += 1
def main():
start = -3
stop = 3
squared_numbers(start, stop)
if __name__ == '__main__':
main() |
lado = float(input())
altura = float(input())
numero = int(input())
area_1 = lado * altura
area_2 = 0
erro_max = 0
# Fazer o somatorio porposto pelo exercicio
for x in range(-50,51):
atual = numero + x
for j in range (0,atual):
area_2 += lado * (altura/(atual))
modulo_dif = abs(area_1 - area_2)
... | lado = float(input())
altura = float(input())
numero = int(input())
area_1 = lado * altura
area_2 = 0
erro_max = 0
for x in range(-50, 51):
atual = numero + x
for j in range(0, atual):
area_2 += lado * (altura / atual)
modulo_dif = abs(area_1 - area_2)
if erro_max < modulo_dif:
erro_max ... |
# Important class
class ImportantClass:
def __init__(self, var):
# Instance variable
self.var = var
# Important function
def importantFunction(self, old_var, new_var):
return old_var + new_var
# Make users happy
def makeUsersHappy(self, users):
... | class Importantclass:
def __init__(self, var):
self.var = var
def important_function(self, old_var, new_var):
return old_var + new_var
def make_users_happy(self, users):
print('Success!') |
def en_even(r):
return r[0] == "en" and len(r[1]) % 2 == 0
def en_odd(r):
return r[0] == "en" and len(r[1]) % 2 == 1
def predict(w):
def result(r):
return (r[0],r[1], np.dot(w.T, r[2])[0][0], r[3])
return result
train = rdd.filter(en_even)
test = rdd.filter(en_odd)
nxxt = train.map(x_xtransp... | def en_even(r):
return r[0] == 'en' and len(r[1]) % 2 == 0
def en_odd(r):
return r[0] == 'en' and len(r[1]) % 2 == 1
def predict(w):
def result(r):
return (r[0], r[1], np.dot(w.T, r[2])[0][0], r[3])
return result
train = rdd.filter(en_even)
test = rdd.filter(en_odd)
nxxt = train.map(x_xtransp... |
rsa_key_data = [
"9cf7192b51a574d1ad3ccb08ba09b87f228573893eee355529ff243e90fd4b86f79a82097cc7922c0485bed1616b1656a9b0b19ef78ea8ec34c384019adc5d5bf4db2d2a0a2d9cf14277bdcb7056f48b81214e3f7f7742231e29673966f9b1106862112cc798dba8d4a138bb5abfc6d4c12d53a5d39b2f783da916da20852ee139bbafda61d429caf2a4f30847ce7e7ae32ab4061e... | rsa_key_data = ['9cf7192b51a574d1ad3ccb08ba09b87f228573893eee355529ff243e90fd4b86f79a82097cc7922c0485bed1616b1656a9b0b19ef78ea8ec34c384019adc5d5bf4db2d2a0a2d9cf14277bdcb7056f48b81214e3f7f7742231e29673966f9b1106862112cc798dba8d4a138bb5abfc6d4c12d53a5d39b2f783da916da20852ee139bbafda61d429caf2a4f30847ce7e7ae32ab4061e27dd9... |
def main():
data = open("day3/input.txt", "r")
data = [line.strip() for line in data.readlines()]
tree_counter = 0
x = 0
for line in data:
if x >= len(line):
x = x % (len(line))
if line[x] == "#":
tree_counter += 1
x += 3
print(tree_counter)
if ... | def main():
data = open('day3/input.txt', 'r')
data = [line.strip() for line in data.readlines()]
tree_counter = 0
x = 0
for line in data:
if x >= len(line):
x = x % len(line)
if line[x] == '#':
tree_counter += 1
x += 3
print(tree_counter)
if __nam... |
iterations = 1
generations_list = [500]
populations_list = [30]
elitism_list = [0.2, 0.8]
mutables_list = [1] | iterations = 1
generations_list = [500]
populations_list = [30]
elitism_list = [0.2, 0.8]
mutables_list = [1] |
# -*- coding: utf-8 -*-
"""
converters package.
"""
| """
converters package.
""" |
{
'variables': { 'target_arch%': 'ia32', 'naclversion': '0.4.5' },
'targets': [
{
'target_name': 'sodium',
'sources': [
'sodium.cc',
],
"dependencies": [
"<(module_root_dir)/dep... | {'variables': {'target_arch%': 'ia32', 'naclversion': '0.4.5'}, 'targets': [{'target_name': 'sodium', 'sources': ['sodium.cc'], 'dependencies': ['<(module_root_dir)/deps/libsodium.gyp:libsodium'], 'include_dirs': ['./deps/libsodium-<(naclversion)/src/libsodium/include'], 'cflags!': ['-fno-exceptions']}]} |
l, r = int(input()), int(input()) / 100
count = 1
result = 0
while True:
l = int(l*r)
if l <= 5:
break
result += (2**count)*l
count += 1
print(result)
| (l, r) = (int(input()), int(input()) / 100)
count = 1
result = 0
while True:
l = int(l * r)
if l <= 5:
break
result += 2 ** count * l
count += 1
print(result) |
# Given a collection of numbers that might contain duplicates, return all possible unique permutations.
# For example,
# [1,1,2] have the following unique permutations:
# [1,1,2], [1,2,1], and [2,1,1].
class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def permuteUnique(self, nums):
... | class Solution:
def permute_unique(self, nums):
if not nums:
return nums
res = {(nums[0],)}
for i in range(1, len(nums)):
tmp = set()
while res:
base = res.pop()
for j in range(len(base) + 1):
tmp.add(tu... |
class Person:
'''
This class represents a person
'''
def __init__(self, id, firstname, lastname, dob):
self.id = id
self.firstname = firstname
self.lastname = lastname
self.dob = dob
def __str__(self):
return "University ID Number: " + self.id + "\nName: " +... | class Person:
"""
This class represents a person
"""
def __init__(self, id, firstname, lastname, dob):
self.id = id
self.firstname = firstname
self.lastname = lastname
self.dob = dob
def __str__(self):
return 'University ID Number: ' + self.id + '\nName: ' +... |
## CamelCase Method
## 6 kyu
## https://www.codewars.com//kata/587731fda577b3d1b0001196
def camel_case(string):
return ''.join([word.title() for word in string.split()]) | def camel_case(string):
return ''.join([word.title() for word in string.split()]) |
#
# PySNMP MIB module Juniper-E2-Registry (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-E2-Registry
# Produced by pysmi-0.3.4 at Mon Apr 29 19:51:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) ... |
#https://leetcode.com/problems/time-needed-to-inform-all-employees/
#Source: https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/532560/JavaC%2B%2BPython-DFS
class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
children = [[] f... | class Solution:
def num_of_minutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
children = [[] for i in range(n)]
for (i, m) in enumerate(manager):
if m >= 0:
children[m].append(i)
def dfs(value):
"""
We h... |
#validation of fields that are required
def validate_required(row, variable, metadata, formater,pre_checks=[]):
"""
:param row:
:param variable:
:param metadata:
:param formater:
:param pre_checks:
:return:
"""
errors=[]
for fun in pre_checks:
if fun(row,variable,metada... | def validate_required(row, variable, metadata, formater, pre_checks=[]):
"""
:param row:
:param variable:
:param metadata:
:param formater:
:param pre_checks:
:return:
"""
errors = []
for fun in pre_checks:
if fun(row, variable, metadata) == False:
return err... |
load("@bazel_skylib//lib:dicts.bzl", _dicts = "dicts")
load(
"//rules/scala_proto:private/core.bzl",
_scala_proto_library_implementation = "scala_proto_library_implementation",
_scala_proto_library_private_attributes = "scala_proto_library_private_attributes",
)
scala_proto_library = rule(
attrs = _dic... | load('@bazel_skylib//lib:dicts.bzl', _dicts='dicts')
load('//rules/scala_proto:private/core.bzl', _scala_proto_library_implementation='scala_proto_library_implementation', _scala_proto_library_private_attributes='scala_proto_library_private_attributes')
scala_proto_library = rule(attrs=_dicts.add(_scala_proto_library_p... |
# -*- coding: utf-8 -*-
class Scope(object):
"""
A base scope.
This indicates a permission access.
The `identifier` should be unique.
"""
identifier = None
def __init__(self, identifier):
self.identifier = identifier
def get_description(self):
return None
def __s... | class Scope(object):
"""
A base scope.
This indicates a permission access.
The `identifier` should be unique.
"""
identifier = None
def __init__(self, identifier):
self.identifier = identifier
def get_description(self):
return None
def __str__(self):
return... |
class Error(Exception):
"""Base class for other exceptions"""
pass
class InvalidSpecies(Error):
"""Species out of bounds of legitimate species"""
pass
class InvalidForm(Error):
"""Form is invalid"""
pass
class APIError(Error):
"""Something wrong with the API"""
pass | class Error(Exception):
"""Base class for other exceptions"""
pass
class Invalidspecies(Error):
"""Species out of bounds of legitimate species"""
pass
class Invalidform(Error):
"""Form is invalid"""
pass
class Apierror(Error):
"""Something wrong with the API"""
pass |
class Solution:
def XXX(self, height: List[int]) -> int:
left = 0
right = len(height)-1
temp = 0
while left<right:
temp = max(temp,min(height[left],height[right])*(right-left))
if height[left] < height[right]:
left+=1
else:
... | class Solution:
def xxx(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
temp = 0
while left < right:
temp = max(temp, min(height[left], height[right]) * (right - left))
if height[left] < height[right]:
left += 1
e... |
'''
core exception module
'''
class ConversionUnitNotImplemented(Exception):
'''
raises when tring can not convert a TemperatureUnit
'''
def __init__(self, unit_name: str):
super().__init__('Conversion unit %s not implemented' % unit_name)
| """
core exception module
"""
class Conversionunitnotimplemented(Exception):
"""
raises when tring can not convert a TemperatureUnit
"""
def __init__(self, unit_name: str):
super().__init__('Conversion unit %s not implemented' % unit_name) |
line, k = input(), int(input())
iterator = line.__iter__()
iterators = zip(*([iterator] * k))
for word in iterators:
d = dict()
result = ''.join([d.setdefault(letter, letter) for letter in word if letter not in d])
print(result)
| (line, k) = (input(), int(input()))
iterator = line.__iter__()
iterators = zip(*[iterator] * k)
for word in iterators:
d = dict()
result = ''.join([d.setdefault(letter, letter) for letter in word if letter not in d])
print(result) |
e_h,K = map(int,input().split())
h,m,s,e_m,e_s,ans = 0,0,0,59,59,0
while e_h != h or e_m != m or e_s != s:
z = "%02d%02d%02d" % (h,m,s)
if z.count(str(K)) >0:
# print(z)
ans+=1
s+=1
if s==60:
m+=1
s=0
if m==60:
h+=1
m=0
z = "%02d%02d%02d" % (h,m,s)
... | (e_h, k) = map(int, input().split())
(h, m, s, e_m, e_s, ans) = (0, 0, 0, 59, 59, 0)
while e_h != h or e_m != m or e_s != s:
z = '%02d%02d%02d' % (h, m, s)
if z.count(str(K)) > 0:
ans += 1
s += 1
if s == 60:
m += 1
s = 0
if m == 60:
h += 1
m = 0
z = '%02d%02d%... |
"""
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
data = [2,4,5,6]
for i in data:
assert i%2 == 0, "{} is not an even number".format(i)
"""
"""
Please write a program which accepts basic mathematic expression from console and print the evaluation result.
Example: If... | """
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
data = [2,4,5,6]
for i in data:
assert i%2 == 0, "{} is not an even number".format(i)
"""
'\n\nPlease write a program which accepts basic mathematic expression from console and print the evaluation result.\n\nExample: I... |
# # 9608/22/PRE/O/N/2020
# The code below declares the variables and arrays that are supposed to be pre-populated.
ItemCode = ["1001", "6056", "5557", "2568", "4458"]
ItemDescription = ["Pencil", "Pen", "Notebook", "Ruler", "Compass"]
Price = [1.0, 10.0, 100.0, 20.0, 30.0]
NumberInStock = [100, 100, 50, 20, 20]
n = ... | item_code = ['1001', '6056', '5557', '2568', '4458']
item_description = ['Pencil', 'Pen', 'Notebook', 'Ruler', 'Compass']
price = [1.0, 10.0, 100.0, 20.0, 30.0]
number_in_stock = [100, 100, 50, 20, 20]
n = len(ItemCode)
threshold_level = int(input('Enter the minumum stock level: '))
for counter in range(n):
if Numb... |
def discover_fields(layout):
"""Discover all fields defined in a layout object
This is used to avoid defining the field list in two places --
the layout object is instead inspected to determine the list
"""
fields = []
try:
comps = list(layout)
except TypeError:
return fiel... | def discover_fields(layout):
"""Discover all fields defined in a layout object
This is used to avoid defining the field list in two places --
the layout object is instead inspected to determine the list
"""
fields = []
try:
comps = list(layout)
except TypeError:
return field... |
# 4.04 Lists
# Purpose: learning how to use lists
#
# Author@ Shawn Velsor
# Date: 1/8/2021
electronics = ["computer", "cellphone", "laptop", "headphones"]
mutualItem = False
print("Hello, these are the items I like:")
count = 1
for i in electronics:
print(str(count) + ".", i)
count += 1
print()
def main()... | electronics = ['computer', 'cellphone', 'laptop', 'headphones']
mutual_item = False
print('Hello, these are the items I like:')
count = 1
for i in electronics:
print(str(count) + '.', i)
count += 1
print()
def main():
item = input('What type of electronic device do you like? ').lower()
for i in electro... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Peter Mounce <public@neverrunwithscissors.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version... | ansible_metadata = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'}
documentation = '\n---\nmodule: win_webpicmd\nversion_added: "2.0"\nshort_description: Installs packages using Web Platform Installer command-line\ndescription:\n - Installs packages using Web Platform Installer comman... |
# ==== PATHS ===================
PATH_TO_DATASET = "houseprice.csv"
OUTPUT_SCALER_PATH = 'scaler.pkl'
OUTPUT_MODEL_PATH = 'lasso_regression.pkl'
# ======= PARAMETERS ===============
# imputation parameters
LOTFRONTAGE_MODE = 60
# encoding parameters
FREQUENT_LABELS = {
'MSZoning': ['FV', 'RH', 'RL', 'RM'],... | path_to_dataset = 'houseprice.csv'
output_scaler_path = 'scaler.pkl'
output_model_path = 'lasso_regression.pkl'
lotfrontage_mode = 60
frequent_labels = {'MSZoning': ['FV', 'RH', 'RL', 'RM'], 'Neighborhood': ['Blmngtn', 'BrDale', 'BrkSide', 'ClearCr', 'CollgCr', 'Crawfor', 'Edwards', 'Gilbert', 'IDOTRR', 'MeadowV', 'Mit... |
__title__ = 'plinn'
__description__ = "Partition Like It's 1999"
__url__ = 'https://github.com/giannitedesco/plinn'
__author__ = 'Gianni Tedesco'
__author_email__ = 'gianni@scaramanga.co.uk'
__copyright__ = 'Copyright 2020 Gianni Tedesco'
__license__ = 'Apache 2.0'
__version__ = '0.0.2'
| __title__ = 'plinn'
__description__ = "Partition Like It's 1999"
__url__ = 'https://github.com/giannitedesco/plinn'
__author__ = 'Gianni Tedesco'
__author_email__ = 'gianni@scaramanga.co.uk'
__copyright__ = 'Copyright 2020 Gianni Tedesco'
__license__ = 'Apache 2.0'
__version__ = '0.0.2' |
# 2. Write Python code to find the cost of the minimum-energy seam in a list of lists.
energies = [[24, 22, 30, 15, 18, 19],
[12, 23, 15, 23, 10, 15],
[11, 13, 22, 13, 21, 14],
[13, 15, 17, 28, ... | energies = [[24, 22, 30, 15, 18, 19], [12, 23, 15, 23, 10, 15], [11, 13, 22, 13, 21, 14], [13, 15, 17, 28, 19, 21], [17, 17, 7, 27, 20, 19]]
energies2 = [[24, 22, 30, 15, 18, 19], [12, 23, 15, 23, 10, 15], [11, 13, 22, 13, 21, 14], [13, 15, 17, 28, 19, 21], [17, 17, 29, 27, 20, 19]]
def min_energy(energies):
cost ... |
mqtt_host = "IP_OR_DOMAIN"
mqtt_port = 1883
mqtt_topic = "screen/rpi"
mqtt_username = "USERNAME"
mqtt_password = "PASSWORD"
# Raspberry Pi
power_on_command = "vcgencmd display_power 1"
power_off_command = "vcgencmd display_power 0"
# Other HDMI linux devices
# power_on_command = "xset -display :0 dpms force on"
# power... | mqtt_host = 'IP_OR_DOMAIN'
mqtt_port = 1883
mqtt_topic = 'screen/rpi'
mqtt_username = 'USERNAME'
mqtt_password = 'PASSWORD'
power_on_command = 'vcgencmd display_power 1'
power_off_command = 'vcgencmd display_power 0' |
"""
Implements mainly the Vector class. See its documentation.
"""
class VectorError(Exception):
"""
An exception to use with Vector
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.value)
class Vector(tuple):
"""
A vector.
"""
def __... | """
Implements mainly the Vector class. See its documentation.
"""
class Vectorerror(Exception):
"""
An exception to use with Vector
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.value)
class Vector(tuple):
"""
A vector.
"""
def ... |
# Child Prime is such a prime number which can be obtained by summing up the square of the digit of its parent prime number.
# For example, 23 is a prime. If we calculate 2^2+3^2 = 4+9 = 13, which is also a prime no. then we call 13 as a child prime of 23.
ul = int(input("Enter Upper Limit: "))
gt = int(input("Genera... | ul = int(input('Enter Upper Limit: '))
gt = int(input('Generation Thresold :'))
def is_prime(m):
q = len(factors(m))
if q == 2:
return True
else:
return False
def sep(num):
res = list(map(int, str(num)))
return res
def factors(n):
flist = []
for i in range(1, n + 1):
... |
class MissingVariableError(Exception):
def __init__(self, name):
self.name = name
self.message = f'The required variable "{self.name}" is missing'
super().__init__(self.message)
class ReservedVariableError(Exception):
def __init__(self, name):
self.name = name
self.mess... | class Missingvariableerror(Exception):
def __init__(self, name):
self.name = name
self.message = f'The required variable "{self.name}" is missing'
super().__init__(self.message)
class Reservedvariableerror(Exception):
def __init__(self, name):
self.name = name
self.mes... |
def main():
# input
a, b, c = map(int, input().split())
# compute
cnt = 0
for i in range(a, b+1):
if c%i == 0:
cnt += 1
# output
print(cnt)
if __name__ == "__main__":
main()
| def main():
(a, b, c) = map(int, input().split())
cnt = 0
for i in range(a, b + 1):
if c % i == 0:
cnt += 1
print(cnt)
if __name__ == '__main__':
main() |
"""
Merge Sort
1. Divide the unsorted list into n sublists, each containing one element (a
list of one element is considered sorted).
2. Repeatedly merge sublists to
produce new sorted sublists until there is only one sublist remaining. This
will be the sorted list.
"""
def merge_sort(arr):
"""
merge sort
... | """
Merge Sort
1. Divide the unsorted list into n sublists, each containing one element (a
list of one element is considered sorted).
2. Repeatedly merge sublists to
produce new sorted sublists until there is only one sublist remaining. This
will be the sorted list.
"""
def merge_sort(arr):
"""
merge sort
... |
class IndexingError(Exception):
"""Exception raised for errors in the indexing flow.
Attributes:
type -- One of 'user', 'user_replica_set', 'user_library', 'tracks', 'social_features', 'playlists'
blocknumber -- block number of error
blockhash -- block hash of error
txhash -- tr... | class Indexingerror(Exception):
"""Exception raised for errors in the indexing flow.
Attributes:
type -- One of 'user', 'user_replica_set', 'user_library', 'tracks', 'social_features', 'playlists'
blocknumber -- block number of error
blockhash -- block hash of error
txhash -- tr... |
"""
Entradas:
lista-->list-->lista
elemento->str-->elemento
Salidas
lista-->lista
"""
frutas = open('frutas.txt', 'r')
lista_frutas = []
for i in frutas:
lista_frutas.append(i)
def eliminar_un_caracter(lista: list, elemento: str):
auxilar = []
for i in lista:
a = i.replace(elemento, "")
auxilar.append(a... | """
Entradas:
lista-->list-->lista
elemento->str-->elemento
Salidas
lista-->lista
"""
frutas = open('frutas.txt', 'r')
lista_frutas = []
for i in frutas:
lista_frutas.append(i)
def eliminar_un_caracter(lista: list, elemento: str):
auxilar = []
for i in lista:
a = i.replace(elemento, '')
aux... |
##########################################################################################
# district data structure
##########################################################################################
class DistrictData:
def __init__(self):
self.data = ""
self.stato = ""
self.c... | class Districtdata:
def __init__(self):
self.data = ''
self.stato = ''
self.codice_regione = ''
self.denominazione_regione = ''
self.codice_provincia = ''
self.denominazione_provincia = ''
self.sigla_provincia = ''
self.lat = ''
self.long = ''... |
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = len(nums) - 2
while (i >= 0 and nums[i+1] <= nums[i]):
i -= 1
# not the first
if i >= 0:
... | class Solution:
def next_permutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = len(nums) - 2
while i >= 0 and nums[i + 1] <= nums[i]:
i -= 1
if i >= 0:
j = len(nums) - 1
while... |
# -*- coding: utf-8 -*-
while True:
try:
hm = list(map(float, input().split()))
h = int((hm[0] / 360) * 12)
m = int((hm[1] / 360) * 60)
if m == 60:
m = 0
print("{:02d}:{:02d}".format(h, m))
except (EOFError, IndexError):
break | while True:
try:
hm = list(map(float, input().split()))
h = int(hm[0] / 360 * 12)
m = int(hm[1] / 360 * 60)
if m == 60:
m = 0
print('{:02d}:{:02d}'.format(h, m))
except (EOFError, IndexError):
break |
# -*- coding: utf-8 -*-
__about__ = """
This project comes fully-featured, with everything that Pinax provides enabled
by default. It provides all tabs available, etc. From here you can remove
applications that you do not want to use, and add your own applications as well.
""" | __about__ = '\nThis project comes fully-featured, with everything that Pinax provides enabled\nby default. It provides all tabs available, etc. From here you can remove\napplications that you do not want to use, and add your own applications as well.\n' |
class Solution:
def rob(self, root):
def f(n):
if not n:
return [0, 0]
l, r = f(n.left), f(n.right)
return [l[1] + r[1], max(l[1] + r[1], n.val + l[0] + r[0])]
return max(f(root))
| class Solution:
def rob(self, root):
def f(n):
if not n:
return [0, 0]
(l, r) = (f(n.left), f(n.right))
return [l[1] + r[1], max(l[1] + r[1], n.val + l[0] + r[0])]
return max(f(root)) |
# -*- coding: utf-8 -*-
def create_3dskullstrip_arg_string(shrink_fac, var_shrink_fac,
shrink_fac_bot_lim, avoid_vent, niter,
pushout, touchup, fill_hole, avoid_eyes,
use_edge, exp_frac, smooth_final,
... | def create_3dskullstrip_arg_string(shrink_fac, var_shrink_fac, shrink_fac_bot_lim, avoid_vent, niter, pushout, touchup, fill_hole, avoid_eyes, use_edge, exp_frac, smooth_final, push_to_edge, use_skull, perc_int, max_inter_iter, blur_fwhm, fac):
"""
Method to return option string for 3dSkullStrip
Parame... |
#!/usr/bin/env python3.7
class Proposal:
"""
Sequence proposed by the player while trying to guess the secret
The problem will add hint information, by setting the value of whites and reds
"""
"""proposed secret sequence"""
sequence = str
"""number of right colours in a wrong position"""... | class Proposal:
"""
Sequence proposed by the player while trying to guess the secret
The problem will add hint information, by setting the value of whites and reds
"""
'proposed secret sequence'
sequence = str
'number of right colours in a wrong position'
whites = int
'number of righ... |
# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | class Operationresult(object):
def __init__(self, result_status, result_reason=None, result_message=None):
self.result_status = result_status
if result_reason is not None:
self.result_reason = result_reason
else:
self.result_reason = None
if result_message is... |
'''
If the parameter to the make payment method of the CreditCard class
were a negative number, that would have the effect of raising the balance
on the account. Revise the implementation so that it raises a ValueError if
a negative value is sent.
'''
def make_payment(self,amount):
if amount < 0:
raise ValueError(... | """
If the parameter to the make payment method of the CreditCard class
were a negative number, that would have the effect of raising the balance
on the account. Revise the implementation so that it raises a ValueError if
a negative value is sent.
"""
def make_payment(self, amount):
if amount < 0:
raise va... |
x = 3
def foo():
y = "String"
return y
foo()
| x = 3
def foo():
y = 'String'
return y
foo() |
n = int(input())
for i in range(n):
r,e,c = map(int, input().split())
if((e-c) > r):
print('advertise')
elif((e-c) == r):
print('does not matter')
else:
print('do not advertise')
| n = int(input())
for i in range(n):
(r, e, c) = map(int, input().split())
if e - c > r:
print('advertise')
elif e - c == r:
print('does not matter')
else:
print('do not advertise') |
def sum(*args):
total = 0
for arg in args:
total+= arg
return total
a = sum(1200, 300, 500)
print(a)
| def sum(*args):
total = 0
for arg in args:
total += arg
return total
a = sum(1200, 300, 500)
print(a) |
#1)
def isnegative(n):
if n < 0:
return True
else:
return False
isnegative(-6)
#1)
list1 = [1,2,3]
def count_evens(list1):
even_count = 0
for num in list1:
if num % 2 == 0:
even_count += 1
print(even_count)
#1)
def increment_odds(n):
nums = []
for n in ... | def isnegative(n):
if n < 0:
return True
else:
return False
isnegative(-6)
list1 = [1, 2, 3]
def count_evens(list1):
even_count = 0
for num in list1:
if num % 2 == 0:
even_count += 1
print(even_count)
def increment_odds(n):
nums = []
for n in range(1, 2 * n,... |
N = int(input())
while N > 0:
texto = input().lower().replace(' ', '')
alfabeto = 'abcdefghijklmnopqrstuvwxyz'
contador = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
result = ''
a, i, count, maior = 0, 0, 0, 0
break_ = True
while count < 52:
if break_ == True:
c... | n = int(input())
while N > 0:
texto = input().lower().replace(' ', '')
alfabeto = 'abcdefghijklmnopqrstuvwxyz'
contador = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
result = ''
(a, i, count, maior) = (0, 0, 0, 0)
break_ = True
while count < 52:
if ... |
"""
Singleton objects that serve as placeholders in pyll graphs.
These are used by e.g. ./nips2011.py
"""
class train_task(object):
"""`train` argument to skdata.LearningAlgo's best_model method
"""
class valid_task(object):
"""`valid` argument to skdata.LearningAlgo's best_model method
"""
class ct... | """
Singleton objects that serve as placeholders in pyll graphs.
These are used by e.g. ./nips2011.py
"""
class Train_Task(object):
"""`train` argument to skdata.LearningAlgo's best_model method
"""
class Valid_Task(object):
"""`valid` argument to skdata.LearningAlgo's best_model method
"""
class Ct... |
# Schema used for pre-2013-2014 TAPR data
SCHEMA = {
'staff-and-student-information': {
'all_students_count': 'PETALLC',
'african_american_count': 'PETBLAC',
'african_american_percent': 'PETBLAP',
'american_indian_count': 'PETINDC',
'american_indian_percent': 'PETINDP',
... | schema = {'staff-and-student-information': {'all_students_count': 'PETALLC', 'african_american_count': 'PETBLAC', 'african_american_percent': 'PETBLAP', 'american_indian_count': 'PETINDC', 'american_indian_percent': 'PETINDP', 'asian_count': 'PETASIC', 'asian_percent': 'PETASIP', 'hispanic_count': 'PETHISC', 'hispanic_... |
class ClientError(Exception):
"""Common base class for all client errors."""
class NotFoundError(ClientError):
"""URL was not found."""
class InvalidRequestError(ClientError):
"""The API request was invalid."""
class TimeoutError(ClientError): # pylint: disable=redefined-builtin
"""The API server... | class Clienterror(Exception):
"""Common base class for all client errors."""
class Notfounderror(ClientError):
"""URL was not found."""
class Invalidrequesterror(ClientError):
"""The API request was invalid."""
class Timeouterror(ClientError):
"""The API server did not respond before the timeout expi... |
# Leo colorizer control file for bbj mode.
# This file is in the public domain.
# Properties for bbj mode.
properties = {
"commentEnd": "*/",
"commentStart": "/*",
"wordBreakChars": ",+-=<>/?^&*",
}
# Attributes dict for bbj_main ruleset.
bbj_main_attributes_dict = {
"default": "null",
... | properties = {'commentEnd': '*/', 'commentStart': '/*', 'wordBreakChars': ',+-=<>/?^&*'}
bbj_main_attributes_dict = {'default': 'null', 'digit_re': '', 'escape': '\\', 'highlight_digits': 'true', 'ignore_case': 'true', 'no_word_sep': ''}
attributes_dict_dict = {'bbj_main': bbj_main_attributes_dict}
bbj_main_keywords_di... |
#
# Time complexity:
# O(lines*columns) (worst case, where all the neighbours have the same color)
# O(1) (best case, where no neighbour has the same color)
#
# Space complexity:
# O(1) (color changes applied in place)
#
def flood_fill(screen, lines, columns, line, column, color):
def inbound(l, c)... | def flood_fill(screen, lines, columns, line, column, color):
def inbound(l, c):
return (l >= 0 and l < lines) and (c >= 0 and c < columns)
def key(l, c):
return '{},{}'.format(l, c)
stack = [[line, column]]
visited = set()
while stack:
(l, c) = stack.pop()
visited.a... |
def __residuumSign(self):
if self.outcome == 0:
return -1
else: return 1
| def __residuum_sign(self):
if self.outcome == 0:
return -1
else:
return 1 |
# -*- coding: utf-8 -*-
class RedisServiceException(Exception):
pass
| class Redisserviceexception(Exception):
pass |
def main(request, response):
headers = [("Content-Type", "text/javascript")]
values = []
for key in request.cookies:
for cookie in request.cookies.get_list(key):
values.append('"%s": "%s"' % (key, cookie.value))
# Update the counter to change the script body for every request to tr... | def main(request, response):
headers = [('Content-Type', 'text/javascript')]
values = []
for key in request.cookies:
for cookie in request.cookies.get_list(key):
values.append('"%s": "%s"' % (key, cookie.value))
key = request.GET['key']
counter = request.server.stash.take(key)
... |
class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
n = len(target)
maxMask = 1 << n
# dp[i] := min # of stickers to spell out i,
# where i is the bit representation of target
dp = [math.inf] * maxMask
dp[0] = 0
for mask in range(maxMask):
if dp[mask] == ... | class Solution:
def min_stickers(self, stickers: List[str], target: str) -> int:
n = len(target)
max_mask = 1 << n
dp = [math.inf] * maxMask
dp[0] = 0
for mask in range(maxMask):
if dp[mask] == math.inf:
continue
for sticker in sticker... |
# -----------------------------------------------------------
# Copyright (c) 2021. Danil Smirnov
# A positive real number is given. Print its fractional part.
# -----------------------------------------------------------
def get_fractional_part(number: float)-> float:
return float(number - (int(number ... | def get_fractional_part(number: float) -> float:
return float(number - int(number // 1))
print(get_fractional_part(float(input()))) |
"""
File: booleans.py
Copyright (c) 2016 Callie Enfield
License: MIT
This code was used to simply gain a better understanding of what different boolean expressions will do.
"""
C = 41 #There will be no output. This expression is setting the variable 'C' equal to 41.
C == 40 #The output will be 'False'. 40 is being... | """
File: booleans.py
Copyright (c) 2016 Callie Enfield
License: MIT
This code was used to simply gain a better understanding of what different boolean expressions will do.
"""
c = 41
C == 40
C != 40 and C < 41
C != 40 or C < 41
not C == 40
not C > 40
C <= 41
not False
True and False
False or True
False or False or ... |
def hello():
print(f"Hello, world!")
if __name__ == '__main__':
hello()
| def hello():
print(f'Hello, world!')
if __name__ == '__main__':
hello() |
class IAuthenticationModule:
""" Provides the base authentication interface for Web client authentication modules. """
def Authenticate(self, challenge, request, credentials):
"""
Authenticate(self: IAuthenticationModule,challenge: str,request: WebRequest,credentials: ICredentials) -> Authorizat... | class Iauthenticationmodule:
""" Provides the base authentication interface for Web client authentication modules. """
def authenticate(self, challenge, request, credentials):
"""
Authenticate(self: IAuthenticationModule,challenge: str,request: WebRequest,credentials: ICredentials) -> Authorization
... |
js = """
const quote = String.fromCharCode(34);
const newline = String.fromCharCode(10);
const marker = quote + quote + quote;
const quine = 'js = ' + marker + js + marker + newline + 'py = ' + marker + py + marker + py;
exports.handler = async (body, ctx) => {
return new ctx.HTTPResponse({
body: Buffer.from(quin... | js = "\nconst quote = String.fromCharCode(34);\nconst newline = String.fromCharCode(10);\nconst marker = quote + quote + quote;\nconst quine = 'js = ' + marker + js + marker + newline + 'py = ' + marker + py + marker + py;\nexports.handler = async (body, ctx) => {\n return new ctx.HTTPResponse({\n body: Buffer.from... |
# 8-3
def make_shirt(size, string):
"""Make shirt"""
print('Size: ' + size + ', String: ' + string)
make_shirt('M', 'Hello, World')
make_shirt(size='M', string='Hello, World again')
# 8-4
def make_shirt(size='L', string='I love Python'):
"""Make python shirt"""
print('Size: ' + size + ', String: ' + ... | def make_shirt(size, string):
"""Make shirt"""
print('Size: ' + size + ', String: ' + string)
make_shirt('M', 'Hello, World')
make_shirt(size='M', string='Hello, World again')
def make_shirt(size='L', string='I love Python'):
"""Make python shirt"""
print('Size: ' + size + ', String: ' + string)
make_s... |
variant = dict(
mlflow_uri="http://128.2.210.74:8080",
gpu=False,
algorithm="PPO",
version="normal",
actor_width=64, # Need to tune
critic_width=256,
replay_buffer_size=int(3E3),
algorithm_kwargs=dict(
min_num_steps_before_training=0,
num_epoch... | variant = dict(mlflow_uri='http://128.2.210.74:8080', gpu=False, algorithm='PPO', version='normal', actor_width=64, critic_width=256, replay_buffer_size=int(3000.0), algorithm_kwargs=dict(min_num_steps_before_training=0, num_epochs=150, num_eval_steps_per_epoch=1000, num_train_loops_per_epoch=10, num_expl_steps_per_tra... |
#
# PySNMP MIB module ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:50:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# U... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) ... |
par = []
impar = []
print('Para o inicio da contagem, inicie com 1 para mostrar os impares e 2 para os pares.')
n1 = int(input('Digite o inico da contagem [ 1 ] [ 2 ]:'))
n2 = int(input('Digite o final da contagem:'))
for c in range(n1, n2+1, 2):
if n1 == 2:
par.append(c)
elif n1 == 1:
impar.app... | par = []
impar = []
print('Para o inicio da contagem, inicie com 1 para mostrar os impares e 2 para os pares.')
n1 = int(input('Digite o inico da contagem [ 1 ] [ 2 ]:'))
n2 = int(input('Digite o final da contagem:'))
for c in range(n1, n2 + 1, 2):
if n1 == 2:
par.append(c)
elif n1 == 1:
impar.a... |
""" Data structures to store CommCareHQ reports """
class Report(object):
""" This class is a generic object for representing data
intended for specific reports. It is mostly useful so that
we can transform these structures arbitrarily into xml,
csv, json, etc. without changing our report generators
... | """ Data structures to store CommCareHQ reports """
class Report(object):
""" This class is a generic object for representing data
intended for specific reports. It is mostly useful so that
we can transform these structures arbitrarily into xml,
csv, json, etc. without changing our report generators
... |
# Crie um programa onde o usuario digite
# uma expressao qualquer que use parenteses.
# Seu aplicativo devera analisar se a
# expressao passada esta com os
# parenteses abertos e fechados na ordem correta.
expr = str(input('Digite a expressao: '))
pilha = list()
for simb in expr:
if simb == '(':
pilha.appen... | expr = str(input('Digite a expressao: '))
pilha = list()
for simb in expr:
if simb == '(':
pilha.append('(')
elif simb == ')':
if len(pilha) > 0:
pilha.pop()
else:
pilha.append(')')
break
if len(pilha) == 0:
print('Sua expressao esta valida!')
else... |
# Python Program To Sort The Elements Of A Dictionary Based On A Key Or Value
'''
Function Name : Sort Elements Of Dictionary Based On Key, Value.
Function Date : 13 Sep 2020
Function Author : Prasad Dangare
Input : String
Output : String
'''
colors = {10: "Red", 35: "Green"... | """
Function Name : Sort Elements Of Dictionary Based On Key, Value.
Function Date : 13 Sep 2020
Function Author : Prasad Dangare
Input : String
Output : String
"""
colors = {10: 'Red', 35: 'Green', 15: 'Blue', 25: 'White'}
c1 = sorted(colors.items(), key=lambda t: t[0])
print(c1)
c2 = ... |
# Mergesort is the best sorting algorithm for use with a linked-list
# Time Complexity O(nlogn)
# Merging will require log(n) doublings from subarrays of size (1) to a single array of size length(n),
# where each pass will require (n) iterations to compare and sort each element
# Space Complexity O(n) arrays
... | def mergesort(a):
if len(a) > 1:
m = len(a) // 2
l = a[:m]
r = a[m:]
mergesort(l)
mergesort(r)
i = 0
j = 0
k = 0
while i < len(l) and j < len(r):
if l[i] < r[j]:
a[k] = l[i]
i += 1
else:
... |
"""VTK/FURY Tools
This module implements a set o tools to enhance VTK given new functionalities.
"""
class Uniform:
"""This creates a uniform shader variable
It's responsible to store the value of a given uniform
variable and call the related vtk_program
"""
def __init__(self, name, uniform_ty... | """VTK/FURY Tools
This module implements a set o tools to enhance VTK given new functionalities.
"""
class Uniform:
"""This creates a uniform shader variable
It's responsible to store the value of a given uniform
variable and call the related vtk_program
"""
def __init__(self, name, uniform_ty... |
def solution(inp):
data = [row.split() for row in inp.splitlines()]
count = 0
for passphrase in data:
if len(passphrase) == len(set(passphrase)):
count = count + 1
return count
def main():
with open('input.txt', 'r') as f:
inp = f.read()
print('[*] Reading input from input.txt...')
print('[*] The soluti... | def solution(inp):
data = [row.split() for row in inp.splitlines()]
count = 0
for passphrase in data:
if len(passphrase) == len(set(passphrase)):
count = count + 1
return count
def main():
with open('input.txt', 'r') as f:
inp = f.read()
print('[*] Reading input ... |
# -*- coding: utf-8 -*-
__author__ = "venkat"
__author_email__ = "venkatram0273@gmail.com"
| __author__ = 'venkat'
__author_email__ = 'venkatram0273@gmail.com' |
# version code 80e56511a793+
# Please fill out this stencil and submit using the provided submission script.
# Be sure that the file voting_record_dump109.txt is in the matrix/ directory.
## 1: (Task 2.12.1) Create Voting Dict
def create_voting_dict(strlist):
"""
Input: a list of strings. Each string rep... | def create_voting_dict(strlist):
"""
Input: a list of strings. Each string represents the voting record of a senator.
The string consists of
- the senator's last name,
- a letter indicating the senator's party,
- a couple of letters indicating the senator'... |
s1=set([1,3,7,94])
s2=set([2,3])
print(s1)
print(s2)
print(s1.intersection(s2))
print(s1.difference(s2))
print(s2.difference(s1))
print(s1.symmetric_difference(s2))
print(s1.union(s2))
s1.difference_update(s2) #S1 becomes equal to the difference
print(s1)
s1=set([1,3])
s1.discard(1)
s1.remove(3)
print(s1)
s1.add(5)
pr... | s1 = set([1, 3, 7, 94])
s2 = set([2, 3])
print(s1)
print(s2)
print(s1.intersection(s2))
print(s1.difference(s2))
print(s2.difference(s1))
print(s1.symmetric_difference(s2))
print(s1.union(s2))
s1.difference_update(s2)
print(s1)
s1 = set([1, 3])
s1.discard(1)
s1.remove(3)
print(s1)
s1.add(5)
print(s1)
t = [6, 7]
s2.upda... |
def convert_to_alt_caps(message):
lower = message.lower()
upper = message.upper()
data = []
space_offset = 0
for i in range(len(lower)):
if not lower[i].isalpha():
space_offset += 1
if (i + space_offset) % 2 == 0:
data.append(lower[i])
else:
... | def convert_to_alt_caps(message):
lower = message.lower()
upper = message.upper()
data = []
space_offset = 0
for i in range(len(lower)):
if not lower[i].isalpha():
space_offset += 1
if (i + space_offset) % 2 == 0:
data.append(lower[i])
else:
... |
TIME_FORMAT = ('day', 'hour')
OPERATORS = {
'==': lambda x, y: x == y,
'<=': lambda x, y: x <= y,
'>=': lambda x, y: x >= y,
'>': lambda x, y: x > y,
'<': lambda x, y: x < y,
}
class TimeDelta(object):
def __init__(self, amount, fmt, operator):
if int(amount) < 0:
raise ... | time_format = ('day', 'hour')
operators = {'==': lambda x, y: x == y, '<=': lambda x, y: x <= y, '>=': lambda x, y: x >= y, '>': lambda x, y: x > y, '<': lambda x, y: x < y}
class Timedelta(object):
def __init__(self, amount, fmt, operator):
if int(amount) < 0:
raise value_error('amount must b... |
# -*- coding: utf-8 -*-
"""
"""
#make noarg a VERY unique value. Was using empty tuple, but python caches it, this should be quite unique
def unique_generator():
def UNIQUE_CLOSURE():
return UNIQUE_CLOSURE
return ("<UNIQUE VALUE>", UNIQUE_CLOSURE,)
NOARG = unique_generator()
| """
"""
def unique_generator():
def unique_closure():
return UNIQUE_CLOSURE
return ('<UNIQUE VALUE>', UNIQUE_CLOSURE)
noarg = unique_generator() |
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
banset = set(banned)
for c in "!?',;.":
paragraph = paragraph.replace(c, ' ')
cnt = Counter(word for word in paragraph.lower().split())
ans, best = '', 0
for word in cnt:
if cnt[word] > best and word no... | class Solution:
def most_common_word(self, paragraph: str, banned: List[str]) -> str:
banset = set(banned)
for c in "!?',;.":
paragraph = paragraph.replace(c, ' ')
cnt = counter((word for word in paragraph.lower().split()))
(ans, best) = ('', 0)
for word in cnt:
... |
#program to input a number, if it is not a number generate an error message.
while True:
try:
a = int(input("Input a number: "))
break
except ValueError:
print("\nThis is not a number. Try again...")
print()
break | while True:
try:
a = int(input('Input a number: '))
break
except ValueError:
print('\nThis is not a number. Try again...')
print()
break |
# Introduction to deep learning with Python
# A. Forward propogation
# Process of working from the input layer to the hidden layer to the final output layer
# Values contained within the input layer are multiplied by the weights that are connected to the interactions for the hidden layer.
# Details contained within th... | node_0_value = (input_data * weights['node_0']).sum()
node_1_value = (input_data * weights['node_1']).sum()
hidden_layer_outputs = np.array([node_0_value, node_1_value])
output = (hidden_layer_outputs * weights['output']).sum()
print(output)
def relu(input):
"""Define your relu activation function here"""
outp... |
class Destiny2APIError(Exception):
pass
class Destiny2InvalidParameters(Destiny2APIError):
pass
class Destiny2APICooldown(Destiny2APIError):
pass
class Destiny2RefreshTokenError(Destiny2APIError):
pass
class Destiny2MissingAPITokens(Destiny2APIError):
pass
class Destiny2MissingManifest(Des... | class Destiny2Apierror(Exception):
pass
class Destiny2Invalidparameters(Destiny2APIError):
pass
class Destiny2Apicooldown(Destiny2APIError):
pass
class Destiny2Refreshtokenerror(Destiny2APIError):
pass
class Destiny2Missingapitokens(Destiny2APIError):
pass
class Destiny2Missingmanifest(Destiny2... |
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
dic = {}
for i, num in enumerate(numbers):
if target - num in dic:
return [dic[target - num] + 1, i + 1]
dic[num] = i
| class Solution:
def two_sum(self, numbers: List[int], target: int) -> List[int]:
dic = {}
for (i, num) in enumerate(numbers):
if target - num in dic:
return [dic[target - num] + 1, i + 1]
dic[num] = i |
# DROP TABLES
songplay_table_drop = "DROP TABLE IF EXISTS songplays;"
user_table_drop = "DROP TABLE IF EXISTS users;"
song_table_drop = "DROP TABLE IF EXISTS songs;"
artist_table_drop = "DROP TABLE IF EXISTS artists;"
time_table_drop = "DROP TABLE IF EXISTS time;"
# CREATE TABLES
songplay_table_create = ("""CREATE T... | songplay_table_drop = 'DROP TABLE IF EXISTS songplays;'
user_table_drop = 'DROP TABLE IF EXISTS users;'
song_table_drop = 'DROP TABLE IF EXISTS songs;'
artist_table_drop = 'DROP TABLE IF EXISTS artists;'
time_table_drop = 'DROP TABLE IF EXISTS time;'
songplay_table_create = 'CREATE TABLE IF NOT EXISTS songplays (\n ... |
# OpenWeatherMap API Key
weather_api_key = "601b4c14f4ddb46a0080bbfb5ca51d3e"
# Google API Key
g_key = "AIzaSyDNUFB01N6sBwZfPznGBiHayHJrON12pYw"
| weather_api_key = '601b4c14f4ddb46a0080bbfb5ca51d3e'
g_key = 'AIzaSyDNUFB01N6sBwZfPznGBiHayHJrON12pYw' |
class BaseModel:
def __init__(self):
self.ops = {}
| class Basemodel:
def __init__(self):
self.ops = {} |
# user.py
__all__ = ['User']
class User:
pass
def user_helper_1():
pass | __all__ = ['User']
class User:
pass
def user_helper_1():
pass |
description = 'IPC Motor bus device configuration'
group = 'lowlevel'
instrument_values = configdata('instrument.values')
tango_base = instrument_values['tango_base']
# data from instrument.inf
# used for:
# - shutter_gamma (addr 0x31)
# - nok2 (addr 0x32, 0x33)
# - nok3 (addr 0x34, 0x35)
# - nok4 reactor side (add... | description = 'IPC Motor bus device configuration'
group = 'lowlevel'
instrument_values = configdata('instrument.values')
tango_base = instrument_values['tango_base']
devices = dict(nokbus1=device('nicos.devices.vendor.ipc.IPCModBusTango', tangodevice=tango_base + 'test/ipcsms_a/bio', lowlevel=True)) |
def extractMichilunWordpressCom(item):
'''
Parser for 'michilun.wordpress.com'
'''
bad = [
'Recommendations and Reviews',
]
if any([tmp in item['tags'] for tmp in bad]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title... | def extract_michilun_wordpress_com(item):
"""
Parser for 'michilun.wordpress.com'
"""
bad = ['Recommendations and Reviews']
if any([tmp in item['tags'] for tmp in bad]):
return None
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'prev... |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: A: A TreeNode in a Binary.
@param: B: A TreeNode in a Binary.
@return: Return... | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: A: A TreeNode in a Binary.
@param: B: A TreeNode in a Binary.
@return: Return ... |
def main():
with open('inputs/01.in') as f:
data = [int(line) for line in f]
print(sum(data))
result = 0
seen = {0}
while True:
for item in data:
result += item
if result in seen:
print(result)
return
seen.add(resu... | def main():
with open('inputs/01.in') as f:
data = [int(line) for line in f]
print(sum(data))
result = 0
seen = {0}
while True:
for item in data:
result += item
if result in seen:
print(result)
return
seen.add(result... |
strikeout = 'K'
className = "This is CS50."
age = 30
anotherAge = 63
pi = 3.14
morePi = 3.1415962
fun = True
print("strikeout: {}".format(strikeout))
print("className: {}".format(className))
print("age: {}".format(age))
print("anotherAge: {}".format(anotherAge))
print("pi: {}".format(pi))
print("morePi: {}".format(mor... | strikeout = 'K'
class_name = 'This is CS50.'
age = 30
another_age = 63
pi = 3.14
more_pi = 3.1415962
fun = True
print('strikeout: {}'.format(strikeout))
print('className: {}'.format(className))
print('age: {}'.format(age))
print('anotherAge: {}'.format(anotherAge))
print('pi: {}'.format(pi))
print('morePi: {}'.format(m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.