content stringlengths 42 6.51k |
|---|
def celsius_to_kelvin(celsius: float) -> float:
"""
Convert a given value from Celsius to Kelvin and round it to 2 decimal places.
>>> celsius_to_kelvin(0)
273.15
>>> celsius_to_kelvin(20.0)
293.15
>>> celsius_to_kelvin("40")
313.15
>>> celsius_to_kelvin("celsius")
Traceback (mo... |
def clean_function(c_hungry, c_dirt, c_mood):
"""Deze functie controlerd of de tamagotchi schoon
is of niet en stuurd de nieuwe waarden terug."""
if c_dirt >= 2:
c_text = 'Fris en fruitig!'
return c_hungry + 1, c_dirt - 2, c_mood + 1, c_text
elif c_dirt < 2:
c_text = 'Grmp... |
def APs2mAP(aps):
"""
Take a mean of APs over all classes to compute mAP
"""
num_classes = 0.
sum_ap = 0.
for _, v in aps.items():
sum_ap += v
num_classes += 1
if num_classes == 0:
return 0
return sum_ap/num_classes |
def action_to_vector(action):
"""
LEFT = 0
RIGHT = 1
UP = 2
DOWN = 3
"""
if action ==0:
return (-1, 0)
if action == 1:
return ( 1, 0)
if action == 2:
return ( 0, 1)
if action == 3:
return (0, -1)
return None |
def write_to_temp_file(iterable, path):
"""
Write iterable to temporary file, an item per line.
:param iterable: list or tuples of contents to write to file
:param path: absolute path to file. We use a tempdir as parent.
:return: path to temporary file
"""
with open(path, 'w', encoding='ut... |
def _is_iterable_non_string(arg):
"""
A helper method to return True if the given argument appears to be iterable
(like a list) but not able to be converted to a Range.
In particular, checks for whether python would consider the argument to be
iterable (it has either __iter__() or __getattr__() def... |
def is_article(url):
"""
tell if an url is a single article, True if yes else False
:type url: String
:rtype: Bool
"""
# remove https://
url = url[8:]
url_split = url.split('/')
if url_split[1] == 'works' and url_split[2].isdigit():
return True
return False |
def _get_tuple_n(x, n, tp):
"""Get a length-n list of type tp."""
assert tp is not list
if isinstance(x, tp):
x = [x, ] * n
assert len(x) == n, 'Parameters should be {} or list of N elements.'.format(tp)
for i in x:
assert isinstance(i, tp), 'Elements of list should be {}.'.format(tp... |
def calculate_lin(current_count, smallest_count, largest_count, max_size, min_size):
""" Calculate ratio (linear version). """
# Specific case when smallest_count == largest_count: We want a medium value
if smallest_count == largest_count:
return (min_size + max_size) / 2.0
else:
... |
def classpath_entry_xml(kind, path):
"""Generates an eclipse xml classpath entry.
Args:
kind: Kind of classpath entry.
Example values are 'lib', 'src', and 'con'
path: Absolute or relative path to the referenced resource.
Paths that are not absolute are relative to the p... |
def logical_resize_disk(device):
"""
Resizes the logical volume to new_size specified in the start command. This is necessary
for some operating systems that do not automatically resize to this value.
:type device: string
:param device: logical volume to resize, e.g. /dev/xvda1 in RedHat famil... |
def boolstr(s):
"""Interpret string s as a Boolean.
This is intended for interpreting HTTP query parameters. "False",
"no" or "off" in any case and any representation of the
integer 0 count as false, everything else - such as the empty
string - counts as true.
"""
if s.lower() in ["false",... |
def binary_search(input_array, value):
"""Your code goes here."""
midpoint = len(input_array)//2
position = midpoint
listy = input_array
while len(listy) > 0:
result = listy[midpoint]
if value > result:
listy = listy[midpoint+1:len(listy)]
position += len(lis... |
def get(row, delimiter, indices):
"""Extract key and value from row.
>>> get('a,b,c', ',', (0, 1))
(('a', 'b'), ('c',))
>>> get('a,b,c', ',', (0, 2))
(('a', 'c'), ('b',))
"""
row = row.rstrip().split(delimiter)
key = tuple(row[k] for k in indices)
val = tuple(v for i, v in enumerat... |
def prefix_average3(S):
"""Return list such that, for all j, A[j] equals average of S[0], ..., S[j].
"""
n = len(S)
A = [0] * n
total = 0
for j in range(n):
total += S[j]
A[j] = total / (j+1)
return A |
def mulaw_to_value(mudata):
"""Convert a mu-law encoded value to linear."""
position = ((mudata & 0xF0) >> 4) + 5
return ((1 << position) | ((mudata & 0xF) << (position - 4)) | (1 << (position - 5))) - 33 |
def is_input_topic(topic, device_id, module_id):
"""
Topics for inputs are of the following format:
devices/<deviceId>/modules/<moduleId>/inputs/<inputName>
:param topic: The topic string
"""
if "devices/{}/modules/{}/inputs/".format(device_id, module_id) in topic:
return True
return... |
def simpsons(f, a, b, n):
"""
Evaluates the integral of f, with endpoints a and b, using Simpson's rule
with n sample points.
@type f: function
@param f: function integrate
@type a: number
@param a: start of interval
@type b: number
@param b: end of interval
@type n: number
... |
def reciprocate_weights(objective_weights):
"""
Reciprocate weights so that they correlate when using modified_tchebyshev scalarization.
:param objective_weights: a dictionary containing the weights for each objective.
:return: a dictionary containing the reciprocated weights.
"""
new_weights = ... |
def bytes_to_str(bytes, base=2, precision=0):
"""Convert number of bytes to a human-readable format
Arguments:
bytes -- number of bytes
base -- base 2 'regular' multiplexer, or base 10 'storage' multiplexer
precision -- number of decimal places to output
Returns:
Human-readable string such... |
def myatoi(sentence: str):
"""
This function aims to pass a str type to int type, like (C / C++)'s atoi function
Time complexity
Running time O(n)
Memory Usage O(n)
:param sentence: str
:return: int
"""
find_number = False
find_less_sign = False
find_pos_sign = False
new... |
def isBalanced(s):
"""
Checks if a string has balanced parentheses. This method can be easily extended to
include braces, curly brackets etc by adding the opening/closing equivalents
in the obvious places.
"""
expr = ''.join([x for x in s if x in '()'])
if len(expr)%2!=0:
re... |
def unpack_quantity(row, concept, value):
"""Unpack row like {"variable": [{"concept":<concept>, <value>:_i_want_this_}]}
Args:
row (dict): Row of Worldbank API data.
concept (str): The name of the dataset containing the variable.
value (str): The name of the variable to unpack.
Ret... |
def frac(a, b):
"""Regular fraction, but result is 0 if a = b = 0"""
if a == 0 and b == 0:
return 0
return a / b |
def rules_ports(
firewall_rules, only_restricted=False, redirect=False, *_, **__):
"""
Return restricted ports (<1024) from firewall rules.
Args:
firewall_rules (list of dict): Firewall rules.
only_restricted (bool): If True, list only ports < 1024.
redirect (bool): If True,... |
def extract_dependencies(parsed_data):
"""
extracts all the dependencies from the parsed data.
Keyword arguments:
parsed_data -- the parsed text to extract lexicon from.
Returns:
list - a list of the dependencies inside parsed_data.
"""
deps = []
for token in parsed_data:
d... |
def get_task_parameter(task_parameters, name):
"""
Get task parameter.
Parameters
----------
task_parameters : list
name : str
Returns
-------
dict
"""
for param in task_parameters:
param_name = param.get('name')
if param_name == name:
return par... |
def dict_diff(d1, d2):
"""Returns the dictionary that is the "set difference" between d1 and d2 (based on keys, not key-value pairs)
E.g. d1 = {"a": 1, "b": 2}, d2 = {"b": 5}, then dict_diff(d1, d2) = {"a": 1}
"""
o_dict = {}
for k in set(d1.keys()) - set(d2.keys()):
o_dict[k] = d1[k]
re... |
def rejoin(tokens, sep=None):
"""Rejoin tokens into the original sentence.
Args:
tokens: a list of dicts containing 'originalText' and 'before' fields.
All other fields will be ignored.
sep: if provided, use the given character as a separator instead of
the 'before' field (e.g. if you wan... |
def get_openmvg_camera_id(kapture_camera_id, kapture_to_openmvg_cam_ids):
""" return a valid openmvg camera id for the given kapture on.
It keeps kapture_to_openmvg_cam_ids uptodate, and ensure there is no collision.
"""
if kapture_camera_id in kapture_to_openmvg_cam_ids:
# already defined
... |
def choose_unit_from_multiple_time_units_series(time_serie, time_key="seconds"):
"""Given a time series in the form
[(x, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0}),
(y, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0}),
(z, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0... |
def _get_non_inhereted_function_names(cls):
"""Gets all methods that cls has that its parents don't have."""
names = set(dir(cls))
for parent in cls.__bases__:
names -= set(dir(parent))
return list(names) |
def kill_spaces(s):
"""
remove spaces from a string; makes testing easier as white space conventions may change in equations
:param s:
:return:
"""
s = s.replace(' ', '')
return s |
def note_to_f(note: int, tuning: int=440) -> float:
"""Convert a MIDI note to frequency.
Args:
note: A MIDI note
tuning: The tuning as defined by the frequency for A4.
Returns:
The frequency in Hertz of the note.
"""
return (2**((note-69)/12)) * tuning |
def run(input1, input2):
"""
Adds input 1 and input 2 then prints them
"""
output = input1 + input2
return output |
def remove_items(headers, condition):
"""
Removes items from a dict whose keys satisfy
the given condition.
:param headers: a dict of headers
:param condition: a function that will be passed the header key as a
single argument and should return True if the header
... |
def oracle_id(account_id):
"""
Compute the oracle id of a oracle registration
:parm account_id: the account registering the oracle
"""
return f"ok_{account_id[3:]}" |
def extract_model_and_compression_states(resuming_checkpoint):
"""
The function return from checkpoint state_dict and compression_state.
"""
if 'model' in resuming_checkpoint:
model_state_dict = resuming_checkpoint['model']
elif 'state_dict' in resuming_checkpoint:
model_state_dict =... |
def get_comp_level_octo(year, match_number):
""" No 2015 support """
if match_number <= 24:
return 'ef'
elif match_number <= 36:
return 'qf'
elif match_number <= 42:
return 'sf'
else:
return 'f' |
def elimate_leading_whitespace(source, target=None):
""" return the count of whitespaces before the first target
if it is not the mode: <whitespace>*_target_, return 0
"""
if not source:
return 0
i, length = 0, len(source)
while i < length:
if source[i] not in ' \t':
... |
def mirror_css_mock(original_css):
"""Mock out the mirroring to simply reverse the whole CSS."""
return [l[::-1] for l in original_css[::-1]] |
def reduceName(flist):
"""
Return a list of classes whose data is being dealt with
This routine takes the file names supplied by edX and returns a
list of classes that can be used to isolate the data files by
course. The current algorithm simply removes the known institutional
prefix, and t... |
def list2dict(flat_list):
"""
Function taking a list of (key, value) tuples,
where the value can be a nested path like:
('title.path', 'Titel')
and transform it into a dictionary like:
{"title":{"path":"Titel"}}
:param flat_list: list of (key, value) tuples
:return: the dictionary
""... |
def ensure_old_data_compatible(data):
"""
Tests and update datas done with old version of the script
This function contain all the data structure history to convertion
"""
try:
del data['submenu']
except:
pass
try:
data['general']['submenu']
except KeyError:
... |
def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x):
"""Give the first value that satisfies the key test.
Args:
seq (iterable):
key (callable): test for each element of iterable
default: returned when all elements fail test
apply (callable): applied to element... |
def collision(obj1 : dict, obj2 : dict) -> bool:
""" detects collision between 2 objects and returns some properties in list """
if (obj1['x'] + obj1['width'] /2 < obj2['x'] - obj2['width'] / 2 or
obj1['x'] - obj1['width'] / 2 > obj2['x'] + obj2['width'] / 2 or
obj1['y'] + obj1['height'] < obj2... |
def get_font_size(w, N):
""" Return an appropriate font size to print number in a figure
of width / height `width` with NxN cells. """
return 0.4 * w * 72 / N |
def get_size(bytes, suffix="B"):
#Found this on some website, i don't remember now. Used to get the total ram in GB.
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if b... |
def normalised_ellipse_mask(ellipse):
"""Return a normalized copy of the supplied ellipse.
Here 'normalised' means that the rotation is as close to zero as possible.
Examples:
>>> normalised_ellipse_mask(
... ((1, 2), (100, 200), 90)
... )
((1, 2), (200, 100), 0)
""... |
def func(x, y):
"""This is a docstring"""
if x < 0:
raise ValueError()
return x + 2.0 * y |
def check_len(key, val, val_len=2, ext='primary'):
"""
Check if the length of the keyword value has a a given length, default value for the length check is 2.
Args:
key: keyword
val: keyword value
val_len: length to be checked against
ext: string, extension number (default va... |
def SanitizeSqlString(value):
"""Returns a prepared string for a SQL value. Quoting and sanitization is applied.
This is onyl for confirmed string values.
"""
sql_value = str(value).replace("'", "''")
return sql_value |
def _update_shape_dtype(shape, dtype, params):
"""Update shape dtype given params information"""
shape = {} if shape is None else shape
if not params:
return shape, dtype
shape = shape.copy()
shape.update({k : v.shape for k, v in params.items()})
if isinstance(dtype, str):
for k,... |
def parseExtn(extn=None):
"""
Parse a string representing a qualified fits extension name as in the
output of `parseFilename` and return a tuple ``(str(extname),
int(extver))``, which can be passed to `astropy.io.fits` functions using
the 'ext' kw.
Default return is the first extension in a fit... |
def create_repl_prompt_str(prompt_msg: str) -> str:
"""
>>> create_repl_prompt_str("give string!")
'give string! > '
>>> create_repl_prompt_str("enter an int >")
'enter an int > '
"""
msg = prompt_msg.strip()
if msg.endswith(">"):
return f"{msg} "
else:
return f"{msg}... |
def improve(update, close, guess=1, max_updates=100):
"""Iteratively improve guess with update until close(guess) is true."""
k = 0
while not close(guess) and k < max_updates:
guess = update(guess)
k = k + 1
return guess |
def get_character_count(line, character):
"""
Returns the number of times a character is found in a line.
"""
return sum(1 for char in line if char == character) |
def extr_byte(value, byte):
"""Extract the given byte in the value"""
return (value >> (8 * byte)) & 0xff |
def selection_sort(numbs: list) -> list:
"""
Go through the list from left to right and search for the
minimum. Once the minimum is found, swap it with the
element at the end of the array. Repeat the same procedure
on the subarray that goes from the element after 'i' to the
end, until the array ... |
def sampletype(sampletype):
""" Confirms that a given value is a valid sampletype and returns
the all lowercase version of it.
"""
if sampletype.lower() not in ('grab', 'composite'):
raise ValueError("`sampletype` must be 'composite' or 'grab'")
return sampletype.lower() |
def _correct_article(noun : str) -> str:
"""Helper to return a noun with the correct article."""
if noun.lower()[0] in 'aeiou':
return 'an ' + noun
else:
return 'a ' + noun |
def deepcopy(val, depth=0):
"""Return a copy of a value. For immutable values, this returns the
value itself. For mutables, it returns a deep copy.
This presumes that the value is DB-storable. Therefore, the only
mutable types are list and dict. (And dict keys are always strings.)
We include a gua... |
def combine(a, b):
""" sandwiches b in two copies of a and wrap by double quotes"""
c = '"' + a + b + a + '"'
return c |
def get_box_area(a1, a2):
"""
Get the area of a box specified by two anchors
Parameters
----------
a1: list(2)
Row/column of first anchor
a2: list(2)
Row/column of second anchor
Returns
-------
Area of box determined by these two anchors
"""
m = a2[0... |
def build_http_response(data, content_type='text/html', response_code='200 OK'):
"""
Base HTTP response maker.
----
data (str | bytes) : Data to be packed into an HTTP response
content_type (str) : Mimetype of data
response_code (str) : HTTP response code
----
Returns (bytes) of the pack... |
def inv_min_max_norm(x, min_x, max_x):
"""
Computes the inverse min-max-norm of input x with minimum min_x and maximum max_x.
"""
return x * (max_x - min_x) + min_x |
def get_section(cfg, section):
"""Parse a cgitrepos cfg returning specified section."""
section_lines = []
is_append_section = False
for line in cfg.splitlines():
line = line.strip()
if line.startswith('section') and not is_append_section:
cfg_section = line.split('=', 1)[1... |
def filter_(order, items):
"""Filter application blueprints."""
def _key(item):
if item.name in order:
return order.index(item.name)
return -1
return sorted(items, key=_key) |
def deadzone(value, threshold, center=0.0):
"""Apply a deadzone to a given value centered around a center value.
Args:
value (number): value to apply the deadzone to.
threshold (number): the threshold to apply.
center (number, optional): center value. Defaults to 0.
Returns:
... |
def product(iterable):
"""Return product of sequence of numbers.
Equivalent of functools.reduce(operator.mul, iterable, 1).
>>> product([2**8, 2**30])
274877906944
>>> product([])
1
"""
prod = 1
for i in iterable:
prod *= i
return prod |
def point_in_box(box, test_point):
"""checks if a point is in a box
Args:
box: two points, a top left and a bottom right
test_point: a test point
Returns:
bool
"""
top_left = box[0]
bottom_right = box[1]
if (top_left[0] < test_point[0]) and (top_left[1] < test_point... |
def get_late_in(hour_in, check_in, tolerance):
"""menghitung berapa lama pegawai terlambat"""
if check_in > hour_in:
if (check_in - hour_in) < tolerance:
result = ' '
else:
result = check_in - hour_in
else:
result = ' '
return result |
def relgq_recode(relship: int, qgqtyp: str, final_pop: int) -> int:
"""
This function returns the recoded value for relgq based on the values of relship, gqgtyp, and final_pop.
:param relship: The value of the relship variable
:param qgqtyp: The value of the qgqtyp variable
:param final_pop: The va... |
def relpath(target, link):
"""Return relative path.
>>> relpath('/usr/share/python-foo/foo.py', '/usr/bin/foo', )
'../share/python-foo/foo.py'
"""
t = target.split('/')
l = link.split('/')
while l[0] == t[0]:
del l[0], t[0]
return '/'.join(['..'] * (len(l) - 1) + t) |
def _force_list(val):
"""Ensure configuration property is a list."""
if val is None:
return []
elif hasattr(val, "__iter__"):
return val
else:
return [val] |
def _get_deployment_preferences_status(function):
"""
Takes a AWS::Serverless::Function resource and checks if resource have a deployment preferences applied
to it. If DeploymentPreference found then it returns its status if it is enabled or not.
"""
deployment_preference = function.get("Properties"... |
def build_idx_dict(l, dir_path):
"""
Given list l, creates a dict with index-filepath pairs per element in the list l
:param l: list of elements
:param dir_path: path to the directory containing the files in l
:return: dict with index-filepath pairs
"""
d = {}
for i in range(len(l)):
... |
def add_string(strings, s):
"""Adds a string to the pool, deduping it. Returns the index of the
entry of the string, whether new or existing."""
for n, t in enumerate(strings):
if t == s:
return n
strings.append(s)
return len(strings) - 1 |
def m_diagonal(i, j):
"""
Useful for creating identity matrix. When making matrix returns '1s' across diagonal.
"""
return 1 if i == j else 0 |
def _percent(x, total, default=0.0):
"""Return what percentage *x* is of *total*, or *default* if
*total* is zero."""
if total:
return 100.0 * x / total
else:
return default |
def TemperatureConverter(temperature, direction=1):
"""
direction 1: from fahrenheit to celsius
direction 2: from celsius to fahrenheit
"""
temp = float(temperature)
if direction == 1:
print("Convert Fahrenheit to Celsius")
result = (temp - 32)*5/9
elif direction == 2:
print("COnvert Celsius to Fahrenh... |
def equilibrium_point(numbers, size):
"""
Given an array A your task is to tell at which position the equilibrium
first occurs in the array. Equilibrium position in an array is a position
such that the sum of elements below it is equal to the sum of elements
after it.
"""
if size == 1:
... |
def convert_type_hierarchy(context, the_type, hierarchy):
"""
List of types in sequence from ancestor to our type.
"""
type_hierarchy = []
while (the_type is not None) and (the_type.name is not None):
type_hierarchy.insert(0, the_type.name)
the_type = hierarchy.get_parent(the_t... |
def post(req, api):
"""
return success if user has rights to access server
user needs to have role owner or admin
Input:
role: string
Output:
result: string
"""
return {
'result': 'success'
} |
def async_format_model(model: str) -> str:
"""Generate a more human readable model."""
return model.replace("_", " ").title() |
def varintToNumber(byteArray):
"""
Converts a varlen bytearray back into a normal number, starting at the most
significant varint byte, adding it to the result, and pushing the result
7 bits to the left each subsequent round.
"""
number = 0
round = 0
for byte in byteArray:
roun... |
def get_context(tex: str, before: int, after: int) -> str:
"""
Extract context around a span of TeX. The extracted context should be
rich enough to support pattern matching to determine the context in which
a sentence appears. The context extracted is one full line above and
below the the "before" a... |
def parse_int(src, key, nentries=1):
"""
Parses a dictionary ``src`` and returns a number ``nentries`` of integers
specified by ``key``. This function checks that the value or values specified
by ``key`` are of type integer and raises a ``ValueError`` otherwise.
:param dict src: the source dictio... |
def numRange(numList):
"""
Get the first and last number in the list
"""
start = numList[0]
end = numList[-1]
if start != end:
return "{}-{}".format(start, end)
else:
return "{}".format(start) |
def fully_qualified_table_name(schema: str, table: str, quoted: bool) -> str:
"""
Returns fully qualified table name
:param str schema: schema name
:param str table: table name
:param bool quoted: whether to quote the table name
:return: fully qualified table name
:rtype: str
"""
if ... |
def _safe_int(string_var):
"""Convert a string to an integer. If the string cannot be cast, return 0."""
try:
return int(string_var)
except ValueError:
return 0 |
def filter3( inumbr):
""" generated source for method filter3 """
# output only to .001
number = 0.0
intermed = 0
intermed = ((inumbr * 1000.))
number = ((intermed / 1000.))
return number |
def funcname(func) -> str:
"""Get the name of a function."""
while hasattr(func, "func"):
func = func.func
try:
return func.__name__
except Exception:
return str(func) |
def _extract_open_mpi(version_buffer_str):
"""
Parses the typical OpenMPI library version message, eg:
Open MPI v4.0.1, package: Open MPI Distribution, ident: 4.0.1, repo rev: v4.0.1, Mar 26, 2019
"""
return version_buffer_str.split("v", 1)[1].split(",", 1)[0] |
def GC(seq):
"""Calculates G+C content, returns the percentage (float between 0 and 100).
Copes mixed case sequences, and with the ambiguous nucleotide S (G or C)
when counting the G and C content. The percentage is calculated against
the full length, e.g.:
>>> from Bio.SeqUtils import GC
>>>... |
def process_test_result(passed, info, is_verbose, exit):
"""
Process and print test results to the console.
"""
# if the environment does not contain necessary programs, exit early.
if passed is False and "spellbook: command not found" in info["stderr"]:
print(f"\nMissing from environment:\n... |
def bytes_to_uint(bytes_obj:bytes) -> int:
"""Convert a big-endian sequence of bytes to an unsigned integer."""
return int.from_bytes(bytes_obj, byteorder="big", signed=False) |
def IntToBytes(n):
"""Return byte string of 4 big-endian ordered byte_array representing n."""
byte_array = [m % 256 for m in [n >> 24, n >> 16, n >> 8, n]]
return "".join([chr(b) for b in byte_array]) # byte array to byte string |
def handle_exception(e):
"""Return JSON instead of HTML for general errors."""
return "ERROR: " + str(e), 500 |
def gcd(a, b):
"""
>>> gcd(2, 5)
1
"""
if a == 0:
return b
return gcd(b % a, a) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.