content stringlengths 42 6.51k |
|---|
def convert_uint32_to_array(value):
"""
Converts a int to an array of 4 bytes (little endian)
:param int value: int value to convert to list
:return list[int]: list with 4 bytes
"""
byte0 = value & 0xFF
byte1 = (value >> 8) & 0xFF
byte2 = (value >> 16) & 0xFF
byte3 = (valu... |
def eval_content(content):
"""Evaluates a python file and return the value defined in it.
Used in practice for .isolate files.
"""
globs = {'__builtins__': None}
locs = {}
value = eval(content, globs, locs)
assert locs == {}, locs
assert globs == {'__builtins__': None}, globs
return value |
def generate_repository_url(repository_type, repository_name, link_type):
"""
This function generates the URL for one repository. (best used in a loop)
Example:
generate_repository_url("git_files", "OpenCloudConfig", "json")
Should throw:
https://github.com/mozilla-releng/firefox-infra-c... |
def square(x):
"""a function to calculate the square of number x""" # the docstring of function square()
return x * x |
def getID(nameKeyword, argList, keywordDict):
"""The function returns 1 string argument from a general list or arguments
The argument can be named with nameKeyword
Parameters
----------
nameKeyword : str
The keyword of the desired argument if named
argList : list
*args passed to t... |
def create_null_summary(station, year_range):
""" Create an empty summary """
return {
'ffmc': None,
'isi': None,
'bui': None,
'years': year_range,
'station': station
} |
def avg_len_sent(text):
"""Calculates the average length of sentences, in tokens"""
token_count = len(text.split())
sent_count = text.count(". ") + 1
if sent_count != 0:
return token_count / sent_count
else:
return 0 |
def format_hex(value, mask):
""" Format an integer as a hexadecimal string """
if mask is None:
return "0x{:x}".format(value)
return "0x{:x}/0x{:x}".format(value, mask) |
def _delta(p1, p2):
"""Computes the shift between the start of two intervals.
Args:
p1 ((int,int)): First interval as (first ts, last ts)
p2 ((int,int)): Second interval as (first ts, last ts)
Returns:
float: interval intersection over armonic mean of intervals' lengths... |
def get_one(it):
"""return first item from iterator
>>> get_one([1,2,3])
1
>>> get_one(set([1,2,3])) in set([1,2,3])
True
"""
for i in it:
return i |
def is_int(s):
""" Check if given var is / can be converted to int """
try:
float(s)
if float(s) - int(s) == 0:
return True
else:
return False
except ValueError:
return False |
def validate_string_to_bool(allow_create):
"""
Validating case insensitive true, false strings
Return boolean value of the arguement if it is valid,
else return original value. Also return status if arguement is valid or not
"""
is_valid = True
# If already bool, return
if type(allow_cr... |
def _h5sanitize(attr_value):
"""Decodes bytestring HDF5 attribute values using UTF-8 format; passes unchanged attribute values of any other type
This helps us support MATLAB-generated HDF5 files, which may save character vectors as fixed length HDF5 strings"""
if isinstance(attr_value, bytes):
retur... |
def get_value_of_card(position_of_card, deck):
"""Returns the value of the card that has the specific position in the deck"""
# print(deck[position_of_card])
value_int = deck[position_of_card][1]
return value_int |
def modify_MOLBlock(string):
"""
Modify Mol block string from KEGG API to have a file source type.
This means setting line 2 to be ' RDKit 2D'.
Without this, no chiral information would be collected.
"""
string = string.split('\n')
string[1] = ' RDKit 2D'
stri... |
def hex(*args):
"""Converts a char or int to a string containing the equivalent hexadecimal notation."""
if isinstance(args[0], str):
number = "%X" % ord(args[0])
else:
number = "%X" % args[0]
if len(args) == 1:
return number
return number[(len(number) - args[1]):] |
def args_for_loop(*args):
"""
factor function used by epilepsy_docx
makes a list of two numbers
"""
list = []
for arg in args:
list.append(arg)
return list |
def merge_bytes(*args):
"""Returns a single list of int from given int and list of int.
:param int,list[int] args: Values to merge
:rtype: list[int]
>>> from rivalcfg.helpers import merge_bytes
>>> merge_bytes(1, 2, 3)
[1, 2, 3]
>>> merge_bytes([1, 2], [3, 4])
[1, 2, 3, 4]
>>> merg... |
def get_exp_name(data, mod, f_s, v_s, target):
""" Unified experiment name generator.
:param data: (str) identifier of the dataset
:param mod: (str) identifier of the attacked model
:param f_s: (str) identifier of the feature selector
:param v_s: (str) identifier of the value selector
:param ta... |
def getSJMotifCode(startBases, endBases):
""" Determines which STAR-style splice junction code applies to a splice motif """
motif = (startBases + endBases).upper()
if motif == "GTAG":
return 1
elif motif == "CTAC":
return 2
elif motif == "GCAG":
return 3
elif mo... |
def disp_to_depth(disp, min_depth, max_depth):
"""Convert network's sigmoid output into depth prediction
The formula for this conversion is given in the 'additional considerations'
section of the paper.
"""
min_disp = 1 / max_depth
max_disp = 1 / min_depth
scaled_disp = min_disp + (max_disp ... |
def lcm(*args):
"""Least commom multiple of a n-uple of integers
>>> lcm(1,2,3)
6
>>> lcm(4,8)
8
>>> lcm(10,4,20)
20
"""
sum = args[0]
while any(map(lambda x: sum % x != 0, args)):
sum += args[0]
return sum |
def checkbandnumbers(bands, checkbands):
"""
Given a list of input bands, check that the passed
tuple contains those bands.
In case of THEMIS, we check for band 9 as band 9 is the temperature
band required to derive thermal temperature. We also check for band 10
which is required for TES atmos... |
def format_elapsed_time(seconds):
"""Format number of seconds as days, hours, & minutes like '12d 3h 45m'"""
minutes = int(round(seconds / 60))
hours, minutes = divmod(minutes, 60)
result = '{minutes}m'.format(minutes=minutes)
if hours:
days, hours = divmod(hours, 24)
result = '{hou... |
def get_movienames2readgroups_from_header(header):
"""Given an input BAM header dict, return a dict {moviename: readgroup}.
Note that although as of SA 5.0, each movie should be associated with an unique read group ID,
however, it may not be true in the future for barcoded samples, when each read group shou... |
def create_starter_script(user, is_master):
"""
Create starter bash script.
"""
template = [
'#!/bin/bash',
'',
'source /home/{}/.ros/env/distributed_ros.bash'.format(user),
'rosrun distributed_system_upstart distributed_ros_{}'.format('master' if is_master else 'slave'),... |
def add( x, y):
"""This function adds two numbers"""
if (not isinstance(x, (int, float))) | \
(not isinstance(y, (int, float))):
raise TypeError("only numbers are allowed")
return x + y |
def merge(left, right):
"""Merge sort merging function."""
merged_array=[]
while left or right:
if not left:
merged_array.append(right.pop())
elif (not right) or left[-1] > right[-1]:
merged_array.append(left.pop())
else:
merged_array.append(right.pop())
merged_array.reverse()
return merged_array |
def camels_in_dest(camel_dict, destination):
"""Find the camels in the destination square
Parameters
----------
camel_dict : nested dict
Dictionary with current camel positions
destination : int
Square where camels are moving
Returns
-------
max_height_dest : int
... |
def bintogray(x: int) -> int:
"""
Convert a binary encoded positive integer into gray code.
"""
assert x >= 0
return x ^ (x >> 1) |
def _set_cadence(lkwargs):
""" Select the cadence of the data to download
Determines the extension to use later in the lookup of cached fits files,
to be passed to LightKurve for online lookup.
If no cadence argument is passed it will default to long cadence.
Parameters
---------... |
def add(a, b, c):
"""Take three inputs as integer and returns their sum."""
total = a+b+c
return total |
def getChrLenList(chrLenDict, c):
""" Given a chromosome length dictionary keyed on chromosome names and
a chromosome name (c) this returns a list of all the runtimes for a given
chromosome across all Step names.
"""
l = []
if c not in chrLenDict:
return l
for n in chrLenDict[c]:
... |
def setlsb(component: int, bit: str) -> int:
"""Set Least Significant Bit of a colour component.
"""
return component & ~1 | int(bit) |
def _all_not_none(*args):
"""Returns a boolean indicating if all arguments are not None"""
for arg in args:
if arg is None:
return False
return True |
def get_distance(highway_now: list, car_index: int) -> int:
"""
membuat jarak antara kendaraan dan kendaraan selanjutnya
>>> get_distance([6, -1, 6, -1, 6], 2)
1
"""
distance = 0
cells = highway_now[car_index + 1 :]
for cell in range(len(cells)):
if cells[cell] != -1:
... |
def _get_status_and_proof_summaries(run_dict):
"""Parse a dict representing a Litani run and create lists summarizing the
proof results.
Parameters
----------
run_dict
A dictionary representing a Litani run.
Returns
-------
A list of 2 lists.
The first sub-list maps a statu... |
def TSA_rn_g( rnet, vegetation_fraction):
"""
//Chen et al., 2005. IJRS 26(8):1755-1762.
//Estimation of daily evapotranspiration using a two-layer remote sensing model.
Bare soil net radiation
TSA_rn_g( rnet, vegetation_fraction)
"""
result = (1 - vegetation_fraction) * rnet
return result |
def remove_non_ascii_string(text, replace_char=' '):
"""remove non-ascii characters from file"""
non_ascii_text = ''.join([i if ord(i) < 128 else replace_char for i in text])
return non_ascii_text |
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
see: https://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points
"""
from math import... |
def digitize(n):
"""Convert a number to a reversed array of digits."""
l = list(str(n))
n_l = []
for d in l:
n_l.append(int(d))
n_l.reverse()
return n_l |
def counting_sort(arr) :
"""
The counting_sort takes a list of integers in unsorted order and returns a
sorted list.
It first creates a list of counters set at zero initially, for elements starting
from 0 to max of the list. Then it iterates through each of the element in
given list and ke... |
def _parse_font(font_string):
"""Parse font
string should be of the form:
<font family name> <font size>
"""
if not font_string:
return None
return (' '.join(font_string.split()[:-1]), int(font_string.split()[-1])) |
def _check(portobj):
"""Helper function used by aristaouput, handles converts missing portobj
to iterable Nones"""
if portobj is None:
portobj = [None]
return portobj |
def bsearch(A, pred):
"""
Assume the boolean function pred returns all False and then all True for
values in A. Return the index of the first True, or len(A) if that does
not exist.
"""
# invariant: last False lies in [l, r) and A[l] is False
if pred(A[0]):
return 0
l = 0
r =... |
def capitalize(s):
"""
Returns
-------
str
"""
return s[0].upper() + s[1:] |
def invert(horseshoe) -> list:
"""Inverts the horseshoe like mirror"""
return [row[::-1] for row in horseshoe] |
def interpret(command):
"""
:type command: str
:rtype: str
"""
res_1 = command.replace("()", "o")
res_2 = res_1.replace("(al)", "al")
return res_2 |
def _is_descriptor(obj):
"""Returns True if obj is a descriptor, False otherwise."""
return (
hasattr(obj, '__get__') or
hasattr(obj, '__set__') or
hasattr(obj, '__delete__')) |
def int_to_start_stop(i, size):
"""For a single dimension with a given size, turn an int into slice(start, stop)
pair."""
if -size < i < 0:
start = i + size
elif i >= size or i < -size:
raise ValueError('Index ({}) out of range (0-{})'.format(i, size - 1))
else:
start = i
... |
def reverse(sequence, keep_nterm=False, keep_cterm=False):
"""
Create a decoy sequence by reversing the original one.
Parameters
----------
sequence : str
The initial sequence string.
keep_nterm : bool, optional
If :py:const:`True`, then the N-terminal residue will be kept.
... |
def intersection(l1, l2):
"""Return intersection of two lists as a new list::
>>> intersection([1, 2, 3], [2, 3, 4])
[2, 3]
>>> intersection([1, 2, 3], [1, 2, 3, 4])
[1, 2, 3]
>>> intersection([1, 2, 3], [3, 4])
[3]
>>> intersection([1, 2, 3], [4, 5, 6])
... |
def frequency_sort(s):
"""
Inputs:
s -> str
Output:
str
"""
# Your code here
freq_dict = {}
for ch in s:
if ch in freq_dict:
freq_dict[ch] += 1
else:
freq_dict[ch] = 1
items = sorted(freq_dict.items(), key=lambda kv: kv[1], reverse=Tr... |
def rdp_password(index):
"""Generate RDP password for the specified chain link"""
return f"WindowsPassword!{index}" |
def _count_subset_sum_memo(arr, total, n, T):
"""Helper function for count_subsets_total_memo()."""
if total < 0:
return 0
if total == 0:
return 1
if n < 0:
return 0
if T[n][total]:
return T[n][total]
if total < arr[n]:
n_subsets = _count_subset_sum_mem... |
def members_in_a_not_in_b(list_a, list_b):
""" members_in_a_not_b(list_a, list_b):
Return a list of members that are in list_a but not in list_b
Args:
list_a: list
list_b: list
Return:
list
"""
return list(set(list_a) - set(list_b)) |
def create_response(status_code, status_description="", body=""):
"""Configure a response JSON object."""
response = {"isBase64Encoded": False, "headers": {"Content-Type": "text/html;"}}
if not status_description:
description = {
200: "200 OK",
400: "400 Bad Request",
... |
def misc_command_str(cmds):
"""Builds the uncategorized command string for the discord embed description."""
uncategorized_commands = ""
for cmd in cmds:
uncategorized_commands += f"`{cmd.name}`, \n"
return uncategorized_commands[:-3] |
def collection_2_listed_string(elems):
"""
Given a Container (i.e. a Set, List, etc.) of strings,
returns an HTML string wherein each item has its own line, and all items are in alphabetical order.
This will be used to help format and contsruct the email text body (as an HTML)
in the build_e... |
def _compute_parameter(a, b, point):
"""
:param a: [float, float]
:param b: [float, float]
:param point: [float, float]
:return: t, such that point = a * (1 - t) + b * t
"""
parameter0 = (point[0] - a[0]) / (b[0] - a[0])
parameter1 = (point[1] - a[1]) / (b[1] - a[1])
return [paramete... |
def eggSafeName(s):
""" (Get from Chicken) Function that converts names into something
suitable for the egg file format - simply puts " around names that
contain spaces and prunes bad characters, replacing them with an
underscore.
"""
s = str(s).replace('"', '_') # Sure there are more bad chara... |
def _corners(d):
"""Return corner coordinates.
@param d: `dict` with keys
`'x', 'y', 'w', 'h'`
@return: quadruple
@rtype: `tuple`
"""
x = d['x']
y = d['y']
w = d['w']
h = d['h']
xmax = x + w
ymax = y + h
return x, xmax, y, ymax |
def automaticity_level(t):
"""Calculates the level of automaticity (the effort the user had to
make to retrieve an item from memory) based on response time. The values
of parameters are based on some statistical experiments.
:param t: Response time in seconds.
:type t: float or int
"""
resu... |
def _get_value_list_from_query_params(query_params, key):
"""
Get a list of values which have keys that start with key[ or key
"""
filter_type_keys = [
qs_key
for qs_key in query_params.keys()
# View should accept "type" as a single query param, or multiple types,
# e.g.:... |
def filter_input_words(all_counts, allowed_chars, max_input_tokens):
"""Filters out words with unallowed chars and limits words to max_input_tokens.
Args:
all_counts: list of (string, int) tuples
allowed_chars: list of single-character strings
max_input_tokens: int, maximum number of tokens a... |
def Path(url,path):
""" Check path """
if url.endswith('/') and path.startswith('/'):
return url[:-1] + path
if not url.endswith('/') and not path.startswith('/'):
return url + "/" + path
else: return url+path |
def remove_elements(list1, list2):
"""
Returns a list with the repeated elements of the two lists
"""
removed_elements = []
for element in list1:
if element in list2:
removed_elements.append(element)
# UNCOMMENT THE FOLLOWINF TO ALSO REMOVE THE REPEATED ELEMENTS IN... |
def _wrap(text, color, reset='\033[0m'):
""" wrap text between color and reset, unless color is None, then return text """
if color:
return '\033[%sm%s%s'%(color, text, reset)
else:
return text |
def mul_constant(I1, n):
"""Calculate the multiplication of an interval by a constant
Keyword arguments:
I1 -- the interval given as a tuple (a, b)
n -- the real constant to multiply with
"""
(from1, to1) = I1
return (min(from1 * n, to1 * n), max(from1 * n, to1 * n)) |
def _MergeSpacedArgs(command_line, argname):
"""Combine all arguments |argname| with their values, separated by a space."""
i = 0
result = []
while i < len(command_line):
arg = command_line[i]
if arg == argname:
result.append(arg + ' ' + command_line[i + 1])
i += 1
else:
result.app... |
def get_game_info(game):
"""
Gets printable game information.
"""
return (
"%d (%s: %s [%d] vs. %s [%d])" % (
game['game_id'], game['date'], game['home_team'], game['home_score'], game['road_team'], game['road_score'],
)) |
def argparse_bool(x):
"""Convert a command line arguments for a boolean value."""
return str(x).lower() in {'true', '1', 'yes'} |
def find_last(list, key):
"""
Return the index of the last occurrence of the given key (if any).
If the key does not occur, return None.
"""
if list == ():
return None
else:
head, tail = list
idx = find_last(tail, key)
if idx is None:
if head == key:
... |
def find_a_sequence_inside_another_sequence(seq, seq_to_find):
"""Check if a sequence exists in another sequence
Example:
seq = [1,2,4,5,6,2,3,1,2,3,4]
seq_to_find = [4,5,6]
find_a_sequence_inside_another_sequence(seq, seq_to_find)
>> True
:type seq: lis... |
def _build_rule_table(bnf_grammar_ast, terminals, skip):
"""
Args:
bnf_grammar_ast: grammar on bnf ast form produced by _ebnf_grammar_to_bnf
terminals (list): list of terminals of the language
Returns:
A dict that maps every non-terminal to a list of
right hand sides of production ... |
def mean(lst):
"""Calculates the mean of a numeric list"""
return sum([float(x) for x in lst])/len(lst) |
def _clean_provider_class(value):
"""Split the value to module name and classname."""
modulename, classname = value.split(':')
if len(modulename) == 0:
raise ValueError('empty module name')
if len(classname) == 0:
raise ValueError('empty class name')
return (modulename, classn... |
def fibonacci_bottom_up_minified(x: int) -> int:
"""Calculates x'th Fibnoacci number in O(N) time, O(1) space"""
# ignoring x<=0
if x == 1 or x == 2:
return 1
res = 0
first = second = 1
for _ in range(3, x + 1):
res = first + second
first = second
second = res
... |
def safe_short_string(value, max_value_len=1000, tail=False):
"""Returns the string limited by max_value_len parameter.
Parameters:
value (str): the string to be shortened
max_value_len (int): max len of output
tail (bool):
Returns:
str: the string limited by max_value_len p... |
def indent(text, indent=1, multiplier=4):
""" Indent the given block of text by indent*4 spaces
"""
if text is None:
return ''
text = str(text)
if indent >= 0:
sindent = ' ' * multiplier * indent
text = '\n'.join((sindent + t).rstrip() for t in text.splitlines())
return t... |
def pretty_print_error(err_json):
"""Pretty print Flask-Potion error messages for the user."""
# Special case validation errors
if len(err_json) == 1 and "validationOf" in err_json[0]:
required_fields = ", ".join(err_json[0]["validationOf"]["required"])
return "Validation error. Requires pro... |
def average(xs):
"""
Return the average of a list of numbers or None for empty lists
"""
return sum(xs)/len(xs) if len(xs) > 0 else None |
def last_player(played_cards, players):
"""
Return person who played the last card.
E.g.:
last_player([(1, "S"), (2, "S")], ["Abi", "Bob"])
returns: "Bob"
Args:
played_cards (list):
players (list):
Returns:
return (str): The players name
"""
... |
def str_str(this):
"""
Identity method
"""
return this # identity |
def windows_translator(value):
"""Translates a "windows" target to windows selections."""
return {
"@com_github_renatoutsch_rules_system//system:windows_x64": value,
"@com_github_renatoutsch_rules_system//system:windows_x64_msvc": value,
"@com_github_renatoutsch_rules_system//system:wind... |
def plutonium_to_time(pu, flux_average, phi_0, pu_0):
"""Approximate time in units of plutonium
With the assumption that plutonium-per-unit-fluence is constant for
an average batch of fuel (one simulation), the total plutonium
over several subsequent batches is related to the operating time
o... |
def partial_es(Y_idx, X_idx, pred, data_in, epsilon=0.0001):
"""
The analysis on the single-variable dependency in the neural network.
The exact partial-related calculation may be highly time consuming, and so the estimated calculation can be used in the bad case.
Args:
Y_idx: index of Y to acce... |
def get_val_or_default(in_dict, key):
"""Helper functions to return either an item in a dictionary or the default value of the dictionary
Parameters
----------
in_dict : `dict`
input dictionary
key : `str`
key to search for
Returns
-------
out : `dict` or `function`
... |
def get_schema_name(full_qualified_table_name):
"""Extracts the schema name from a full qualified table name.
Parameters
----------
full_qualified_table_name : str, mandatory
A full qualified table name (i.e. schema name and table name)
Returns
-------
The schema name or None.
... |
def _vectorize(value):
"""Vectorize a value.
If VALUE is a scalar, return a list consisting of that scalar.
Otherwise return VALUE."""
if type (value) != list:
return [value]
return value |
def bulk_check(checker, items):
"""Bulk check files.
Some programs can only accept a single file or directory to process at a
time. This function receives a function that returns the check function and
list to go through. The function returns 0 if all checks returned 0 or 1
otherwise.
"""
r... |
def editor_valid(
enough_edits: bool,
account_old_enough: bool,
not_blocked: bool,
ignore_wp_blocks: bool,
):
"""
Check all eligibility criteria laid out in the terms of service.
Note that we won't prohibit signups or applications on this basis.
Coordinators have discretion to approve pe... |
def count_back(array):
"""
This is a helper function that provides functionality specific to streaming ordered
merges. It takes an array in sorted order and calculates a trimmed length that excludes
the final sequence of equal values:
Example::
[10, 20, 30, 40, 50] -> 4 ([10, 20, 30, 40])
... |
def parse_int(strng):
"""
In this kata we want to convert a string into an integer. The strings simply represent the numbers in words.
Examples:
"one" => 1
"twenty" => 20
"two hundred forty-six" => 246
"seven hundred eighty-three thousand nine hundred and nineteen" => 783919
Additional N... |
def gr_PSRF(B, W, N):
"""Computes potential scale reduction factor (PSRF), the Gelman-Rubin statistic"""
return (1-1./N)*W + 1/N * B |
def _to_camel_case(s: str) -> str:
"""
Convert given string to Camel case.
If the string has no space or under score, it will be
treated as Camel case thus no change will be made.
>>> _to_camel_case('eagleDiao')
'eagleDiao'
>>> _to_camel_case('eagle_diao')
'EagleDiao'
>>> _to_camel_... |
def file_chunker(files, files_per_output=-1, events_per_output=-1, MB_per_output=-1, flush=False):
"""
Chunks a list of File objects into list of lists by
- max number of files (if files_per_output > 0)
- max number of events (if events_per_output > 0)
- filesize in MB (if MB_per_output > 0)
Chu... |
def diff2(array):
"""
:param array: input x
:return: processed data which is the 2-order difference
"""
return [j - i for i, j in zip(array[:-2], array[2:])] |
def encode_pos(i, j):
"""Encodes a pair (i, j) as a scalar position on the board."""
return 3 * i + j |
def getSirionCuCpsPerNa(e0):
"""getSirionCuCpsPerNa(e0)
Output the cps per nA for the Sirion Oxford EDS detector for a given e0.
These values were determined for PT 6, 5 eV/ch, 2K channels in 2014-09-12-QC
Example:
import dtsa2.jmGen as jmg
a = jmg.getSirionCuCpsPerNa(7.0)"""
val = 0.0
if(e0 == 5.0):
val = 25... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.