content stringlengths 42 6.51k |
|---|
def sum_digit(i):
"""Die Funktion berechnet die Quersumme von i."""
summe = 0
for digit in str(i):
summe += int(digit)
return summe |
def sort_key(buffer):
"""Returns a sort key such that "simpler" buffers are smaller than
"more complicated" ones.
We define sort_key so that x is simpler than y if x is shorter than y or if
they have the same length and x < y lexicographically. This is called the
shortlex order.
The reason for... |
def simple_lang(pressure, n_total, k_const):
"""A simple Langmuir equation returning loading at a pressure."""
return (n_total * k_const * pressure / (1 + k_const * pressure)) |
def translate_lon_to_geos5_native(longitude):
"""See function above"""
return ((longitude + 180) / 0.625) |
def graph_return(resp, keys):
"""Based on concepts of GraphQL, return specified subset of response.
Args:
resp: dictionary with values from function
keys: list of keynames from the resp dictionary
Returns:
the `resp` dictionary with only the keys specified in the `keys` list
R... |
def binary_search(array: list, target: int) -> bool:
""" searches through a sorted list to find a target integer """
mid = len(array) // 2
if len(array) < 1:
return False
if len(array) == 1:
return array[0] == target
if array[mid] < target:
return binary_search(array[... |
def _find_calframe(calframes, calpaths, values, calname, verbose=False):
""" Find the calibration frame and path from given dicts for dict values.
"""
if calframes is None:
calpath = None
calframe = None
else:
try:
calframe = calframes[values]
calpath = ca... |
def merge_configs(driver: dict, client: dict) -> dict:
"""
Merge Driver and Client config. The Client configs will overwrite matching keys in the Driver config.
Args:
driver (dict): driver dictionary of configs
client (dict): client dictionary of configs
Returns:
Merged configs... |
def partition(nums, lo, hi, idx):
"""
Partition using nums[idx] as value.
Note lo and hi are INCLUSIVE on both ends and idx must be valid index.
Count the number of comparisons by populating A with RecordedItem instances.
"""
if lo == hi:
return lo
nums[idx], nums[lo] = nums[lo], num... |
def batches_list(project='batch', n_batches=5):
"""
Create buttons corresponding to number of batches inside the given project.
Args:
project (str): name of the project, *default:* ``batch``
n_batches (int): number of batches inside this project, *default:* ``5``
Returns:
list: list of tuples ``(project, ba... |
def _get_tracklet(tracks: dict, idx: int) -> list:
"""Get a tracklet by the first object ID"""
target = [t for t in tracks.values() if t[0] == idx]
if target:
return target[0]
else:
raise ValueError("Object ID not found.") |
def _format_spacing(details):
"""Formats spacing to build weather section."""
length = 19
spaces = ''
if len(details) < length:
for i in range(length - len(details) - 1):
spaces += " "
return spaces |
def get_scene(videoname):
"""ActEV scene extractor from videoname."""
s = videoname.split("_S_")[-1]
s = s.split("_")[0]
return s[:4] |
def get_resume_name(stage_name):
"""return a new name with resume and an increasing index"""
split_stage_name = stage_name.split("_")
if len(split_stage_name) > 2 and split_stage_name[-2] == "resume":
resume_index = int(split_stage_name[-1]) + 1
return "_".join(split_stage_name[:-2] + ["resu... |
def greedy_cow_transport(cows, limit=10):
"""
Uses a greedy heuristic to determine an allocation of cows that attempts to
minimize the number of spaceship trips needed to transport all the cows. The
returned allocation of cows may or may not be optimal.
The greedy heuristic should follow the followi... |
def cmp(a, b):
"""replaces the missing built-in in Python3"""
if a is None and b is None:
return 0
elif a is None:
return -1
elif b is None:
return 1
else:
return (a > b) - (a < b) |
def five_interp(x, a0, a1, a2, a3, a4):
"""``Approximation degree = 5``
"""
return a0 + a1 * x + a2 * (x ** 2) + a3 * (x ** 3) + a4 * (x ** 4) |
def filter_invalid_flags(item):
"""Filter our all flags not needed for getting the compilestats."""
filter_list = ["-O1", "-O2", "-O3", "-Os", "-O4"]
prefix_list = ['-o', '-l', '-L']
result = item not in filter_list
result = result and not any([item.startswith(x) for x in prefix_list])
return r... |
def is_palindrome(number):
""" Returns True if the variable passed is a palindrome, False otherwise. """
numlist = list(str(number))
if len(numlist) <= 0:
return False
if len(numlist) == 1:
return True
i = 0
while i <= len(numlist) / 2:
if numlist[i] != numlist[-(i+1)]... |
def mscb(t):
"""
Find the index of the most significant change bit,
the bit that will change when t is incremented
aka the power of 2 boundary we are at
>>> mscb(0)
0
>>> mscb(1)
1
>>> mscb(7)
3
>>> mscb(8)
0
"""
return (t^(t+1)).bit_length()-1 |
def parse_tripos_bond(mol2):
"""
Parse Tripos MOL2 BOND records to a dictionary
:param mol2: Tripos MOL2 file as string
:type mol2: :py:str
:return: Tripos bond records
:rtype: :py:dict
"""
read = False
bond_dict = {}
headers = ('b_start', 'b_end', 'b_typ... |
def keys_and_values(d):
"""Return the keys and values as separate lists.
Sorted by the key value.
"""
return [list(keys_values)
for keys_values
in list(zip(*sorted(list(d.items()))))] |
def min_list(lst):
"""
A helper function for finding the minimum of a list of integers where some of the entries might be None.
Args:
lst (list): The list.
Returns:
int: The entry with the minimal value.
"""
if len(lst) == 0:
return None
elif len(lst) == 1:
... |
def format_seconds(seconds):
"""
Return ':ss' if seconds are < 60, 'm:ss' if minutes are less than 60,
'h:mm:ss' if more than an hour
:param seconds:
:return:
"""
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
if hours:
return '%d:%02d:%02d' % (ho... |
def pressure_from_altitude(y):
"""
Calculate standard atmospheric pressure based on an altitude in m. The
basic formula can be found many places. For instance, Munson, Young, and
Okiishi, 'Fundamentals of Fluid Mechanics', p. 51.
Enter: y: altitude in m.
Exit: p: pressure in N/m/m.
"""
... |
def rescale(value, orig_min, orig_max, new_min, new_max):
"""
Rescales a `value` in the old range defined by
`orig_min` and `orig_max`, to the new range
`new_min` and `new_max`. Assumes that
`orig_min` <= value <= `orig_max`.
Parameters
----------
value: float, default=None
The... |
def gauss(A, b):
"""
@param A: matrix
@param b: vector
@return: reduced echelon form of A|b
"""
n = len(A)
for i in range (0,n):
if A[i][i] != 0:
p = 1 / A[i][i]
for j in range (i,n):
A[i][j] *= p
b[i]*p
for k in ran... |
def get_first_non_empty(lst):
"""
lst = [[], [], 1, [2, 3, 4], [], []] -> 1
lst = [[], [], False, (), [2, 3, 4], [], []] -> [2, 3, 4]
"""
for element in lst:
if element:
return element |
def _get_lua_base_module_parts(base_path, base_module):
"""
Get a base module from either provided data, or from the base path of the package
Args:
base_path: The package path
base_module: None, or a string representing the absence/presence of a base
module override
... |
def substitute_variables(model_params_variables, model_data_raw):
"""
:param model_params_variables:
:param model_data_raw:
:return:
"""
model_data_list = []
for argument_raw in model_data_raw:
argument_split_raw = argument_raw.split(",")
argument_split = []
for par... |
def is_category_suspicious(category, reputation_params):
"""
determine if category is suspicious in reputation_params
"""
return category and category.lower() in reputation_params['suspicious_categories'] |
def max_sequence(arr):
"""Find the largest sum of any contiguous subarray."""
best_sum = 0 # or: float('-inf')
current_sum = 0
for x in arr:
current_sum = max(0, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum |
def trailing_zeros(n):
"""Count trailing zero bits in an integer."""
if n & 1: return 0
if not n: return 0
if n < 0: n = -n
t = 0
while not n & 0xffffffffffffffff: n >>= 64; t += 64
while not n & 0xff: n >>= 8; t += 8
while not n & 1: n >>= 1; t += 1
return t |
def config_writer(proxies):
"""Converting proxies into a config string
"""
config = ""
def get_proxy(location, address):
config = (
"\n\tlocation "
+ location
+ "{\n\t\tproxy_set_header X-Real-IP $remote_addr;\n\t\tproxy_pass "
+ address
... |
def parser_parental_rating_Descriptor(data,i,length,end):
"""\
parser_parental_rating_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "parental_rating", "contents" : unparsed_descriptor_contents }
... |
def quintic_ease_out(p):
"""Modeled after the quintic y = (x - 1)^5 + 1"""
f = p - 1
return (f * f * f * f * f) + 1 |
def get_status(status):
"""Returns a numeric status value."""
status_map = {
'running': 1,
'stopped': 0}
return status_map[status] |
def safe_format_amount(commodity, amount):
"""
Formats an amount with a commodity, or without it if the commodity is None
"""
if commodity is None:
return str(amount)
return commodity.format_amount(amount) |
def select(headers, vectors):
"""
Select a vector whose .host attribute matches the Host header
"""
host_header = headers.get("Host", "")
if not host_header:
return None
for v in vectors:
if v['.host'] == host_header:
return v
return None |
def vec_dotprod(vector1, vector2):
"""
Dot product of 2 vectors
Parameters
----------
vector1 : list
Input vector 1.
vector2 : list
Input vector 2.
Returns
-------
dotp_res : float
Resulting dot product.
"""
dotp_res = sum(v1_i * v2_i for v1_i, v2_i... |
def strip_url_parameters (url):
"""Remove any client or user parameters from this url, and return
the string without them (it leaves urls w/o parameters as-is)"""
return url.split('?')[0] |
def extract_uid_metadata(uid):
"""Extract metadata for a given UID.
Apply to all UIDs: see `extract_all_uid_metadata`.
Return extracted metadata with format
[uid, label, speaker, paired_image, production, frames].
"""
uid_parts = uid.split("_")
extracted = [
uid, uid_parts[0], uid_... |
def split_unit_quantity(string):
"""Given a physical quantity as a string, returns a tuple containing the quantity's magnitude and unit, both
as strings."""
quantity = ""
index = 0
quantity_characters = [str(num) for num in range(10)] + [".", "-", "+"]
for character in string:
if charact... |
def sendController(msg, q):
"""Communicate with connected controller
Arguments:
msg {str} -- Message to be sent
q {socket.socket} -- Controller's socket
Returns:
int -- Error Code:
0) Error
1) Success
"""
try:
q.send(msg)
... |
def check_list(listvar):
"""Turns single items into a list of 1."""
if not isinstance(listvar, list):
listvar = [listvar]
return listvar |
def sentence(*args):
"""
SENTENCE thing1 thing2
SE thing1 thing2
(SENTENCE thing1 thing2 thing3 ...)
(SE thing1 thing2 thing3 ...)
outputs a list whose members are its inputs, if those inputs are
not lists, or the members of its inputs, if those inputs are lists.
"""
result = []
... |
def build_counts(haplotypes):
"""
# ========================================================================
BUILD COUNTS
PURPOSE
-------
Builds the a list of the counts of each haplotype in a passed haplotype
list.
Example:
haplotype1.sequence = "AAA"
haplotype1.count = 3
... |
def cell_start(position, cell_width, wall_width):
"""Compute <row, col> indices of top-left pixel of cell at given position"""
row, col = position
row_start = wall_width + row * (cell_width + wall_width)
col_start = wall_width + col * (cell_width + wall_width)
return (row_start, col_start) |
def find_distance_from_1_to(number):
"""Find Manhattan Distance between number and 1 in square."""
last_corner = 1
steps = 1
side = 0
while last_corner < number:
if side == 0:
steps += 2
last_corner += steps - 1
side += 1
if side == 4:
side = 0... |
def process_changes(results):
"""Split GCS change events into trivial acks and builds to further process."""
acks = [] # pubsub message ids to acknowledge
todo = [] # (id, job, build) of builds to grab
# process results, find finished builds to process
for ack_id, message in results:
if m... |
def get_pair_equality(row, column_1, column_2):
"""
Helper function used by pair_equality, to test values of two columns for
equality in a single row.
:param row:
Row from dataframe
:param column_1:
Name of first column
:param column_2:
Name of second column
:return:... |
def sum_word_len(tokens):
"""Given list of words, return sum of length of words (int)"""
return sum([len(token) for token in tokens]) |
def intersection(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1=set(nums1)
nums2=set(nums2)
return list(nums1.intersection(nums2)) |
def nexthop_is_local(next_hop):
"""
Check if next-hop points to the local interface.
Will be True for Connected and Local route strings on Cisco devices.
"""
interface_types = (
'Eth', 'Fast', 'Gig', 'Ten', 'Port',
'Serial', 'Vlan', 'Tunn', 'Loop', 'Null'
)
for type in interf... |
def part2(tree_line):
""" Product of the no. of trees on diff. slopes """
slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
height = len(tree_line)
width = len(tree_line[0])
product_trees = 1
for slope in slopes:
x_coord, y_coord, trees = 0, 0, 0
while y_coord < height - 1:
... |
def _is_typing_object(type_object):
"""Checks to see if a type belong to the typing module.
Parameters
----------
type_object: type or typing._GenericAlias
The type to check
Returns
-------
bool
True if `type_object` is a member of `typing`.
"""
return type_object._... |
def PoolVec2Array_to_list(array):
"""Return a copy of the array as a list of 2-element lists of floats.
This is not efficient."""
result = []
for elt in array:
v2 = [elt.x, elt.y]
result.append(v2)
return result |
def _parse_tool_list(tl):
"""
A convenience method for parsing the output from an API call to a Galaxy
instance listing all the tools installed on the given instance and
formatting it for use by functions in this file. Sample API call:
`https://test.galaxyproject.org/api/tools?in_panel=true`
:t... |
def fill_in_missing_output_path(output, output_name, tool_inputs):
"""
Creates a path template for outputs that are missing one
This is needed for the descriptor to be valid (path template is required)
"""
# Look for an input with the same name as the output and use its value key
found = False
... |
def create_label_groups(groups):
"""Create info dictionaries for label groups."""
group_dicts = []
if groups:
for item in groups:
dic = {}
if len(item) == 1:
dic['label'] = item[0]
dic['name'] = item[0]
elif len(item) == 2:
... |
def _dict_to_yaml(data, indent=""):
"""
Helper function for recursively turning the json data into yaml strings.
"""
yaml_data = ""
for (k, v) in data.items():
if isinstance(v, dict) and "lazyObject" in v.keys():
name = v["lazyObject"]
yaml_data += f"{indent}{k}: {nam... |
def axis_diff(direction, rect_start, rect_finish,
boundaries_start, boundaries_finish):
"""
detects if an segment is outside its boundaries and returns the
difference between segment and boundary; if the segment is inside
boundaries returns 0
"""
if direction < 0:
if rect_... |
def make_pipeline_image_name(pipeline_class_name):
""" Create the string for the image for this pipeline_class_name
'disdat-module[-submodule]...'
Args:
pipeline_class_name:
Returns:
str: The name of the image 'disdat-module[-submodule]...'
"""
return '-'.join(['disdat'] + pi... |
def _element_basis(string: str):
"""
Parse element and basis from string
Args: str
Returns: element, basis
"""
cut_list = string.split(".")
element = cut_list[0]
basis = " ".join(cut_list[1:])
return element, basis |
def get_default_data():
"""Default data for Composer tests.
Returns:
dict: object with bands, product, url and output_dir.
"""
return {
"bands": [],
"product": "LC08_L1TP_221071_20170521_20170526_01_T1",
"url": "https://landsat-pds.s3.amazonaws.com/c1/L8/221/071",
... |
def differential_frequency(a, C, e, eref=1):
"""
Differential frequency of events with energies (or other metric) greater than e for a power-law of the form
f = C*e**-a
to the flare energy distribution, where f is the cumulative frequency of flares with energies greater than e.
"""
return a*C*... |
def find_span_binsearch(degree, knot_vector, num_ctrlpts, knot, **kwargs):
""" Finds the span of the knot over the input knot vector using binary search.
Implementation of Algorithm A2.1 from The NURBS Book by Piegl & Tiller.
The NURBS Book states that the knot span index always starts from zero, i.e. for... |
def single_to_plural(string: str) -> str:
"""This function Convert singular to plural """
for char in string:
"""Checks weather it is word or not"""
if not char.isalpha():
raise ValueError('You did not input a word. ')
if string.endswith('y'):
if string.endswith(... |
def convert_to_list (line):
"""
This program makes the rows of the matrix making lists of list.
@type line: string
@param line: m columns of the matrix
@rtype: list
@return: convert string into a list
"""
line_list = line.split()
i = 0
row = []
while i < len(line_list):
... |
def map_device(materials):
"""
Get (first) material, if available
:param materials: list with checked materials, can be empty
:return: device name, e.g. "trek-rad"
"""
if len(materials) == 0:
return ""
return materials[0] |
def simple_name_from(long_name):
""" Extracts primary name from uniprot string containing all names.
Additional names are given in brackets and parantheses
"""
out = []
buffer = []
in_bracket = 0
in_square_bracket = 0
for letter in long_name:
if letter == "(":
in_bra... |
def extended_euclidean_gcd(a, b):
"""Copied from
http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm"""
x,y, u,v = 0,1, 1,0
while a != 0:
q,r = b//a,b%a; m,n = x-u*q,y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
return b, x, y |
def _serialize_headers(headers):
"""Serialize CIMultiDictProxy to a pickle-able dict because proxy
objects forbid pickling:
https://github.com/aio-libs/multidict/issues/340
"""
# Mark strings as keys so 'istr' types don't show up in
# the cassettes as comments.
return {str(k): v for... |
def isprime_eratosteene(n):
"""Returns True if n is prime.
It uses the fact that a prime (except 2 and 3) is of form 6k - 1 or 6k + 1.
Function looks only at divisors of this form (after checking 2 & 3).
"""
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
... |
def convert_array_to_string(array):
"""Returns a string containing the given array"""
string = '{'
for value in array:
string = string + str(value) + ','
if (len(string)!=1):
string = string[:-1]
return string + '}' |
def workspace_command(cmd):
"""Simple command to always go to the workspace directory"""
return ' && '.join([
'cd {job.ws}',
cmd if not isinstance(cmd, list) else ' && '.join(cmd),
'cd ..',
]) |
def _numstages(ord, type='lowpass') -> int:
""" compute the number of stages based on the filter type. """
if type in ['lowpass', 'highpass', 'allpass']:
ncount = (ord-1)/2 + 1 if (ord % 2) else ord/2 # 6 coeffs/stage.
elif type in ['bandpass', 'bandstop']:
ncount = ord
else:
raise ValueError('filter type %s ... |
def IsFloat(s):
"""Is a string an floating point number?"""
try:
float(s)
return True
except ValueError:
return False |
def get_darkvariance(camcol,band,run=None):
"""
data.sdss3.org/datamodel/files/BOSS_PHOTOOBJ/frames/RERUN/RUN/CAMCOL/frame.html
"""
DARK_VAR_CCD = {
0:{"u":9.61, "g":15.6025,"r":1.8225,
"i":7.84, "z":0.81},
1:{"u":12.6025,"g":1.44, "r":1.00,
... |
def norm1(m):
"""
Return the L1-norm of the point m
"""
s = 0.0
for (name, value) in m.items():
s += abs(value)
return s |
def direction(pos, prev):
"""
Determine the direction of travel given current and previous position, as
a unit vector and magnitude.
"""
dx, dy = pos[0] - prev[0], pos[1] - prev[1]
mag = 1
if abs(dx) > 1:
mag = 2
dx /= abs(dx)
if abs(dy) > 1:
mag = 2
dy ... |
def elementwise_list_division(numerator, denominator, percentage=False):
"""
Simple method to element-wise divide a list by the values in another list of the same length.
"""
assert len(numerator) == len(denominator), 'Attempted to divide two lists of different lengths'
percentage_multiplier = 100.... |
def trim_by_part_and_type(response, type, part):
""" get specific data """
array = []
for item in response:
if item['type'] == type:
array.append(item[part])
return array |
def get_summary(html_text):
"""Returns the summary part of the raw html text string of the wikipedia article.
:param html_text: The html content of an article.
:type html_text: str
:return: The summary of the input wikipedia article.
:rtype: str
"""
# The summary ends before the first h tag... |
def npy_cdouble_from_double_complex(var):
"""Cast a cython double complex to a numpy cdouble."""
res = "_complexstuff.npy_cdouble_from_double_complex({})".format(var)
return res |
def splitlines(value):
"""
Returns the value turned into a list.
"""
return value.splitlines() |
def post_add(db, usernick, message):
"""Add a new post to the database.
The date of the post will be the current time and date.
Return a the id of the newly created post or None if there was a problem"""
if(len(message) < 551): # 551 words limits
cur = db.cursor()
cur.execute("INSERT I... |
def dahua_brightness_to_hass_brightness(bri_str: str) -> int:
"""
Converts a dahua brightness (which is 0 to 100 inclusive) and converts it to what HASS
expects, which is 0 to 255 inclusive
"""
bri = 100
if not bri_str:
bri = int(bri_str)
current = bri / 100
return int(current *... |
def bottom_up_fibonacci(n: int, return_ith: bool = False) -> object:
"""Returns the nth fibonacci number if return_ith=False, else it returns a
list containing all the ith fibonacci numbers, for i=0, ... , n.
For example, suppose return_ith == True and n == 5, then this function
returns [0, 1, 1, 2, 3,... |
def is_subtask(task):
"""Whether the task name represents a subtask."""
return ":" in task |
def aggregate_count(items, col):
"""
Function to use on Group by Charts.
accepts a list and returns the count of the list's items
"""
return len(list(items)) |
def blur(blur_width=1.0, blur_height=1.0, sample_num_x=4, sample_num_y=4):
"""
Blur filter.
distance = distance apart each sample is
percentage = amount of blurring to apply
sample_num_x = number of samples to apply on the X axis
sample_num_y = number of samples to apply on the Y axis
Auth... |
def generate_winner_list(winners):
""" Takes a list of winners, and combines them into a string. """
return ', '.join([winner.username_raw for winner in winners]) |
def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h |
def subdivide(events: list, splits: list) -> list:
"""Split the given events to match the keys in the splits list"""
formatted_events = []
for i in range(len(splits)-1):
formatted_event = {}
formatted_event["temporalRange"] = [splits[i], splits[i + 1]]
# Get the events of the enclos... |
def calculate_alpha(alpha=0.5):
# type: (float)-> float
""" Calculates alpha for train_model (py27) """
alpha += 0.1
return alpha |
def record_sets_fetcher(record):
"""Fetch a record's sets."""
return record.get('_oai', {}).get('sets', []) |
def is_pon(item):
"""
:param item: array of tile 34 indices
:return: boolean
"""
if len(item) != 3:
return False
return item[0] == item[1] == item[2] |
def getFromLongestMatchingValue(
objectList,
listOfValues,
keyToMatch,
caseInsensitive=True
):
"""
Function to take a list of objects, a list of values and a key to match and
return the object with the longest matching value for that key or None if
no value matches for that that key.
... |
def normal_log_deriv(x, mu, sig):
"""
Derivative of the log of the normal distribution with respect to x
:param x: value to be tested
:param mu: mean
:param sig: variance
:return: d/dx
"""
return (-2.0 * x + mu) / (2 * sig ** 2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.