content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python3
def get_vertices(wire):
x = y = steps = 0
vertices = [(x, y, 0)]
for edge in wire:
length = int(edge[1:])
steps += length
if edge[0] == "R":
x += length
if edge[0] == "L":
x -= length
if edge[0] == "U":
... | def get_vertices(wire):
x = y = steps = 0
vertices = [(x, y, 0)]
for edge in wire:
length = int(edge[1:])
steps += length
if edge[0] == 'R':
x += length
if edge[0] == 'L':
x -= length
if edge[0] == 'U':
y += length
if edge[0... |
dim=10.0
eta=0.5
steps=100 #must be integer (no decimal point)
rneighb=eta
| dim = 10.0
eta = 0.5
steps = 100
rneighb = eta |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: apemodefb
class EAnimCurvePropertyFb(object):
LclTranslation = 0
RotationOffset = 1
RotationPivot = 2
PreRotation = 3
PostRotation = 4
LclRotation = 5
ScalingOffset = 6
ScalingPivot = 7
LclScaling = 8... | class Eanimcurvepropertyfb(object):
lcl_translation = 0
rotation_offset = 1
rotation_pivot = 2
pre_rotation = 3
post_rotation = 4
lcl_rotation = 5
scaling_offset = 6
scaling_pivot = 7
lcl_scaling = 8
geometric_translation = 9
geometric_rotation = 10
geometric_scaling = 11 |
__author__ = 'tylin'
# from .bleu import Bleu
#
# __all__ = ['Bleu']
| __author__ = 'tylin' |
# General ES Constants
COUNT = 'count'
CREATE = 'create'
DOCS = 'docs'
FIELD = 'field'
FIELDS = 'fields'
HITS = 'hits'
ID = '_id'
INDEX = 'index'
INDEX_NAME = 'index_name'
ITEMS = 'items'
KILOMETERS = 'km'
MAPPING_DYNAMIC = 'dynamic'
MAPPING_MULTI_FIELD = 'multi_field'
MAPPING_NULL_VALUE = 'null_value'
MILES = 'mi'
OK ... | count = 'count'
create = 'create'
docs = 'docs'
field = 'field'
fields = 'fields'
hits = 'hits'
id = '_id'
index = 'index'
index_name = 'index_name'
items = 'items'
kilometers = 'km'
mapping_dynamic = 'dynamic'
mapping_multi_field = 'multi_field'
mapping_null_value = 'null_value'
miles = 'mi'
ok = 'ok'
properties = 'pr... |
load("//third_party:common.bzl", "err_out", "execute")
_LLVM_BINARIES = [
"clang",
"clang-cpp",
"ld.lld",
"llvm-ar",
"llvm-as",
"llvm-nm",
"llvm-objcopy",
"llvm-objdump",
"llvm-profdata",
"llvm-dwp",
"llvm-ranlib",
"llvm-readelf",
"llvm-strip",
"llvm-symbolizer",... | load('//third_party:common.bzl', 'err_out', 'execute')
_llvm_binaries = ['clang', 'clang-cpp', 'ld.lld', 'llvm-ar', 'llvm-as', 'llvm-nm', 'llvm-objcopy', 'llvm-objdump', 'llvm-profdata', 'llvm-dwp', 'llvm-ranlib', 'llvm-readelf', 'llvm-strip', 'llvm-symbolizer']
_llvm_version_minimal = '10.0.0'
def _label(filename):
... |
valid=False
def marray(arr,*args,**kwargs):
return arr
def unitsDict(*args,**kwargs):
return None
def varMeta(*args,**kwargs):
return None
| valid = False
def marray(arr, *args, **kwargs):
return arr
def units_dict(*args, **kwargs):
return None
def var_meta(*args, **kwargs):
return None |
{
'OS-EXT-STS:task_state': None,
'addresses':
{'int-net':
[
{'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22',
'version': 4,
'addr': '192.168.1.8',
'OS-EXT-IPS:type': 'fixed'
},
{'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22',
'version': 4,
'addr': '192.168.166.23',
'O... | {'OS-EXT-STS:task_state': None, 'addresses': {'int-net': [{'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22', 'version': 4, 'addr': '192.168.1.8', 'OS-EXT-IPS:type': 'fixed'}, {'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22', 'version': 4, 'addr': '192.168.166.23', 'OS-EXT-IPS:type': 'floating'}]}, 'OS-EXT-STS:vm_state': '... |
with open('input.txt') as f:
lines = f.readlines()
count = 0
curDepth = 0
for line in lines:
newDepth = int(line)
if curDepth != 0:
if newDepth > curDepth:
count += 1
curDepth = newDepth
print(count)
| with open('input.txt') as f:
lines = f.readlines()
count = 0
cur_depth = 0
for line in lines:
new_depth = int(line)
if curDepth != 0:
if newDepth > curDepth:
count += 1
cur_depth = newDepth
print(count) |
def add(x, y=3):
print(x + y)
add(5) # 8
add(5, 8) # 13
add(y=3) # Error, missing x
# -- Order of default parameters --
# def add(x=5, y): # Not OK, default parameters must go after non-default
# print(x + y)
# -- Usually don't use variables as default value --
default_y = 3
def add(x, y=default_y):... | def add(x, y=3):
print(x + y)
add(5)
add(5, 8)
add(y=3)
default_y = 3
def add(x, y=default_y):
sum = x + y
print(sum)
add(2)
default_y = 4
print(default_y)
add(2) |
'''
Filippo Aleotti
filippo.aleotti2@unibo.it
29 November 2019
I PROFESSIONAL MASTER'S PROGRAM, II LEVEL "SIMUR", Imola 2019
Given a list of integer, store the frequency of each value in a dict, where the key is the value.
'''
def are_equals(dict1, dict2):
''' check if two dict are equal.
Both the dicts... | """
Filippo Aleotti
filippo.aleotti2@unibo.it
29 November 2019
I PROFESSIONAL MASTER'S PROGRAM, II LEVEL "SIMUR", Imola 2019
Given a list of integer, store the frequency of each value in a dict, where the key is the value.
"""
def are_equals(dict1, dict2):
""" check if two dict are equal.
Both the dicts... |
#!/usr/bin/env python
print("Hello from cx_Freeze Advanced #1\n")
module = __import__("testfreeze_1")
| print('Hello from cx_Freeze Advanced #1\n')
module = __import__('testfreeze_1') |
# Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.
def even_or_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
assert (even_or_odd(2)) == "Even", "Debe devolver Even"
assert (even_or_odd(0)) == "Even", "Debe... | def even_or_odd(number):
if number % 2 == 0:
return 'Even'
else:
return 'Odd'
assert even_or_odd(2) == 'Even', 'Debe devolver Even'
assert even_or_odd(0) == 'Even', 'Debe devolver Even'
assert even_or_odd(7) == 'Odd', 'Debe devolver Odd'
assert even_or_odd(1) == 'Odd', 'Debe devolver Odd' |
class Solution:
def isAlienSorted(self, words, order):
"""
:type words: List[str]
:type order: str
:rtype: bool
"""
order = {alpha: index for index, alpha in enumerate(order)}
for i in range(len(words) - 1):
flag = True
for j in range(m... | class Solution:
def is_alien_sorted(self, words, order):
"""
:type words: List[str]
:type order: str
:rtype: bool
"""
order = {alpha: index for (index, alpha) in enumerate(order)}
for i in range(len(words) - 1):
flag = True
for j in ra... |
class Producto:
"""Producto de venta"""
def __init__(self, nombre, desc, precio):
self.nombre = nombre
self.descripcion = desc
self.precio = precio
# Es una salida para la muestra de la info
def formateo_textual(self):
textoFinal = ""
for atr in [self.nombre... | class Producto:
"""Producto de venta"""
def __init__(self, nombre, desc, precio):
self.nombre = nombre
self.descripcion = desc
self.precio = precio
def formateo_textual(self):
texto_final = ''
for atr in [self.nombre, self.descripcion, self.precio]:
text... |
n = int(input())
L = list(map(int,input().split()))
A = list(set(L[:]))
d = {}
A.sort()
for i in range(len(A)):
d[A[i]] = i
for i in L:
print(d[i],end = " ") | n = int(input())
l = list(map(int, input().split()))
a = list(set(L[:]))
d = {}
A.sort()
for i in range(len(A)):
d[A[i]] = i
for i in L:
print(d[i], end=' ') |
"""
Jour de fete - Django_JDF
Convertion de nombres en toutes lettres
@date: 2014/09/12
@copyright: 2014 by Luc LEGER <artefacts.lle@gmail.com>
@license: MIT
"""
class numbers :
def __init__(self) :
self.schu=["","UN ","DEUX ","TROIS ","QUATRE ","CINQ ","SIX ","SEPT ","HUIT "... | """
Jour de fete - Django_JDF
Convertion de nombres en toutes lettres
@date: 2014/09/12
@copyright: 2014 by Luc LEGER <artefacts.lle@gmail.com>
@license: MIT
"""
class Numbers:
def __init__(self):
self.schu = ['', 'UN ', 'DEUX ', 'TROIS ', 'QUATRE ', 'CINQ ', 'SIX ', 'SEPT ', 'HU... |
# Url https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
class Solution:
def subtractProductAndSum(self, n):
prod, sum_n, curr = 1, 0, 0
while n != 0:
curr = n % 10
prod = prod * curr
sum_n = sum_n + curr
n = n//10
... | class Solution:
def subtract_product_and_sum(self, n):
(prod, sum_n, curr) = (1, 0, 0)
while n != 0:
curr = n % 10
prod = prod * curr
sum_n = sum_n + curr
n = n // 10
return prod - sum_n
if __name__ == '__main__':
a = solution()
print(... |
# Work out the first ten digits of the sum of N 50 digit numbers.
total = 0
for x in range(int(input())):
total += int(input().rstrip())
print(str(total)[:10])
| total = 0
for x in range(int(input())):
total += int(input().rstrip())
print(str(total)[:10]) |
__author__ = "Sylvain Dangin"
__licence__ = "Apache 2.0"
__version__ = "1.0"
__maintainer__ = "Sylvain Dangin"
__email__ = "sylvain.dangin@gmail.com"
__status__ = "Development"
class concat():
def action(input_data, params, current_row, current_index):
"""Concat multiple columns in the cell.
:param... | __author__ = 'Sylvain Dangin'
__licence__ = 'Apache 2.0'
__version__ = '1.0'
__maintainer__ = 'Sylvain Dangin'
__email__ = 'sylvain.dangin@gmail.com'
__status__ = 'Development'
class Concat:
def action(input_data, params, current_row, current_index):
"""Concat multiple columns in the cell.
:param ... |
"""
This module is for generating a Markov chain order two from a text.
"""
def generate_markov_chain(tweet_array):
"""
Input assumes text is an array of tweets, each tweet with words separated by spaces with no new lines.
This requires some changes to most transcripts ahead of time. Output will be a dictionary
wi... | """
This module is for generating a Markov chain order two from a text.
"""
def generate_markov_chain(tweet_array):
"""
Input assumes text is an array of tweets, each tweet with words separated by spaces with no new lines.
This requires some changes to most transcripts ahead of time. Output will be a dictionary
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:
class TaskName():
Classify_Task = "classify"
Detect2d_Task = "detect2d"
Segment_Task = "segment"
PC_Classify_Task = "pc_classify"
| class Taskname:
classify__task = 'classify'
detect2d__task = 'detect2d'
segment__task = 'segment'
pc__classify__task = 'pc_classify' |
class TheEquation:
def leastSum(self, X, Y, P):
m = 2*P
for i in xrange(1, P+1):
for j in xrange(1, P+1):
if (X*i + Y*j)%P == 0:
m = min(m, i+j)
return m
| class Theequation:
def least_sum(self, X, Y, P):
m = 2 * P
for i in xrange(1, P + 1):
for j in xrange(1, P + 1):
if (X * i + Y * j) % P == 0:
m = min(m, i + j)
return m |
#!/usr/bin/env python3
""" Top students """
def top_students(mongo_collection: object):
"""function that returns all students sorted by average score"""
top = mongo_collection.aggregate([
{
"$project": {
"name": "$name",
"averageScore": {"$avg": "$topics.sc... | """ Top students """
def top_students(mongo_collection: object):
"""function that returns all students sorted by average score"""
top = mongo_collection.aggregate([{'$project': {'name': '$name', 'averageScore': {'$avg': '$topics.score'}}}, {'$sort': {'averageScore': -1}}])
return top |
#!/usr/bin/env python3
class FakeSerial:
def __init__(self):
self._last_written_data = None
self._response = None
self.read_data = []
@property
def last_written_data(self):
return self._last_written_data
@property
def response(self):
return self._response
... | class Fakeserial:
def __init__(self):
self._last_written_data = None
self._response = None
self.read_data = []
@property
def last_written_data(self):
return self._last_written_data
@property
def response(self):
return self._response
@response.setter
... |
# coding=utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x, next=None):
self.val = x
self.next = next
class DoubleNode(object):
def __init__(self, key, val, pre=None, next=None):
self.key = key
self.val = val
self.pre = pre
... | class Listnode(object):
def __init__(self, x, next=None):
self.val = x
self.next = next
class Doublenode(object):
def __init__(self, key, val, pre=None, next=None):
self.key = key
self.val = val
self.pre = pre
self.next = next
class Treenode(object):
def ... |
seen = []
# Prduces the length of the longest Substring
# thats comprised of just unique characters
def max_diff(string):
seen = [0]*256
curr_start = 0
max_start = 0
unique = 0
max_unique = 0
for n,i in enumerate(string):
if seen[assn_num(i)] == 0:
unique += 1 ... | seen = []
def max_diff(string):
seen = [0] * 256
curr_start = 0
max_start = 0
unique = 0
max_unique = 0
for (n, i) in enumerate(string):
if seen[assn_num(i)] == 0:
unique += 1
else:
if unique > max_unique:
max_unique = unique
w... |
# package org.apache.helix.messaging.handling
#from org.apache.helix.messaging.handling import *
#from java.util import HashMap
#from java.util import Map
class HelixTaskResult:
def __init__(self):
self._success = False
self._message = ""
self._taskResultMap = {}
self._interrupte... | class Helixtaskresult:
def __init__(self):
self._success = False
self._message = ''
self._taskResultMap = {}
self._interrupted = False
self._exception = None
def is_sucess(self):
"""
Returns boolean
"""
return self._success
def is_... |
def _test_sources_aspect_impl(target, ctx):
result = depset()
if hasattr(ctx.rule.attr, "tags") and "NODE_MODULE_MARKER" in ctx.rule.attr.tags:
return struct(node_test_sources=result)
if hasattr(ctx.rule.attr, "deps"):
for dep in ctx.rule.attr.deps:
if hasattr(dep, "node_test_s... | def _test_sources_aspect_impl(target, ctx):
result = depset()
if hasattr(ctx.rule.attr, 'tags') and 'NODE_MODULE_MARKER' in ctx.rule.attr.tags:
return struct(node_test_sources=result)
if hasattr(ctx.rule.attr, 'deps'):
for dep in ctx.rule.attr.deps:
if hasattr(dep, 'node_test_sou... |
def is_prime(n):
if n > 1:
for i in range(2, n // 2 + 1):
if (n % i) == 0:
return False
else:
return True
else:
return False
def fibonacci(n):
n1, n2 = 1, 1
count = 0
if n == 1:
print(n1)
else:
while count < n:
... | def is_prime(n):
if n > 1:
for i in range(2, n // 2 + 1):
if n % i == 0:
return False
else:
return True
else:
return False
def fibonacci(n):
(n1, n2) = (1, 1)
count = 0
if n == 1:
print(n1)
else:
while count < n:
... |
######################################################################################
# Date: 2016/July/11
#
# Module: module_2DScatter.py
#
# VERSION: 0.9
#
# AUTHOR: Matt Thoburn (mthoburn@ufl.edu);
# edited by Miguel A. Ibarra-Arellano(miguelib@ufl.edu)
#
# DESCRIPTION: This module contains a primary met... | def scatter2_d(ax, x, y, colorList, ec='black'):
"""
This function is to be called by makeScatter2D, creates a 2D scatter plot on a given axis with
colors determined by the given colorHandler or an optional override
:Arguments:
:type ax: matplotlib Axis2D
:param ax: Axis on which sc... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
running_min = prices[0]
best_trans1 = [0]
for p in prices[1:]:
if p < running_min:
running_min = p
best_trans1.append(max(p - running_min, best_trans1[-1]))
running_max = prices[... | class Solution:
def max_profit(self, prices: List[int]) -> int:
running_min = prices[0]
best_trans1 = [0]
for p in prices[1:]:
if p < running_min:
running_min = p
best_trans1.append(max(p - running_min, best_trans1[-1]))
running_max = prices[-... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 16:46:12 2019
@author: Alexandre Janin
"""
"""Exceptions raised by pypStag"""
class PypStagError(Exception):
""" Main class for all pypStag """
pass
class PackageWarning(PypStagError):
"""Raised when a precise package is needed"""
def __init__(s... | """
Created on Wed Jan 30 16:46:12 2019
@author: Alexandre Janin
"""
'Exceptions raised by pypStag'
class Pypstagerror(Exception):
""" Main class for all pypStag """
pass
class Packagewarning(PypStagError):
"""Raised when a precise package is needed"""
def __init__(self, pack):
super().__ini... |
version = "dev 0.0"
running = False
def init():
global running
if not running:
print("JFUtils-python \"" + version + "\" by jonnelafin")
running = True
| version = 'dev 0.0'
running = False
def init():
global running
if not running:
print('JFUtils-python "' + version + '" by jonnelafin')
running = True |
"""Utility functions not closely tied to other spec_tools types."""
# Copyright (c) 2018-2019 Collabora, Ltd.
# Copyright (c) 2013-2019 The Khronos Group Inc.
#
# 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... | """Utility functions not closely tied to other spec_tools types."""
def get_elem_name(elem, default=None):
"""Get the name associated with an element, either a name child or name attribute."""
name_elem = elem.find('name')
if name_elem is not None:
return name_elem.text
return elem.get('name', ... |
class FiniteAutomataState:
def __init__(self, structure):
self.states = []
self.alphabet = []
self.initial = []
self.finals = []
self.transitions = {}
self._file = open(structure, "r")
self._load()
# print(self.validate())
def _load(self):
... | class Finiteautomatastate:
def __init__(self, structure):
self.states = []
self.alphabet = []
self.initial = []
self.finals = []
self.transitions = {}
self._file = open(structure, 'r')
self._load()
def _load(self):
reading = 'none'
readin... |
#!/usr/bin/python
compteur = 0
i,j = 3,1
terrain = []
fichier = open('day3_input.txt')
for l in fichier:
terrain.append(fichier.readline().strip('\n'))
nblig = len(terrain)
nbcol = len(terrain[0])
print('nblig : %s / nbcol : %s' % (nblig,nbcol))
for f in terrain:
print(f)
while j<nblig:
#print(i,j,terra... | compteur = 0
(i, j) = (3, 1)
terrain = []
fichier = open('day3_input.txt')
for l in fichier:
terrain.append(fichier.readline().strip('\n'))
nblig = len(terrain)
nbcol = len(terrain[0])
print('nblig : %s / nbcol : %s' % (nblig, nbcol))
for f in terrain:
print(f)
while j < nblig:
if terrain[j][i] == '#':
... |
dicionario_sites = {"Diego": "diegomariano.com"}
print(dicionario_sites['Diego'])
dicionario_sites = {"Diego": "diegomariano.com", "Google": "google.com", "Udemy": "udemy.com", "Luiz Carlin" : "luizcarlin.com.br"}
print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=")
for chave in dicionario_sites:
print (chave + " -... | dicionario_sites = {'Diego': 'diegomariano.com'}
print(dicionario_sites['Diego'])
dicionario_sites = {'Diego': 'diegomariano.com', 'Google': 'google.com', 'Udemy': 'udemy.com', 'Luiz Carlin': 'luizcarlin.com.br'}
print('-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=')
for chave in dicionario_sites:
print(chave + ' -:- ' ... |
# -*- coding: utf-8 -*-
# Author: Tonio Teran <tonio@stateoftheart.ai>
# Copyright: Stateoftheart AI PBC 2021.
'''RLlib's library wrapper.'''
SOURCE_METADATA = {
'name': 'rllib',
'original_name': 'RLlib',
'url': 'https://docs.ray.io/en/master/rllib.html'
}
MODELS = {
'discrete': [
'A2C', 'A3C'... | """RLlib's library wrapper."""
source_metadata = {'name': 'rllib', 'original_name': 'RLlib', 'url': 'https://docs.ray.io/en/master/rllib.html'}
models = {'discrete': ['A2C', 'A3C', 'ARS', 'BC', 'ES', 'DQN', 'Rainbow', 'APEX-DQN', 'IMPALA', 'MARWIL', 'PG', 'PPO', 'APPO', 'R2D2', 'SAC', 'SlateQ', 'LinUCB', 'LinTS', 'Alph... |
# Recursive, O(2^n)
def LCS(X, Y, m, n):
if m == 0 or n == 0:
return 0
elif X[m - 1] == Y[n - 1]:
return 1 + LCS(X, Y, m - 1, n - 1)
else:
return max(LCS(X, Y, m - 1, n), LCS(X, Y, m, n - 1))
X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is ", LCS(X, Y, len(X), len(Y)))
# Overl... | def lcs(X, Y, m, n):
if m == 0 or n == 0:
return 0
elif X[m - 1] == Y[n - 1]:
return 1 + lcs(X, Y, m - 1, n - 1)
else:
return max(lcs(X, Y, m - 1, n), lcs(X, Y, m, n - 1))
x = 'AGGTAB'
y = 'GXTXAYB'
print('Length of LCS is ', lcs(X, Y, len(X), len(Y)))
def lcs(X, Y):
m = len(X)
... |
class CalculoZ():
def calcular_z(self, n1, n2, x, y, ux, uy, ox, oy):
arriba = (x-y)-(ux-uy)
abajo = (((ox)**2/(n1))+((oy)**2/(n2)))**0.5
z = arriba/abajo
return z | class Calculoz:
def calcular_z(self, n1, n2, x, y, ux, uy, ox, oy):
arriba = x - y - (ux - uy)
abajo = (ox ** 2 / n1 + oy ** 2 / n2) ** 0.5
z = arriba / abajo
return z |
class Solution:
def intToRoman(self, num: int) -> str:
res = ""
s = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
index = 0
while num > 0:
x = num % 10
if x < 5:
if x == 4:
temp = s[index] + s[index + 1]
else:
... | class Solution:
def int_to_roman(self, num: int) -> str:
res = ''
s = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
index = 0
while num > 0:
x = num % 10
if x < 5:
if x == 4:
temp = s[index] + s[index + 1]
else:
... |
class BasicScript(object):
def __init__(self, parser):
"""
Initialize the class
:param parser: ArgumentParser
"""
super(BasicScript, self).__init__()
self._parser = parser
def get_arguments(self):
"""
Get the arguments to configure current script,... | class Basicscript(object):
def __init__(self, parser):
"""
Initialize the class
:param parser: ArgumentParser
"""
super(BasicScript, self).__init__()
self._parser = parser
def get_arguments(self):
"""
Get the arguments to configure current script... |
class ApiError(Exception):
"""
Exception raised when user does not have appropriate credentials
Used for 301 & 401 HTTP Status codes
"""
def __init__(self, response):
if 'error_description' in response:
self.message = response['error_description']
else:
... | class Apierror(Exception):
"""
Exception raised when user does not have appropriate credentials
Used for 301 & 401 HTTP Status codes
"""
def __init__(self, response):
if 'error_description' in response:
self.message = response['error_description']
else:
self... |
N, X, T = map(int, input().split())
time = N // X
if(N%X == 0):
print(time * T)
else:
print((time+1) * T) | (n, x, t) = map(int, input().split())
time = N // X
if N % X == 0:
print(time * T)
else:
print((time + 1) * T) |
class Token:
__slots__ = ('start', 'end')
def __init__(self, start: int=None, end: int=None):
self.start = start
self.end = end
@property
def type(self):
"Type of current token"
return self.__class__.__name__
def to_json(self):
return dict([(k, self.__getat... | class Token:
__slots__ = ('start', 'end')
def __init__(self, start: int=None, end: int=None):
self.start = start
self.end = end
@property
def type(self):
"""Type of current token"""
return self.__class__.__name__
def to_json(self):
return dict([(k, self.__g... |
literals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.?/:;{[]}-=_+~!@#$%^&*()"
#obfuscated
literals = "tJ;EM mKrFzQ_SOT?]B[U@$yqec~fhd{=is&alxPIbnuRkC%Z(jDw#G:/)L,*.V!pov+HNYA^g-}WX"
key = 7
def shuffle(plaintext):
shuffled = ""
# shuffle plaintext
for i in range(int(len(plaintext) / 3)):
... | literals = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.?/:;{[]}-=_+~!@#$%^&*()'
literals = 'tJ;EM mKrFzQ_SOT?]B[U@$yqec~fhd{=is&alxPIbnuRkC%Z(jDw#G:/)L,*.V!pov+HNYA^g-}WX'
key = 7
def shuffle(plaintext):
shuffled = ''
for i in range(int(len(plaintext) / 3)):
block = plaintext[i * 3] + plain... |
# apis_v1/documentation_source/organization_suggestion_tasks_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_suggestion_tasks_doc_template_values(url_root):
"""
Show documentation about organizationSuggestionTask
"""
required_query_parameter_list = [
{
... | def organization_suggestion_tasks_doc_template_values(url_root):
"""
Show documentation about organizationSuggestionTask
"""
required_query_parameter_list = [{'name': 'voter_device_id', 'value': 'string', 'description': 'An 88 character unique identifier linked to a voter record on the server'}, {'name'... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class ConstraintSyntaxError(SyntaxError):
"""A generic error indicating an improperly defined constraint."""
pass
class ConstraintValueError(ValueError):
"""A generic error indicating a value violates a constraint."""
pass
| class Constraintsyntaxerror(SyntaxError):
"""A generic error indicating an improperly defined constraint."""
pass
class Constraintvalueerror(ValueError):
"""A generic error indicating a value violates a constraint."""
pass |
curupira = int(input())
boitata = int(input())
boto = int(input())
mapinguari = int(input())
lara = int(input())
total = 225 + (curupira * 300) + (boitata *1500) + (boto * 600) + (mapinguari * 1000)+(lara*150)
print(total) | curupira = int(input())
boitata = int(input())
boto = int(input())
mapinguari = int(input())
lara = int(input())
total = 225 + curupira * 300 + boitata * 1500 + boto * 600 + mapinguari * 1000 + lara * 150
print(total) |
class Sibling:
pass
| class Sibling:
pass |
if True:
foo = 42
else:
foo = None
| if True:
foo = 42
else:
foo = None |
#!/usr/bin/python3
print("Sum of even-valued terms less than four million in the Fibonacci sequence:")
a, b, sum = 1, 1, 0
while b < 4000000:
sum += b if b % 2 == 0 else 0
a, b = b, a + b
print(sum)
| print('Sum of even-valued terms less than four million in the Fibonacci sequence:')
(a, b, sum) = (1, 1, 0)
while b < 4000000:
sum += b if b % 2 == 0 else 0
(a, b) = (b, a + b)
print(sum) |
class Solution:
def numFactoredBinaryTrees(self, A):
"""
:type A: List[int]
:rtype: int
"""
A.sort()
nums, res, trees, factors = set(A), 0, {}, collections.defaultdict(set)
for i, num in enumerate(A):
for n in A[:i]:
if num % n == 0... | class Solution:
def num_factored_binary_trees(self, A):
"""
:type A: List[int]
:rtype: int
"""
A.sort()
(nums, res, trees, factors) = (set(A), 0, {}, collections.defaultdict(set))
for (i, num) in enumerate(A):
for n in A[:i]:
if nu... |
#LeetCode problem 200: Number of Islands
class Solution:
def check(self,grid,nodesVisited,row,col,m,n):
return (row>=0 and row<m and col>=0 and col<n and grid[row][col]=="1" and nodesVisited[row][col]==0)
def dfs(self,grid,nodesVisited,row,col,m,n):
a=[-1,1,0,0]
b=[0,0,1,-1]
... | class Solution:
def check(self, grid, nodesVisited, row, col, m, n):
return row >= 0 and row < m and (col >= 0) and (col < n) and (grid[row][col] == '1') and (nodesVisited[row][col] == 0)
def dfs(self, grid, nodesVisited, row, col, m, n):
a = [-1, 1, 0, 0]
b = [0, 0, 1, -1]
nod... |
'''
################
# 55. Jump Game
################
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or (nums[0]==0 and len(nums)>1):
return False
if len(nums)==1:
return True
l = len(num... | '''
################
# 55. Jump Game
################
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or (nums[0]==0 and len(nums)>1):
return False
if len(nums)==1:
return True
l = len(num... |
'''
Create exceptions based on your inputs. Please follow the tasks below.
- Capture and handle system exceptions
- Create custom user-based exceptions
'''
class CustomInputError(Exception):
def __init__(self, *args, **kwargs):
print("Going through my own CustomInputError")
# Exception.__init_... | """
Create exceptions based on your inputs. Please follow the tasks below.
- Capture and handle system exceptions
- Create custom user-based exceptions
"""
class Custominputerror(Exception):
def __init__(self, *args, **kwargs):
print('Going through my own CustomInputError')
class Myzerodivisionexcepti... |
"""
This folder contains help-functions to Bokeh visualizations
in Python.
There are functions that align 2nd-ary y-axis to primary
y-axis as well as functions that align 3 y-axes.
"""
__credits__ = "ICOS Carbon Portal"
__license__ = "GPL-3.0"
__version__ = "0.1.0"
__maintainer__ = "I... | """
This folder contains help-functions to Bokeh visualizations
in Python.
There are functions that align 2nd-ary y-axis to primary
y-axis as well as functions that align 3 y-axes.
"""
__credits__ = 'ICOS Carbon Portal'
__license__ = 'GPL-3.0'
__version__ = '0.1.0'
__maintainer__ = 'ICOS Carbon Por... |
"""Collection of all documented ADS constants. Only a small subset of these
are used by code in this library.
Source: http://infosys.beckhoff.com/english.php?content=../content/1033/tcplclibsystem/html/tcplclibsys_constants.htm&id= # nopep8
"""
"""Port numbers"""
# Port number of the standard loggers.
AMSP... | """Collection of all documented ADS constants. Only a small subset of these
are used by code in this library.
Source: http://infosys.beckhoff.com/english.php?content=../content/1033/tcplclibsystem/html/tcplclibsys_constants.htm&id= # nopep8
"""
'Port numbers'
amsport_logger = 100
amsport_eventlog = 110
amsport_r0_rti... |
# https://www.acmicpc.net/problem/8393
a = int(input())
result = 0
for i in range(a + 1):
result = result + i
print(result) | a = int(input())
result = 0
for i in range(a + 1):
result = result + i
print(result) |
# conf.py/Open GoPro, Version 1.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Tue May 18 22:08:50 UTC 2021
project = "Open GoPro Python SDK"
copyright = "2020, GoPro Inc."
author = "Tim Camise"
version = "0.5.8"
release = "0.5.8"
templates_path = ["_templates"]
s... | project = 'Open GoPro Python SDK'
copyright = '2020, GoPro Inc.'
author = 'Tim Camise'
version = '0.5.8'
release = '0.5.8'
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
pygments_style = 'sphinx'
html_static_path = ['_static']
extensions = ['sphinx.ext.autodoc', 'sphinxcontrib.napoleon', 's... |
# Link --> https://www.hackerrank.com/challenges/maximum-element/problem
# Code:
def getMax(operations):
maximum = 0
temp = []
answer = []
for i in operations:
if i != '2' and i != '3':
numbers = i.split()
number = int(numbers[1])
temp.append(number)
... | def get_max(operations):
maximum = 0
temp = []
answer = []
for i in operations:
if i != '2' and i != '3':
numbers = i.split()
number = int(numbers[1])
temp.append(number)
if number > maximum:
maximum = number
elif i == '2':
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 30 15:49:24 2021
@author: alann
"""
arr = [[1,1,0,1,0],
[0,1,1,1,0],
[1,1,1,1,0],
[0,1,1,1,1]]
def largestSquare(arr ) -> int:
if len(arr) < 1 or len(arr[0]) < 1:
return 0
largest = 0
cache = [[0 for i in range(len(arr[0]))] for j in range(len(a... | """
Created on Mon Aug 30 15:49:24 2021
@author: alann
"""
arr = [[1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [0, 1, 1, 1, 1]]
def largest_square(arr) -> int:
if len(arr) < 1 or len(arr[0]) < 1:
return 0
largest = 0
cache = [[0 for i in range(len(arr[0]))] for j in range(len(arr))]
for ... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 12 19:10:03 2019
@author: DiPu
"""
shopping_list=[]
print("enter items to add in list and type quit when you arew done")
while True:
ip=input("enter list")
if ip=="QUIT":
break
elif ip.upper()=="SHOW":
print(shopping_list)
elif ip.upper()==... | """
Created on Sun May 12 19:10:03 2019
@author: DiPu
"""
shopping_list = []
print('enter items to add in list and type quit when you arew done')
while True:
ip = input('enter list')
if ip == 'QUIT':
break
elif ip.upper() == 'SHOW':
print(shopping_list)
elif ip.upper() == 'HELP':
... |
#!/usr/bin/env python3
if __name__ == "__main__":
N = int(input().strip())
stamps = set()
for _ in range(N):
stamp = input().strip()
stamps.add(stamp)
print(len(stamps)) | if __name__ == '__main__':
n = int(input().strip())
stamps = set()
for _ in range(N):
stamp = input().strip()
stamps.add(stamp)
print(len(stamps)) |
"""Provide a class for yWriter chapter representation.
Copyright (c) 2021 Peter Triesberger
For further information see https://github.com/peter88213/PyWriter
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
class Chapter():
"""yWriter chapter representation.
# ... | """Provide a class for yWriter chapter representation.
Copyright (c) 2021 Peter Triesberger
For further information see https://github.com/peter88213/PyWriter
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
class Chapter:
"""yWriter chapter representation.
# xml: <CHAPTER... |
"""
"""
# TODO: make this list complete [exclude stuffs ending with 's']
conditionals = [
"cmp",
"cmn",
"tst",
"teq"
]
class CMP(object):
def __init__(self, line_no, text):
self.line_no = line_no
self.text = text
class Branch(object):
def __init__(self, line_no, text, label... | """
"""
conditionals = ['cmp', 'cmn', 'tst', 'teq']
class Cmp(object):
def __init__(self, line_no, text):
self.line_no = line_no
self.text = text
class Branch(object):
def __init__(self, line_no, text, label=None):
text = text.strip()
self.line_no = line_no
self.text... |
# coding: utf-8
"""
Union-Find (Disjoint Set)
https://en.wikipedia.org/wiki/Disjoint-set_data_structure
"""
class QuickFindUnionFind:
def __init__(self, union_pairs=()):
self.num_groups = 0
self.auto_increment_id = 1
self.element_groups = {
# element: group_id,
}
... | """
Union-Find (Disjoint Set)
https://en.wikipedia.org/wiki/Disjoint-set_data_structure
"""
class Quickfindunionfind:
def __init__(self, union_pairs=()):
self.num_groups = 0
self.auto_increment_id = 1
self.element_groups = {}
for (p, q) in union_pairs:
self.union(p, q)
... |
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums: return None
i = len(nums)-1
j = -1 # j is set to -1 for case `4321`, so need to reverse all i... | class Solution(object):
def next_permutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums:
return None
i = len(nums) - 1
j = -1
while i > 0:
if nums[i... |
def sort_data_by_cumulus(data):
"""
Sort data by submitted_by field, which holds
the cumulus number (or id),
Parameters:
data (list): A list containing the report
data.
Returns:
(dict): A dict containg the data sorted by the
cumulus ... | def sort_data_by_cumulus(data):
"""
Sort data by submitted_by field, which holds
the cumulus number (or id),
Parameters:
data (list): A list containing the report
data.
Returns:
(dict): A dict containg the data sorted by the
cumulus ... |
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Intel Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | class Group(object):
def __init__(self, name):
self.name = name
self.__attributes = {}
def equals(self, obj):
return self.name == obj.get_name()
def get_attribute(self, key):
return self._attributes[key]
def get_device_members(self):
devices = []
all_d... |
"""
Configuration file
"""
class Config:
"""
Base Configuration
"""
DEBUG = True
SECRET_KEY = r'f\x13\xd9fM\xdc\x82\x01b\xdb\x03'
SQLALCHEMY_POOL_SIZE = 5
SQLALCHEMY_POOL_TIMEOUT = 120
SQLALCHEMY_POOL_RECYCLE = 280
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USERNA... | """
Configuration file
"""
class Config:
"""
Base Configuration
"""
debug = True
secret_key = 'f\\x13\\xd9fM\\xdc\\x82\\x01b\\xdb\\x03'
sqlalchemy_pool_size = 5
sqlalchemy_pool_timeout = 120
sqlalchemy_pool_recycle = 280
mail_server = 'smtp.gmail.com'
mail_port = 465
mail_us... |
# -*- coding:utf-8 -*-
# https://leetcode.com/problems/permutation-sequence/description/
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
factorial = [1]
for i in range(1, n):
factor... | class Solution(object):
def get_permutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
factorial = [1]
for i in range(1, n):
factorial.append(i * factorial[-1])
num = [i for i in range(1, n + 1)]
ret = []
fo... |
datasetDir = '../dataset/'
model = '../model/lenet'
modelDir = '../model/'
epochs = 20
batchSize = 128
rate = 0.001
mu = 0
sigma = 0.1
| dataset_dir = '../dataset/'
model = '../model/lenet'
model_dir = '../model/'
epochs = 20
batch_size = 128
rate = 0.001
mu = 0
sigma = 0.1 |
"""A board is a list of list of str. For example, the board
ANTT
XSOB
is represented as the list
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
A word list is a list of str. For example, the list of words
ANT
BOX
SOB
TO
is represented as the list
['ANT', 'BOX', 'SOB', 'TO']
"""
def is_va... | """A board is a list of list of str. For example, the board
ANTT
XSOB
is represented as the list
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
A word list is a list of str. For example, the list of words
ANT
BOX
SOB
TO
is represented as the list
['ANT', 'BOX', 'SOB', 'TO']
"""
def is_va... |
# flake8: noqa
_JULIA_V1 = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PythonRuntimeMetadata v1.0",
"description": "PythonRuntimeMetadata runtime/metadata.json schema.",
"type": "object",
"properties": {
"metadata_version": {
"description": "The metadata ver... | _julia_v1 = {'$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'PythonRuntimeMetadata v1.0', 'description': 'PythonRuntimeMetadata runtime/metadata.json schema.', 'type': 'object', 'properties': {'metadata_version': {'description': 'The metadata version.', 'type': 'string'}, 'implementation': {'description... |
# Copyright 2009 Moyshe BenRabi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | class Programfragment(object):
def __init__(self):
self.max_program_name = 25
self.program_name = ''
self.program_major_version = 0
self.program_minor_version = 0
self.protocol_major_version = 0
self.protocol_minor_version = 0
self.protocol_source_revision = ... |
class Singleton:
__instance = None
@classmethod
def __get_instance(cls):
return cls.__instance
@classmethod
def instance(cls, *args, **kargs):
cls.__instance = cls(*args, **kargs)
cls.instance = cls.__get_instance
return cls.__instance
"""""
class MyClass(BaseClass... | class Singleton:
__instance = None
@classmethod
def __get_instance(cls):
return cls.__instance
@classmethod
def instance(cls, *args, **kargs):
cls.__instance = cls(*args, **kargs)
cls.instance = cls.__get_instance
return cls.__instance
'""\nclass MyClass(BaseClass, ... |
test_cases = int(input())
for t in range(1, test_cases + 1):
nums = list(map(int, input().strip().split()))
result = []
for i in range(0, 5):
for j in range(i + 1, 6):
for k in range(j + 1, 7):
result.append(nums[i] + nums[j] + nums[k])
result = sorted(list(set(resul... | test_cases = int(input())
for t in range(1, test_cases + 1):
nums = list(map(int, input().strip().split()))
result = []
for i in range(0, 5):
for j in range(i + 1, 6):
for k in range(j + 1, 7):
result.append(nums[i] + nums[j] + nums[k])
result = sorted(list(set(result... |
# atomic level
def get_idx(list, key):
for idx in range(len(list)):
if key == list[idx][0]:
return idx
def ins(list, key, val):
list.append([key, val])
return list
def ret(list, key):
idx = get_idx(list, key)
return list[idx][1]
def upd(list, key, val):
new_item = [key.... | def get_idx(list, key):
for idx in range(len(list)):
if key == list[idx][0]:
return idx
def ins(list, key, val):
list.append([key, val])
return list
def ret(list, key):
idx = get_idx(list, key)
return list[idx][1]
def upd(list, key, val):
new_item = [key.lower(), val]
... |
class Example:
def __init__(self):
self.name = ""
pass
def greet(self, name):
self.name = name
print("hello " + name)
| class Example:
def __init__(self):
self.name = ''
pass
def greet(self, name):
self.name = name
print('hello ' + name) |
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
i = 0
maxlen = 0
self.longest = {}
while i < len(s):
if s[i] == ")":
i = i + 1
continue
else:
... | class Solution(object):
def longest_valid_parentheses(self, s):
"""
:type s: str
:rtype: int
"""
i = 0
maxlen = 0
self.longest = {}
while i < len(s):
if s[i] == ')':
i = i + 1
continue
else:
... |
#!/usr/bin/env python3
visited = set()
visited.add((0, 0))
turn = 0 # Santa = 0, Robo-Santa = 1
locations = [[0, 0], [0, 0]]
with open('input.txt', 'r') as f:
for line in f:
for ch in line:
pos = locations[turn]
turn = (turn + 1) % 2
if ch == '^':
pos[... | visited = set()
visited.add((0, 0))
turn = 0
locations = [[0, 0], [0, 0]]
with open('input.txt', 'r') as f:
for line in f:
for ch in line:
pos = locations[turn]
turn = (turn + 1) % 2
if ch == '^':
pos[0] += 1
elif ch == 'v':
pos... |
# import pytest
class TestBaseReplacerMixin:
def test_target(self): # synced
assert True
def test_write(self): # synced
assert True
def test_flush(self): # synced
assert True
def test_close(self): # synced
assert True
class TestStdOutReplacerMixin:
def test... | class Testbasereplacermixin:
def test_target(self):
assert True
def test_write(self):
assert True
def test_flush(self):
assert True
def test_close(self):
assert True
class Teststdoutreplacermixin:
def test_target(self):
assert True
class Teststderrrepla... |
# coding: utf8
db.define_table('post',
Field('Email',requires=IS_EMAIL()),
Field('filen','upload'),
auth.signature)
| db.define_table('post', field('Email', requires=is_email()), field('filen', 'upload'), auth.signature) |
class Solution:
def dfs(self,row_cnt:int, col_cnt:int, i:int, j:int, obs_arr:list, solve_dict:dict):
if (i, j) in solve_dict:
return solve_dict[(i,j)]
right_cnt = 0
down_cnt = 0
#right
if i + 1 < row_cnt and not obs_arr[i + 1][j]:
if (i + 1, j) in sol... | class Solution:
def dfs(self, row_cnt: int, col_cnt: int, i: int, j: int, obs_arr: list, solve_dict: dict):
if (i, j) in solve_dict:
return solve_dict[i, j]
right_cnt = 0
down_cnt = 0
if i + 1 < row_cnt and (not obs_arr[i + 1][j]):
if (i + 1, j) in solve_dict... |
class MkDocsTyperException(Exception):
"""
Generic exception class for mkdocs-typer errors.
"""
| class Mkdocstyperexception(Exception):
"""
Generic exception class for mkdocs-typer errors.
""" |
dataset_type = 'ShipRSImageNet_Level2'
# data_root = 'data/Ship_ImageNet/'
data_root = './data/ShipRSImageNet/'
CLASSES = ('Other Ship', 'Other Warship', 'Submarine', 'Aircraft Carrier', 'Cruiser', 'Destroyer',
'Frigate', 'Patrol', 'Landing', 'Commander', 'Auxiliary Ships', 'Other Merchant',
'Con... | dataset_type = 'ShipRSImageNet_Level2'
data_root = './data/ShipRSImageNet/'
classes = ('Other Ship', 'Other Warship', 'Submarine', 'Aircraft Carrier', 'Cruiser', 'Destroyer', 'Frigate', 'Patrol', 'Landing', 'Commander', 'Auxiliary Ships', 'Other Merchant', 'Container Ship', 'RoRo', 'Cargo', 'Barge', 'Tugboat', 'Ferry',... |
def dbapi_subscription(dbsession, action, input_dict, action_filter={}, caller_area={}):
_api_name = "dbapi_subscription"
_api_entity = 'SUBSCRIPTION'
_api_action = action
_api_msgID = set_msgID(_api_name, _api_action, _api_entity)
_process_identity_kwargs = {'type': 'api', 'module': module_id, 'na... | def dbapi_subscription(dbsession, action, input_dict, action_filter={}, caller_area={}):
_api_name = 'dbapi_subscription'
_api_entity = 'SUBSCRIPTION'
_api_action = action
_api_msg_id = set_msg_id(_api_name, _api_action, _api_entity)
_process_identity_kwargs = {'type': 'api', 'module': module_id, 'n... |
def recursiveCalc(n, counter=0, steps=''):
if n<10:
steps += 'Total Steps: ' + str(counter) + '.'
return steps, counter
counter+=1
result = calc(n)
steps += str(result)+', '
return recursiveCalc(result, counter, steps)
def calc(n):
result = 1
while (n>0):
mod = n % 1... | def recursive_calc(n, counter=0, steps=''):
if n < 10:
steps += 'Total Steps: ' + str(counter) + '.'
return (steps, counter)
counter += 1
result = calc(n)
steps += str(result) + ', '
return recursive_calc(result, counter, steps)
def calc(n):
result = 1
while n > 0:
m... |
def ifPossible(a):
while a%2==0:
a/=2
return a
test=int(input())
while test:
a,b = input().split()
a=int(a)
b=int(b)
if a>b:
n=b
b=a
a=n
num=ifPossible(b)
ans=0
if num!=ifPossible(a):
print("-1")
else:
b/=a
while b>=8:
b/=8
ans+=1
if b>1:
ans+=1
print(ans)
test-=1
| def if_possible(a):
while a % 2 == 0:
a /= 2
return a
test = int(input())
while test:
(a, b) = input().split()
a = int(a)
b = int(b)
if a > b:
n = b
b = a
a = n
num = if_possible(b)
ans = 0
if num != if_possible(a):
print('-1')
else:
... |
#!/usr/bin/python3
class Student():
"""Student class with name and age"""
def __init__(self, first_name, last_name, age):
"""initializes new instance of Student"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
"... | class Student:
"""Student class with name and age"""
def __init__(self, first_name, last_name, age):
"""initializes new instance of Student"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
"""returns dict attri... |
def bubble_sort(arr):
swapped = True
while swapped:
swapped = False
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
def selection_sort(arr):
for i in range(len(arr)):
minpos =... | def bubble_sort(arr):
swapped = True
while swapped:
swapped = False
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
(arr[i], arr[i + 1]) = (arr[i + 1], arr[i])
swapped = True
def selection_sort(arr):
for i in range(len(arr)):
minpos ... |
class Project():
def __init__(self, client, project_id=None):
self.client = client
self.project_id = project_id
def get_details(self, project_id=None):
"""
Get information about a specific project
http://developer.dribbble.com/v1/projects/#get-a-project
... | class Project:
def __init__(self, client, project_id=None):
self.client = client
self.project_id = project_id
def get_details(self, project_id=None):
"""
Get information about a specific project
http://developer.dribbble.com/v1/projects/#get-a-project
""... |
class AllennlpReaderToDict:
def __init__(self, **kwargs):
self.kwargs = kwargs
def __call__(self, *args_ignore, **kwargs_ignore):
kwargs = self.kwargs
reader = kwargs.get("reader")
file_path = kwargs.get("file_path")
n_samples = kwargs.get("n_samples")
instances... | class Allennlpreadertodict:
def __init__(self, **kwargs):
self.kwargs = kwargs
def __call__(self, *args_ignore, **kwargs_ignore):
kwargs = self.kwargs
reader = kwargs.get('reader')
file_path = kwargs.get('file_path')
n_samples = kwargs.get('n_samples')
instances... |
def one_hot_encode(_df, _col):
_values = set(_df[_col].values)
for v in _values:
_df[_col + str(v)] = _df[_col].apply(lambda x : float(x == v) )
return _df | def one_hot_encode(_df, _col):
_values = set(_df[_col].values)
for v in _values:
_df[_col + str(v)] = _df[_col].apply(lambda x: float(x == v))
return _df |
class Solution(object):
def sumOddLengthSubarrays(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
# Runtime: 32 ms
# Memory: 13.4 MB
prefix_sum = []
last_sum = 0
for item in arr:
last_sum += item
prefix_sum.append(... | class Solution(object):
def sum_odd_length_subarrays(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
prefix_sum = []
last_sum = 0
for item in arr:
last_sum += item
prefix_sum.append(last_sum)
total = sum(arr)
for s... |
"""
This code was written by JonECope
Using Python 3035 in Processing 3.3.7
"""
color_choice = color(0, 0, 0)
circ = True
instructions = "Press Mouse to draw, Right-click to erase, Q to exit, R, O, Y, G, B, V for colors. Press S for square brush or C for circle brush. Press Enter to save."
def setup():
#size(800, 8... | """
This code was written by JonECope
Using Python 3035 in Processing 3.3.7
"""
color_choice = color(0, 0, 0)
circ = True
instructions = 'Press Mouse to draw, Right-click to erase, Q to exit, R, O, Y, G, B, V for colors. Press S for square brush or C for circle brush. Press Enter to save.'
def setup():
full_screen... |
def differ(string_1, string_2):
new_string = ""
for i in range(len(string_1)):
if string_1[i] == string_2[i]:
new_string += string_1[i]
return new_string
def main():
f = [line.rstrip("\n") for line in open("Data.txt")]
for i in range(len(f)):
for j in range(i + 1, len... | def differ(string_1, string_2):
new_string = ''
for i in range(len(string_1)):
if string_1[i] == string_2[i]:
new_string += string_1[i]
return new_string
def main():
f = [line.rstrip('\n') for line in open('Data.txt')]
for i in range(len(f)):
for j in range(i + 1, len(f)... |
class Car(object):
# setting some default values
num_of_doors = 4
num_of_wheels = 4
def __init__(self, name='General', model='GM', car_type='saloon', speed=0):
self.name = name
self.model = model
self.car_type = car_type
self.speed = speed
if self.name is 'Porshe... | class Car(object):
num_of_doors = 4
num_of_wheels = 4
def __init__(self, name='General', model='GM', car_type='saloon', speed=0):
self.name = name
self.model = model
self.car_type = car_type
self.speed = speed
if self.name is 'Porshe' or self.name is 'Koenigsegg':
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.