content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
limit = 10000
sum_divisors = 0
val = [0, 0]
for number in range(2, limit):
sum_divisor = 0
for number2 in range(1, int(number / 2) + 1):
if (number % number2 == 0):
sum_divisor += number2
val.append(sum_divisor)
sum_amicable_numbers = 0
for number in range(2, limit):
if (val[number]... | limit = 10000
sum_divisors = 0
val = [0, 0]
for number in range(2, limit):
sum_divisor = 0
for number2 in range(1, int(number / 2) + 1):
if number % number2 == 0:
sum_divisor += number2
val.append(sum_divisor)
sum_amicable_numbers = 0
for number in range(2, limit):
if val[number] < l... |
"""Flask configuration"""
class Config:
"""Setting up config variables"""
# General
FLASK_ENV = "development"
TESTING = True
# Database
SQLALCHEMY_DATABASE_URI = "sqlite:///sqlite_db/catalogue.db"
SQLALCHEMY_TRACK_MODIFICATIONS = False
# JWT
JWT_SECRET_KEY = 'super-secret'
... | """Flask configuration"""
class Config:
"""Setting up config variables"""
flask_env = 'development'
testing = True
sqlalchemy_database_uri = 'sqlite:///sqlite_db/catalogue.db'
sqlalchemy_track_modifications = False
jwt_secret_key = 'super-secret'
fake_database_uri = 'sqlite:///tests/test.db... |
peso_maior = 0
peso_menor = 0
for c in range(1, 6):
peso = float(input("Informe o peso da {0} pessoa: ".format(c)))
if(c == 1):
peso_maior = peso
peso_menor = peso
else:
if(peso > peso_maior):
peso_maior = peso
if(peso < peso_menor):
peso_menor = peso... | peso_maior = 0
peso_menor = 0
for c in range(1, 6):
peso = float(input('Informe o peso da {0} pessoa: '.format(c)))
if c == 1:
peso_maior = peso
peso_menor = peso
else:
if peso > peso_maior:
peso_maior = peso
if peso < peso_menor:
peso_menor = peso
pri... |
class Cache:
"""
Class used for storing a data
from one instance and allow
a different class instance to
access this data.
"""
_state: dict = {
'Data': ''
}
def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
obj.__dict__ = cls._state
return... | class Cache:
"""
Class used for storing a data
from one instance and allow
a different class instance to
access this data.
"""
_state: dict = {'Data': ''}
def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
obj.__dict__ = cls._state
return obj
def ... |
#Tokenizer of Expression
#Example Expression: ~(T & F) | T
def tokenize(expr):
ac = ["T", "F", "(", ")", "~", "&", "|", " ", "\t"]
ls = []
for i in range(0, len(expr)):
if expr[i] not in ac:
raise Exception("invalid expression")
if expr[i] != " ":
ls.append(expr[i])
... | def tokenize(expr):
ac = ['T', 'F', '(', ')', '~', '&', '|', ' ', '\t']
ls = []
for i in range(0, len(expr)):
if expr[i] not in ac:
raise exception('invalid expression')
if expr[i] != ' ':
ls.append(expr[i])
return ls
'\nTest expressions:\n(T & F)\n~(T | T)\nT & (... |
'''
this is used to add a comment line
or a set of lines that the computer ignores
'''
# this is used to add a single comment line
print("this is used to" + " concatenate 2 strings")
'''
a string and a number cannot be concatenated this way
instead we can use a comma to separate the two different data types... | """
this is used to add a comment line
or a set of lines that the computer ignores
"""
print('this is used to' + ' concatenate 2 strings')
'\na string and a number cannot be concatenated this way\ninstead we can use a comma to separate the two different data types'
print(9, ' aousnik')
magic_number = 26
for x in range(... |
'''
Created on 11 juni 2017
@author: Wilma
'''
| """
Created on 11 juni 2017
@author: Wilma
""" |
"""
* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
* Find the sum of all the multiples of 3 or 5 below 1000.
"""
def sum_multiples(mul, below):
first = mul # First multiple of mul
last = ((below - 1)... | """
* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
* Find the sum of all the multiples of 3 or 5 below 1000.
"""
def sum_multiples(mul, below):
first = mul
last = (below - 1) // mul * mul
n = (last - first) // mul + 1
... |
num=grt=1
def collatz(no):
if no==1:
return 1
else:
if no%2==0:
return 1+collatz(int(no/2))
else:
return 1+collatz((3*no)+1)
for i in range(2, 1000000, 1):
a=collatz(i)
if (a>grt):
num=i
grt=a
if (i%1000==0):
print(i)
print(num) | num = grt = 1
def collatz(no):
if no == 1:
return 1
elif no % 2 == 0:
return 1 + collatz(int(no / 2))
else:
return 1 + collatz(3 * no + 1)
for i in range(2, 1000000, 1):
a = collatz(i)
if a > grt:
num = i
grt = a
if i % 1000 == 0:
print(i)
print(n... |
"""
Three in One: Describe how you could use a single array to implement three stacks.
"""
class Stack:
def __init__(self, start, parent):
self.start = start
self.count = 0
self.parent = parent
def push(self, value):
return self.parent.push(self, value)
def pop(self):
... | """
Three in One: Describe how you could use a single array to implement three stacks.
"""
class Stack:
def __init__(self, start, parent):
self.start = start
self.count = 0
self.parent = parent
def push(self, value):
return self.parent.push(self, value)
def pop(self):
... |
"""
The MIT License (MIT)
Copyright (c) Serenity Software, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, m... | """
The MIT License (MIT)
Copyright (c) Serenity Software, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, m... |
"""
Types Base
==========
Provides the base types on top of which user visible types will be built.
"""
# pylint: disable=too-few-public-methods
class CFFICDataWrapper(object):
"""
Base class for exposing Python types and interfaces to pywincffi users:
* Wraps a CFFI cdata object in self._cdata.
* D... | """
Types Base
==========
Provides the base types on top of which user visible types will be built.
"""
class Cfficdatawrapper(object):
"""
Base class for exposing Python types and interfaces to pywincffi users:
* Wraps a CFFI cdata object in self._cdata.
* Delegates attribute getting/setting to self... |
# Utilities related to colors.
# A standard color-blind palette, with equalized luminance, adding another a blue.
colors = [
((165, 54, 0, 255), ["orange", "brown"]),
((179, 45, 181, 255), ["pink"]),
((0, 114, 178, 255), ["blue", "lightBlue", "blue1"]),
((144, 136, 39... | colors = [((165, 54, 0, 255), ['orange', 'brown']), ((179, 45, 181, 255), ['pink']), ((0, 114, 178, 255), ['blue', 'lightBlue', 'blue1']), ((144, 136, 39, 255), ['yellow']), ((52, 142, 83, 255), ['green']), ((5, 60, 255, 255), ['darkBlue', 'blue2'])]
colors = [((c[0][0] / 255.0, c[0][1] / 255.0, c[0][2] / 255.0, c[0][3... |
class Foo:
def say(self):
return 'bar'
| class Foo:
def say(self):
return 'bar' |
#########################
# 162. Find Peak Element
#########################
class Solution:
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==1:
peak = 0
return peak
else:
if nums[0]>nums[1]:
... | class Solution:
def find_peak_element(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
peak = 0
return peak
else:
if nums[0] > nums[1]:
peak = 0
return peak
if nu... |
#works reguardless the size of the strings
def compare(_firstString, _secondString):
_list = list(set(_firstString.lower()) - set(_secondString.lower()))
print("The Non-Common Charecters are: ")
for i in _list:
print(i)
# works only for equal length strings
def COMPARE(_firstString, _secondString)... | def compare(_firstString, _secondString):
_list = list(set(_firstString.lower()) - set(_secondString.lower()))
print('The Non-Common Charecters are: ')
for i in _list:
print(i)
def compare(_firstString, _secondString):
print('The Non-Common Charecters are: ')
if len(_firstString) == len(_se... |
class Student(object):
def __init__(self, name, score):
self.__name = name
self._score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
bart = Student("Zero", 32)
print(bart)
| class Student(object):
def __init__(self, name, score):
self.__name = name
self._score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
bart = student('Zero', 32)
print(bart) |
def rearrange_sorted_list_in_max_into_set(lst):
result = []
for i in range(len(lst)//2):
result.append((lst[i], lst[-i - 1]))
if len(lst) % 2 == 1:
result.append(lst[len(lst)//2])
return result
| def rearrange_sorted_list_in_max_into_set(lst):
result = []
for i in range(len(lst) // 2):
result.append((lst[i], lst[-i - 1]))
if len(lst) % 2 == 1:
result.append(lst[len(lst) // 2])
return result |
# Students dictionary
students = {"Ahmed" : 87, "Waleed" : 69, "Hesham" : 92}
# Khaled grades
kh_grades = {"Math": 86, "English": 74}
#1 Add Khaled and his grades to students
students[________] = _________
# Print out students
print(students)
#2 Print out Khaled grade in English
print(_____________________________)... | students = {'Ahmed': 87, 'Waleed': 69, 'Hesham': 92}
kh_grades = {'Math': 86, 'English': 74}
students[________] = _________
print(students)
print(_____________________________) |
load("@com_github_pybind_bazel//:build_defs.bzl", "pybind_extension")
def pybind_py_library(name,
cc_so_name = None,
copts = [],
features = [],
tags = [],
cc_srcs = [],
cc_deps = [],
py_library_rule = native.py_library,
py_srcs = [],
py_deps = [],... | load('@com_github_pybind_bazel//:build_defs.bzl', 'pybind_extension')
def pybind_py_library(name, cc_so_name=None, copts=[], features=[], tags=[], cc_srcs=[], cc_deps=[], py_library_rule=native.py_library, py_srcs=[], py_deps=[], py_imports=[], cc_linkopts=[], visibility=None, testonly=None, **kwargs):
if not cc_s... |
n = 10000
df = pd.DataFrame({'x': np.random.randn(n),
'y': np.random.randn(n)})
ax = df.plot.hexbin(x='x', y='y', gridsize=20)
| n = 10000
df = pd.DataFrame({'x': np.random.randn(n), 'y': np.random.randn(n)})
ax = df.plot.hexbin(x='x', y='y', gridsize=20) |
def do_stuff(num):
"""Adds 5 to passed int"""
try:
return int(num) + 5
except ValueError as err:
return err
| def do_stuff(num):
"""Adds 5 to passed int"""
try:
return int(num) + 5
except ValueError as err:
return err |
#
# Py Word Permutations
#
# Author: Afaan Bilal
# URL: https://afaan.ml
#
# Display all possible permutaions for a set of characters.
#
# (c) 2016 Afaan Bilal
# Released under the MIT License
#
def base_convert(number, fromBase, toBase):
''' Convert numbers to and from decimal '''
... | def base_convert(number, fromBase, toBase):
""" Convert numbers to and from decimal """
i = 0
result = 0
number = int(number)
while number > 0:
result += number % toBase * fromBase ** i
i += 1
number //= toBase
return str(result)
def bin_search(arr, s, ubound):
""" B... |
temperature = 35
if temperature == 30:
print("It's a hot day.")
else:
print("It's not a hot day.")
# Exercise
name = input("Enter name: ")
if len(name) < 3:
print("Name must be at least 3 characters.")
elif len(name) > 20:
print("Name must be a maximum of 20 characters.")
else:
print("Name looks... | temperature = 35
if temperature == 30:
print("It's a hot day.")
else:
print("It's not a hot day.")
name = input('Enter name: ')
if len(name) < 3:
print('Name must be at least 3 characters.')
elif len(name) > 20:
print('Name must be a maximum of 20 characters.')
else:
print('Name looks good!') |
#!/usr/bin/python3
# @JUDGE_ID: mobluse 11044 Python 3 "Closed-form expression"
t = int(input())
for i in range(t):
n, m = [int(x) for x in input().split()]
print((n//3)*(m//3))
| t = int(input())
for i in range(t):
(n, m) = [int(x) for x in input().split()]
print(n // 3 * (m // 3)) |
print("This file tests Elif.")
a=99
if a<=0:
print("Plese enter a correct number")
if a<=60:
print('E')
elif a<=70:
print("D")
elif a<=80:
print("C")
elif a<=90:
print("B")
elif a<=95:
print("A")
elif a<=99:
print("A+")
else:
print("A++") | print('This file tests Elif.')
a = 99
if a <= 0:
print('Plese enter a correct number')
if a <= 60:
print('E')
elif a <= 70:
print('D')
elif a <= 80:
print('C')
elif a <= 90:
print('B')
elif a <= 95:
print('A')
elif a <= 99:
print('A+')
else:
print('A++') |
#!/usr/bin/env python3
# The MIT License
# Copyright (c) 2016 Estonian Information System Authority (RIA), Population Register Centre (VRK)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software ... | __all__ = ['test_simple_store_and_query', 'test_soap_fault', 'test_get_metadata', 'test_metaservices', 'test_attachments', 'test_health_data', 'test_limited_operational_data_response', 'test_service_cluster', 'test_outputspec', 'test_time_interval', 'test_client_filter', 'test_zero_buffer_size'] |
#!/usr/bin/env python
def fac(n):
'''compute the factorial of given number'''
assert type(n) == int, 'argument must be integer'
assert n >= 0, 'argument must be positive'
if n > 1:
return n*fac(n - 1)
else:
return 1
if __name__ == '__main__':
for i in range(5):
print('{... | def fac(n):
"""compute the factorial of given number"""
assert type(n) == int, 'argument must be integer'
assert n >= 0, 'argument must be positive'
if n > 1:
return n * fac(n - 1)
else:
return 1
if __name__ == '__main__':
for i in range(5):
print('{0}! = {1}'.format(i, f... |
bjobTemplate="""#!/bin/tcsh
cd $CMSSW_BASE/src
eval `scramv1 runtime -csh`
source /afs/cern.ch/cms/caf/setup.csh
cd -
xrdcp {inputFile} reco.root
cmsRun $CMSSW_BASE/src/Alignment/APEEstimation/test/cfgTemplate/apeEstimator_cfg.py {inputCommands}
rm -- "$0"
"""
submitJobTemplate="""
bsub -J {jobName} -e {errorFil... | bjob_template = '#!/bin/tcsh\n\ncd $CMSSW_BASE/src\n\neval `scramv1 runtime -csh`\n\nsource /afs/cern.ch/cms/caf/setup.csh\ncd -\n\nxrdcp {inputFile} reco.root\n\ncmsRun $CMSSW_BASE/src/Alignment/APEEstimation/test/cfgTemplate/apeEstimator_cfg.py {inputCommands}\n\nrm -- "$0"\n'
submit_job_template = '\nbsub -J {jobNam... |
# Demonstrate how to use set comprehensions
def main():
# define a list of temperature data points
ctemps = [5, 10, 12, 14, 10, 23, 41, 30, 12, 24, 12, 18, 29]
# TODO: build a set of unique Fahrenheit temperatures
# TODO: build a set from an input source
if __name__ == "__main__":
main()
| def main():
ctemps = [5, 10, 12, 14, 10, 23, 41, 30, 12, 24, 12, 18, 29]
if __name__ == '__main__':
main() |
been_called = False
def example2():
global been_called
been_called = True
# example2()
# print(been_called)
def sort_words_by_length():
fin = open('words.txt')
lt = []
for line in fin:
line = line.strip()
lt.append((len(line), line))
lt.sort(reverse=True)
res = []
for ... | been_called = False
def example2():
global been_called
been_called = True
def sort_words_by_length():
fin = open('words.txt')
lt = []
for line in fin:
line = line.strip()
lt.append((len(line), line))
lt.sort(reverse=True)
res = []
for (_, word) in lt:
res.append... |
#!/usr/bin/env python
# Copyright (c) 2005-2009 Jaroslav Gresula
#
# Distributed under the MIT license (See accompanying file
# LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt)
#
# names generator
# http://www.neoprogrammics.com/randomisers/random_names_generator/
names_str="""Steven Eden
Madelyn E. Vinci
Cor... | names_str = 'Steven Eden\nMadelyn E. Vinci\nCorliss S. Widener\nTerresa Dumond\nLean C. Willison\nMan King\nBettina M. Haslam\nAngele V. Heidelberg\nJames E. Satter\nMaryjane Kunkel\nChara Y. Cyr\nSuzanne S. Perrin\nEmilia V. Noda\nAliza R. Charpentier\nNeva Guida\nMariette L. Mcvay\nCristine Heid\nDaisy Weidman\nTilda... |
# Using the seive of Eratosthenes https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
def sum_primes(n):
sum = 0
sieve = [True] * n
for i in range(2, n):
if sieve[i]:
sum += i
for j in range(i**2, n, i):
sieve[j] = False
return sum
if __name__ == "__mai... | def sum_primes(n):
sum = 0
sieve = [True] * n
for i in range(2, n):
if sieve[i]:
sum += i
for j in range(i ** 2, n, i):
sieve[j] = False
return sum
if __name__ == '__main__':
print(sum_primes(2000000)) |
ans=0
x1,y1,r1=map(int,input().split())
x2,y2,r2=map(int,input().split())
x3,y3,r3=map(int,input().split())
for i in range(23001):
for j in range(23001):
if (x1-i/230+0.0022)**2+(y1-j/230+0.0022)**2<=r1*r1: ans+=1
elif (x2-i/230+0.0022)**2+(y2-j/230+0.0022)**2<=r2*r2: ans+=1
elif (x3-i/230+0.0022)**2+(y3-... | ans = 0
(x1, y1, r1) = map(int, input().split())
(x2, y2, r2) = map(int, input().split())
(x3, y3, r3) = map(int, input().split())
for i in range(23001):
for j in range(23001):
if (x1 - i / 230 + 0.0022) ** 2 + (y1 - j / 230 + 0.0022) ** 2 <= r1 * r1:
ans += 1
elif (x2 - i / 230 + 0.0022... |
num = int(input("enter any Number"))
rev = 0
while num > 0:
Rem = num % 10
num = num // 10
rev = rev * 10 + Rem
print("The Reverse of the number", rev)
##################
# could also simply do this another way
num = input()
print(int(num[::-1]))
| num = int(input('enter any Number'))
rev = 0
while num > 0:
rem = num % 10
num = num // 10
rev = rev * 10 + Rem
print('The Reverse of the number', rev)
num = input()
print(int(num[::-1])) |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2021 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Softw... | count = 425
exceptions = {406: {'_': 'NotAcceptable', 'AUTH_KEY_DUPLICATED': 'AuthKeyDuplicated', 'FILEREF_UPGRADE_NEEDED': 'FilerefUpgradeNeeded', 'FRESH_CHANGE_ADMINS_FORBIDDEN': 'FreshChangeAdminsForbidden', 'FRESH_CHANGE_PHONE_FORBIDDEN': 'FreshChangePhoneForbidden', 'FRESH_RESET_AUTHORISATION_FORBIDDEN': 'FreshRes... |
class Node:
def __init__(self,name):
self.name = name
self.left = None
self.right = None
self.visit = False
def insert(self, name):
if name < self.name:
if self.left is None:
self.left = Node(name)
else:
self.le... | class Node:
def __init__(self, name):
self.name = name
self.left = None
self.right = None
self.visit = False
def insert(self, name):
if name < self.name:
if self.left is None:
self.left = node(name)
else:
self.left... |
# fixed constants
WEIERSTRASS = 0
EDWARDS = 1
MONTGOMERY = 2
D_TYPE = 0
M_TYPE = 1
NEGATIVEX = 0
POSITIVEX = 1
BN = 0
BLS = 1
ECDH_INVALID_PUBLIC_KEY = -2
ECDH_ERROR = -3
| weierstrass = 0
edwards = 1
montgomery = 2
d_type = 0
m_type = 1
negativex = 0
positivex = 1
bn = 0
bls = 1
ecdh_invalid_public_key = -2
ecdh_error = -3 |
def actuator_add(type='', name="", object=""):
'''Add an actuator to the active object
:param type: Type, Type of actuator to add
:type type: enum in [], (optional)
:param name: Name, Name of the Actuator to add
:type name: string, (optional, never None)
:param object: Object, Name of the Ob... | def actuator_add(type='', name='', object=''):
"""Add an actuator to the active object
:param type: Type, Type of actuator to add
:type type: enum in [], (optional)
:param name: Name, Name of the Actuator to add
:type name: string, (optional, never None)
:param object: Object, Name of the Ob... |
def xoppy_calc_black_body(TITLE="Thermal source: Planck distribution",TEMPERATURE=1200000.0,E_MIN=10.0,E_MAX=1000.0,NPOINTS=500):
print("Inside xoppy_calc_black_body. ")
return(None)
def xoppy_calc_mlayer(MODE=0,SCAN=0,F12_FLAG=0,SUBSTRATE="Si",ODD_MATERIAL="Si",EVEN_MATERIAL="W",ENERGY=8050.0,THETA=0.0,S... | def xoppy_calc_black_body(TITLE='Thermal source: Planck distribution', TEMPERATURE=1200000.0, E_MIN=10.0, E_MAX=1000.0, NPOINTS=500):
print('Inside xoppy_calc_black_body. ')
return None
def xoppy_calc_mlayer(MODE=0, SCAN=0, F12_FLAG=0, SUBSTRATE='Si', ODD_MATERIAL='Si', EVEN_MATERIAL='W', ENERGY=8050.0, THETA=... |
SS
array = [1,1,2,2]
array1 = set(array)
print(array1)
for a in array1:
print(a)
| SS
array = [1, 1, 2, 2]
array1 = set(array)
print(array1)
for a in array1:
print(a) |
# Humanoid A (2111003) | Magatia (261000000)
snowfieldRose = 3335
snowRoseGrows = 926120300
if sm.hasQuest(snowfieldRose):
response = sm.sendAskYesNo("Are you ready to grow the Snow Rose?")
if response:
sm.warpInstanceIn(snowRoseGrows, False)
else:
sm.sendSayOkay("Remember to bring #bMay M... | snowfield_rose = 3335
snow_rose_grows = 926120300
if sm.hasQuest(snowfieldRose):
response = sm.sendAskYesNo('Are you ready to grow the Snow Rose?')
if response:
sm.warpInstanceIn(snowRoseGrows, False)
else:
sm.sendSayOkay('Remember to bring #bMay Mist#k with you so the Snow Rose can bloom.')... |
class Algo(object):
def generate(self, interface):
# TODO: Write algorithm here
pass
| class Algo(object):
def generate(self, interface):
pass |
class SnakesistError(Exception):
"""Snakesist base exception class"""
pass
class SnakesistConfigError(SnakesistError):
"""Raised if the database connection is improperly configured"""
pass
class SnakesistReadError(SnakesistError):
"""Raised if a writing operation fails"""
pass
class Sna... | class Snakesisterror(Exception):
"""Snakesist base exception class"""
pass
class Snakesistconfigerror(SnakesistError):
"""Raised if the database connection is improperly configured"""
pass
class Snakesistreaderror(SnakesistError):
"""Raised if a writing operation fails"""
pass
class Snakesist... |
width = 17
height = 12.0
print(width//2) # should return the quotient
print(width/2.0) # should return the quotient in float
print(height/3.0) # should return the quotient in float
ans = 1 + 2 * 5 # should return 11
print(ans)
| width = 17
height = 12.0
print(width // 2)
print(width / 2.0)
print(height / 3.0)
ans = 1 + 2 * 5
print(ans) |
"""
|||||||||||||||||||||||||||| DECISION THEORY MODEL |||||||||||||||||||||
"""
def dt_model_speed_and_distances(self, plot=False, sqrt=True):
speed = stats.norm(loc=self.speed_mu, scale=self.speed_sigma)
if sqrt: dnoise = math.sqrt(self.distance_noise)
else: dnoise = self.distance_noise
d... | """
|||||||||||||||||||||||||||| DECISION THEORY MODEL |||||||||||||||||||||
"""
def dt_model_speed_and_distances(self, plot=False, sqrt=True):
speed = stats.norm(loc=self.speed_mu, scale=self.speed_sigma)
if sqrt:
dnoise = math.sqrt(self.distance_noise)
else:
dnoise = self.dista... |
# Copyright 2014 The Bazel Authors. 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
#
# Unless required by applicable la... | load('@io_bazel_rules_go//go/private:repositories.bzl', 'go_repositories')
load('@io_bazel_rules_go//go/private:go_repository.bzl', 'go_repository', 'new_go_repository')
load('@io_bazel_rules_go//go/private:go_prefix.bzl', 'go_prefix')
load('@io_bazel_rules_go//go/private:library.bzl', 'go_library')
load('@io_bazel_rul... |
d = {"a": 1, "b": 2, "c": 3}
newDict={}
for (key,value) in d.items():
if(value<=1):
newDict[key]=value
# for key,values in d.items():
# if values>1:
# d.pop[key]
print(newDict)
| d = {'a': 1, 'b': 2, 'c': 3}
new_dict = {}
for (key, value) in d.items():
if value <= 1:
newDict[key] = value
print(newDict) |
__docformat__ = "restructuredtext"
__version__ = "0.2.7"
__doc__ = """
This<https://github.com/WinVector/wvpy> is a package of example files for teaching data science.
"""
| __docformat__ = 'restructuredtext'
__version__ = '0.2.7'
__doc__ = '\nThis<https://github.com/WinVector/wvpy> is a package of example files for teaching data science.\n' |
#!/usr/bin/env python3
# imports go here
#
# Free Coding session for 2015-04-02
# Written by Matt Warren
#
class MyClass(object):
def __init__(self):
self.meta = self.Meta()
class Meta:
CONSTANT = 'HELLO'
def do_something(self):
print(self.meta.CONSTANT)
class MySubclass(MyCl... | class Myclass(object):
def __init__(self):
self.meta = self.Meta()
class Meta:
constant = 'HELLO'
def do_something(self):
print(self.meta.CONSTANT)
class Mysubclass(MyClass):
class Meta:
constant = 'MATT IS COOL'
if __name__ == '__main__':
mc = my_class()
mc.... |
# coding=utf-8
class Context(object):
is_finished = False
text = None
state = None
current_index = 0
is_pair_sign_opened = False
has_split_sign = False
pair_sign = None
back_pair_sign = None
token_num = 0
char_num = 0
def __init__(self,
text,
... | class Context(object):
is_finished = False
text = None
state = None
current_index = 0
is_pair_sign_opened = False
has_split_sign = False
pair_sign = None
back_pair_sign = None
token_num = 0
char_num = 0
def __init__(self, text, state, split_signs, pair_signs, soften_split_si... |
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
j=0
for i in range(len(A)):
if (A[i]%2)==0:
temp = A[i]
A[i]=A[j]
A[j]=temp
j+=1
return A
| class Solution:
def sort_array_by_parity(self, A: List[int]) -> List[int]:
j = 0
for i in range(len(A)):
if A[i] % 2 == 0:
temp = A[i]
A[i] = A[j]
A[j] = temp
j += 1
return A |
def solve(prices, fee):
t_i_k_0 = 0
t_i_k_1 = -float('inf')
for price in prices:
t_i_k_0 = max(t_i_k_0, t_i_k_1 + price - fee)
t_i_k_1 = max(t_i_k_1, t_i_k_0 - price)
return t_i_k_0
A = [1, 3, 2, 8, 4, 9]
B = 2
print(solve(A, B))
| def solve(prices, fee):
t_i_k_0 = 0
t_i_k_1 = -float('inf')
for price in prices:
t_i_k_0 = max(t_i_k_0, t_i_k_1 + price - fee)
t_i_k_1 = max(t_i_k_1, t_i_k_0 - price)
return t_i_k_0
a = [1, 3, 2, 8, 4, 9]
b = 2
print(solve(A, B)) |
class ObjectFactory:
'''Generic object factory. Maintains a dictionary of provider objects,
which can be created and returned on demand.
'''
def __init__(self):
self._providers = {}
def register_provider(self, key, provider):
'''Register a new provider for future use. The `key` valu... | class Objectfactory:
"""Generic object factory. Maintains a dictionary of provider objects,
which can be created and returned on demand.
"""
def __init__(self):
self._providers = {}
def register_provider(self, key, provider):
"""Register a new provider for future use. The `key` val... |
def test_grade_above_1_is_passing(passing_grade):
assert passing_grade.is_passing() is True
def test_grade_below_2_is_failing(failing_grade):
assert failing_grade.is_passing() is False
| def test_grade_above_1_is_passing(passing_grade):
assert passing_grade.is_passing() is True
def test_grade_below_2_is_failing(failing_grade):
assert failing_grade.is_passing() is False |
# .split() breaks a string at specified character into a list of strings
my_string = "Boulder,CO,80304,106392"
my_split_string = my_string.split(",")
print(my_split_string)
# .strip() will remove leading or trailing whitespace
white_str = " Boulder,CO,80304,106392\n"
strip_split_str = white_str.split(",").strip()... | my_string = 'Boulder,CO,80304,106392'
my_split_string = my_string.split(',')
print(my_split_string)
white_str = ' Boulder,CO,80304,106392\n'
strip_split_str = white_str.split(',').strip()
print(strip_split_str) |
# SPDX-License-Identifier: MIT
# Map the entire MMIO range as traceable
map_sw(0x2_00000000,
0x2_00000000 | hv.SPTE_TRACE_READ | hv.SPTE_TRACE_WRITE,
0x5_00000000)
# Skip some noisy devices
try:
trace_device("/arm-io/usb-drd0", False)
except KeyError:
pass
try:
trace_device("/arm-io/usb-drd1... | map_sw(8589934592, 8589934592 | hv.SPTE_TRACE_READ | hv.SPTE_TRACE_WRITE, 21474836480)
try:
trace_device('/arm-io/usb-drd0', False)
except KeyError:
pass
try:
trace_device('/arm-io/usb-drd1', False)
except KeyError:
pass
trace_device('/arm-io/uart2', False)
trace_device('/arm-io/error-handler', False)
t... |
class AdjNode:
def __init__(self, value):
self.value = value
self.next = None
class AdjListGraph:
def __init__(self, num_vertices):
self.storage = [None] * num_vertices
self.num_vertices = num_vertices
def add_edge(self, v, w):
new_adj_node = AdjNode(w)
ne... | class Adjnode:
def __init__(self, value):
self.value = value
self.next = None
class Adjlistgraph:
def __init__(self, num_vertices):
self.storage = [None] * num_vertices
self.num_vertices = num_vertices
def add_edge(self, v, w):
new_adj_node = adj_node(w)
n... |
# -*- coding: utf-8 -*-
db.define_table('MESSAGE_BOARD',
Field('sender', 'text'),
Field('receiver', 'text'),
Field('message_content', 'text'),
# Field('sent_time', 'datetime', requires=IS_DATE(format='%d-%m-%Y %H:%M:%S')),
Field('sent_time'... | db.define_table('MESSAGE_BOARD', field('sender', 'text'), field('receiver', 'text'), field('message_content', 'text'), field('sent_time', 'datetime'), field('has_read', 'boolean', default=False), field('comments', 'text'), redefine=True) |
BASE_AUTH = "bemullen_crussack_dharmesh_vinwah"
CONTRIBUTOR = "bemullen_crussack_dharmesh_vinwah"
BASE_NAME = "bemullen_crussack_dharmesh_vinwah"
def setBaseName(baseAuth):
global BASE_AUTH
global BASE_NAME
global CONTRIBUTOR
BASE_AUTH = baseAuth
CONTRIBUTOR = baseAuth
BASE_NAME = baseAuth | base_auth = 'bemullen_crussack_dharmesh_vinwah'
contributor = 'bemullen_crussack_dharmesh_vinwah'
base_name = 'bemullen_crussack_dharmesh_vinwah'
def set_base_name(baseAuth):
global BASE_AUTH
global BASE_NAME
global CONTRIBUTOR
base_auth = baseAuth
contributor = baseAuth
base_name = baseAuth |
class Solution(object):
def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if not n or not k:
return 0
if n == 1:
return k
dp = [0] * (n+1)
dp[1] = k
dp[2] = k*(k-1) + k
for i in range... | class Solution(object):
def num_ways(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if not n or not k:
return 0
if n == 1:
return k
dp = [0] * (n + 1)
dp[1] = k
dp[2] = k * (k - 1) + k
for i ... |
def grade(key, submission):
if submission == "it_is_only_uphill_from_here_%s" % str(key):
return True, "Good luck!"
else:
return False, "Ask Julius again..."
| def grade(key, submission):
if submission == 'it_is_only_uphill_from_here_%s' % str(key):
return (True, 'Good luck!')
else:
return (False, 'Ask Julius again...') |
class Solution:
def solve(self, source, target):
locs = defaultdict(list)
for i,char in enumerate(source):
locs[char].append(i)
ans = 0
cur = len(source)
for char in target:
if char not in locs:
return -1
nxt = bisect_le... | class Solution:
def solve(self, source, target):
locs = defaultdict(list)
for (i, char) in enumerate(source):
locs[char].append(i)
ans = 0
cur = len(source)
for char in target:
if char not in locs:
return -1
nxt = bisect_le... |
def encripter(key,entrada):
alfabeto = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
mapa = [["X0","X1","X2","X3","X4"],["X0","X1","X2","X3","X4"],["X0","X1","X2","X3","X4"],["X0","X1","X2","X3","X4"],["X0","X1","X2","X3","X4"]]
x = 0 # index pa... | def encripter(key, entrada):
alfabeto = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
mapa = [['X0', 'X1', 'X2', 'X3', 'X4'], ['X0', 'X1', 'X2', 'X3', 'X4'], ['X0', 'X1', 'X2', 'X3', 'X4'], ['X0', 'X1', 'X2', 'X3', 'X4'], ['X0'... |
# class TreeNode():
# def __init__(self, val=None, left_ptr=None, right_ptr=None):
# self.val = val
# self.left_ptr = left_ptr
# self.right_ptr = right_ptr
# complete the function below
traversal = []
PRE = 1
PROCESS = 2
POST = 3 # not used
def postorderTraversal(root):
def postorderHe... | traversal = []
pre = 1
process = 2
post = 3
def postorder_traversal(root):
def postorder_helper(root):
stack = [(root, PRE)]
while stack:
(node, state) = stack.pop()
if not node:
continue
if state == PRE:
stack.append((node, PROCE... |
expected_output = {
"FiveGigabitEthernet1/0/48": {
"service_policy": {
"output": {
"policy_name": {
"PWRED-CHILD": {
"class_map": {
"CWRED": {
"afd_wred_stats": {
... | expected_output = {'FiveGigabitEthernet1/0/48': {'service_policy': {'output': {'policy_name': {'PWRED-CHILD': {'class_map': {'CWRED': {'afd_wred_stats': {'total_drops_bytes': 0, 'total_drops_packets': 0, 'virtual_class': {0: {'afd_weight': 12, 'dscp': 1, 'max': 20, 'min': 10, 'random_drop_bytes': 0, 'random_drop_packet... |
#
# @lc app=leetcode id=4 lang=python3
#
# [4] Median of Two Sorted Arrays
#
# @lc code=start
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
for element in nums2:
nums1.append(element)
nums1.sort()
lenth = len(nums1)
... | class Solution:
def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
for element in nums2:
nums1.append(element)
nums1.sort()
lenth = len(nums1)
if lenth % 2 == 0:
n1 = lenth // 2
n2 = n1 - 1
return (nums1[... |
"""
NeoTrellis M4 Express MIDI synth
Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!
Written by Dave Astels for Adafruit Industries
Copyright (c) 2018 Adafruit Industries
Licensed under the MIT license.
All te... | """
NeoTrellis M4 Express MIDI synth
Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!
Written by Dave Astels for Adafruit Industries
Copyright (c) 2018 Adafruit Industries
Licensed under the MIT license.
All te... |
r,g,b = map(int,input().split())
l=[]
for i in range(min(r+1,g+1,b+1,3)):
l.append(i+(r-i)//3+(g-i)//3+(b-i)//3)
print(max(l)) | (r, g, b) = map(int, input().split())
l = []
for i in range(min(r + 1, g + 1, b + 1, 3)):
l.append(i + (r - i) // 3 + (g - i) // 3 + (b - i) // 3)
print(max(l)) |
"""
This script encrypt http and transfer it to port 443.
By Olivier Soucy.
"""
def request(context, flow):
flow.request.port = 443
flow.request.scheme = "https"
| """
This script encrypt http and transfer it to port 443.
By Olivier Soucy.
"""
def request(context, flow):
flow.request.port = 443
flow.request.scheme = 'https' |
#!/usr/bin/env python
NAME = 'Comodo WAF'
def is_waf(self):
return self.matchheader(('server', "Protected by COMODO WAF"))
| name = 'Comodo WAF'
def is_waf(self):
return self.matchheader(('server', 'Protected by COMODO WAF')) |
def read_groups(full_text: str) -> []:
"Separate groups from newlines and join answers."
lines = full_text.splitlines()
groups = []
group = []
for line in lines:
line = line.strip()
if line != '':
group += [line]
else:
groups.append(group)
... | def read_groups(full_text: str) -> []:
"""Separate groups from newlines and join answers."""
lines = full_text.splitlines()
groups = []
group = []
for line in lines:
line = line.strip()
if line != '':
group += [line]
else:
groups.append(group)
... |
"""
@author: Anirudh Sharma
"""
# Example #1
def sum_of_list_elements(L):
total = 0
for i in L:
total += L[i - 1]
return total
L = [1, 2, 3, 4, 5, 6]
print(sum_of_list_elements(L))
# Example #2
def list_operations(L1, L2):
L3 = L1 + L2
print("L1 + L2: ", L3)
L1.remove(2)
... | """
@author: Anirudh Sharma
"""
def sum_of_list_elements(L):
total = 0
for i in L:
total += L[i - 1]
return total
l = [1, 2, 3, 4, 5, 6]
print(sum_of_list_elements(L))
def list_operations(L1, L2):
l3 = L1 + L2
print('L1 + L2: ', L3)
L1.remove(2)
L2.remove(6)
print('Mutated L1 a... |
X, N = [int(x) for x in input().split()]
PS = [int(x) for x in input().split()]
mindist = 1e+99
for p in PS:
dist = abs(X - p)
if dist < mindist:
mindist = dist
answer = p
elif dist == mindist:
if p < answer:
ansewr = p
print(answer)
| (x, n) = [int(x) for x in input().split()]
ps = [int(x) for x in input().split()]
mindist = 1e+99
for p in PS:
dist = abs(X - p)
if dist < mindist:
mindist = dist
answer = p
elif dist == mindist:
if p < answer:
ansewr = p
print(answer) |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
@author: Jesus Salgado
@contact: jesusjuansalgado@gmail.com
European Space Astronomy Centre (ESAC)
European Space Agency (ESA)
Created on 15 July 2020
"""
| """
@author: Jesus Salgado
@contact: jesusjuansalgado@gmail.com
European Space Astronomy Centre (ESAC)
European Space Agency (ESA)
Created on 15 July 2020
""" |
N = int(input())
A = list(map(int, input().split()))
result = []
for i in range(N):
x = i
j = 1
x = A[x] - 1
while x != i:
x = A[x] - 1
j += 1
result.append(j)
print(*result)
| n = int(input())
a = list(map(int, input().split()))
result = []
for i in range(N):
x = i
j = 1
x = A[x] - 1
while x != i:
x = A[x] - 1
j += 1
result.append(j)
print(*result) |
def increasing_or_decreasing(seq):
is_up = False
is_down = False
length = len(seq)
if length == 1:
return False
if seq[0] > seq[1]:
is_down = True
elif seq[0] < seq[1]:
is_up = True
for i in range(1, length - 1):
if(seq[i] > seq[i + 1] and is_up) or \
(seq[i] < seq[i + 1] and is_down) or \
... | def increasing_or_decreasing(seq):
is_up = False
is_down = False
length = len(seq)
if length == 1:
return False
if seq[0] > seq[1]:
is_down = True
elif seq[0] < seq[1]:
is_up = True
for i in range(1, length - 1):
if seq[i] > seq[i + 1] and is_up or (seq[i] < s... |
# errors from Transition function
TransitionComplete = 10
TransitionDbConnectionFailed = 11
TransitionDbRetrieveFailed = 12
TransitionFunctionException = 13
# errors from JobStatusReceiver
JobStatusReceiverRetrieveArgoSubJobFailed = 21
JobStatusReceiverRe... | transition_complete = 10
transition_db_connection_failed = 11
transition_db_retrieve_failed = 12
transition_function_exception = 13
job_status_receiver_retrieve_argo_sub_job_failed = 21
job_status_receiver_retrieve_argo_job_failed = 22
job_status_receiver_balsam_state_map_failure = 23
job_status_receiver_completed = 24... |
# -*- coding: utf-8 -*-
DATA_SET = [
(
[u"123", u"12345"],
[1, 3],
([3, 5], [3, 5])
),
(
[u"123", u"12345"],
[4, 3],
([3, 5], [4, 5])
),
(
[u"123", u"12345"],
[5, 8],
([3, 5], [5, 8])
),
(
[u"123", u"12345", ... | data_set = [([u'123', u'12345'], [1, 3], ([3, 5], [3, 5])), ([u'123', u'12345'], [4, 3], ([3, 5], [4, 5])), ([u'123', u'12345'], [5, 8], ([3, 5], [5, 8])), ([u'123', u'12345', u'lorem ipsum'], [5, 3, 4], ([3, 5, 11], [5, 5, 11]))] |
def cep(*args):
try:
telaPrincipal = args[0]
telaErro = args[1]
pycep_correios = args[2]
cep = telaPrincipal.cep.text()
end = pycep_correios.get_address_from_cep(cep)
telaPrincipal.end.setText(end['logradouro'])
telaPrincipal.bairro.setText(end['bairro'])
... | def cep(*args):
try:
tela_principal = args[0]
tela_erro = args[1]
pycep_correios = args[2]
cep = telaPrincipal.cep.text()
end = pycep_correios.get_address_from_cep(cep)
telaPrincipal.end.setText(end['logradouro'])
telaPrincipal.bairro.setText(end['bairro'])
... |
"""
Exception classes - Subclassing to check for specific errors
"""
class AlpineException(Exception):
"""
General Alpine Exception
"""
def __init__(self, reason, *args):
super(AlpineException, self).__init__(reason, *args)
self.reason = reason
def __repr__(self):
return '... | """
Exception classes - Subclassing to check for specific errors
"""
class Alpineexception(Exception):
"""
General Alpine Exception
"""
def __init__(self, reason, *args):
super(AlpineException, self).__init__(reason, *args)
self.reason = reason
def __repr__(self):
return '... |
def up(config, conn, semester, course):
with conn.cursor() as cursor:
cursor.execute("""CREATE TABLE IF NOT EXISTS notification_settings (
user_id character varying NOT NULL,
merge_threads BOOLEAN DEFAULT FALSE NOT NULL,
all_new_threads BOOLEAN DEFAULT FALSE NOT NULL,
all_new_pos... | def up(config, conn, semester, course):
with conn.cursor() as cursor:
cursor.execute('CREATE TABLE IF NOT EXISTS notification_settings (\n\t\t\t\t\t\t\tuser_id character varying NOT NULL,\n\t\t\t\t\t\t\tmerge_threads BOOLEAN DEFAULT FALSE NOT NULL,\n\t\t\t\t\t\t\tall_new_threads BOOLEAN DEFAULT FALSE NOT NU... |
"""
File:
phillips_hue.py
George Farris <farrisg@gmsys.com>
Copyright (c), 2015
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later ver... | """
File:
phillips_hue.py
George Farris <farrisg@gmsys.com>
Copyright (c), 2015
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later ver... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/81079015
class Solution(object):
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
stack = []
for ast in asteroids:
while stack and ast < 0 and sta... | class Solution(object):
def asteroid_collision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
stack = []
for ast in asteroids:
while stack and ast < 0 and (stack[-1] >= 0):
pre = stack.pop()
if ast =... |
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
min1 = min2 = inf
max1 = max2 = max3 = -inf
for n in nums:
if n < min1:
min2, min1 = min1, n
elif n < min2:
min2 = n
if n > max1:
max3, max2... | class Solution:
def maximum_product(self, nums: List[int]) -> int:
min1 = min2 = inf
max1 = max2 = max3 = -inf
for n in nums:
if n < min1:
(min2, min1) = (min1, n)
elif n < min2:
min2 = n
if n > max1:
(max3,... |
OUTCOMES = [
[None, "Buzz"],
["Fizz", "FizzBuzz"],
]
def fizzbuzz(number: int) -> str:
mod3 = number % 3 == 0
mod5 = number % 5 == 0
outcome = OUTCOMES[mod3][mod5]
return outcome or str(number)
def main():
for i in range(101):
fbi = fizzbuzz(i)
print(fbi)
if __name__ ... | outcomes = [[None, 'Buzz'], ['Fizz', 'FizzBuzz']]
def fizzbuzz(number: int) -> str:
mod3 = number % 3 == 0
mod5 = number % 5 == 0
outcome = OUTCOMES[mod3][mod5]
return outcome or str(number)
def main():
for i in range(101):
fbi = fizzbuzz(i)
print(fbi)
if __name__ == '__main__':
... |
_.targets # unused attribute (packages/cli/odahuflow/cli/parsers/local/packaging.py:118)
build_client # unused function (packages/sdk/odahuflow/sdk/clients/api_aggregated.py:88)
ConfigurationClient # unused class (packages/sdk/odahuflow/sdk/clients/configuration.py:28)
AsyncConfigurationClient # unused class (packa... | _.targets
build_client
ConfigurationClient
AsyncConfigurationClient
PROCESSING_STATE
log_message
do_GET
SCHEDULING_STATE
RUNNING_STATE
UNKNOWN_STATE
PROCESSING_STATE
reset_context
get_config_file_section
ODAHUFLOWCTL_OAUTH_AUTH_URL
JUPYTER_REDIRECT_URL
REQUEST_ID
MODEL_REQUEST_ID
MODEL_NAME
MODEL_VERSION
get_model_outp... |
class Schema(object):
def __init__(self, name, tag_name, tag_case_sensitive, model, validators, attributes, children, content):
self.name = name
self.tag_name = tag_name
self.tag_case_sensitive = tag_case_sensitive
self.model = model
self.validators = validators
sel... | class Schema(object):
def __init__(self, name, tag_name, tag_case_sensitive, model, validators, attributes, children, content):
self.name = name
self.tag_name = tag_name
self.tag_case_sensitive = tag_case_sensitive
self.model = model
self.validators = validators
self... |
"""
Problem Statement
Given a target amount n and a list (array) of distinct coin values, what's the fewest coins needed to make the change amount.
For example:
If n = 10 and coins = [1,5,10]. Then there are 4 possible ways to make change:
1+1+1+1+1+1+1+1+1+1
5 + 1+1+1+1+1
5+5
10
With 1 coin being the minimum amoun... | """
Problem Statement
Given a target amount n and a list (array) of distinct coin values, what's the fewest coins needed to make the change amount.
For example:
If n = 10 and coins = [1,5,10]. Then there are 4 possible ways to make change:
1+1+1+1+1+1+1+1+1+1
5 + 1+1+1+1+1
5+5
10
With 1 coin being the minimum amoun... |
{
'variables': {
'linear_sample_parent_path': '/',
},
'targets': [
{
'target_name': 'tcp_client_sample',
'type': 'executable',
'sources': [
'tcp_client_sample.cpp',
],
},
{
'target_name': 'tcp_server_sample',
'type': 'executable',
'sources': [
... | {'variables': {'linear_sample_parent_path': '/'}, 'targets': [{'target_name': 'tcp_client_sample', 'type': 'executable', 'sources': ['tcp_client_sample.cpp']}, {'target_name': 'tcp_server_sample', 'type': 'executable', 'sources': ['tcp_server_sample.cpp']}, {'target_name': 'ws_client_sample', 'type': 'executable', 'sou... |
def rna_to_protein(rna):
'''
Takes a string and returns a protein sequence WIHOUT
using biopython
Input params:
rna = rna string
Output params:
protein = protein sequence
'''
codon = []
protein = []
while rna:
codon.append(rna[:3])
rna = rna[3:]
f... | def rna_to_protein(rna):
"""
Takes a string and returns a protein sequence WIHOUT
using biopython
Input params:
rna = rna string
Output params:
protein = protein sequence
"""
codon = []
protein = []
while rna:
codon.append(rna[:3])
rna = rna[3:]
for tri... |
PROG_NAME = "MTSv"
VERSION = "2.0.0"
DEFAULT_CFG_FNAME = "mtsv.cfg"
DEFAULT_LOG_FNAME = "mtsv_{COMMAND}_{TIMESTAMP}.log"
CONFIG_STRING = """
# NOTE: Changes to the config file in the middle of the pipeline
# may force previous steps to be rerun.
#
# ===============================================================
#
... | prog_name = 'MTSv'
version = '2.0.0'
default_cfg_fname = 'mtsv.cfg'
default_log_fname = 'mtsv_{COMMAND}_{TIMESTAMP}.log'
config_string = '\n# NOTE: Changes to the config file in the middle of the pipeline\n# may force previous steps to be rerun.\n# \n# ===============================================================\n#... |
class Solution:
def isTransformable(self, s: str, t: str) -> bool:
positions = defaultdict(list)
for i in reversed(range(len(s))):
positions[int(s[i])].append(i)
for char in t:
num = int(char)
if not positions[num]:
return False
... | class Solution:
def is_transformable(self, s: str, t: str) -> bool:
positions = defaultdict(list)
for i in reversed(range(len(s))):
positions[int(s[i])].append(i)
for char in t:
num = int(char)
if not positions[num]:
return False
... |
class Solution:
def solve(self, intervals, types):
sorted_endpoints = sorted(list({end for interval in intervals for end in interval}))
counts = defaultdict(int)
for start, end in intervals:
counts[start] += 1
counts[end] -= 1
counts = dict(zip(sorted_endpoi... | class Solution:
def solve(self, intervals, types):
sorted_endpoints = sorted(list({end for interval in intervals for end in interval}))
counts = defaultdict(int)
for (start, end) in intervals:
counts[start] += 1
counts[end] -= 1
counts = dict(zip(sorted_endpo... |
def add_data_opts(parser):
data_opts = parser.add_argument_group("General Data Options")
data_opts.add_argument('--manifest-dir', default='./', type=str,
help='Output directory for manifests')
data_opts.add_argument('--min-duration', default=1, type=int,
... | def add_data_opts(parser):
data_opts = parser.add_argument_group('General Data Options')
data_opts.add_argument('--manifest-dir', default='./', type=str, help='Output directory for manifests')
data_opts.add_argument('--min-duration', default=1, type=int, help='Prunes training samples shorter than the min du... |
class object_ustr(object):
def __unicode__(self):
'''This should really be overriden in subclasses'''
class_name = self.__class__.__name__
attr_pairs = ('%s=%s' % (key, val) for key, val in self.__dict__.items())
return u'<%s %s>' % (class_name, ' '.join(attr_pairs))
def __str__... | class Object_Ustr(object):
def __unicode__(self):
"""This should really be overriden in subclasses"""
class_name = self.__class__.__name__
attr_pairs = ('%s=%s' % (key, val) for (key, val) in self.__dict__.items())
return u'<%s %s>' % (class_name, ' '.join(attr_pairs))
def __st... |
# The gameboy color has no cpu opcodes for multiplication. I could write some
# complicated algorithm to do this stuff on the gameboy's cpu, but I'm going to
# cheat and just use canned data. If you feed the assembly code for a color
# palette into this script, it will output a canned fade animation, 32 steps in
# size... | def get_rgb(bgr_555):
r = 31 & bgr_555
g = (992 & bgr_555) >> 5
b = (31744 & bgr_555) >> 10
return (r, g, b)
lines = []
with open('palette_data.txt') as data:
for line in data:
vector = []
parsed = line[3:].split(',')
parity = False
coll = ''
for elem in parse... |
"""
Video encoding names
"""
class EncodingNames:
"""Simple class to hold encoding names"""
ORIGINAL = "original"
HLS = "HLS"
SMALL = "small"
BASIC = "basic"
MEDIUM = "medium"
LARGE = "large"
HD = "HD"
MP4 = [HD, LARGE, MEDIUM, BASIC, SMALL]
| """
Video encoding names
"""
class Encodingnames:
"""Simple class to hold encoding names"""
original = 'original'
hls = 'HLS'
small = 'small'
basic = 'basic'
medium = 'medium'
large = 'large'
hd = 'HD'
mp4 = [HD, LARGE, MEDIUM, BASIC, SMALL] |
#
# PySNMP MIB module IEEE8021-CFM-V2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IEEE8021-CFM-V2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:40:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_size_constraint, constraints_intersection, value_range_constraint) ... |
SPEC = \
{
"input": [
{
"name": "first number",
"type": "int"
},
{
"name": "second number",
"type": "int"
}
],
"output": [
{
"name": "number sum",
"type": "int"
}
],
"package": {
"author": "Stefan Maetschke",
"author_email": "stefan.maetsch... | spec = {'input': [{'name': 'first number', 'type': 'int'}, {'name': 'second number', 'type': 'int'}], 'output': [{'name': 'number sum', 'type': 'int'}], 'package': {'author': 'Stefan Maetschke', 'author_email': 'stefan.maetschke@gmail.com', 'description': 'Adds two numbers', 'type': 'Adder', 'version': '1.0.0'}} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.