content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class MachineDetails:
"""
Class to represent the HTB machine details
"""
def __init__(self, identifier, name, operating_system, ip, avatar, avatar_thumb, points, release, retired_date,
maker, maker2, ratings_pro, ratings_sucks, user_blood, root_blood, user_owns, root_owns):
s... | class Machinedetails:
"""
Class to represent the HTB machine details
"""
def __init__(self, identifier, name, operating_system, ip, avatar, avatar_thumb, points, release, retired_date, maker, maker2, ratings_pro, ratings_sucks, user_blood, root_blood, user_owns, root_owns):
self.identifier = id... |
file1 = ""
file2 = ""
with open('Hello.txt') as f:
file1 = f.read()
with open('Hi.txt') as f:
file2 = f.read()
file1 += "\n"
file1 += file2
with open('file3.txt', 'w') as f:
f.write(file1) | file1 = ''
file2 = ''
with open('Hello.txt') as f:
file1 = f.read()
with open('Hi.txt') as f:
file2 = f.read()
file1 += '\n'
file1 += file2
with open('file3.txt', 'w') as f:
f.write(file1) |
ix.enable_command_history()
ix.api.SdkHelpers.enable_disable_items_selected(ix.application, False)
ix.disable_command_history() | ix.enable_command_history()
ix.api.SdkHelpers.enable_disable_items_selected(ix.application, False)
ix.disable_command_history() |
# -*- coding: utf-8 -*-
"""
pepipost
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class TimeperiodEnum(object):
"""Implementation of the 'Timeperiod' enum.
The periodic \n\nAllowed values \"daily\", \"weekly\", \"monhtly\"
Attributes:
... | """
pepipost
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Timeperiodenum(object):
"""Implementation of the 'Timeperiod' enum.
The periodic
Allowed values "daily", "weekly", "monhtly"
Attributes:
DAILY: TODO: type description here.
W... |
#!/usr/bin/env python
######################################
# Installation module for King Phisher
######################################
# AUTHOR OF MODULE NAME
AUTHOR="Spencer McIntyre (@zeroSteiner)"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install/update the King Phisher phishing campaign toolki... | author = 'Spencer McIntyre (@zeroSteiner)'
description = 'This module will install/update the King Phisher phishing campaign toolkit'
install_type = 'GIT'
repository_location = 'https://github.com/securestate/king-phisher/'
install_location = 'king-phisher'
debian = 'git'
fedora = 'git'
after_commands = 'cd {INSTALL_LO... |
num = int(input())
for i in range(1, num+1):
s = ''
for j in range(1, i):
s += str(j)
for j in range(i, 0, -1):
s += str(j)
print(s) | num = int(input())
for i in range(1, num + 1):
s = ''
for j in range(1, i):
s += str(j)
for j in range(i, 0, -1):
s += str(j)
print(s) |
def replace_spaces_dashes(line):
return "-".join(line.split())
def last_five_lowercase(line):
return line[-5:].lower()
def backwards_skipped(line):
return line[::-2]
if __name__ == '__main__':
line = input("Enter a string: ")
print(replace_spaces_dashes(line))
print(last_five_lowercase(lin... | def replace_spaces_dashes(line):
return '-'.join(line.split())
def last_five_lowercase(line):
return line[-5:].lower()
def backwards_skipped(line):
return line[::-2]
if __name__ == '__main__':
line = input('Enter a string: ')
print(replace_spaces_dashes(line))
print(last_five_lowercase(line))
... |
# TODO: refactor nested_dict into common library with ATen
class nested_dict(object):
"""
A nested dict is a dictionary with a parent. If key lookup fails,
it recursively continues into the parent. Writes always happen to
the top level dict.
"""
def __init__(self, base, parent):
self.... | class Nested_Dict(object):
"""
A nested dict is a dictionary with a parent. If key lookup fails,
it recursively continues into the parent. Writes always happen to
the top level dict.
"""
def __init__(self, base, parent):
(self.base, self.parent) = (base, parent)
def __contains__(... |
beggars_jobs = [int(x) for x in input().split(", ")]
count_of_beggars = int(input())
final_list = []
for num in range(count_of_beggars):
jobs = 0
for index in range(num, len(beggars_jobs), count_of_beggars):
jobs += beggars_jobs[index]
final_list.append(jobs)
print(final_list)
| beggars_jobs = [int(x) for x in input().split(', ')]
count_of_beggars = int(input())
final_list = []
for num in range(count_of_beggars):
jobs = 0
for index in range(num, len(beggars_jobs), count_of_beggars):
jobs += beggars_jobs[index]
final_list.append(jobs)
print(final_list) |
""" --- geometry parameters for simple geometry of cylindrical tube with spherical particle inside, 2D --- """
# length scale
nm = 1e-0
# tolerance for coordinate comparisons
tolc = 1e-9*nm
dim = 2
# cylinder radius
R = 40*nm
# cylinder length
l = 80*nm
# particle position (z-axis)
z0 = 0*nm
# particle radius
r = ... | """ --- geometry parameters for simple geometry of cylindrical tube with spherical particle inside, 2D --- """
nm = 1.0
tolc = 1e-09 * nm
dim = 2
r = 40 * nm
l = 80 * nm
z0 = 0 * nm
r = 6 * nm |
try:
raise
except:
pass
try:
raise NotImplementedError('User Defined Error Message.')
except NotImplementedError as err:
print('NotImplementedError')
except:
print('Error :')
try:
raise KeyError('missing key')
except KeyError as ex:
print('KeyError')
except:
print('Error :')
try:
... | try:
raise
except:
pass
try:
raise not_implemented_error('User Defined Error Message.')
except NotImplementedError as err:
print('NotImplementedError')
except:
print('Error :')
try:
raise key_error('missing key')
except KeyError as ex:
print('KeyError')
except:
print('Error :')
try:
... |
"""
Given a string s and an integer array indices of the same length.
The string s will be shuffled such that the character at the ith position
moves to indices[i] in the shuffled string.
Return the shuffled string.
Example:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetc... | """
Given a string s and an integer array indices of the same length.
The string s will be shuffled such that the character at the ith position
moves to indices[i] in the shuffled string.
Return the shuffled string.
Example:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetc... |
def extractBersekerTranslations(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if 'Because the world has changed into a death game is funny' in item['tags'] and (chp or vol or 'Prologue' in postfix):
return buildReleaseMessageWithType(item, 'Sekai ga death game ni natta ... | def extract_berseker_translations(item):
"""
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if 'Because the world has changed into a death game is funny' in item['tags'] and (chp or vol or 'Prologue' in postfix):
return build_release_message_with_type(item, 'Se... |
N = int(input())
combined_length = 0
for _ in range(N):
length = int(input())
combined_length += length
print(combined_length - (N-1))
| n = int(input())
combined_length = 0
for _ in range(N):
length = int(input())
combined_length += length
print(combined_length - (N - 1)) |
class Resort:
def __init__(self):
self._mysql = False
self._postgres = False
self._borg = False
def name(self, name):
self._name = name
return self
def appendName(self, text):
return text+self._name
return self
def storage(self, storage):
... | class Resort:
def __init__(self):
self._mysql = False
self._postgres = False
self._borg = False
def name(self, name):
self._name = name
return self
def append_name(self, text):
return text + self._name
return self
def storage(self, storage):
... |
#! python3
# -*- coding: utf-8 -*-
def method(args1='sample2'):
print(args1 + " is runned")
print("")
| def method(args1='sample2'):
print(args1 + ' is runned')
print('') |
def extract_author(simple_author_1):
list_tokenize_name=simple_author_1.split("and")
if len(list_tokenize_name)>1:
authors_list = []
for tokenize_name in list_tokenize_name:
splitted=tokenize_name.split(",")
authors_list.append((splitted[0].strip(),splitted[1].strip()))
... | def extract_author(simple_author_1):
list_tokenize_name = simple_author_1.split('and')
if len(list_tokenize_name) > 1:
authors_list = []
for tokenize_name in list_tokenize_name:
splitted = tokenize_name.split(',')
authors_list.append((splitted[0].strip(), splitted[1].stri... |
class SwaggerYaml:
def __init__(self, swagger, info, schemes, basePath, produces, paths, definitions):
self.swagger = swagger
self.info = info
self.schemes = schemes
self.basePath = basePath
self.produces = produces
self.paths = paths
self.definitions = def... | class Swaggeryaml:
def __init__(self, swagger, info, schemes, basePath, produces, paths, definitions):
self.swagger = swagger
self.info = info
self.schemes = schemes
self.basePath = basePath
self.produces = produces
self.paths = paths
self.definitions = defin... |
# ------------------------------
# 401. Binary Watch
#
# Description:
# A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
# Each LED represents a zero or one, with the least significant bit on the right.
#
# Given a non-negative integer n... | class Solution(object):
def read_binary_watch(self, num):
"""
:type num: int
:rtype: List[str]
"""
res = []
for h in range(12):
for m in range(60):
if (bin(h) + bin(m)).count('1') == num:
if m < 10:
... |
"""
Question:
Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:... | """
Question:
Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:... |
# Temperature of an oven setting by reading from a pressure meter
r = int(input("Enter the reading:- "))
if( (r == 2) or (r == 3) ):
print("Temperature set to 500 degrees.")
elif( r==4):
print("Temperature set to 600 degrees.")
elif((r==5)or(r==6)or(r==7)):
print("Temperature set to 700 degrees.")
... | r = int(input('Enter the reading:- '))
if r == 2 or r == 3:
print('Temperature set to 500 degrees.')
elif r == 4:
print('Temperature set to 600 degrees.')
elif r == 5 or r == 6 or r == 7:
print('Temperature set to 700 degrees.')
elif r < 2 or r > 7:
print('DEFAULT:- The temperature setting is 300 degree... |
# tested
def Main():
a = 1
b = 10
c = 20
d = add(a, b, 10)
d2 = add(d, d, d)
return d2
def add(a, b, c):
result = a + b + c
return result
| def main():
a = 1
b = 10
c = 20
d = add(a, b, 10)
d2 = add(d, d, d)
return d2
def add(a, b, c):
result = a + b + c
return result |
#
# @lc app=leetcode id=779 lang=python3
#
# [779] K-th Symbol in Grammar
#
# @lc code=start
class Solution(object):
def kthGrammar(self, N, K):
"""
:type N: int
:type K: int
:rtype: int
"""
if N == 1: return 0
if K == 2: return 1
if K <= 1 << N - 2: ... | class Solution(object):
def kth_grammar(self, N, K):
"""
:type N: int
:type K: int
:rtype: int
"""
if N == 1:
return 0
if K == 2:
return 1
if K <= 1 << N - 2:
return self.kthGrammar(N - 1, K)
k -= 1 << N - 2... |
#!/usr/bin/env python
#########################################################################################
#
# Test function sct_documentation
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca>
# Author: Aug... | def test(data_path):
cmd = 'sct_propseg'
return sct.run(cmd)
if __name__ == '__main__':
test() |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
# encoding: utf-8
# module Tekla.Structures.Geometry3d calls itself Geometry3d
# from Tekla.Structures,Version=2017.0.0.0,Culture=neutral,PublicKeyToken=2f04dbe497b71114
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class AABB(object):
"""
AABB()
AABB(MinPoint: Point,MaxPo... | class Aabb(object):
"""
AABB()
AABB(MinPoint: Point,MaxPoint: Point)
AABB(AABB: AABB)
"""
def collide(self, Other):
""" Collide(self: AABB,Other: AABB) -> bool """
pass
def get_center_point(self):
""" GetCenterPoint(self: AABB) -> Point """
pass
def is_inside(sel... |
nilai = 9
if (nilai > 7):
print ("Selamat Anda Jadi programmer")
if (nilai > 10):
print ("Selamat Anda Jadi programmer handal") | nilai = 9
if nilai > 7:
print('Selamat Anda Jadi programmer')
if nilai > 10:
print('Selamat Anda Jadi programmer handal') |
# list all array connections
res = client.get_array_connections()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
# list all array connections with remote name "otherarray"
res = client.get_array_connections(remote_names=["otherarray"])
print(res)
if type(res) == pypureclient... | res = client.get_array_connections()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
res = client.get_array_connections(remote_names=['otherarray'])
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
res = client.get_array_connections(... |
kanto, johto, hoenn = input().split()
catch_kanto, catch_johto, catch_hoenn = input().split()
total_kanto = int(kanto) + int(catch_kanto)
total_johto = int(johto) + int(catch_johto)
total_hoenn = int(hoenn) + int(catch_hoenn)
print(f"{total_kanto} {total_johto} {total_hoenn}") | (kanto, johto, hoenn) = input().split()
(catch_kanto, catch_johto, catch_hoenn) = input().split()
total_kanto = int(kanto) + int(catch_kanto)
total_johto = int(johto) + int(catch_johto)
total_hoenn = int(hoenn) + int(catch_hoenn)
print(f'{total_kanto} {total_johto} {total_hoenn}') |
{
'variables':
{
'external_libmediaserver%' : '<!(echo $LIBMEDIASERVER)',
'external_libmediaserver_include_dirs%' : '<!(echo $LIBMEDIASERVER_INCLUDE)',
},
"targets":
[
{
"target_name": "medooze-fake-h264-encoder",
"cflags":
[
"-march=native",
"-fexceptions",
"-O3",
... | {'variables': {'external_libmediaserver%': '<!(echo $LIBMEDIASERVER)', 'external_libmediaserver_include_dirs%': '<!(echo $LIBMEDIASERVER_INCLUDE)'}, 'targets': [{'target_name': 'medooze-fake-h264-encoder', 'cflags': ['-march=native', '-fexceptions', '-O3', '-g', '-Wno-unused-function -Wno-comment'], 'cflags_cc': ['-fex... |
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
ns = [e for e in s]
left, right = 0, len(s) - 1
while right > left:
while s[left] not in vowels and left < right:
left += 1
... | class Solution:
def reverse_vowels(self, s: str) -> str:
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
ns = [e for e in s]
(left, right) = (0, len(s) - 1)
while right > left:
while s[left] not in vowels and left < right:
left += 1
... |
def reverse(string):
return string[::-1]
print('Gimmie some word')
s = input()
print(reverse(s))
| def reverse(string):
return string[::-1]
print('Gimmie some word')
s = input()
print(reverse(s)) |
"""
External repositories used in this workspace.
"""
load("@bazel_gazelle//:deps.bzl", "go_repository")
def go_repositories():
go_repository(
name = "co_honnef_go_tools",
importpath = "honnef.co/go/tools",
sum = "h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=",
version = "v0.0.0-... | """
External repositories used in this workspace.
"""
load('@bazel_gazelle//:deps.bzl', 'go_repository')
def go_repositories():
go_repository(name='co_honnef_go_tools', importpath='honnef.co/go/tools', sum='h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=', version='v0.0.0-20190523083050-ea95bdfd59fc')
go_repos... |
"""Load dependencies needed to compile and test the grpc library as a 3rd-party consumer."""
def grpc_deps():
"""Loads dependencies need to compile and test the grpc library."""
pass
| """Load dependencies needed to compile and test the grpc library as a 3rd-party consumer."""
def grpc_deps():
"""Loads dependencies need to compile and test the grpc library."""
pass |
# Roman Ramirez, rr8rk@virginia.edu
# Advent of Code 2021, Day 14: Extended Polymerization
#%% LONG INPUT
my_input = []
with open('input.txt', 'r') as f:
for line in f:
my_input.append(line.strip('\n'))
#%% EXAMPLE INPUT
my_input = [
'NNCB',
'',
'CH -> B',
'HH -> N',
'CB -> H',
... | my_input = []
with open('input.txt', 'r') as f:
for line in f:
my_input.append(line.strip('\n'))
my_input = ['NNCB', '', 'CH -> B', 'HH -> N', 'CB -> H', 'NH -> C', 'HB -> C', 'HC -> B', 'HN -> C', 'NN -> C', 'BH -> H', 'NC -> B', 'NB -> B', 'BN -> B', 'BB -> N', 'BC -> B', 'CC -> N', 'CN -> C']
polymer = m... |
board = sum([list(input()) for _ in range(3)], [])
assert(board[4] == '1')
rest = list(range(2, 10))
clock = [1, 2, 5, 0, -1, 8, 3, 6, 7]
cclock = [3, 0, 1, 6, -1, 2, 7, 8, 5]
for start in [1, 3, 5, 7]:
for next_idx in [clock, cclock]:
now = start
ans = board[:]
for i in rest:
if... | board = sum([list(input()) for _ in range(3)], [])
assert board[4] == '1'
rest = list(range(2, 10))
clock = [1, 2, 5, 0, -1, 8, 3, 6, 7]
cclock = [3, 0, 1, 6, -1, 2, 7, 8, 5]
for start in [1, 3, 5, 7]:
for next_idx in [clock, cclock]:
now = start
ans = board[:]
for i in rest:
if ... |
class UnmodifiableModeError(Exception):
"""Raised when file-like object has indeterminate open mode."""
def __init__(self, target, *args, **kwargs):
super().__init__(target, *args, **kwargs)
self.target = target
def __repr__(self):
return '{}: {}'.format(self.__class__.__name__, se... | class Unmodifiablemodeerror(Exception):
"""Raised when file-like object has indeterminate open mode."""
def __init__(self, target, *args, **kwargs):
super().__init__(target, *args, **kwargs)
self.target = target
def __repr__(self):
return '{}: {}'.format(self.__class__.__name__, se... |
# -*- coding: utf-8 -*-
'''
Created on 1983. 08. 09.
@author: Hye-Churn Jang, CMBU Specialist in Korea, VMware [jangh@vmware.com]
'''
name = 'Project' # custom resource name
sdk = 'vra' # imported SDK at common directory
inputs = {
'create': {
'VraManager': 'constant'
},
'read': {
... | """
Created on 1983. 08. 09.
@author: Hye-Churn Jang, CMBU Specialist in Korea, VMware [jangh@vmware.com]
"""
name = 'Project'
sdk = 'vra'
inputs = {'create': {'VraManager': 'constant'}, 'read': {}, 'update': {'VraManager': 'constant'}, 'delete': {'VraManager': 'constant'}}
properties = {'name': {'type': 'string', 'tit... |
# coding=utf-8
class DictProxy(object):
store = None
def __init__(self, d):
self.Dict = d
super(DictProxy, self).__init__()
if self.store not in self.Dict or not self.Dict[self.store]:
self.Dict[self.store] = self.setup_defaults()
self.save()
self.__initia... | class Dictproxy(object):
store = None
def __init__(self, d):
self.Dict = d
super(DictProxy, self).__init__()
if self.store not in self.Dict or not self.Dict[self.store]:
self.Dict[self.store] = self.setup_defaults()
self.save()
self.__initialized = True
... |
class TextBoxBase(FocusWidget):
def getCursorPos(self):
try :
elem = self.getElement()
tr = elem.document.selection.createRange()
if tr.parentElement().uniqueID != elem.uniqueID:
return -1
return -tr.move("character", -65535)
except:
... | class Textboxbase(FocusWidget):
def get_cursor_pos(self):
try:
elem = self.getElement()
tr = elem.document.selection.createRange()
if tr.parentElement().uniqueID != elem.uniqueID:
return -1
return -tr.move('character', -65535)
except:
... |
strategies = {}
def strategy(strategy_name: str):
"""Register a strategy name and strategy Class.
Use as a decorator.
Example:
@strategy('id')
class FindById:
...
Strategy Classes are used to build Elements Objects.
Arguments:
strategy_name (... | strategies = {}
def strategy(strategy_name: str):
"""Register a strategy name and strategy Class.
Use as a decorator.
Example:
@strategy('id')
class FindById:
...
Strategy Classes are used to build Elements Objects.
Arguments:
strategy_name (str): Name of the... |
def shape(A):
num_rows = len(A)
num_cols=len(A[0]) if A else 0
return num_rows, num_cols
A=[
[1,2,3],
[3,4,5],
[4,5,6],
[6,7,8]
]
print(shape(A))
| def shape(A):
num_rows = len(A)
num_cols = len(A[0]) if A else 0
return (num_rows, num_cols)
a = [[1, 2, 3], [3, 4, 5], [4, 5, 6], [6, 7, 8]]
print(shape(A)) |
class ContentUnavailable(Exception):
"""Raises when fetching content fails or type is invalid."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
class ClosedSessionError(Exception):
"""Raises when attempting to interact with a closed client instance."""
def __... | class Contentunavailable(Exception):
"""Raises when fetching content fails or type is invalid."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
class Closedsessionerror(Exception):
"""Raises when attempting to interact with a closed client instance."""
def __i... |
INT_LITTLE_ENDIAN = '<i' # little-endian with 4 bytes
INT_BIG_ENDIAN = '>i' # big-endian with 4 bytes
SHORT_LITTLE_ENDIAN = '<h' # little-endian with 2 bytes
SHORT_BIG_ENDIAN = '<h' # big-endian with 2 bytes
| int_little_endian = '<i'
int_big_endian = '>i'
short_little_endian = '<h'
short_big_endian = '<h' |
'''
lab2
'''
#3.1
my_name = 'Tom'
print(my_name.upper())
#3.
my_id = 123
print(my_id)
#3.3
#123=my_id
my_id=your_id=123
print(my_id)
print(your_id)
#3.4
my_id_str = '123'
print(my_id_str)
#3.5
#print(my_name=my_id)
#3.6
print(my_name+my_id_str)
#3.7
print(my_name*3)
#3.8
print('hello, world. This is my first... | """
lab2
"""
my_name = 'Tom'
print(my_name.upper())
my_id = 123
print(my_id)
my_id = your_id = 123
print(my_id)
print(your_id)
my_id_str = '123'
print(my_id_str)
print(my_name + my_id_str)
print(my_name * 3)
print('hello, world. This is my first python string.'.split('.'))
message = "Tom's id is 123"
print(message) |
def sqrt(x):
"""for x>=0, return non-negative y such that y^2 = x"""
estimate = x/2.0
while True:
newestimate = ((estimate+(x/estimate))/2.0)
if newestimate == estimate:
break
estimate = newestimate
return estimate
print("The answer is ", sqrt(2.0))
print("That answe... | def sqrt(x):
"""for x>=0, return non-negative y such that y^2 = x"""
estimate = x / 2.0
while True:
newestimate = (estimate + x / estimate) / 2.0
if newestimate == estimate:
break
estimate = newestimate
return estimate
print('The answer is ', sqrt(2.0))
print('That an... |
"""Folder structure of the platform."""
class Folders:
"""Class containing the relevant folders of the platforms.
The members without underscore at the beginning are the exported (useful)
ones. The tests folders are omitted.
"""
_ROOT = "/opt/dike/"
_CODEBASE = _ROOT + "codebase/"
_DATA ... | """Folder structure of the platform."""
class Folders:
"""Class containing the relevant folders of the platforms.
The members without underscore at the beginning are the exported (useful)
ones. The tests folders are omitted.
"""
_root = '/opt/dike/'
_codebase = _ROOT + 'codebase/'
_data = ... |
def vampire_test(x, y):
product = x * y
if len(str(x) + str(y)) != len(str(product)):
return False
for i in str(x) + str(y):
if i in str(product):
return True
else:
return False
| def vampire_test(x, y):
product = x * y
if len(str(x) + str(y)) != len(str(product)):
return False
for i in str(x) + str(y):
if i in str(product):
return True
else:
return False |
#!/usr/bin/env python
class Config(object):
GABRIEL_IP='128.2.213.107'
RECEIVE_FRAME=True
VIDEO_STREAM_PORT = 9098
RESULT_RECEIVING_PORT = 9101
TOKEN=1
| class Config(object):
gabriel_ip = '128.2.213.107'
receive_frame = True
video_stream_port = 9098
result_receiving_port = 9101
token = 1 |
"""The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?"""
# from math import sqrt, ceil
NUMB = 600851475143
FACTOR = 2
PRIME_ARY = []
DIVIDER_ARY = []
while FACTOR <= NUMB:
for i in PRIME_ARY:
if FACTOR % i == 0:
break
else:
... | """The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?"""
numb = 600851475143
factor = 2
prime_ary = []
divider_ary = []
while FACTOR <= NUMB:
for i in PRIME_ARY:
if FACTOR % i == 0:
break
else:
PRIME_ARY.append(FACTOR)
... |
def isEvilNumber(n):
count = 0
for char in str(bin(n)[2:]):
if char == '1':
count += 1
if count % 2 == 0:
return True
else:
return False
print(isEvilNumber(4)) | def is_evil_number(n):
count = 0
for char in str(bin(n)[2:]):
if char == '1':
count += 1
if count % 2 == 0:
return True
else:
return False
print(is_evil_number(4)) |
b1 >> fuzz([0, 2, 3, 5], dur=1/2, amp=0.8, lpf=linvar([100, 1000], 12), lpr=0.4, oct=3).every(16, "shuffle").every(8, "bubble")
d1 >> play("x o [xx] oxx o [xx] {oO} ", room=0.4).every(16, "shuffle")
d2 >> play("[--]", amp=[1.3, 0.5, 0.5, 0.5], hpf=linvar([6000, 10000], 8), hpr=0.4, spin=4)
p1 >> pasha([0, 2, 3, 5], dur... | b1 >> fuzz([0, 2, 3, 5], dur=1 / 2, amp=0.8, lpf=linvar([100, 1000], 12), lpr=0.4, oct=3).every(16, 'shuffle').every(8, 'bubble')
d1 >> play('x o [xx] oxx o [xx] {oO} ', room=0.4).every(16, 'shuffle')
d2 >> play('[--]', amp=[1.3, 0.5, 0.5, 0.5], hpf=linvar([6000, 10000], 8), hpr=0.4, spin=4)
p1 >> pasha([0, 2, 3, 5], d... |
class Dog:
def __init__(self, age, name, is_male, weight):
self.age = age
self.name = name
self.is_male = is_male # Boolean. True if Male, False if Female.
self.weight = weight
# Create your instance below this line
my_dog = Dog(5, "Yogi", True, 15)
| class Dog:
def __init__(self, age, name, is_male, weight):
self.age = age
self.name = name
self.is_male = is_male
self.weight = weight
my_dog = dog(5, 'Yogi', True, 15) |
class TimetableException(Exception):
"""Base class exception."""
class TimetableNotFound(TimetableException):
def __init__(self, timetable_set):
self.timetable_set = timetable_set
super().__init__(f'timetable set not found: \'{timetable_set}\'')
class RequestedDayNotSupported(Tim... | class Timetableexception(Exception):
"""Base class exception."""
class Timetablenotfound(TimetableException):
def __init__(self, timetable_set):
self.timetable_set = timetable_set
super().__init__(f"timetable set not found: '{timetable_set}'")
class Requesteddaynotsupported(TimetableException... |
"""
Takes in a fasta file and creates a javascript variable containing protein accession number --> protein sequence objects
----------------------------------------------------------------
Industrial Microbes C 2017 All Rights Reserved
Contact: J Paris Morgan (jparismorgan@gmail.com) or Derek Greenfield (derek@imicrob... | """
Takes in a fasta file and creates a javascript variable containing protein accession number --> protein sequence objects
----------------------------------------------------------------
Industrial Microbes C 2017 All Rights Reserved
Contact: J Paris Morgan (jparismorgan@gmail.com) or Derek Greenfield (derek@imicrob... |
# https://www.codechef.com/viewsolution/36973732
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
count = 0
for i in range(n):
for j in range(i + 1, n):
if a[i] & a[j] == a[i]:
count += 1
print(count) | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
count = 0
for i in range(n):
for j in range(i + 1, n):
if a[i] & a[j] == a[i]:
count += 1
print(count) |
"""
Lambda functions
Functions without names, kind of similar to arrow functions in JavaScript.
"""
square = lambda num: num * num
print(square(9)) # 81
add = lambda a,b: a + b
print(add(3,10)) # 13 | """
Lambda functions
Functions without names, kind of similar to arrow functions in JavaScript.
"""
square = lambda num: num * num
print(square(9))
add = lambda a, b: a + b
print(add(3, 10)) |
"""
428. Pow(x, n)
https://www.lintcode.com/problem/powx-n/description?_from=ladder&&fromId=152
"""
class Solution:
"""
@param x {float}: the base number
@param n {int}: the power number
@return {float}: the result
"""
def myPow(self, x, n):
# write your code here
if n == 0:
... | """
428. Pow(x, n)
https://www.lintcode.com/problem/powx-n/description?_from=ladder&&fromId=152
"""
class Solution:
"""
@param x {float}: the base number
@param n {int}: the power number
@return {float}: the result
"""
def my_pow(self, x, n):
if n == 0:
return 1
ans... |
# This should be an enum once we make our own buildkite AMI with py3
class SupportedPython:
V3_8 = "3.8.1"
V3_7 = "3.7.6"
V3_6 = "3.6.10"
V3_5 = "3.5.8"
V2_7 = "2.7.17"
SupportedPythons = [
SupportedPython.V2_7,
SupportedPython.V3_5,
SupportedPython.V3_6,
SupportedPython.V3_7,
... | class Supportedpython:
v3_8 = '3.8.1'
v3_7 = '3.7.6'
v3_6 = '3.6.10'
v3_5 = '3.5.8'
v2_7 = '2.7.17'
supported_pythons = [SupportedPython.V2_7, SupportedPython.V3_5, SupportedPython.V3_6, SupportedPython.V3_7, SupportedPython.V3_8]
supported_pythons_no38 = [SupportedPython.V2_7, SupportedPython.V3_5,... |
#!/usr/bin/env python3
"""Basic utilities for nova"""
class _superpass(object):
"""Simple object to be a placeholder"""
def __getattr__(self, name):
return self
def __setattr__(self, name, value):
return
def __delattr__(self, name):
return
def __getitem__(self, name)... | """Basic utilities for nova"""
class _Superpass(object):
"""Simple object to be a placeholder"""
def __getattr__(self, name):
return self
def __setattr__(self, name, value):
return
def __delattr__(self, name):
return
def __getitem__(self, name):
return self
... |
print(
3 + 4,
3 - 4,
3 * 4,
3 / 4,
3 ** 4,
3 // 4,
3 % 4) # 2
| print(3 + 4, 3 - 4, 3 * 4, 3 / 4, 3 ** 4, 3 // 4, 3 % 4) |
#Project Euler Problem 14
y=True
i=1
maxz=0
while i <= 1000000:
i=i+1
c=0
y=True
n=i
while y:
if n % 2 == 0:
n=n/2
else :
n=3 * n + 1
c=c+1
if c > maxz:
maxz=c
x=i
if n == 1:
y=False
print("max: ",max... | y = True
i = 1
maxz = 0
while i <= 1000000:
i = i + 1
c = 0
y = True
n = i
while y:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
c = c + 1
if c > maxz:
maxz = c
x = i
if n == 1:
y = False
print('max: ... |
# -*- coding: utf-8 -*-
TESTING = True
SECURITY_PASSWORD_HASH = 'plaintext'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
SLIM_FILE_LOGGING_LEVEL = None
# LOGIN_DISABLED = True
# PRESERVE_CONTEXT_ON_EXCEPTION = False
| testing = True
security_password_hash = 'plaintext'
sqlalchemy_database_uri = 'sqlite://'
slim_file_logging_level = None |
# File: atbash_cipher.py
# Purpose: Create an implementation of the atbash cipher, an ancient encryption system created in the Middle East.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Thursday 3rd September 2016, 09:15 PM
alpha = "abcdefghijklmnopqrstuvwxyz"
rev = list(alpha)[::-1]
sto... | alpha = 'abcdefghijklmnopqrstuvwxyz'
rev = list(alpha)[::-1]
store = dict(zip(alpha, rev))
def decode(string):
dec = ''
for x in string:
dec += str(store[x])
return dec
def encode(string):
enc = ''
for x in string:
enc += str(store.keys[x])
return enc |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"Exceptions definition."
class ElementNotFound(Exception):
"""Raised when an element is not found. Selenium has it's own exception but
when we're iterating through multiple elements and expect one, we ra... | """Exceptions definition."""
class Elementnotfound(Exception):
"""Raised when an element is not found. Selenium has it's own exception but
when we're iterating through multiple elements and expect one, we raise our
own.
"""
class Docstringsmissing(Exception):
"""Since we require for certain classes to have... |
def _root_path(f):
if f.is_source:
return f.owner.workspace_root
return "/".join([f.root.path, f.owner.workspace_root])
def _colon_paths(data):
return ":".join([
f.path
for f in sorted(data)
])
def encode_named_generators(named_generators):
return ",".join([k + "=" + v for ... | def _root_path(f):
if f.is_source:
return f.owner.workspace_root
return '/'.join([f.root.path, f.owner.workspace_root])
def _colon_paths(data):
return ':'.join([f.path for f in sorted(data)])
def encode_named_generators(named_generators):
return ','.join([k + '=' + v for (k, v) in sorted(named... |
__author__ = "Marten Scheuck"
"""This runs the Linux Version of the AWC"""
def main():
"""Main function to run all the code"""
...
if __name__ == "__main__":
... | __author__ = 'Marten Scheuck'
'This runs the Linux Version of the AWC'
def main():
"""Main function to run all the code"""
...
if __name__ == '__main__':
... |
class DBRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'panglao':
return 'panglao'
if model._meta.app_label == 'cheapcdn':
return 'cheapcdn'
if model._meta.app_label == 'lifecycle':
return 'lifecycle'
return 'def... | class Dbrouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'panglao':
return 'panglao'
if model._meta.app_label == 'cheapcdn':
return 'cheapcdn'
if model._meta.app_label == 'lifecycle':
return 'lifecycle'
return 'de... |
# -*- coding: utf-8 -*-
def echofilter():
print("OK, 'echofilter()' function executed!")
| def echofilter():
print("OK, 'echofilter()' function executed!") |
test_cases = int(input().strip())
def recursion(n, value):
global result
if value >= result:
return
if n == N:
result = min(result, value)
return
for i in range(N):
if not visited[i]:
visited[i] = True
recursion(n + 1, value + mat[n][i])
... | test_cases = int(input().strip())
def recursion(n, value):
global result
if value >= result:
return
if n == N:
result = min(result, value)
return
for i in range(N):
if not visited[i]:
visited[i] = True
recursion(n + 1, value + mat[n][i])
... |
# Creating parameters for STFT test
"""
It is equivalent to
[(1024, 128, 'ones'),
(1024, 128, 'hann'),
(1024, 128, 'hamming'),
(2048, 128, 'ones'),
(2048, 512, 'ones'),
(2048, 128, 'hann'),
(2048, 512, 'hann'),
(2048, 128, 'hamming'),
(2048, 512, 'hamming'),
(None, None, None)]
"""
stft_parameters = []
n_fft... | """
It is equivalent to
[(1024, 128, 'ones'),
(1024, 128, 'hann'),
(1024, 128, 'hamming'),
(2048, 128, 'ones'),
(2048, 512, 'ones'),
(2048, 128, 'hann'),
(2048, 512, 'hann'),
(2048, 128, 'hamming'),
(2048, 512, 'hamming'),
(None, None, None)]
"""
stft_parameters = []
n_fft = [1024, 2048]
hop_length = {128, 51... |
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.items = []
self.indexes = dict()
def get(self, key: int) -> int:
if self.indexes.get(key) is None:
return -1
index = self.indexes[key]
value = self.items[index]... | class Lrucache:
def __init__(self, capacity: int):
self.capacity = capacity
self.items = []
self.indexes = dict()
def get(self, key: int) -> int:
if self.indexes.get(key) is None:
return -1
index = self.indexes[key]
value = self.items[index]
... |
# coding=utf-8
# autogenerated using ms_props_generator.py
DATA_TYPE_MAP = {
"0x0000": "PtypUnspecified",
"0x0001": "PtypNull",
"0x0002": "PtypInteger16",
"0x0003": "PtypInteger32",
"0x0004": "PtypFloating32",
"0x0005": "PtypFloating64",
"0x0006": "PtypCurrency",
"0x0007": "PtypFloating... | data_type_map = {'0x0000': 'PtypUnspecified', '0x0001': 'PtypNull', '0x0002': 'PtypInteger16', '0x0003': 'PtypInteger32', '0x0004': 'PtypFloating32', '0x0005': 'PtypFloating64', '0x0006': 'PtypCurrency', '0x0007': 'PtypFloatingTime', '0x000A': 'PtypErrorCode', '0x000B': 'PtypBoolean', '0x000D': 'PtypObject', '0x0014': ... |
print(' a string that you "dont" have to escape \n This \n is a multi-line \n heredoc string -------> example')
| print(' a string that you "dont" have to escape \n This \n is a multi-line \n heredoc string -------> example') |
def GetXSection(fileName): #[pb]
if fileName.find("ST_t-channel_antitop_4f_InclusiveDecays_mtop1695_TuneCP5_PSweights_13TeV-powheg-madspin-pythia8") !=-1 : return 70.89
elif fileName.find("ST_t-channel_antitop_4f_InclusiveDecays_mtop1715_TuneCP5_PSweights_13TeV-powheg-madspin-pythia8") !=-1 : return 69.66
elif fil... | def get_x_section(fileName):
if fileName.find('ST_t-channel_antitop_4f_InclusiveDecays_mtop1695_TuneCP5_PSweights_13TeV-powheg-madspin-pythia8') != -1:
return 70.89
elif fileName.find('ST_t-channel_antitop_4f_InclusiveDecays_mtop1715_TuneCP5_PSweights_13TeV-powheg-madspin-pythia8') != -1:
return... |
#
# PySNMP MIB module HH3C-LswMAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-LswMAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:15:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint, constraints_union) ... |
"""Author: Gina Chatzimarkaki"""
#test-calculator-substract.py
def handle(str):
"""
Substract two numbers and return the result. If there are more
just take the first two
Parameters
----------
str : String
the provided input
Returns
... | """Author: Gina Chatzimarkaki"""
def handle(str):
"""
Substract two numbers and return the result. If there are more
just take the first two
Parameters
----------
str : String
the provided input
Returns
-------
int
the 2 numb... |
class MemeDataGenerator(tf.keras.utils.Sequence):
"""
An iterable that returns [batch_size, (images embeddigns, [unrolled input text sequences, text target])].
Instead of batching over images, we choose to batch over [image, description] pairs because unlike typical
image captioning tasks that has 3-5 t... | class Memedatagenerator(tf.keras.utils.Sequence):
"""
An iterable that returns [batch_size, (images embeddigns, [unrolled input text sequences, text target])].
Instead of batching over images, we choose to batch over [image, description] pairs because unlike typical
image captioning tasks that has 3-5 t... |
#
# elkme - the command-line sms utility
# see main.py for the main entry-point
#
__version__ = '0.6.0'
__release_date__ = '2017-07-17'
| __version__ = '0.6.0'
__release_date__ = '2017-07-17' |
#
# add leapfrog's template loader
#
TEMPLATE_LOADERS = (
'leapfrog.loaders.Loader',
# then the default template loaders
# ...
)
#
# enable the leapfrog app
#
INSTALLED_APPS = (
# ...
# all your other apps, plus south and the sentry apps:
'south',
'indexer',
'paging',
'sentry',
... | template_loaders = ('leapfrog.loaders.Loader',)
installed_apps = ('south', 'indexer', 'paging', 'sentry', 'sentry.client', 'leapfrog')
template_context_processors = ('django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_process... |
class BinaryOption:
def __init__(self):
self.__data = None
def SetData(self, bit):
self.__data = bit
def Has(self, value):
return (self.__data & value)
def Set(self, value):
self.__data = self.__data | value
@staticmethod
def Create(value):
... | class Binaryoption:
def __init__(self):
self.__data = None
def set_data(self, bit):
self.__data = bit
def has(self, value):
return self.__data & value
def set(self, value):
self.__data = self.__data | value
@staticmethod
def create(value):
result = bi... |
#!/usr/bin/env python3
n, p, *a = map(int, open(0).read().split())
c = 0
for a, b in zip(a, a[n:]):
c += min(p+a, b)
p = a - max(min(b-p, a), 0)
print(c) | (n, p, *a) = map(int, open(0).read().split())
c = 0
for (a, b) in zip(a, a[n:]):
c += min(p + a, b)
p = a - max(min(b - p, a), 0)
print(c) |
var2 = {
# Video Only files
'.webm' : ('WebM', 'Free and libre format created for HTML5 video.'),
'.mkv' : ('Matroska', ''),
'.flv' : ('Flash Video', 'Use of the H.264 and AAC compression formats in the FLV file format has some limitations and authors of Flash Player strongly encourage everyone to embrace the new stan... | var2 = {'.webm': ('WebM', 'Free and libre format created for HTML5 video.'), '.mkv': ('Matroska', ''), '.flv': ('Flash Video', 'Use of the H.264 and AAC compression formats in the FLV file format has some limitations and authors of Flash Player strongly encourage everyone to embrace the new standard F4V file format.[2]... |
# -*- coding: utf-8 -*-
abstract = """BACKGROUND:
The systematic, complete and correct reconstruction of genome-scale metabolic networks or metabolic pathways is one of
the most challenging tasks in systems biology research. An essential requirement is the access to the complete
biochemical knowledge - especially on... | abstract = 'BACKGROUND:\nThe systematic, complete and correct reconstruction of genome-scale metabolic networks or metabolic pathways is one of \nthe most challenging tasks in systems biology research. An essential requirement is the access to the complete \nbiochemical knowledge - especially on the biochemical reactio... |
def example_1():
###### 0123456789012345678901234567890123456789012345678901234567890
record = ' 100 513.25 '
cost = int(record[20:32]) * float(record[40:48])
print(cost)
SHARES = slice(20, 32)
PRICE = slice(40, 48)
cost = int(record[SHARE... | def example_1():
record = ' 100 513.25 '
cost = int(record[20:32]) * float(record[40:48])
print(cost)
shares = slice(20, 32)
price = slice(40, 48)
cost = int(record[SHARES]) * float(record[PRICE])
print(cost)
def example_2():
items = [0, ... |
name = 'Escape'
movies = [
{'title': 'My Neighbor Totoro', 'year': '1988'},
{'title': 'Dead Poets Society', 'year': '1989'},
{'title': 'A Perfect World', 'year': '1993'},
{'title': 'Leon', 'year': '1994'},
{'title': 'Mahjong', 'year': '1996'},
{'title': 'Swallowtail Butterfly', 'year': '1996'},... | name = 'Escape'
movies = [{'title': 'My Neighbor Totoro', 'year': '1988'}, {'title': 'Dead Poets Society', 'year': '1989'}, {'title': 'A Perfect World', 'year': '1993'}, {'title': 'Leon', 'year': '1994'}, {'title': 'Mahjong', 'year': '1996'}, {'title': 'Swallowtail Butterfly', 'year': '1996'}, {'title': 'King of Comedy... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020- IBM Inc. All rights reserved
# SPDX-License-Identifier: Apache2.0
#
"""
"""
class Array:
array_length = 0
array_element_size = 0
base_element = None
def __init__(self, array_length, base_element, array_element_size):
self.ba... | """
"""
class Array:
array_length = 0
array_element_size = 0
base_element = None
def __init__(self, array_length, base_element, array_element_size):
self.base_element = base_element
self.array_length = array_length
self.array_element_size = array_element_size
def __call__(... |
def calculated_quadratic_equation(a = 0, b = 0, c = 0):
r = a ** 2 + b + c
return r
print(calculated_quadratic_equation())
| def calculated_quadratic_equation(a=0, b=0, c=0):
r = a ** 2 + b + c
return r
print(calculated_quadratic_equation()) |
# %%
__depends__ = []
__dest__ = ['../../data/']
# %% | __depends__ = []
__dest__ = ['../../data/'] |
class WorkCli:
def __init__(self, workbranch):
self.workbranch = workbranch
def add_subparser(self, subparsers):
work_parser = subparsers.add_parser('work', help="Keep track of a currently important branch")
work_parser.add_argument("current", nargs="?", type=str, default=None, help="... | class Workcli:
def __init__(self, workbranch):
self.workbranch = workbranch
def add_subparser(self, subparsers):
work_parser = subparsers.add_parser('work', help='Keep track of a currently important branch')
work_parser.add_argument('current', nargs='?', type=str, default=None, help='S... |
class Scope:
def __init__ (self, parent=None):
self.parent = parent
self.elements = dict()
def get_element (self, name, type, current=False):
r = self.elements.get(type, None)
if r != None:
r = r.get(name, None)
if r == None and self.parent ... | class Scope:
def __init__(self, parent=None):
self.parent = parent
self.elements = dict()
def get_element(self, name, type, current=False):
r = self.elements.get(type, None)
if r != None:
r = r.get(name, None)
if r == None and self.parent != None and (not cu... |
# Fibonacci: Sum of the last two numbers gives the next one.
# Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 .....
# Works only with positive integers
# Step1: Recursive Case
# fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
# Step2: Base Case
# fibonacci(0) = 0
# fibonacci(1) = 1
# S... | def fibonacci(n):
if n in [0, 1]:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def is_int(n, is_pos=False):
try:
n = int(n)
if is_pos:
if n > 0:
return True
else:
return False
else:
retu... |
class Player:
def __init__(self, name):
"""Initializes the player's name. The default score is 0"""
self._name = name
self._score = 0
def get_name(self):
"""Return player's name"""
return self._name
def get_score(self):
"""Return player's score"""
r... | class Player:
def __init__(self, name):
"""Initializes the player's name. The default score is 0"""
self._name = name
self._score = 0
def get_name(self):
"""Return player's name"""
return self._name
def get_score(self):
"""Return player's score"""
r... |
'''
URL: https://leetcode.com/problems/count-the-number-of-consistent-strings/
Difficulty: Easy
Description: Count the Number of Consistent Strings
You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the stri... | """
URL: https://leetcode.com/problems/count-the-number-of-consistent-strings/
Difficulty: Easy
Description: Count the Number of Consistent Strings
You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the stri... |
board_width, board_length = list(map(int, input().split()))
domino_length = 2
if board_width % 2 == 0:
print((board_width // domino_length) * board_length)
elif board_length % 2 == 0:
print((board_length // domino_length) * board_width)
else:
print((board_width * board_length) // domino_length)
| (board_width, board_length) = list(map(int, input().split()))
domino_length = 2
if board_width % 2 == 0:
print(board_width // domino_length * board_length)
elif board_length % 2 == 0:
print(board_length // domino_length * board_width)
else:
print(board_width * board_length // domino_length) |
class VehiclesDataset:
def __init__(self):
self.num_vehicle = 0
self.num_object = 0
self.num_object_with_kp = 0
self.vehicles = dict()
self.valid_ids = set()
self.mean_shape = None
self.pca_comp = None
self.camera_mtx = None
self.image_names = ... | class Vehiclesdataset:
def __init__(self):
self.num_vehicle = 0
self.num_object = 0
self.num_object_with_kp = 0
self.vehicles = dict()
self.valid_ids = set()
self.mean_shape = None
self.pca_comp = None
self.camera_mtx = None
self.image_names =... |
class UrineProcessorAssembly:
name = "Urine Processor Assembly"
params = [
{
"key": "max_urine_consumed_per_hour",
"label": "",
"units": "kg/hr",
"private": False,
"value": 0.375,
"confidence": 0,
"notes": "9 kg/day / 24... | class Urineprocessorassembly:
name = 'Urine Processor Assembly'
params = [{'key': 'max_urine_consumed_per_hour', 'label': '', 'units': 'kg/hr', 'private': False, 'value': 0.375, 'confidence': 0, 'notes': '9 kg/day / 24 per wikipedia', 'source': 'https://en.wikipedia.org/wiki/ISS_ECLSS'}, {'key': 'min_urine_cons... |
n=6
while n >0:
n-=1
if n % 2 ==0:
print(n, end ="")
if n % 3 == 0:
print(n, end='') | n = 6
while n > 0:
n -= 1
if n % 2 == 0:
print(n, end='')
if n % 3 == 0:
print(n, end='') |
#https://www.wwpdb.org/documentation/file-format-content/format23/v2.3.html
def line_is_ATOM_record(line):
return line.startswith('ATOM ')
def line_is_HETATM_record(line):
return line.startswith('HETATM')
def get_fields_from_ATOM_record(record):
fields={}
fields['ATOM '] = record[0:6]
fields... | def line_is_atom_record(line):
return line.startswith('ATOM ')
def line_is_hetatm_record(line):
return line.startswith('HETATM')
def get_fields_from_atom_record(record):
fields = {}
fields['ATOM '] = record[0:6]
fields['serial'] = int(record[6:11])
fields['name'] = record[12:16]
fields['... |
class CircularBufferError(Exception):
pass
class CircularBuffer(object):
"""Unlike traditional circular buffers, this allows reading and writing
multiple values at a time. Additionally, this object provides peeking and
commiting reads. See test_circular_buffer.py for examples.
The interface is ... | class Circularbuffererror(Exception):
pass
class Circularbuffer(object):
"""Unlike traditional circular buffers, this allows reading and writing
multiple values at a time. Additionally, this object provides peeking and
commiting reads. See test_circular_buffer.py for examples.
The interface is alm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.