content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Config(object):
DEBUG = True
# Define the database
SQLALCHEMY_DATABASE_URI = '{}://{}:{}@{}'.format('mysql+pymysql', 'root', '1234',
'192.168.10.22:3306/boilerplate')
DATABASE_CONNECT_OPTIONS = {}
SQLALCHEMY_TRACK_MODIFICATIONS = False
... | class Config(object):
debug = True
sqlalchemy_database_uri = '{}://{}:{}@{}'.format('mysql+pymysql', 'root', '1234', '192.168.10.22:3306/boilerplate')
database_connect_options = {}
sqlalchemy_track_modifications = False
sqlalchemy_echo = True |
# You're on your way to the market when you hear beautiful music coming from a nearby street performer. The notes come together like you wouln't believe as the musician puts together patterns of tunes. As you wonder what kind of algorithm you could use to shift octaves by 8 pitches or something silly like that, it dawn... | def is_lock_ness_monster(string):
if 'tree fiddy' in string:
return True
if 'three fifty' in string:
return True
if '3.50' in string:
return True
return False |
# Automatically generated by pb2py
# fmt: off
UnexpectedMessage = 1
ButtonExpected = 2
DataError = 3
ActionCancelled = 4
PinExpected = 5
PinCancelled = 6
PinInvalid = 7
InvalidSignature = 8
ProcessError = 9
NotEnoughFunds = 10
NotInitialized = 11
PinMismatch = 12
FirmwareError = 99
| unexpected_message = 1
button_expected = 2
data_error = 3
action_cancelled = 4
pin_expected = 5
pin_cancelled = 6
pin_invalid = 7
invalid_signature = 8
process_error = 9
not_enough_funds = 10
not_initialized = 11
pin_mismatch = 12
firmware_error = 99 |
def compoundInterest(principle, time, rate):
print("Principle is : ",principle)
print("Time is : ",time)
print("Rate is : ",rate)
A=principle*pow((1+rate/100),time)
CI=A-principle
print("compound Interest is : ",CI)
compoundInterest(1200,2,5.4)
| def compound_interest(principle, time, rate):
print('Principle is : ', principle)
print('Time is : ', time)
print('Rate is : ', rate)
a = principle * pow(1 + rate / 100, time)
ci = A - principle
print('compound Interest is : ', CI)
compound_interest(1200, 2, 5.4) |
def slowest(orders):
brokers_second = []
for i in range(len(orders)):
b_second = [orders[i][0]]
if i == 0:
time = orders[i][1]
b_second.append(time)
else:
time = orders[i][1] - orders[i-1][1]
b_second.append(time)
brokers_second.app... | def slowest(orders):
brokers_second = []
for i in range(len(orders)):
b_second = [orders[i][0]]
if i == 0:
time = orders[i][1]
b_second.append(time)
else:
time = orders[i][1] - orders[i - 1][1]
b_second.append(time)
brokers_second.a... |
"""
Structures of the Shell Link Binary File Format can define strings in
fixed-length fields, strings MUST be null-terminated. If a string is smaller
than the size of the field that contains it, the bytes in the field following
the terminating null character are undefined and can have any value. The
undefined bytes MU... | """
Structures of the Shell Link Binary File Format can define strings in
fixed-length fields, strings MUST be null-terminated. If a string is smaller
than the size of the field that contains it, the bytes in the field following
the terminating null character are undefined and can have any value. The
undefined bytes MU... |
class Writer:
"""
Abstract class that encapsulates a writing a row to an output.
Subclasses should implement the "write_row" method.
"""
def write_row(self):
raise NotImplementedError | class Writer:
"""
Abstract class that encapsulates a writing a row to an output.
Subclasses should implement the "write_row" method.
"""
def write_row(self):
raise NotImplementedError |
class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
d = {}
for i in edges:
head, tail = min(i[0],i[1]), max(i[0],i[1])
if head not in d:
d[head] = deque()
d[head].append(tail)
print(d)
... | class Solution:
def frog_position(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
d = {}
for i in edges:
(head, tail) = (min(i[0], i[1]), max(i[0], i[1]))
if head not in d:
d[head] = deque()
d[head].append(tail)
print(... |
width = int(input())
while width % 2 == 0:
text = input()
totalDots = chr(46) * (width - len(text))
halfDots = int(width / 2)
halfLen = len(text) / 2
firstDots = chr(46) * (halfDots - int(halfLen))
secondDots = chr(46) * (halfDots - int(halfLen))
if text == "END":
break
... | width = int(input())
while width % 2 == 0:
text = input()
total_dots = chr(46) * (width - len(text))
half_dots = int(width / 2)
half_len = len(text) / 2
first_dots = chr(46) * (halfDots - int(halfLen))
second_dots = chr(46) * (halfDots - int(halfLen))
if text == 'END':
break
elif... |
# By Kamran Bigdely Nov. 2020
# Move Field (attribute)
# Refactored.
class Gun:
def __init__(self, name):
self.name = name
self.num_cathridge_bullet = 0
def shoot(self):
if self.num_cathridge_bullet <= 0:
return False
print('shoot')
self.num_c... | class Gun:
def __init__(self, name):
self.name = name
self.num_cathridge_bullet = 0
def shoot(self):
if self.num_cathridge_bullet <= 0:
return False
print('shoot')
self.num_cathridge_bullet -= 1
return True
def reload(self):
print('reloa... |
class Solution(object):
def getMaximumGold(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# early check
if not grid or len(grid) == 0:
return 0
global_max = 0
visited = [[False for j in range(len(grid[0]))] for i ... | class Solution(object):
def get_maximum_gold(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or len(grid) == 0:
return 0
global_max = 0
visited = [[False for j in range(len(grid[0]))] for i in range(len(grid))]
for... |
class Solution:
def numDecodings(self, s: str) -> int:
values = dict()
def decode(s,values):
if s in values:
return values[s]
n = len(s)
if n==0:
ans = 1
values[s] = ans
return ans
x = int... | class Solution:
def num_decodings(self, s: str) -> int:
values = dict()
def decode(s, values):
if s in values:
return values[s]
n = len(s)
if n == 0:
ans = 1
values[s] = ans
return ans
x... |
def get_power_set(s):
"""
Returns a list of all possible subsets of the given set s.
"""
#---------------------------------------------------------------------------
# Version 1: The input s is stored as a set. Recursive.
#-------------------------------------------------------------------------... | def get_power_set(s):
"""
Returns a list of all possible subsets of the given set s.
"""
subsets = []
m = 1 << len(s)
for i in range(m):
subsets.append([s[j] for j in range(len(s)) if i >> j & 1 == 1])
return subsets
def main():
test_sets = [[], [1], [1, 2], [1, 2, 3], [1, 2, 3,... |
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if (len(s)>1):
temp =s[0]
templ=len(temp)
bestl= 1
best =s[0]
i=0
for j in range(1,len(s)):
... | class Solution(object):
def length_of_longest_substring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) > 1:
temp = s[0]
templ = len(temp)
bestl = 1
best = s[0]
i = 0
for j in range(1, len(s)):
... |
_temperament_names = {
'SP': ['Artisan', 'Creator'],
'SJ': ['Guardian', 'Protector'],
'NF': ['Idealist', 'Visionary'],
'NT': ['Rational', 'Intellectual']
}
_personality_type_names = {
'SP': {
'ESFP': ['Performer', 'Entertainer', 'Performer'],
'ESTP': ['Promoter', 'Persuader', 'Doer'],
'ISFP': ['Composer', '... | _temperament_names = {'SP': ['Artisan', 'Creator'], 'SJ': ['Guardian', 'Protector'], 'NF': ['Idealist', 'Visionary'], 'NT': ['Rational', 'Intellectual']}
_personality_type_names = {'SP': {'ESFP': ['Performer', 'Entertainer', 'Performer'], 'ESTP': ['Promoter', 'Persuader', 'Doer'], 'ISFP': ['Composer', 'Artist', 'Artist... |
"""https://app.codesignal.com/interview-practice/task/rMe9ypPJkXgk3MHhZ
You have a collection of coins, and you know the values of the coins
and the quantity of each type of coin in it. You want to know how many
distinct sums you can make from non-empty groupings of these coins.
Example
For coins = [10, 50, 100] and... | """https://app.codesignal.com/interview-practice/task/rMe9ypPJkXgk3MHhZ
You have a collection of coins, and you know the values of the coins
and the quantity of each type of coin in it. You want to know how many
distinct sums you can make from non-empty groupings of these coins.
Example
For coins = [10, 50, 100] and... |
df = WyomingUpperAir.request_data(datetime(2017, 9, 10, 0), 'KEY')
p = df['pressure'].values * units(df.units['pressure'])
T = df['temperature'].values * units(df.units['temperature'])
Td = df['dewpoint'].values * units(df.units['dewpoint'])
u = df['u_wind'].values * units(df.units['u_wind'])
v = df['v_wind'].values *... | df = WyomingUpperAir.request_data(datetime(2017, 9, 10, 0), 'KEY')
p = df['pressure'].values * units(df.units['pressure'])
t = df['temperature'].values * units(df.units['temperature'])
td = df['dewpoint'].values * units(df.units['dewpoint'])
u = df['u_wind'].values * units(df.units['u_wind'])
v = df['v_wind'].values * ... |
# -*-coding:utf-8 -*-
#
# Copyright (C) 2012-2015 Lianbi TECH Co., Ltd. All rights reserved.
# Created on 2015-03-09, by $USER
#
#
__author__ = 'Danny'
| __author__ = 'Danny' |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
class McrouterGlobals:
@staticmethod
def binPath(name):
bins = {
'mcrouter': './mcrouter/mc... | class Mcrouterglobals:
@staticmethod
def bin_path(name):
bins = {'mcrouter': './mcrouter/mcrouter', 'mcpiper': './mcrouter/tools/mcpiper/mcpiper', 'mockmc': './mcrouter/lib/network/test/mock_mc_server', 'prodmc': './mcrouter/lib/network/test/mock_mc_server'}
return bins[name]
@staticmethod... |
n=str(input('Digite um nome: '))
if (n.upper().find('SILVA') != (-1)):
print('True')
else:
print('False') | n = str(input('Digite um nome: '))
if n.upper().find('SILVA') != -1:
print('True')
else:
print('False') |
exam_st_date = (11, 12, 2014)
day = exam_st_date[0]
month = exam_st_date[1]
year = exam_st_date[2]
print("The examination will start from:",day, "/",month,"/",year) | exam_st_date = (11, 12, 2014)
day = exam_st_date[0]
month = exam_st_date[1]
year = exam_st_date[2]
print('The examination will start from:', day, '/', month, '/', year) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 14 13:48:42 2018
@author: efrem
"""
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
result = 0
for list in aDict.values():
resul... | """
Created on Wed Feb 14 13:48:42 2018
@author: efrem
"""
def how_many(aDict):
"""
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
"""
result = 0
for list in aDict.values():
result += len(list)
return result |
class A:
def a(self):
return 'b'
try:
object
except NameError:
pass
else:
class B(A, object):
def b(self):
return 'c'
class Inherit(A):
def a(self):
return 'd'
| class A:
def a(self):
return 'b'
try:
object
except NameError:
pass
else:
class B(A, object):
def b(self):
return 'c'
class Inherit(A):
def a(self):
return 'd' |
num_1 = 10
num_2 = 10
test1= "mauricio"
test2="maurici"
mayor = num_1 > num_2
menor = num_1 < num_2
mayor_igual = num_1 >= num_2
menor_igual = num_1 <= num_2
igual = num_1 == num_2
# para validar que dos valores son iguales puedes utiliza == o is -> funciona con strings? si
igual_is = test1 is test2
difere... | num_1 = 10
num_2 = 10
test1 = 'mauricio'
test2 = 'maurici'
mayor = num_1 > num_2
menor = num_1 < num_2
mayor_igual = num_1 >= num_2
menor_igual = num_1 <= num_2
igual = num_1 == num_2
igual_is = test1 is test2
diferente = num_1 != num_2
print(mayor)
print(menor)
print(mayor_igual)
print(menor_igual)
print(igual)
print(... |
#sd.baseline = [ring_curr, gcpress,
#epu1.gap, epu1.phase,
#feslt.hc, feslt.vc, feslt.hg, feslt.vg,
#m1.x, m1.pit, m1.rol,
#pgm.cff, pgm.en, pgm.grx, pgm.m2pit, pgm.grpit, pgm.grlines,
#m3slt.hs, m3slt.ha, m3slt.vs, m3slt.va,
#m3diag,
#m3.x, m3.y, m3.z, m3.yaw, m3.pit, m3.rol,
#extslt.hg, extslt.vg, extslt.hc,
#gc... | sd.baseline = [ring_curr, gcpress, epu1, feslt, m1, pgm, m3slt, m3diag, m3, extslt, gcdiag, m4_diag1, m4slt, m4, cryo, stemp, ow, m5, m5mask, m6_msk, m6, espgm.m7pit, espgm.grpit, espgm.grxrb, espgmmask, oc, dcslt, dc] |
def play():
print("****************************")
print("Welcome to the Hangaman Game")
print("****************************")
secret_word = "vitor"
hanged = False
hit = False
while (not hanged and not hit):
attempt = input("What's the letter? ")
attempt = attempt.strip()
... | def play():
print('****************************')
print('Welcome to the Hangaman Game')
print('****************************')
secret_word = 'vitor'
hanged = False
hit = False
while not hanged and (not hit):
attempt = input("What's the letter? ")
attempt = attempt.strip()
... |
def some_other_function():
assert scope.get('foo') == 'bar'
# we can access the "current scope"
current_scope = scope.get_current_scope()
# and use it like a dict
assert current_scope['foo'] == 'bar'
def main():
# the my_scope variable is now defined
# inside a function scope, so it is n... | def some_other_function():
assert scope.get('foo') == 'bar'
current_scope = scope.get_current_scope()
assert current_scope['foo'] == 'bar'
def main():
my_scope = scope.Scope()
my_scope['foo'] = 'bar'
with my_scope():
some_other_function()
main() |
def mean_longitude(t: float) -> float:
"""
Calculate the sun's mean longitude in decimal degrees.
Parameters:
t (float): The time in Julian Centuries (36525 days) since J2000.0
Returns:
float: The sun's mean longitude at the given time
"""
# t must be in the range fro... | def mean_longitude(t: float) -> float:
"""
Calculate the sun's mean longitude in decimal degrees.
Parameters:
t (float): The time in Julian Centuries (36525 days) since J2000.0
Returns:
float: The sun's mean longitude at the given time
"""
if t < -0.99 or 1.0 < t:
raise... |
"""
#!/bin/bash
secs_to_human() {
echo "$(( ${1} / 3600 ))h $(( (${1} / 60) % 60 ))m $(( ${1} % 60 ))s"
}
SKIPSTEPS=0
TMPDIR=/data/kite/tmp
for i in "$@"
do
case $i in
--model=*)
MODEL="${i#*=}"
shift # past argument=value
;;
--lang=*)
LANG="${i#*=}"
shift # past argument=value
;;... | """
#!/bin/bash
secs_to_human() {
echo "$(( ${1} / 3600 ))h $(( (${1} / 60) % 60 ))m $(( ${1} % 60 ))s"
}
SKIPSTEPS=0
TMPDIR=/data/kite/tmp
for i in "$@"
do
case $i in
--model=*)
MODEL="${i#*=}"
shift # past argument=value
;;
--lang=*)
LANG="${i#*=}"
shift # past argument=value
;;... |
"""
SQLAlchemy Owner model class
"""
def init(db):
class Owner(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True, nullable=False)
def __repr__(self):
return f'<Owner {self.name}>'
def as_dict(self):
d = {
... | """
SQLAlchemy Owner model class
"""
def init(db):
class Owner(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True, nullable=False)
def __repr__(self):
return f'<Owner {self.name}>'
def as_dict(self):
d = {'... |
n = int(input())
for i in range(n):
num = float(input())
contDias = 0
while(num / 2 > 1):
contDias = contDias + 1
num = num / 2
print("{} dias".format(contDias + 1)) | n = int(input())
for i in range(n):
num = float(input())
cont_dias = 0
while num / 2 > 1:
cont_dias = contDias + 1
num = num / 2
print('{} dias'.format(contDias + 1)) |
class Vrchol:
def __init__(self, px, py, psize, pid, pinfo = ''):
self.size = psize
self.x = px
self.y = py
self.info = pinfo
self.sus = []
self.farba = "#FFFFFF"
self.rozliaty = False
self.id = pid
def vykresli(self,cnv):
for i in range(l... | class Vrchol:
def __init__(self, px, py, psize, pid, pinfo=''):
self.size = psize
self.x = px
self.y = py
self.info = pinfo
self.sus = []
self.farba = '#FFFFFF'
self.rozliaty = False
self.id = pid
def vykresli(self, cnv):
for i in range(l... |
my_dict = {'a':[0, 1, 2, 3], 'b':[0, 1, 2, 3], 'c':[0, 1, 2, 3], 'd':[0, 1, 2, 3]}
i = 0
output = []
for key in my_dict:
output.append(my_dict[key][i])
i += 1
print(output) | my_dict = {'a': [0, 1, 2, 3], 'b': [0, 1, 2, 3], 'c': [0, 1, 2, 3], 'd': [0, 1, 2, 3]}
i = 0
output = []
for key in my_dict:
output.append(my_dict[key][i])
i += 1
print(output) |
while(True):
s0,s1, r0,r1 = map(int,input().split())
if not(s0):
exit()
S0,S1=min(s0,s1),max(s0,s1)
R0,R1=min(r0,r1),max(r0,r1)
if S0+S1==3 and R0+R1==3:
print("Tie.")
elif S0+S1==3:
print("Player 1 wins.")
elif R0+R1==3:
print("Player 2 wins.")
elif S0==... | while True:
(s0, s1, r0, r1) = map(int, input().split())
if not s0:
exit()
(s0, s1) = (min(s0, s1), max(s0, s1))
(r0, r1) = (min(r0, r1), max(r0, r1))
if S0 + S1 == 3 and R0 + R1 == 3:
print('Tie.')
elif S0 + S1 == 3:
print('Player 1 wins.')
elif R0 + R1 == 3:
... |
'''
Let's do some simple tasks for your homework. This week, we'll do some practice using what we learned about functions
and conditional blocks to make some useful, reusable code! First, let's start by writing a function called plus_five
which takes a number and prints out that number plus five.
'''
def plus_five(x):... | """
Let's do some simple tasks for your homework. This week, we'll do some practice using what we learned about functions
and conditional blocks to make some useful, reusable code! First, let's start by writing a function called plus_five
which takes a number and prints out that number plus five.
"""
def plus_five(x):... |
# pylint: skip-file
# flake8: noqa
class Repoquery(RepoqueryCLI):
''' Class to wrap the repoquery
'''
# pylint: disable=too-many-arguments
def __init__(self, name, query_type, show_duplicates,
match_version, verbose):
''' Constructor for YumList '''
super(Repoquery, se... | class Repoquery(RepoqueryCLI):
""" Class to wrap the repoquery
"""
def __init__(self, name, query_type, show_duplicates, match_version, verbose):
""" Constructor for YumList """
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.... |
maximum = 20
count = maximum
found = False
while(not found):
for x in range(1,maximum+1):
if(count % x != 0):
break
if(x == maximum):
found = True
if(not found):
count += maximum
print(count)
| maximum = 20
count = maximum
found = False
while not found:
for x in range(1, maximum + 1):
if count % x != 0:
break
if x == maximum:
found = True
if not found:
count += maximum
print(count) |
load("//dependencies/navx/4_0_425:deps.bzl", "setup_navx_4_0_425_dependencies")
load("//dependencies/navx/4_0_435:deps.bzl", "setup_navx_4_0_435_dependencies")
load("//dependencies/navx/4_0_442:deps.bzl", "setup_navx_4_0_442_dependencies")
def setup_navx_dependencies(version):
if version == "4.0.425":
setu... | load('//dependencies/navx/4_0_425:deps.bzl', 'setup_navx_4_0_425_dependencies')
load('//dependencies/navx/4_0_435:deps.bzl', 'setup_navx_4_0_435_dependencies')
load('//dependencies/navx/4_0_442:deps.bzl', 'setup_navx_4_0_442_dependencies')
def setup_navx_dependencies(version):
if version == '4.0.425':
setu... |
class Solution:
def predictPartyVictory(self, senate: str) -> str:
qr = collections.deque()
qd = collections.deque()
for i, ch in enumerate(senate):
if ch == 'R':
qr.append(i)
else:
qd.append(i)
n = len(senate)
while qr ... | class Solution:
def predict_party_victory(self, senate: str) -> str:
qr = collections.deque()
qd = collections.deque()
for (i, ch) in enumerate(senate):
if ch == 'R':
qr.append(i)
else:
qd.append(i)
n = len(senate)
whil... |
class CtMap:
"""
A cache implemented map using linear lists. This is a hold over from the javascript library when we couldn't be sure
that a student's javascript could use maps.
The design pattern used in this map is to always used the cached key/associated index. So methods accessing values
will f... | class Ctmap:
"""
A cache implemented map using linear lists. This is a hold over from the javascript library when we couldn't be sure
that a student's javascript could use maps.
The design pattern used in this map is to always used the cached key/associated index. So methods accessing values
will f... |
meal_cost = float(input())
tip_percent = int(input())
tax_percent = int(input())
tip = meal_cost * tip_percent / 100
tax = meal_cost * tax_percent / 100
total = meal_cost + tip + tax
print(int(round(total)))
| meal_cost = float(input())
tip_percent = int(input())
tax_percent = int(input())
tip = meal_cost * tip_percent / 100
tax = meal_cost * tax_percent / 100
total = meal_cost + tip + tax
print(int(round(total))) |
{
"targets": [
{
"target_name": "wtf8",
"sources": [ "wtf8.cc" ],
"include_dirs" : [
"<!(node -e \"require('nan')\")"
]
}
]
} | {'targets': [{'target_name': 'wtf8', 'sources': ['wtf8.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")']}]} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Ian'
__create_date__ = '2015/1/8'
## opensubtitles
LANGUAGE_MATRIX = []
f = open('MainMenu.strings', 'r')
f.readline()
for l in f:
str = l.decode('utf-8').strip()
if not str.startswith("/*"):
LANGUAGE_MATRIX.append(str)
f.close()
fw = open(... | __author__ = 'Ian'
__create_date__ = '2015/1/8'
language_matrix = []
f = open('MainMenu.strings', 'r')
f.readline()
for l in f:
str = l.decode('utf-8').strip()
if not str.startswith('/*'):
LANGUAGE_MATRIX.append(str)
f.close()
fw = open('MainMenu_opt.strings', 'wb')
for str in LANGUAGE_MATRIX:
if st... |
line = input()
line_pal = line[::-1]
if line_pal == line:
print("Yes")
else:
print("No")
| line = input()
line_pal = line[::-1]
if line_pal == line:
print('Yes')
else:
print('No') |
"""
Copyright 2020 The Microsoft DeepSpeed Team
"""
#########################################
# Elasticity
#########################################
''' Elasticity Utility in DeepSpeed can be used to create highly elastic jobs compatible
with a large number of GPUs. For elastic jobs, DeepSpeed will provide a batch siz... | """
Copyright 2020 The Microsoft DeepSpeed Team
"""
' Elasticity Utility in DeepSpeed can be used to create highly elastic jobs compatible\nwith a large number of GPUs. For elastic jobs, DeepSpeed will provide a batch size that\ncan support a large number of GPUs based on the user specified parameters\n'
format = '\nEl... |
class EndPoint:
def __init__(self, end_point_json):
self.id = end_point_json["_postman_id"]
self.name = end_point_json["name"]
self.authentication = end_point_json["request"].get("auth")
self.method = end_point_json["request"]["method"]
self.header = end_point_json["request"]... | class Endpoint:
def __init__(self, end_point_json):
self.id = end_point_json['_postman_id']
self.name = end_point_json['name']
self.authentication = end_point_json['request'].get('auth')
self.method = end_point_json['request']['method']
self.header = end_point_json['request'... |
# -*- coding: utf-8 -*-
"""
gspread.ns
~~~~~~~~~~
This module contains namespaces used across the project and related
helper functions.
"""
ATOM_NS = 'http://www.w3.org/2005/Atom'
SPREADSHEET_NS = 'http://schemas.google.com/spreadsheets/2006'
EXTENDED_SPREADSHEET_NS = 'http://schemas.google.com/spreadsheets/2006/ex... | """
gspread.ns
~~~~~~~~~~
This module contains namespaces used across the project and related
helper functions.
"""
atom_ns = 'http://www.w3.org/2005/Atom'
spreadsheet_ns = 'http://schemas.google.com/spreadsheets/2006'
extended_spreadsheet_ns = 'http://schemas.google.com/spreadsheets/2006/extended'
batch_ns = 'http:/... |
class Solution:
def shortestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) <= 1:
return s
for i in range(len(s)//2, -1, -1):
# mid
if s[:i][::-1] == s[i+1:2*i+1]:
return s[i+1:][::-1] + s[i] + s[i+1:... | class Solution:
def shortest_palindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) <= 1:
return s
for i in range(len(s) // 2, -1, -1):
if s[:i][::-1] == s[i + 1:2 * i + 1]:
return s[i + 1:][::-1] + s[i] + s[i + 1:]
... |
#!/usr/bin/env qork
FONT = "./data/PressStart2P-Regular.ttf:64"
canvas.font(FONT)
def script(ctx):
canvas.text("Health: |||||", anchor="", align="l")
player = add("spirit.cson", scale=1 / 16)
player.state["stance"] = "walk"
player.rotate(0.125, X)
player.z = 1 / 16
camera.fov = 0.09
player.y = 2.5 / 16
camera.... | font = './data/PressStart2P-Regular.ttf:64'
canvas.font(FONT)
def script(ctx):
canvas.text('Health: |||||', anchor='', align='l')
player = add('spirit.cson', scale=1 / 16)
player.state['stance'] = 'walk'
player.rotate(0.125, X)
player.z = 1 / 16
camera.fov = 0.09
player.y = 2.5 / 16
camera.mode = '3D'
camera.y = -... |
class Solution:
def check(self, i, haystack, needle):
for j in range(len(needle)):
if haystack[i] != needle[j]:
return False
i += 1
return True
def strStr(self, haystack: str, needle: str) -> int:
len_haystack = len(haystack)
... | class Solution:
def check(self, i, haystack, needle):
for j in range(len(needle)):
if haystack[i] != needle[j]:
return False
i += 1
return True
def str_str(self, haystack: str, needle: str) -> int:
len_haystack = len(haystack)
len_needle ... |
#42 Frequency to note
#Asking for frequency of note
x = float(input("Enter the frequency of note = "))
if x == 261.63:
print("The note of frequency is C4.")
elif x == 293.66:
print("The note of frequency is D4.")
elif x == 329.63:
print("the note of frequency is E4.")
elif x == 349.23:
print("... | x = float(input('Enter the frequency of note = '))
if x == 261.63:
print('The note of frequency is C4.')
elif x == 293.66:
print('The note of frequency is D4.')
elif x == 329.63:
print('the note of frequency is E4.')
elif x == 349.23:
print('The note of frequency is F4.')
elif x == 392.0:
print('The... |
class PeerPingProtocol(basestring):
"""
The network protocol to use when performing the ping operation.
Possible values:
<ul>
<li> "data" - Data Ping,
<li> "icmp" - ICMP Ping
</ul>
"""
@staticmethod
def get_api_name():
return "peer-ping-protocol"
| class Peerpingprotocol(basestring):
"""
The network protocol to use when performing the ping operation.
Possible values:
<ul>
<li> "data" - Data Ping,
<li> "icmp" - ICMP Ping
</ul>
"""
@staticmethod
def get_api_name():
return 'peer-ping-protocol' |
numeros = list()
test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("digite 10 numeros")
#"""
for i in range(10):
numeros.append(int(input()))
pass
print(numeros)
#"""
#para teste rapido.
#numeros = test
#print(numeros)
media = 0
for num in numeros:
media += num
pass
media /= 10
print("A media foi... | numeros = list()
test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print('digite 10 numeros')
for i in range(10):
numeros.append(int(input()))
pass
print(numeros)
media = 0
for num in numeros:
media += num
pass
media /= 10
print('A media foi de: ' + str(media))
acima_media = list()
for num in numeros:
if num >... |
# _page_layout.html: Autogenerated file start
def render(name,header,footer,layout,vars):
yield """<!DOCTYPE html>
<html lang=\"en\">
"""
# _html_head.html: Autogenerated file start
def render1(name):
yield """<head>
<meta charset='utf-8'/>
<meta name='viewport' content='width=device-width, init... | def render(name, header, footer, layout, vars):
yield '<!DOCTYPE html>\n<html lang="en">\n'
def render1(name):
yield "<head>\n <meta charset='utf-8'/>\n <meta name='viewport' content='width=device-width, initial-scale=1.0'>\n <title>Fellsafe CP"
if name is not None:
yield '... |
print('curl localhost:10101/index/test/query -X POST -d \'')
for i in range(1,51):
for j in range(0,100):
print('Count(Row(c'+str(i)+'=a'+str(j)+'))')
print('\'')
| print("curl localhost:10101/index/test/query -X POST -d '")
for i in range(1, 51):
for j in range(0, 100):
print('Count(Row(c' + str(i) + '=a' + str(j) + '))')
print("'") |
class JenkinsMetadata(object):
""" This class is the model of the Jenkins data relating to the build that ran the tests or collected the metrics.
This class is how the model is represented in the HTTP API """
def __init__(self, jenkins_job_id):
self.jenkins_job_id = jenkins_job_id
| class Jenkinsmetadata(object):
""" This class is the model of the Jenkins data relating to the build that ran the tests or collected the metrics.
This class is how the model is represented in the HTTP API """
def __init__(self, jenkins_job_id):
self.jenkins_job_id = jenkins_job_id |
"""
Given an array arr, replace every element in that array with the greatest
element among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
"""
#Difficulty: Easy
#15 / 15 test cases... | """
Given an array arr, replace every element in that array with the greatest
element among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
"""
class Solution:
def replace_ele... |
def registerPredefined(modules_avail):
for m in ["modules", "events", "info", "settings"]:
module_name_id = 'miniflask.' + m
importname = 'miniflask.modules.' + m
modules_avail[module_name_id] = {
'id': module_name_id,
'importpath': "system",
'importname'... | def register_predefined(modules_avail):
for m in ['modules', 'events', 'info', 'settings']:
module_name_id = 'miniflask.' + m
importname = 'miniflask.modules.' + m
modules_avail[module_name_id] = {'id': module_name_id, 'importpath': 'system', 'importname': importname, 'lowpriority': False} |
h, w = [int(x) for x in input().split(' ')]
c = int(input())
h += (w + c) // 60
w = (w + c) % 60
h %= 24
print(h, w) | (h, w) = [int(x) for x in input().split(' ')]
c = int(input())
h += (w + c) // 60
w = (w + c) % 60
h %= 24
print(h, w) |
class Solution:
def maxProfit(self, prices):
if not prices:
return 0
ascents = []
lower = prices[0]
upper = prices[0]
res = 0
for i in prices:
if i > upper:
upper = i
elif i < upper:
ascents.append(... | class Solution:
def max_profit(self, prices):
if not prices:
return 0
ascents = []
lower = prices[0]
upper = prices[0]
res = 0
for i in prices:
if i > upper:
upper = i
elif i < upper:
ascents.append(... |
# Title : Count the number of element list of a list
# Author : Kiran raj R.
# Date : 25:10:2020
list1 = [[1, 2], 3, 4, [5, 6], 7, [8, 9, 10]]
list2 = [('a', 'b'), 'c', 'd', 'e', ['f', 'g', 'h']]
print(f"Number of elements in list1 {len(list1)}")
print(f"Number of elements in list2 {len(list2)}")
def list_in_lis... | list1 = [[1, 2], 3, 4, [5, 6], 7, [8, 9, 10]]
list2 = [('a', 'b'), 'c', 'd', 'e', ['f', 'g', 'h']]
print(f'Number of elements in list1 {len(list1)}')
print(f'Number of elements in list2 {len(list2)}')
def list_in_list(list_name):
return sum((type(elem) == type([]) for elem in list_name))
print(f'Number of list ins... |
# String replacement / substitution
welcome_message = 'Hello World!'
print(welcome_message.replace("Hello", "Goodbye"))
# Generating multiple strings
print('*' * 10)
print('Hi' * 10)
# Testing strings containing another string
print('Edward Alan Rawlings'.find('Alan'))
print('Edward John Rawlings'.find('Alan'))
prin... | welcome_message = 'Hello World!'
print(welcome_message.replace('Hello', 'Goodbye'))
print('*' * 10)
print('Hi' * 10)
print('Edward Alan Rawlings'.find('Alan'))
print('Edward John Rawlings'.find('Alan'))
print('James' == 'James')
print('James' == 'John')
print('James' != 'John')
print('James' == 'james')
some_string = '... |
total = 0
for i in range(1,1000):
if i % 3 ==0 or i %5 ==0:
total += i
print(total)
| total = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
total += i
print(total) |
__version__ = "2.1.5"
default_app_config = "channels.apps.ChannelsConfig"
DEFAULT_CHANNEL_LAYER = "default"
| __version__ = '2.1.5'
default_app_config = 'channels.apps.ChannelsConfig'
default_channel_layer = 'default' |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:Joselyn Zhao
@CONTACT:zhaojing17@foxmail.com
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:lianbiao.py
@TIME:2020/5/12 20:53
@DES:
'''
class Node:
def __init__(self,data,pnext=None):
self.data = data
self._next=pnext
def __repr__(self)... | """
@AUTHOR:Joselyn Zhao
@CONTACT:zhaojing17@foxmail.com
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:lianbiao.py
@TIME:2020/5/12 20:53
@DES:
"""
class Node:
def __init__(self, data, pnext=None):
self.data = data
self._next = pnext
def __repr__(self):
return str(self.data) |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 17:11:20 2021
@author: Patricia
"""
print= "Hello, World!"
idade= int(input("digite a idade:"))
if idade>=7 and idade<=9:
print("infantil A")
elif idade>=8 and idade<= 12:
print(" infantil B")
elif idade>=13 and idade<= 15:
print("juvenil A")
elif idade>= ... | """
Created on Thu Sep 9 17:11:20 2021
@author: Patricia
"""
print = 'Hello, World!'
idade = int(input('digite a idade:'))
if idade >= 7 and idade <= 9:
print('infantil A')
elif idade >= 8 and idade <= 12:
print(' infantil B')
elif idade >= 13 and idade <= 15:
print('juvenil A')
elif idade >= 15 and idade... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"names": "10_pref.ipynb",
"short_names": "10_pref.ipynb",
"df": "10_pref.ipynb",
"__code2name": "10_pref.ipynb",
"__name2code": "10_pref.ipynb",
"name2code": "10_p... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'names': '10_pref.ipynb', 'short_names': '10_pref.ipynb', 'df': '10_pref.ipynb', '__code2name': '10_pref.ipynb', '__name2code': '10_pref.ipynb', 'name2code': '10_pref.ipynb', 'code2name': '10_pref.ipynb'}
modules = ['prefecture.py']
doc_url = 'https... |
# coding: utf-8
["DEFAULT"]
max_tempfile_number = 100
max_thread_num = 8
["account"]
username = ""
password = ""
["proxies"]
proxies_enable = False
socks = ""
["path"]
local_save_root = "./default_save/"
temp_save_root = "./temp_save/"
["data"]
garage_file = "./garage.txt"
cookies_file = "./cooki... | ['DEFAULT']
max_tempfile_number = 100
max_thread_num = 8
['account']
username = ''
password = ''
['proxies']
proxies_enable = False
socks = ''
['path']
local_save_root = './default_save/'
temp_save_root = './temp_save/'
['data']
garage_file = './garage.txt'
cookies_file = './cookies.txt'
['classification']
pic_per_page... |
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------... | default_providers = ['nbviewer.providers.{}'.format(prov) for prov in ['url', 'github', 'gist']]
default_rewrites = ['nbviewer.providers.{}'.format(prov) for prov in ['gist', 'github', 'dropbox', 'url']]
def provider_handlers(providers):
"""Load tornado URL handlers from an ordered list of dotted-notation modules
... |
# encoding: utf-8
class Style(object):
def __init__(self, newline, indent):
self.newline = str(newline)
self.indent = str(indent)
class Pretty(Style):
def __init__(self):
super(Pretty, self).__init__("\n", ' ')
class Sparse(Style):
def __init__(self):
super(Sparse, s... | class Style(object):
def __init__(self, newline, indent):
self.newline = str(newline)
self.indent = str(indent)
class Pretty(Style):
def __init__(self):
super(Pretty, self).__init__('\n', ' ')
class Sparse(Style):
def __init__(self):
super(Sparse, self).__init__('', '... |
def test_enter(player, limo):
player.perform("enter limo")
assert player.saw("You enter a fancy limo")
assert player.saw("electric")
def test_enter_and_exit(player, limo):
player.perform("enter limo")
player.forget()
player.perform("go out")
assert player.saw("Antechamber")
| def test_enter(player, limo):
player.perform('enter limo')
assert player.saw('You enter a fancy limo')
assert player.saw('electric')
def test_enter_and_exit(player, limo):
player.perform('enter limo')
player.forget()
player.perform('go out')
assert player.saw('Antechamber') |
#!/bin/python3
'''
String concatenation
f string - This is prefferable because its straight forward and simple
+
.format
'''
# answ = input("enter the name of your best friend: ")
# digit = " Dude"
# # Example of f string
# def stringJoiner(data):
# con_cat = f"{data} is the real {digit}!"
# return con_cat
... | """
String concatenation
f string - This is prefferable because its straight forward and simple
+
.format
"""
"\nSteps\n1. define an input variable to allow users to add their friend's name\n\n2. Write a function that accept the users's input and add it to predefined strings\n\n3. print the result\n"
user_name = input(... |
"""Utilities for module and path manipulations."""
load("@bazel_skylib//lib:paths.bzl", "paths")
load(":private/set.bzl", "set")
def module_name(hs, f, rel_path = None):
"""Given Haskell source file path, turn it into a dot-separated module name.
module_name(
hs,
"some-workspace/some-package/src/... | """Utilities for module and path manipulations."""
load('@bazel_skylib//lib:paths.bzl', 'paths')
load(':private/set.bzl', 'set')
def module_name(hs, f, rel_path=None):
"""Given Haskell source file path, turn it into a dot-separated module name.
module_name(
hs,
"some-workspace/some-package/src/Foo... |
'''
Demo_2 is a simple implementation of factorial calculation
'''
n = int(input('please enter a number: '))
fac = 1
for n in range(n):
fac = fac * (n + 1)
print('the answer is: ', fac) | """
Demo_2 is a simple implementation of factorial calculation
"""
n = int(input('please enter a number: '))
fac = 1
for n in range(n):
fac = fac * (n + 1)
print('the answer is: ', fac) |
sum_sq = 0
sq_sum = 0
for i in range(1, 101):
sum_sq += i**2
sq_sum += i
diff = sum_sq - sq_sum**2
print(diff) | sum_sq = 0
sq_sum = 0
for i in range(1, 101):
sum_sq += i ** 2
sq_sum += i
diff = sum_sq - sq_sum ** 2
print(diff) |
"""Dictionary Data Parsing Functions."""
META = {}
def flatten_dictionary_with_int(dictionary_data):
"""Return flat meta report dictionary from nested dictionary with ints."""
meta_dict = META
meta_dict["report"] = {}
for item in dictionary_data:
if type(dictionary_data[item]) is dict:
... | """Dictionary Data Parsing Functions."""
meta = {}
def flatten_dictionary_with_int(dictionary_data):
"""Return flat meta report dictionary from nested dictionary with ints."""
meta_dict = META
meta_dict['report'] = {}
for item in dictionary_data:
if type(dictionary_data[item]) is dict:
... |
# Refresh SENSU
# salt-run cache.clear_grains tgt="*" ; salt '*' state.sls sensu.client; salt '*' service.restart salt-minion; salt '*' mine.flush; salt '*' mine.update ; salt 'mon01*' state.sls sensu
@roles('ntw')
def clean_contrail():
sudo(uptime)
sudo(hostname)
| @roles('ntw')
def clean_contrail():
sudo(uptime)
sudo(hostname) |
# https://leetcode.com/problems/merge-intervals/
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals = sorted(intervals, key=lambda x: x[0])
i = 0
while i < len(intervals) - 1:
if intervals[i][1] >= intervals[i+1][0]:
... | class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals = sorted(intervals, key=lambda x: x[0])
i = 0
while i < len(intervals) - 1:
if intervals[i][1] >= intervals[i + 1][0]:
intervals[i][1] = max(intervals[i][1], intervals[i + 1... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 26 20:25:09 2019
@author: Administrator
"""
class Solution:
def isPowerOfThree(self, n: int) -> bool:
# if n <= 0:
# return False
# while n != 1:
# if n%3 != 0:
# return False
# n //= 3
# return Tru... | """
Created on Sun May 26 20:25:09 2019
@author: Administrator
"""
class Solution:
def is_power_of_three(self, n: int) -> bool:
return n > 0 and 1162261467 % n == 0
solu = solution()
n = 27
print(solu.isPowerOfThree(n)) |
x = int(input())
y = int(input())
menor = min(x, y) + 1
maior = max(x, y) - 1
soma = 0
while menor <= maior:
if menor % 2 != 0:
soma += menor
menor += 1
print(soma)
| x = int(input())
y = int(input())
menor = min(x, y) + 1
maior = max(x, y) - 1
soma = 0
while menor <= maior:
if menor % 2 != 0:
soma += menor
menor += 1
print(soma) |
def solution(enroll, referral, seller, amount):
answer = []
name = {}
money = {}
for _ in range(len(enroll)):
name[enroll[_]] = referral[_]
money[enroll[_]] = 0
for _ in range (len(amount)):
amount[_] *= 100
for _ in range (len(seller)):
str = ""
tmp = amo... | def solution(enroll, referral, seller, amount):
answer = []
name = {}
money = {}
for _ in range(len(enroll)):
name[enroll[_]] = referral[_]
money[enroll[_]] = 0
for _ in range(len(amount)):
amount[_] *= 100
for _ in range(len(seller)):
str = ''
tmp = amoun... |
def shellSort(array):
gap = len(array) // 2
# loop over the gaps
while gap > 0:
# insertion sort
for i in range(gap, len(array)):
val = array[i]
j = i
while j >= gap and array[j - gap] > val:
array[j] = array[j - gap]
j -= gap
... | def shell_sort(array):
gap = len(array) // 2
while gap > 0:
for i in range(gap, len(array)):
val = array[i]
j = i
while j >= gap and array[j - gap] > val:
array[j] = array[j - gap]
j -= gap
array[j] = val
gap //=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: config.sample.py
Description: unittest configuration for Python SDK of the Cognitive Face API.
- Copy `config.sample.py` to `config.py`.
- Change the `BASE_URL` if necessary.
- Assign the `KEY` with a valid Subscription Key.
"""
# Subscription Key for calling th... | """
File: config.sample.py
Description: unittest configuration for Python SDK of the Cognitive Face API.
- Copy `config.sample.py` to `config.py`.
- Change the `BASE_URL` if necessary.
- Assign the `KEY` with a valid Subscription Key.
"""
key = 'a1e1cb41a20c40d8b17b1691236760c6'
base_url = 'https://westus.api.cognitiv... |
# Databricks notebook source
# MAGIC
# MAGIC %md
# MAGIC # Dataset-Mounts-Test
# MAGIC The purpose of this notebook is to faciliate testing of our systems.
# COMMAND ----------
spark.conf.set("com.databricks.training.module-name", "dataset-mounts-test")
# COMMAND ----------
# MAGIC %run ./Dataset-Mounts
# COMMAND... | spark.conf.set('com.databricks.training.module-name', 'dataset-mounts-test') |
class Adjunct:
def apply(self, right, arg):
pass
class A: pass
def foo(): pass
class B: pass
print('239')
| class Adjunct:
def apply(self, right, arg):
pass
class A:
pass
def foo():
pass
class B:
pass
print('239') |
class Solution(object):
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
stack = []
pop_ptr = 0
for push_num in pushed:
stack.append(push_num)
while stack ... | class Solution(object):
def validate_stack_sequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
stack = []
pop_ptr = 0
for push_num in pushed:
stack.append(push_num)
while stack ... |
#!/usr/bin/env python3
# This program converts Fahrenheit to Celsius
embedded = 1 # using embedded python libraries
if embedded == 1:
fahr_temp = 33
print("Fahrenheit Temperature = ", fahr_temp)
else:
fahr_temp = float(input("Fahrenheit temperature: "))
print("Celsius temperature:", (fahr_temp - 32.0) * 5... | embedded = 1
if embedded == 1:
fahr_temp = 33
print('Fahrenheit Temperature = ', fahr_temp)
else:
fahr_temp = float(input('Fahrenheit temperature: '))
print('Celsius temperature:', (fahr_temp - 32.0) * 5.0 / 9.0) |
def fibonacci(input,memory):
if(input == 0 or input == 1):
return memory[input]
else:
memory[input] = fibonacci(input - 1,memory) + fibonacci(input - 2,memory)
return memory[input]
memory = [0] * 10
memory[0] = 0
memory[1] = 1
for i in range(10):
print(fibonacci(i,memory))
| def fibonacci(input, memory):
if input == 0 or input == 1:
return memory[input]
else:
memory[input] = fibonacci(input - 1, memory) + fibonacci(input - 2, memory)
return memory[input]
memory = [0] * 10
memory[0] = 0
memory[1] = 1
for i in range(10):
print(fibonacci(i, memory)) |
def ways(n, k) :
if n == 1:
return k
elif n == 2:
return k*k
elif n == 3:
return k * (k-1 +(k-1)*k)
else:
return k * ways(n-1,k)- ways(n-3,k)*(k-1)
if __name__ == "__main__" :
## n, k = 2,4
## n, k = 3,2
## n, k = 6,3
n, k = 5,2
... | def ways(n, k):
if n == 1:
return k
elif n == 2:
return k * k
elif n == 3:
return k * (k - 1 + (k - 1) * k)
else:
return k * ways(n - 1, k) - ways(n - 3, k) * (k - 1)
if __name__ == '__main__':
(n, k) = (5, 2)
print(ways(n, k)) |
class CallTracer:
def __init__(self, func):
"""# On @ decoration: save original func
'calls' variable is a state retainer; it maintains knowledge of the number of function calls, since the function
itself cannot. It is tied into the 'func' variable so each decorated function has its own sta... | class Calltracer:
def __init__(self, func):
"""# On @ decoration: save original func
'calls' variable is a state retainer; it maintains knowledge of the number of function calls, since the function
itself cannot. It is tied into the 'func' variable so each decorated function has its own st... |
# Comment it before submitting
# class Node:
# def __init__(self, value, left=None, right=None):
# self.value = value
# self.right = right
# self.left = left
def is_search_tree(root):
if root is None:
return True
if root.left is None and root.right is None:
return ... | def is_search_tree(root):
if root is None:
return True
if root.left is None and root.right is None:
return True
if is_tree_less(root.left, root.value) and is_tree_greater(root.right, root.value) and is_search_tree(root.left) and is_search_tree(root.right):
return True
return Fals... |
"""For experiments on n-puzzle from IPC'08 learning track."""
PDDL_DIR = '../problems/ipc08-learn/n-puzzle/'
COMMON_PDDLS = ['learning/n-puzzle-typed.pddl']
TRAIN_PDDLS = [
# 'learning/bootstrap/typed/bootstrap-typed-01.pddl',
# 'learning/bootstrap/typed/bootstrap-typed-02.pddl',
# 'learning/bootstrap/type... | """For experiments on n-puzzle from IPC'08 learning track."""
pddl_dir = '../problems/ipc08-learn/n-puzzle/'
common_pddls = ['learning/n-puzzle-typed.pddl']
train_pddls = ['learning/bootstrap/typed/bootstrap-typed-09.pddl', 'learning/bootstrap/typed/bootstrap-typed-11.pddl', 'learning/bootstrap/typed/bootstrap-typed-13... |
# -*- coding: UTF-8 -*-
#
# Given a binary tree, return the inorder traversal of its nodes' values.
#
# For example:
# Given binary tree [1,null,2,3],
# 1
# \
# 2
# /
# 3
# return [1,3,2].
#
# Note: Recursive solution is trivial, could you do it iteratively?
#
# Python, Python 3 all accepted.
class BinaryTreeInorderT... | class Binarytreeinordertraversal:
def inorder_traversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = []
if root is None:
return result
stack = []
while root is not None or len(stack) != 0:
while root is ... |
#!/usr/bin/env python2.7
# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | """Generates the appropriate build.json data for all the bad_client tests."""
load('//bazel:grpc_build_system.bzl', 'grpc_cc_test', 'grpc_cc_library')
def test_options():
return struct()
bad_client_tests = {'badreq': test_options(), 'bad_streaming_id': test_options(), 'connection_prefix': test_options(), 'duplicat... |
### most of this will only work for Blast -- not psi-blast
def is_new_query_id_line( line ):
return line and line.split() and line.split()[0] == 'Query='
def is_new_hit_id_line( line ):
return line and line[0] == '>'
def is_new_match_line( line ):
return line and line[:3] == ' Sc'
def is_query_alig... | def is_new_query_id_line(line):
return line and line.split() and (line.split()[0] == 'Query=')
def is_new_hit_id_line(line):
return line and line[0] == '>'
def is_new_match_line(line):
return line and line[:3] == ' Sc'
def is_query_alignment_line(line):
return line and line.split() and (line.split()[... |
class TestMesosAgentFailure(object):
def test_agent_restart(self, failure_tester):
"""
Restart Mesos agents after creating a job and verify that
the job is restarted and succeeds. Use a non-default restart-policy
so that lost tasks will be retried.
"""
job = failure_... | class Testmesosagentfailure(object):
def test_agent_restart(self, failure_tester):
"""
Restart Mesos agents after creating a job and verify that
the job is restarted and succeeds. Use a non-default restart-policy
so that lost tasks will be retried.
"""
job = failure_... |
#
# Copyright (c) 2020 Cord Technologies Limited
#
# 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 ag... | class Cordexception(Exception):
""" Base class for all exceptions. """
def __init__(self, message):
super().__init__(message)
self.message = message
def __str__(self):
return self.message
class Authenticationerror(CordException):
""" Exception thrown when API key fails authent... |
def fun(s):
sum = 0
ff = len(s)
for i in range(ff):
sum += int(s[i])
return sum
print(fun(str(input())))
| def fun(s):
sum = 0
ff = len(s)
for i in range(ff):
sum += int(s[i])
return sum
print(fun(str(input()))) |
AUTH_MODULE = 'auth.ldap'
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'django_python3_ldap.auth.LDAPBackend'
]
# LDAP Server Settings
LDAP_BASE_DN = 'dc=demo1,dc=freeipa,dc=org'
LDAP_SERVER_URI = 'ipa.demo1.freeipa.org'
LDAP_MANAGER_DN = 'cn=Directory Manager'
LDAP_MANAGER_SECRET = ... | auth_module = 'auth.ldap'
authentication_backends = ['django.contrib.auth.backends.ModelBackend', 'django_python3_ldap.auth.LDAPBackend']
ldap_base_dn = 'dc=demo1,dc=freeipa,dc=org'
ldap_server_uri = 'ipa.demo1.freeipa.org'
ldap_manager_dn = 'cn=Directory Manager'
ldap_manager_secret = SECRET_KEY
ldap_user_table = 'ou=... |
#!/usr/bin/env python3
"""
This program is the implementation of the famous fizzbuzz program.
If the number is divisible by both 3 and 5, then the progrma prints 'FizzBuzz'.
If the enumber is only divisible by 3, then the program prints 'Fizz'
If the enumber is only divisible by 5, then the program prints 'Buzz'
"""
d... | """
This program is the implementation of the famous fizzbuzz program.
If the number is divisible by both 3 and 5, then the progrma prints 'FizzBuzz'.
If the enumber is only divisible by 3, then the program prints 'Fizz'
If the enumber is only divisible by 5, then the program prints 'Buzz'
"""
def fizz_buzz(num):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.