content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#Author:
#Dilpreet Singh Chawla
#Indian Institute of Information Technology Kalyani.
#Newton's Method to find square root of a positive number
def square_root(n):
if n<0:
raise RuntimeError("Please enter a positive number!")
else:
root=n/2 #initial_guess
for k in range(20):
... | def square_root(n):
if n < 0:
raise runtime_error('Please enter a positive number!')
else:
root = n / 2
for k in range(20):
root = 1 / 2 * (root + n / root)
return root
n = float(input('Enter a number: '))
sqrt = square_root(n)
print('The square root of the number is ... |
class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
A, ncnt = sorted(A), sum([1 for a in A if a < 0])
cnt1, cnt2 = min(K, ncnt), K - ncnt if K > ncnt else 0
for i in range(cnt1): A[i] = -A[i]
return sum(A) - min(A) * 2 * (cnt2 % 2) if cnt2 else sum(A)
| class Solution:
def largest_sum_after_k_negations(self, A: List[int], K: int) -> int:
(a, ncnt) = (sorted(A), sum([1 for a in A if a < 0]))
(cnt1, cnt2) = (min(K, ncnt), K - ncnt if K > ncnt else 0)
for i in range(cnt1):
A[i] = -A[i]
return sum(A) - min(A) * 2 * (cnt2 % ... |
'''
Stuff for the lambda role
'''
role_parameter_section = """ role:
Description: name of the role
Type: String"""
parameter_role_spec = 'Ref: role'
imported_role_spec = 'Fn::ImportValue: {}'
'''
Stuff for the subnet(s)
'''
subnets_parameter_section = """ subnetIds:
Description: list of subnets
Type:... | """
Stuff for the lambda role
"""
role_parameter_section = ' role:\n Description: name of the role\n Type: String'
parameter_role_spec = 'Ref: role'
imported_role_spec = 'Fn::ImportValue: {}'
'\nStuff for the subnet(s)\n'
subnets_parameter_section = ' subnetIds:\n Description: list of subnets\n Type: Comm... |
BLOCK_REGISTRY = {}
NO_BLOCK_ERR = 'Block {} not in BLOCK_REGISTRY! Available blocks are {}'
def RegisterBlock(block_name):
"""Registers a block."""
def decorator(f):
BLOCK_REGISTRY[block_name] = f
return f
return decorator
def get_block(block_name):
"""Get block from BLOCK_REGISTRY... | block_registry = {}
no_block_err = 'Block {} not in BLOCK_REGISTRY! Available blocks are {}'
def register_block(block_name):
"""Registers a block."""
def decorator(f):
BLOCK_REGISTRY[block_name] = f
return f
return decorator
def get_block(block_name):
"""Get block from BLOCK_REGISTRY ... |
#unexpected results, can use try statement to make trial statement
try:
print(a) #have not defined a, will return exception
except:
print("a is not defined!")
#these are specific errors
try:
print(a) # a still not defined
except NameError:
print("a is still not defined")
except:
print("something else went wrong... | try:
print(a)
except:
print('a is not defined!')
try:
print(a)
except NameError:
print('a is still not defined')
except:
print('something else went wrong')
print(a) |
MHP = open('numeros.txt','w')
for linha in range(1,101):
arquivo.write('%d\n'%linha)
arquivo.close()
| mhp = open('numeros.txt', 'w')
for linha in range(1, 101):
arquivo.write('%d\n' % linha)
arquivo.close() |
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
invalid_open = []
invalid_close = []
for i,char in enumerate(s):
if char == '(':
invalid_open.append(i)
elif char == ')':
if not invalid_open:
... | class Solution:
def min_remove_to_make_valid(self, s: str) -> str:
invalid_open = []
invalid_close = []
for (i, char) in enumerate(s):
if char == '(':
invalid_open.append(i)
elif char == ')':
if not invalid_open:
in... |
class BBAWriter:
def __init__(self, f):
self.f = f
def pre(self, s):
print("pre {}".format(s), file=self.f)
def post(self, s):
print("post {}".format(s), file=self.f)
def push(self, s):
print("push {}".format(s), file=self.f)
def offset32(self):
print("offset32", file=self.f)
def ref(self, r, comment=""... | class Bbawriter:
def __init__(self, f):
self.f = f
def pre(self, s):
print('pre {}'.format(s), file=self.f)
def post(self, s):
print('post {}'.format(s), file=self.f)
def push(self, s):
print('push {}'.format(s), file=self.f)
def offset32(self):
print('of... |
del_items(0x80079E14)
SetType(0x80079E14, "int GetTpY__FUs(unsigned short tpage)")
del_items(0x80079E30)
SetType(0x80079E30, "int GetTpX__FUs(unsigned short tpage)")
del_items(0x80079E3C)
SetType(0x80079E3C, "void Remove96__Fv()")
del_items(0x80079E74)
SetType(0x80079E74, "void AppMain()")
del_items(0x80079F14)
SetType... | del_items(2147982868)
set_type(2147982868, 'int GetTpY__FUs(unsigned short tpage)')
del_items(2147982896)
set_type(2147982896, 'int GetTpX__FUs(unsigned short tpage)')
del_items(2147982908)
set_type(2147982908, 'void Remove96__Fv()')
del_items(2147982964)
set_type(2147982964, 'void AppMain()')
del_items(2147983124)
set... |
x = 10
y = 'Hi'
z = 'Hello'
print(y)
# breakpoint() is introduced in Python 3.7
breakpoint()
print(z)
# Execution Steps
# Default:
# $python3.7 python_breakpoint_examples.py
# Disable Breakpoint:
# $PYTHONBREAKPOINT=0 python3.7 python_breakpoint_examples.py
# Using Other Debugger (for example web-pdb):
# $PYTHONB... | x = 10
y = 'Hi'
z = 'Hello'
print(y)
breakpoint()
print(z) |
# Test if list is Palindrome
# Using list slicing
# initializing list
test_list = [1, 4, 5, 4, 1]
# printing original list
print("The original list is : " + str(test_list))
# Reversing the list
reverse = test_list[::-1]
# checking if palindrome
res = test_list == reverse
# printing result
print("Is list Palindrome... | test_list = [1, 4, 5, 4, 1]
print('The original list is : ' + str(test_list))
reverse = test_list[::-1]
res = test_list == reverse
print('Is list Palindrome : ' + str(res)) |
def _file_name(filePathName):
if "/" in filePathName:
return filePathName.rsplit("/", -1)[1]
else:
return filePathName
def _base_name(fileName):
return fileName.split(".")[0]
def qt_cc_library(name, src, hdr, uis = [], res = [], normal_hdrs = [], deps = None, **kwargs):
srcs = src
... | def _file_name(filePathName):
if '/' in filePathName:
return filePathName.rsplit('/', -1)[1]
else:
return filePathName
def _base_name(fileName):
return fileName.split('.')[0]
def qt_cc_library(name, src, hdr, uis=[], res=[], normal_hdrs=[], deps=None, **kwargs):
srcs = src
for h_it... |
def winning_move(board, piece):
# Check horizontal locations for win
# every possibility horizontal 4 in the board
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece\
and board[r][c+2] == piece and b... | def winning_move(board, piece):
for c in range(COLUMN_COUNT - 3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c + 1] == piece and (board[r][c + 2] == piece) and (board[r][c + 3] == piece):
return True
for c in range(COLUMN_COUNT):
for r in range(RO... |
#!/usr/bin/env python
"""
Project: CLIPRT - Client Information Parsing and Reporting Tool.
@author: mhodges
Copyright 2020 Michael Hodges
"""
class MessageRegistry:
"""
The message registry contains all of the message content needed for
error handling throughout the project.
"""
def __init_... | """
Project: CLIPRT - Client Information Parsing and Reporting Tool.
@author: mhodges
Copyright 2020 Michael Hodges
"""
class Messageregistry:
"""
The message registry contains all of the message content needed for
error handling throughout the project.
"""
def __init__(self):
"""
... |
count = 0
while count < 5:
print(count)
count += 1
else:
print(count)
count = 0
while count < 5:
print(count)
count += 1
if count == 3:
break
count = 0
while count < 5:
if count == 3:
count += 1
continue
print(count)
count += 1
| count = 0
while count < 5:
print(count)
count += 1
else:
print(count)
count = 0
while count < 5:
print(count)
count += 1
if count == 3:
break
count = 0
while count < 5:
if count == 3:
count += 1
continue
print(count)
count += 1 |
class WrapperException(BaseException):
def __init__(self, original_e, subcode=None):
super().__init__()
self.original_exception = original_e
self.subcode = subcode
def __str__(self) -> str:
return self.original_exception.__str__()
class ClientErrorException(WrapperException):
... | class Wrapperexception(BaseException):
def __init__(self, original_e, subcode=None):
super().__init__()
self.original_exception = original_e
self.subcode = subcode
def __str__(self) -> str:
return self.original_exception.__str__()
class Clienterrorexception(WrapperException):
... |
#
# Virtual Block Device (VBD) Xen API Configuration
#
# Note: There is a non-API field here called "image" which is a backwards
# compat addition so you can mount to old images.
#
VDI = ''
device = 'sda1'
mode = 'RW'
driver = 'paravirtualised'
image = 'file:/root/gentoo.amd64.img'
| vdi = ''
device = 'sda1'
mode = 'RW'
driver = 'paravirtualised'
image = 'file:/root/gentoo.amd64.img' |
# Use this playground to experiment with list methods, using Test Run
list_method = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
list_method.append(5, )
print(list_method)
list_method.extend([5, 5, 5, 5])
print(list_method)
list_method.insert(3, 2)
print(list_method)
list_method.remove(2)
print(list_method)
print(list_method.count... | list_method = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
list_method.append(5)
print(list_method)
list_method.extend([5, 5, 5, 5])
print(list_method)
list_method.insert(3, 2)
print(list_method)
list_method.remove(2)
print(list_method)
print(list_method.count(5))
print(list_method.pop(10))
print(list_method)
list_method.reverse()
p... |
min3 = 100
max3 = 999
mul = 0
mx = 0 # max palindrome
for i in range(max3, min3-1, -1):
for j in range(i, min3-1, -1):
mul = i*j
rev = int(str(mul)[::-1]) # reversed
if (mul <= mx):
break
if (mul == rev):
mx = mul
print(mx)
| min3 = 100
max3 = 999
mul = 0
mx = 0
for i in range(max3, min3 - 1, -1):
for j in range(i, min3 - 1, -1):
mul = i * j
rev = int(str(mul)[::-1])
if mul <= mx:
break
if mul == rev:
mx = mul
print(mx) |
# Slide link: https://kathrinschuler.github.io/slide-python-intro/#/11/4
# Current repl: https://repl.it/@kathrinschuler/Lesson1ExBooleanOperators - question text varies a little
# TASKS is a list of lists. Each sublist follows this structure:
# [
# <string of background information to print>,
# <string of questio... | """
empty object for copy-paste:
[
"", # background info
"", # question
[], # list of required keywords
{}, # dict of variables to set up before question
],
"""
blurb = "\nImagine you've got clients who are interested in the share prices of Google and Facebook.\nThe variables we're using for these quest... |
###
# Created on Apr 13,2020
# @author: Jordon Malcolm
# jordonm1@umbc.edu
###
class Events:
def __init__(self, arg1=" ", arg2=" ", arg3=" ", arg4=" ", arg5=" ", arg6=" ", arg7=0):
self.subject = arg1
self.courseNum = arg2
self.version = arg3
self.section = arg4
self.instruct... | class Events:
def __init__(self, arg1=' ', arg2=' ', arg3=' ', arg4=' ', arg5=' ', arg6=' ', arg7=0):
self.subject = arg1
self.courseNum = arg2
self.version = arg3
self.section = arg4
self.instructor = arg5
self.time = arg6
self.capacity = arg7
def get_s... |
# @Time : 2019/4/22 23:31
# @Author : shakespere
# @FileName: Palindromic Substrings.py
'''
647. Palindromic Substrings
Medium
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings... | """
647. Palindromic Substrings
Medium
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palind... |
countries = input().split(", ")
capitals = input().split(", ")
my_dict = {country: capital for country, capital in tuple(zip(countries, capitals))}
[print (f"{country} -> {capital}") for country, capital in my_dict.items()] | countries = input().split(', ')
capitals = input().split(', ')
my_dict = {country: capital for (country, capital) in tuple(zip(countries, capitals))}
[print(f'{country} -> {capital}') for (country, capital) in my_dict.items()] |
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
i, j = len(a) - 1, len(b) - 1
ret = ""
plus = 0
while True:
ta, tb = 0, 0
if i >= 0:
ta = int(a[i])
... | class Solution(object):
def add_binary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
(i, j) = (len(a) - 1, len(b) - 1)
ret = ''
plus = 0
while True:
(ta, tb) = (0, 0)
if i >= 0:
ta = int(a[i... |
class Interface:
QUERY_SCHEDULE = "0"
QUERY_TEAM_STATS = "1"
# add new query type above this line
RESP_SCHEDULE = "0"
RESP_TEAM_STATS = "1"
# add new response type above this line
| class Interface:
query_schedule = '0'
query_team_stats = '1'
resp_schedule = '0'
resp_team_stats = '1' |
class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
ans = numBottles
while numBottles >= numExchange:
remaining = numBottles%numExchange
numBottles = numBottles // numExchange
ans += numBottles
numBottles += remaining
... | class Solution:
def num_water_bottles(self, numBottles: int, numExchange: int) -> int:
ans = numBottles
while numBottles >= numExchange:
remaining = numBottles % numExchange
num_bottles = numBottles // numExchange
ans += numBottles
num_bottles += rema... |
def get_matrix():
return [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
| def get_matrix():
return [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
'''
This is Day 2 of 100 Days of Python
Today, we are going to build a tip calculator
The knowledge that we need are basic school mathematics and the usage of the different operators in Python
In python the different operators used are +, - , *, /, // , **, and the % operators.
Each has its own function, which we shal... | """
This is Day 2 of 100 Days of Python
Today, we are going to build a tip calculator
The knowledge that we need are basic school mathematics and the usage of the different operators in Python
In python the different operators used are +, - , *, /, // , **, and the % operators.
Each has its own function, which we shal... |
GENERAL_EXCEPTION = "internal_server_error"
LOGIN_EXCEPTION = "login_error"
REGISTER_EXCEPTION = "register_error"
NOT_AUTHORIZED = "not_authorized"
QUERY_PARAM_EXCEPTION = "query_param_error"
NOT_FOUND = "resource_not_found"
BAD_REQUEST_EXCEPTION = "bad_request_error"
| general_exception = 'internal_server_error'
login_exception = 'login_error'
register_exception = 'register_error'
not_authorized = 'not_authorized'
query_param_exception = 'query_param_error'
not_found = 'resource_not_found'
bad_request_exception = 'bad_request_error' |
# coding: utf-8
class BaseAPI(object):
"""
Base class for API related classes
Provides basic skeleton for API related classes
"""
def __init__(self, client, context=None):
self.client = client
self.context = context or {}
def list(self, *args, **kwargs):
raise NotImplem... | class Baseapi(object):
"""
Base class for API related classes
Provides basic skeleton for API related classes
"""
def __init__(self, client, context=None):
self.client = client
self.context = context or {}
def list(self, *args, **kwargs):
raise not_implemented('Object ... |
lista = [2, 4, 2, 2, 3, 3, 1]
def soma_elementos(lista):
soma = 0
for element in lista:
soma += element
return soma
print(soma_elementos(lista)) | lista = [2, 4, 2, 2, 3, 3, 1]
def soma_elementos(lista):
soma = 0
for element in lista:
soma += element
return soma
print(soma_elementos(lista)) |
def get_strob_numbers(num_digits):
if not num_digits:
return [""]
elif num_digits == 1:
return ["0", "1", "8"]
smaller_strob_numbers = get_strob_numbers(num_digits - 2)
strob_numbers = list()
for x in smaller_strob_numbers:
strob_numbers.extend([
"1" + x + "1",
... | def get_strob_numbers(num_digits):
if not num_digits:
return ['']
elif num_digits == 1:
return ['0', '1', '8']
smaller_strob_numbers = get_strob_numbers(num_digits - 2)
strob_numbers = list()
for x in smaller_strob_numbers:
strob_numbers.extend(['1' + x + '1', '6' + x + '9', ... |
PAIRSAM_FORMAT_VERSION = '1.0.0'
PAIRSAM_SEP = '\t'
PAIRSAM_SEP_ESCAPE = r'\t'
SAM_SEP = '\031'
SAM_SEP_ESCAPE = r'\031'
INTER_SAM_SEP = '\031NEXT_SAM\031'
COL_READID = 0
COL_C1 = 1
COL_P1 = 2
COL_C2 = 3
COL_P2 = 4
COL_S1 = 5
COL_S2 = 6
COL_PTYPE = 7
COL_SAM1 = 8
COL_SAM2 = 9
COLUMNS = ['readID', 'chrom1', 'pos1', '... | pairsam_format_version = '1.0.0'
pairsam_sep = '\t'
pairsam_sep_escape = '\\t'
sam_sep = '\x19'
sam_sep_escape = '\\031'
inter_sam_sep = '\x19NEXT_SAM\x19'
col_readid = 0
col_c1 = 1
col_p1 = 2
col_c2 = 3
col_p2 = 4
col_s1 = 5
col_s2 = 6
col_ptype = 7
col_sam1 = 8
col_sam2 = 9
columns = ['readID', 'chrom1', 'pos1', 'chr... |
def sum(number_one, number_two):
number_one_int = convert_integer(number_one)
number_two_int = convert_integer(number_two)
result = number_one_int + number_two_int
return result
def convert_integer(number_string):
convert_integer = int(number_string)
return convert_integer
answer = sum("1... | def sum(number_one, number_two):
number_one_int = convert_integer(number_one)
number_two_int = convert_integer(number_two)
result = number_one_int + number_two_int
return result
def convert_integer(number_string):
convert_integer = int(number_string)
return convert_integer
answer = sum('1', '2'... |
def Bin(L,start,end,x,k):
if end > start:
mid = (start+end)//2
if (x==L[mid]):
j = mid
i = mid
while(i>-1 and L[i]==x):
i-=1
while(j<k and L[j]==x):
j+=1
return(i,j)
elif x<L[mid]:
... | def bin(L, start, end, x, k):
if end > start:
mid = (start + end) // 2
if x == L[mid]:
j = mid
i = mid
while i > -1 and L[i] == x:
i -= 1
while j < k and L[j] == x:
j += 1
return (i, j)
elif x < L[mid... |
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
if not nums:
return 0
degree = 0
freqs = {}
for num in nums:
if num not in freqs:
freqs[num] = 0
freqs[num] += 1
for key, value in freqs.items():
... | class Solution:
def find_shortest_sub_array(self, nums: List[int]) -> int:
if not nums:
return 0
degree = 0
freqs = {}
for num in nums:
if num not in freqs:
freqs[num] = 0
freqs[num] += 1
for (key, value) in freqs.items():
... |
"""
Created on Nov 12 11:21 2019
@author: nishit
"""
# import pandas as pd
class TimeSeries:
@staticmethod
def expand_and_resample(raw_data, dT, append_next_dT=False):
if TimeSeries.valid_time_series(raw_data):
if append_next_dT:
raw_data = TimeSeries.append_next_dT_value(... | """
Created on Nov 12 11:21 2019
@author: nishit
"""
class Timeseries:
@staticmethod
def expand_and_resample(raw_data, dT, append_next_dT=False):
if TimeSeries.valid_time_series(raw_data):
if append_next_dT:
raw_data = TimeSeries.append_next_dT_value(raw_data, dT)
... |
'''Utilities for generating graphs
This provides a set of utilities that will allow us to geenrate a
girected graph. This assumes that configuration files for all the
modules are present in the ``config/modules/`` folder. The files
should be JSON files with the folliwing specifications:
.. code-block:: JSON
{
... | """Utilities for generating graphs
This provides a set of utilities that will allow us to geenrate a
girected graph. This assumes that configuration files for all the
modules are present in the ``config/modules/`` folder. The files
should be JSON files with the folliwing specifications:
.. code-block:: JSON
{
... |
expected_regimen_to_treatment = [
{
"id": "1",
"regimen_ontology_term_id": "1",
"treatment_ontology_term_id": "1"
},
{
"id": "2",
"regimen_ontology_term_id": "1",
"treatment_ontology_term_id": "2"
},
{
"id": "3",
"regimen_ontology_term_... | expected_regimen_to_treatment = [{'id': '1', 'regimen_ontology_term_id': '1', 'treatment_ontology_term_id': '1'}, {'id': '2', 'regimen_ontology_term_id': '1', 'treatment_ontology_term_id': '2'}, {'id': '3', 'regimen_ontology_term_id': '1', 'treatment_ontology_term_id': '3'}, {'id': '4', 'regimen_ontology_term_id': '1',... |
def test_java_version(host):
ansible_vars = host.ansible.get_variables()
java_version = ansible_vars.get('java__version')
java_output = host.run('java -version')
assert str(java_version) + '.' in java_output.stderr
| def test_java_version(host):
ansible_vars = host.ansible.get_variables()
java_version = ansible_vars.get('java__version')
java_output = host.run('java -version')
assert str(java_version) + '.' in java_output.stderr |
def get_php_handle__sql_command(connect_type):
if (connect_type == "pdo"):
return """try{%s
$r=$con->query(base64_decode('%s'));
$rows=$r->fetchAll(PDO::FETCH_ASSOC);
foreach($rows[0] as $k=>$v){
echo "$k"."%s";
}
echo "%s";
foreach($rows as $array){foreach($array as $k=>$v){echo "$v"."%s";};echo "%s";... | def get_php_handle__sql_command(connect_type):
if connect_type == 'pdo':
return 'try{%s\n$r=$con->query(base64_decode(\'%s\'));\n$rows=$r->fetchAll(PDO::FETCH_ASSOC);\nforeach($rows[0] as $k=>$v){\n echo "$k"."%s";\n}\necho "%s";\nforeach($rows as $array){foreach($array as $k=>$v){echo "$v"."%s";};echo "... |
# Copyright 2018 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
class SecretStoreMock:
args = None
id_to_document = dict()
def __init__(self, secret_store_url, keeper_url, account):
self.args = (secret_store_url, keeper_url, account)
def set_secret_store_url(self, url):
... | class Secretstoremock:
args = None
id_to_document = dict()
def __init__(self, secret_store_url, keeper_url, account):
self.args = (secret_store_url, keeper_url, account)
def set_secret_store_url(self, url):
return
def encrypt_document(self, document_id, document, threshold=0):
... |
m1 = 0; m2 = 0; n = int(input())
while n:
n -= 1
a, b = map(int, input().split())
m1 = max(m1, a*b)
m = int(input())
while m:
m -= 1
a, b = map(int, input().split())
m2 = max(m2, a*b)
if m1 == m2:
print("Tie")
elif m1 > m2:
print("Casper")
else:
print("Natalie") | m1 = 0
m2 = 0
n = int(input())
while n:
n -= 1
(a, b) = map(int, input().split())
m1 = max(m1, a * b)
m = int(input())
while m:
m -= 1
(a, b) = map(int, input().split())
m2 = max(m2, a * b)
if m1 == m2:
print('Tie')
elif m1 > m2:
print('Casper')
else:
print('Natalie') |
class ListNode:
def __init__(self, val, next = None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def getIntersectionNode(self,headA, headB):
if headA is None or headB is None:
return None
pa = headA # 2 pointers
pb = headB
LinkedLi... | class Listnode:
def __init__(self, val, next=None):
self.val = val
self.next = next
class Linkedlist:
def __init__(self):
self.head = None
def get_intersection_node(self, headA, headB):
if headA is None or headB is None:
return None
pa = headA
... |
"""
WAP to calculate the sum of following series where n is input by user. 1 + 1/2 + 1/3 + 1/4 + 1/5 + ... 1/n
"""
n = int(input())
result = 0
for i in range(1, n + 1):
result += 1 / i
print(result)
| """
WAP to calculate the sum of following series where n is input by user. 1 + 1/2 + 1/3 + 1/4 + 1/5 + ... 1/n
"""
n = int(input())
result = 0
for i in range(1, n + 1):
result += 1 / i
print(result) |
class Credential:
'''
class that generates new instance for credentials
'''
credential_list=[]
def __init__(self,account_name,password):
'''
__init__ method that helps us define properties for our objects.
Args:
account_name: New credential account name.
... | class Credential:
"""
class that generates new instance for credentials
"""
credential_list = []
def __init__(self, account_name, password):
"""
__init__ method that helps us define properties for our objects.
Args:
account_name: New credential account name.
... |
times = input("How many times do I have to tell you? ")
times = int(times)
for time in range(times):
print("CLEAN UP YOUR ROOM")
| times = input('How many times do I have to tell you? ')
times = int(times)
for time in range(times):
print('CLEAN UP YOUR ROOM') |
class MultiReferenceAnnotationOptions(object, IDisposable):
"""
Options which control the creation of MultiReferenceAnnotations.
MultiReferenceAnnotationOptions(multiReferenceAnnotationType: MultiReferenceAnnotationType)
"""
def Dispose(self):
""" Dispose(self: MultiReferenceAnnotation... | class Multireferenceannotationoptions(object, IDisposable):
"""
Options which control the creation of MultiReferenceAnnotations.
MultiReferenceAnnotationOptions(multiReferenceAnnotationType: MultiReferenceAnnotationType)
"""
def dispose(self):
""" Dispose(self: MultiReferenceAnnotationOptions) "... |
touched_files = danger.git.modified_files + danger.git.created_files
has_source_changes = any(map(lambda f: f.startswith("danger_python"), touched_files))
has_changelog_entry = "CHANGELOG.md" in touched_files
is_trivial = "#trivial" in danger.github.pr.title
if has_source_changes and not has_changelog_entry and not is... | touched_files = danger.git.modified_files + danger.git.created_files
has_source_changes = any(map(lambda f: f.startswith('danger_python'), touched_files))
has_changelog_entry = 'CHANGELOG.md' in touched_files
is_trivial = '#trivial' in danger.github.pr.title
if has_source_changes and (not has_changelog_entry) and (not ... |
"""
@author: acfromspace
"""
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return print("is_empty():", self.items == [])
def push(self, item):
print("push():", item)
self.items.append(item)
def pop(self):
return print("pop():", self.ite... | """
@author: acfromspace
"""
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return print('is_empty():', self.items == [])
def push(self, item):
print('push():', item)
self.items.append(item)
def pop(self):
return print('pop():', self.ite... |
def facerecognizer():
i01.opencv.capture()
i01.opencv.addFilter("PyramidDown")
i01.opencv.setDisplayFilter("FaceRecognizer")
fr=i01.opencv.addFilter("FaceRecognizer")
fr.train()# it takes some time to train and be able to recognize face
#if((lastName+"-inmoovWebKit" not in inmoovWebKit.getSessionNames())):
#... | def facerecognizer():
i01.opencv.capture()
i01.opencv.addFilter('PyramidDown')
i01.opencv.setDisplayFilter('FaceRecognizer')
fr = i01.opencv.addFilter('FaceRecognizer')
fr.train() |
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if len(str) == 0 or str[0] not in list('+- 0123456789') or '+-' in str or '-+' in str:
return 0
sign = 1
answer = []
for i, s in enumerate(str):
... | class Solution(object):
def my_atoi(self, str):
"""
:type str: str
:rtype: int
"""
if len(str) == 0 or str[0] not in list('+- 0123456789') or '+-' in str or ('-+' in str):
return 0
sign = 1
answer = []
for (i, s) in enumerate(str):
... |
class ARGA ( object ) :
def __init__( self ) :
pass
def __len__( self ) :
return 0
def build_primitive_dispatch( self ) :
return ''
class ARG( ARGA ) :
def __init__( self, *pattern ) :
self.pattern = pattern
CORE.register_pattern( self )
def __repr__( self ) :
return 'ARG[ ' ... | class Arga(object):
def __init__(self):
pass
def __len__(self):
return 0
def build_primitive_dispatch(self):
return ''
class Arg(ARGA):
def __init__(self, *pattern):
self.pattern = pattern
CORE.register_pattern(self)
def __repr__(self):
return 'A... |
def setup ():
strokeWeight(140)
size (500, 500)
smooth ()
noLoop ()
noStroke()
def draw ():
background (50)
fill (94, 206, 40, 250)
ellipse (100, 100, 150, 150)
fill (94, 206, 40, 150)
ellipse (100, 200, 150, 150)
fill (94, 206, 40, 100)
ellipse (100, 300... | def setup():
stroke_weight(140)
size(500, 500)
smooth()
no_loop()
no_stroke()
def draw():
background(50)
fill(94, 206, 40, 250)
ellipse(100, 100, 150, 150)
fill(94, 206, 40, 150)
ellipse(100, 200, 150, 150)
fill(94, 206, 40, 100)
ellipse(100, 300, 150, 150)
fill(94, ... |
{
'targets': [
{
'target_name': 'serialport',
'sources': [
'src/serialport.cpp',
'src/serialport_unix.cpp',
],
'conditions': [
['OS=="win"',
{
'sources': [
"src/serialport_win.cpp",
'src/win/disphelper.c',
... | {'targets': [{'target_name': 'serialport', 'sources': ['src/serialport.cpp', 'src/serialport_unix.cpp'], 'conditions': [['OS=="win"', {'sources': ['src/serialport_win.cpp', 'src/win/disphelper.c', 'src/win/enumser.cpp']}], ['OS!="win"', {'sources': ['src/serialport_unix.cpp']}]]}]} |
# Create a file phonebook.det that stores the details in following format:
# Name Phone
# Jiving 8666000
# Kriti 1010101
# Obtain the details from the user.
fileObj = open("phonebook.det","w")
fileObj.write("Name \t")
fileObj.write("Phone \t")
fileObj.write("\n")
while True :
name = input("Ente... | file_obj = open('phonebook.det', 'w')
fileObj.write('Name \t')
fileObj.write('Phone \t')
fileObj.write('\n')
while True:
name = input('Enter Name: ')
fileObj.write(name + '\t')
phone = input('Enter Phone: ')
fileObj.write(phone + '\t')
fileObj.write('\n')
user = input("Enter 'Q' or 'q' to quit (... |
class XacException(Exception):
"""
Generic exception
"""
def __init__(self, original_exc, msg=None):
msg = 'An exception occurred in the Xac service' if msg is None else msg
super(XacException, self).__init__(
msg=msg + ': {}'.format(original_exc))
self.original_exc =... | class Xacexception(Exception):
"""
Generic exception
"""
def __init__(self, original_exc, msg=None):
msg = 'An exception occurred in the Xac service' if msg is None else msg
super(XacException, self).__init__(msg=msg + ': {}'.format(original_exc))
self.original_exc = original_ex... |
def readBinaryDataSet(metaFilePath,binaryFilePath):
dfmeta = pd.read_csv(metaFilePath)
binaryFile = open(binaryFilePath,'rb')
# print binaryFile.seek()
FileVars={}
for ind in dfmeta.index:
binaryFile.seek(dfmeta.loc[ind,'startBytePosition'])
typenum = None
if dfmeta.loc[ind,'internalVartype'] == 'int':
... | def read_binary_data_set(metaFilePath, binaryFilePath):
dfmeta = pd.read_csv(metaFilePath)
binary_file = open(binaryFilePath, 'rb')
file_vars = {}
for ind in dfmeta.index:
binaryFile.seek(dfmeta.loc[ind, 'startBytePosition'])
typenum = None
if dfmeta.loc[ind, 'internalVartype'] =... |
def hello_world(event):
return f"Hello, World!"
def hello_bucket(event, context):
return f"A new file was uploaded to the bucket" | def hello_world(event):
return f'Hello, World!'
def hello_bucket(event, context):
return f'A new file was uploaded to the bucket' |
def solve():
for n in range(1, 1001):
for m in range(n + 1, 1001):
a, b, c = (m**2 - n**2, 2 * m * n, m**2 + n**2)
if a + b + c == 1000:
return a * b * c
if __name__ == "__main__":
print(solve()) | def solve():
for n in range(1, 1001):
for m in range(n + 1, 1001):
(a, b, c) = (m ** 2 - n ** 2, 2 * m * n, m ** 2 + n ** 2)
if a + b + c == 1000:
return a * b * c
if __name__ == '__main__':
print(solve()) |
def matrixElementsSum(matrix):
sum = 0
for i in range(0,len(matrix)-1):
for j in range(0,len(matrix[i])):
if matrix[i][j] == 0:
matrix[i+1][j] = 0
for row in matrix:
for element in row:
sum = sum + element
return sum
| def matrix_elements_sum(matrix):
sum = 0
for i in range(0, len(matrix) - 1):
for j in range(0, len(matrix[i])):
if matrix[i][j] == 0:
matrix[i + 1][j] = 0
for row in matrix:
for element in row:
sum = sum + element
return sum |
"""SECCOMP policy.
This policy is based on the default Docker SECCOMP policy profile. It
allows several syscalls, which are most commonly used. We make one major
change regarding the network-related ``socket`` syscall in that we only
allow AF_INET/AF_INET6 SOCK_DGRAM/SOCK_STREAM sockets for TCP and UDP
protocols.
"""
... | """SECCOMP policy.
This policy is based on the default Docker SECCOMP policy profile. It
allows several syscalls, which are most commonly used. We make one major
change regarding the network-related ``socket`` syscall in that we only
allow AF_INET/AF_INET6 SOCK_DGRAM/SOCK_STREAM sockets for TCP and UDP
protocols.
"""
... |
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def opentelemetry_cpp_deps():
"""Loads dependencies need to compile the opentelemetry-cpp library."""
# Google Benchmark library.
# Only needed for benchmarks, not to build t... | load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def opentelemetry_cpp_deps():
"""Loads dependencies need to compile the opentelemetry-cpp library."""
maybe(http_archive, name='com_github_google_benchmark', sha256='dccbdab796baa... |
""""
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
... | """"
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
"""
class Solution(object):
def has_cycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
'\n Method 1: Using a hash set\n\n * As we tra... |
# 28. Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.
# Question:
# Input:
"""
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237,... | """
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]
"""
'\n1. \n'
' \n'
'\n'
numbers = [386, 462, 4... |
class MapPiece(object):
name = ""
tiles = ""
symbolic_links = {}
spawn_ratios = tuple()
spawners = tuple()
connectors = {}
@classmethod
def write_tiles_level(cls, level, left_x, top_y):
local_x = 0
local_y = 0
for line in cls.tiles:
for char in line:
... | class Mappiece(object):
name = ''
tiles = ''
symbolic_links = {}
spawn_ratios = tuple()
spawners = tuple()
connectors = {}
@classmethod
def write_tiles_level(cls, level, left_x, top_y):
local_x = 0
local_y = 0
for line in cls.tiles:
for char in line:
... |
# Copyright 2010-2021, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... | {'targets': [{'target_name': 'ios_engine_main', 'type': 'executable', 'sources': ['ios_engine_main.cc'], 'dependencies': ['ios_engine']}, {'target_name': 'ios_engine', 'type': 'static_library', 'sources': ['ios_engine.cc', 'ios_engine.h'], 'dependencies': ['../base/absl.gyp:absl_synchronization', '../base/base.gyp:base... |
class Solution:
def __init__(self, w: List[int]):
self.length = sum(w)
self.n = len(w)
self.w_pool = [0]
for i in range(self.n):
self.w_pool.append(self.w_pool[-1] + w[i])
def pickIndex(self) -> int:
picked_val = random.uniform(0, self.length)
i = 0
... | class Solution:
def __init__(self, w: List[int]):
self.length = sum(w)
self.n = len(w)
self.w_pool = [0]
for i in range(self.n):
self.w_pool.append(self.w_pool[-1] + w[i])
def pick_index(self) -> int:
picked_val = random.uniform(0, self.length)
i = 0... |
def montana_getEnhancedLocation(location):
"""Add Montana to the location if not there already."""
return add_state(location, "Montana")
def montana_cleanPrice(price):
return price_quantity_us_number(price)
def montana_getCurrency(price):
return price_currency(price)
| def montana_get_enhanced_location(location):
"""Add Montana to the location if not there already."""
return add_state(location, 'Montana')
def montana_clean_price(price):
return price_quantity_us_number(price)
def montana_get_currency(price):
return price_currency(price) |
class WordDictionary(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.root = {}
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
node = self.root
... | class Worddictionary(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.root = {}
def add_word(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
node = self.root
... |
class TrainTaskConfig(object):
use_gpu = False
# the epoch number to train.
pass_num = 2
# the number of sequences contained in a mini-batch.
batch_size = 64
# the hyper parameters for Adam optimizer.
learning_rate = 0.001
beta1 = 0.9
beta2 = 0.98
eps = 1e-9
# the paramete... | class Traintaskconfig(object):
use_gpu = False
pass_num = 2
batch_size = 64
learning_rate = 0.001
beta1 = 0.9
beta2 = 0.98
eps = 1e-09
warmup_steps = 4000
use_avg_cost = False
model_dir = 'trained_models'
class Infertaskconfig(object):
use_gpu = False
batch_size = 10
... |
INSTALLED_APPS = [
"django_event_sourcing",
"django.contrib.auth",
"django.contrib.contenttypes",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
SECRET_KEY = "This is a SECRET_KEY"
EVENT_TYPES = [
"tests.event_types.DummyEventType"... | installed_apps = ['django_event_sourcing', 'django.contrib.auth', 'django.contrib.contenttypes']
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
secret_key = 'This is a SECRET_KEY'
event_types = ['tests.event_types.DummyEventType'] |
#! python2.7
## -*- coding: utf-8 -*-
## kun for Apk View Tracing
## TreeType.py
#===============================================================================
# # data structures
#===============================================================================
class CRect(object):
mLeft = 0
mRigh... | class Crect(object):
m_left = 0
m_right = 0
m_top = 0
m_bottom = 0
class Cpoint:
x = 0
y = 0
class Ctreenode(object):
m_class_name = 'mClassName'
m_hash_code = 'fffff'
m_id = 'mId'
m_text = 'mText'
m_absolute_rect = c_rect()
m_rect = c_rect()
m_location = c_point()
... |
grades = {
"English": 97,
"Math": 93,
"Art": 74,
"Music": 86
}
grades.setdefault("Art", 87) # Art key exists. No change.
print("Art grade:", grades["Art"])
grades.setdefault("Gym", 97) # Gym key is new. Added and set.
print("Gym grade:", grades["Gym"]) | grades = {'English': 97, 'Math': 93, 'Art': 74, 'Music': 86}
grades.setdefault('Art', 87)
print('Art grade:', grades['Art'])
grades.setdefault('Gym', 97)
print('Gym grade:', grades['Gym']) |
# Utility functions for viterbi-trellis.
#
# argmin is defined here to avoid dependence on e.g., numpy.
def argmin(list_obj):
"""Returns the index of the min value in the list."""
min = None
best_idx = None
for idx, val in enumerate(list_obj):
if min is None or val < min:
min = val... | def argmin(list_obj):
"""Returns the index of the min value in the list."""
min = None
best_idx = None
for (idx, val) in enumerate(list_obj):
if min is None or val < min:
min = val
best_idx = idx
return best_idx |
strategy_type = "learning"
config = {
"strategy_id": "svm",
"name": "Support Vector Machine Classifier",
"parameters": [
{
"parameter_id": "C",
"label": "C - Error term weight",
"type": "float",
"default_value": 2.6,
},
{
"p... | strategy_type = 'learning'
config = {'strategy_id': 'svm', 'name': 'Support Vector Machine Classifier', 'parameters': [{'parameter_id': 'C', 'label': 'C - Error term weight', 'type': 'float', 'default_value': 2.6}, {'parameter_id': 'kernel', 'label': 'SVM kernel', 'selection_values': ['linear', 'poly', 'sigmoid', 'rbf'... |
# is_learning = True
# while is_learning:
# print('Learning...')
# ask = input('Are you still learning? ')
# is_learning = ask == 'yes'
# if not is_learning:
# print('You finally mastered it')
people = ['Alice', 'Bob', 'Charlie']
for person in people:
print(person)
indices = [0, 1, 2, 3, 4]
for _ i... | people = ['Alice', 'Bob', 'Charlie']
for person in people:
print(person)
indices = [0, 1, 2, 3, 4]
for _ in indices:
print('I will repeat 5 times')
for _ in range(5):
print('I will repeat 5 times again')
start = 2
stop = 20
step = 3
for index in range(start, stop, step):
print(index)
students = [{'name'... |
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
This module contains miscellaneous functions used by the modules that convert a GNDS reactionSuite into an ACE file.
"""
... | """
This module contains miscellaneous functions used by the modules that convert a GNDS reactionSuite into an ACE file.
"""
float_format_others = '%20.12E'
float_format_energy_grid = '%21.13E'
float_format_energy_grid = floatFormatOthers
def update_xss_info(label, annotates, XSS, data):
annotates.append((len(XSS)... |
def height(root):
if root is None:
return -1
left_height = height(root.left)
right_height = height(root.right)
return 1 + max(left_height, right_height) | def height(root):
if root is None:
return -1
left_height = height(root.left)
right_height = height(root.right)
return 1 + max(left_height, right_height) |
class Solution:
"""
@param M: a matrix
@return: the total number of friend circles among all the students
"""
def findCircleNum(self, M):
# Write your code here
res, queue = 0, []
visited = [False for _ in range(len(M))]
for i in range(len(M)):
if... | class Solution:
"""
@param M: a matrix
@return: the total number of friend circles among all the students
"""
def find_circle_num(self, M):
(res, queue) = (0, [])
visited = [False for _ in range(len(M))]
for i in range(len(M)):
if not visited[i]:
... |
#
# PySNMP MIB module LIEBERT-GP-REGISTRATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LIEBERT-GP-REGISTRATION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:56:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
class BadRequest(Exception):
pass
class ParamError(BadRequest):
pass
class Unauthorized(Exception):
pass
class Forbidden(Exception):
pass
class NotFound(Exception):
pass
class IDNotFoundError(NotFound):
pass
class Conflict(Exception):
pass
class ParamConflict(Conflict):
pass
cla... | class Badrequest(Exception):
pass
class Paramerror(BadRequest):
pass
class Unauthorized(Exception):
pass
class Forbidden(Exception):
pass
class Notfound(Exception):
pass
class Idnotfounderror(NotFound):
pass
class Conflict(Exception):
pass
class Paramconflict(Conflict):
pass
clas... |
# Copyright (c) 2017 Mark D. Hill and David A. Wood
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditio... | class Result:
enums = '\n NotRun\n Skipped\n Passed\n Failed\n Errored\n '.split()
for (idx, enum) in enumerate(enums):
locals()[enum] = idx
@classmethod
def name(cls, enum):
return cls.enums[enum]
def __init__(self, value, reason=None):
... |
a= "goat"
def animal():
global a
b = "pakka"
a = a * 6
print(a)
print(b)
animal()
| a = 'goat'
def animal():
global a
b = 'pakka'
a = a * 6
print(a)
print(b)
animal() |
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
alist = input('Enter the list of numbers: ').split()... | def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
(alist[i], alist[smallest]) = (alist[smallest], alist[i])
alist = input('Enter the list of numbers: ').split()... |
# Idenpotant
# Closure
def outer_function(tag):
pass
def add(x, y):
return x + y
def deco(orig_func):
def wrapper(*args, **kwargs):
print("That is to know that I ran the deco func")
return orig_func(*args, **kwargs)
return wrapper
add = deco(add)
print(add(3, 5))
| def outer_function(tag):
pass
def add(x, y):
return x + y
def deco(orig_func):
def wrapper(*args, **kwargs):
print('That is to know that I ran the deco func')
return orig_func(*args, **kwargs)
return wrapper
add = deco(add)
print(add(3, 5)) |
skills = [
{
"id" : "0001",
"name" : "Liver of Steel",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"maximumInebriety" : "+5",
},
},
{
"id" : "0002",
"name" : "Chronic Indigestion",
"type" : "Combat",
... | skills = [{'id': '0001', 'name': 'Liver of Steel', 'type': 'Passive', 'isPermable': False, 'effects': {'maximumInebriety': '+5'}}, {'id': '0002', 'name': 'Chronic Indigestion', 'type': 'Combat', 'mpCost': 5}, {'id': '0003', 'name': 'The Smile of Mr. A.', 'type': 'Buff', 'mpCost': 5, 'isPermable': False}, {'id': '0004',... |
for cat1 in range(1, 21):
for cat2 in range(1, 21):
hypo = (cat1 ** 2 + cat2 ** 2) ** 0.5
if hypo.is_integer():
print(cat1, cat2, hypo)
| for cat1 in range(1, 21):
for cat2 in range(1, 21):
hypo = (cat1 ** 2 + cat2 ** 2) ** 0.5
if hypo.is_integer():
print(cat1, cat2, hypo) |
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""Module testing the Legend Studio Operator."""
| """Module testing the Legend Studio Operator.""" |
#
# Copyright 2018-2019 IBM Corp. 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 law... | debug = False
restplus_mask_swagger = False
api_title = 'MAX Weather Forecaster'
api_desc = 'An API for serving models'
api_version = '1.1.0'
model_name = 'lstm_weather_forecaster'
default_model_path = 'assets/models'
model_license = 'Apache 2'
models = ['univariate', 'multistep', 'multivariate']
default_model = MODELS... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
h = set()
while head and head not in h:
h.add(head)
head = head.next
retu... | class Solution:
def has_cycle(self, head: ListNode) -> bool:
h = set()
while head and head not in h:
h.add(head)
head = head.next
return head |
class Default():
"""Single repository for default values."""
EXEC_DIRECTORY = ''
# Unit Test defaults
GOOD_CONFIG = 'null.cfg'
BAD_CONFIG = 'none.cfg'
TEST_DIR = './test_directory'
TEST_FILE_NAME = 'test.zip'
TEST_FILE_SIZE = 4 * 1024 * 1024
TEST_FILE_NULL_COUNT = 4 * 1024 * 1024 *... | class Default:
"""Single repository for default values."""
exec_directory = ''
good_config = 'null.cfg'
bad_config = 'none.cfg'
test_dir = './test_directory'
test_file_name = 'test.zip'
test_file_size = 4 * 1024 * 1024
test_file_null_count = 4 * 1024 * 1024 * 0.25
test_null_char = '\... |
class ServiceModel:
@property
def short_name(self):
return self.__service_short_name
@property
def count(self):
return self.__count_slot
@count.setter
def count(self, value):
self.__count_slot = int(value)
def object_factory(name, base_class, argnames):
... | class Servicemodel:
@property
def short_name(self):
return self.__service_short_name
@property
def count(self):
return self.__count_slot
@count.setter
def count(self, value):
self.__count_slot = int(value)
def object_factory(name, base_class, argnames):
def __ini... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"main": "00_beproductive.ipynb",
"parse_arguments": "00_beproductive.ipynb",
"in_notebook": "00_beproductive.ipynb",
"APP_NAME": "01_blocker.ipynb",
"REDIRECT": "01... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'main': '00_beproductive.ipynb', 'parse_arguments': '00_beproductive.ipynb', 'in_notebook': '00_beproductive.ipynb', 'APP_NAME': '01_blocker.ipynb', 'REDIRECT': '01_blocker.ipynb', 'WIN_PATH': '01_blocker.ipynb', 'LINUX_PATH': '01_blocker.ipynb', 'N... |
def sumar(a, b):
return a + b
def restar(a, b):
return a - b
def multiplicador(a, b):
return a * b
def dividir(numerador, denominador):
return float(numerador)/denominador | def sumar(a, b):
return a + b
def restar(a, b):
return a - b
def multiplicador(a, b):
return a * b
def dividir(numerador, denominador):
return float(numerador) / denominador |
class MockOpenedFile(object):
def __init__(self, value='value'):
self.seek_values = []
self.buf_values = []
self.value = value
def seek(self, offset):
self.seek_values.append(offset)
def read(self, buf):
self.buf_values.append(buf)
return self.value
def... | class Mockopenedfile(object):
def __init__(self, value='value'):
self.seek_values = []
self.buf_values = []
self.value = value
def seek(self, offset):
self.seek_values.append(offset)
def read(self, buf):
self.buf_values.append(buf)
return self.value
de... |
"""Write a function that checks whether an element occurs in a list."""
def check_existence_of_element(a,b):
if a in b:
print ("the item in list")
else:
print ("the item is not in the list")
item = 1
mylist = [1, 4, 5, 100, 2, 1, -1, -7]
check_existence_of_element(item,mylist)
#index = -1 | """Write a function that checks whether an element occurs in a list."""
def check_existence_of_element(a, b):
if a in b:
print('the item in list')
else:
print('the item is not in the list')
item = 1
mylist = [1, 4, 5, 100, 2, 1, -1, -7]
check_existence_of_element(item, mylist) |
"""
Binary Search
Given a sorted array arr[] of n elements, write a function to search a given
element x in arr[].
A simple approach is to do linear search.The time complexity of above algorithm
is O(n). Another approach to perform the same task is using Binary Search.
Binary Search: Search a sorted array by repeate... | """
Binary Search
Given a sorted array arr[] of n elements, write a function to search a given
element x in arr[].
A simple approach is to do linear search.The time complexity of above algorithm
is O(n). Another approach to perform the same task is using Binary Search.
Binary Search: Search a sorted array by repeate... |
"""
extended GCD algorithm
return s,t,g
such that a s + b t = GCD(a, b)
and s and t are coprime
"""
def extended_gcd(a,b):
old_s, s = 1, 0
old_t, t = 0, 1
old_r, r = a, b
while r != 0:
quotient = old_r / r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - qu... | """
extended GCD algorithm
return s,t,g
such that a s + b t = GCD(a, b)
and s and t are coprime
"""
def extended_gcd(a, b):
(old_s, s) = (1, 0)
(old_t, t) = (0, 1)
(old_r, r) = (a, b)
while r != 0:
quotient = old_r / r
(old_r, r) = (r, old_r - quotient * r)
(old_s, s) = (s, old_... |
# CountFirstCharaters
# --------------------------------------
# It counts how many times a character appears at the beginning of a line
def CountFirstCharacters (Line, Character):
n = 0
for letter in Line:
if letter == Character:
n = n + 1
else:
return n
# Remove all the Character characters from the li... | def count_first_characters(Line, Character):
n = 0
for letter in Line:
if letter == Character:
n = n + 1
else:
return n
def remove_first_characters(Line, Character):
n = count_firstcharacters(Line, Character)
return Line[n:] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.