content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def subtract_mean_vector(frame):
"""
Re-center the vectors in a DataFrame by subtracting the mean vector from
each row.
"""
return frame.sub(frame.mean(axis='rows'), axis='columns') | 4a6207889b958aebd608c349ad889e109ab3f4a9 | 702,906 |
from typing import Union
def get_n_docs_to_assign(docs_to_assign: Union[int, float, str], corpus_n: int) -> int:
"""Converts a parameter with the number of docs to extract into an integer
Args:
docs_to_assign: value we want to extract
corpus_n: number of documents that have been topic modelle... | 9b2b1aa2e674df383542264be7ba7caa98571c17 | 374,498 |
import torch
def makeInp(inputs):
"""Move tensors onto GPU if available.
Args:
inputs: A dict with a batch of word-indexed data from DataLoader. Contains
['brk_sentence', 'bs_inp_lengths', 'style', 'sentence', 'st_inp_lengths', 'marker', 'mk_inp_lengths']
Returns:
inputs: The dict with same structure but s... | af00b78f33627f45e505a6b8c75fb07ef29b94e6 | 13,285 |
import glob
def has_glob(pth):
"""
Return True if pth contains glob metacharacters (*, ?, [])
"""
return pth != glob.escape(pth) | dd739739d0b1bde4fd00105e77c259cd085927b7 | 611,681 |
from typing import Sequence
def move_position(password: str, args: Sequence[str]) -> str:
"""
Move position operation: the sequence 'args' should contain two indices, X and Y. The character
at index X will be removed from the original string and inserted at position Y.
"""
first, second, *_ = [int... | 30b8702ceabfebf9f84d6502d333711fdb56f8f7 | 493,725 |
def labelOfCluster(labelList, clusts, c):
"""
Inputs:
labelList: (N,) list, each is a LabelHelper object
clusts: (K,) list of set (each set is a cluster)
c: scalar, cluster index
Return:
labelObj of (any) observations in cluster c.
Runtime:
O(1)
"""
retu... | e1e1954ba451854fd9642ef813ac8afef7c27359 | 472,388 |
def get_feature_directory_name(settings_dict):
"""Get the directory name from the supplied parameters and features."""
dir_string = "%s_%d_%d_%d_%d" % (
settings_dict["feature"],
settings_dict["fft_sample_rate"],
settings_dict["stft_window_length"],
settings_dict["stft_hop_length... | 5b0a72a4e1c38637119e54022e1b23a7a5482988 | 60,954 |
from typing import Dict
from pathlib import Path
def _get_arg(
root_dir: str,
tmpdirname: str,
nb_to_py_mapping: Dict[Path, Path],
project_root: Path,
) -> Path:
"""
Get argument to run command against.
If running against a single notebook, it'll be the filepath of the converted
noteb... | e1c50b811fc0fef0cae2a976f69aa9c3eba5031c | 587,002 |
def parse_addr(addrstr):
"""
parse 64 or 32-bit address from string into int
"""
if addrstr.startswith('??'):
return 0
return int(addrstr.replace('`', ''), 16) | 95ab1196de84cf3be26789aa08b3a07305e40721 | 214,766 |
def get_snapshot_run_correlation_id(test_run_name, snapshot_type):
"""Returns the qualified string to use as correlation id.
Keyword arguments:
test_run_name -- the test run name for this run
snapshot_type -- either 'full' or 'incremental'
"""
return f"{test_run_name}_{snapshot_type}" | bccc40d43bc39c74f655557dc975b22083476513 | 649,299 |
from typing import Any
from typing import List
def get_attr_names(obj: Any) -> List[str]:
"""Return object attribute name list"""
return [ a for a in dir(obj) if not a.startswith("_")] | ef8cfd47835b84f0b8a6b7d53e4a7d7b1409240f | 521,852 |
def get_stats_query(table: str):
"""Returns PostgresSQL table count and size stats query
by Erwin Brandstetter, source:
https://dba.stackexchange.com/a/23933/139107
"""
db_query = f"""
SELECT l.metric, l.nr AS "bytes/ct"
, CASE WHEN is_size THEN pg_size_pretty(nr) END AS bytes_pretty
... | 82edfeba837a4528029df09e91dd92ba40652be9 | 446,916 |
from typing import OrderedDict
def create_model(api, name, fields):
"""Helper for creating api models with ordered fields
:param flask_restx.Api api: Flask-RESTX Api object
:param str name: Model name
:param list fields: List of tuples containing ['field name', <type>]
"""
d = OrderedDict()
... | 9119e43e07ba3c7baeb176b0f7ba285f64c8c8da | 682,519 |
def _parse_choice_parameters(optim_paras, params):
"""Parse utility parameters for choices."""
for choice in optim_paras["choices"]:
if f"wage_{choice}" in params.index:
optim_paras[f"wage_{choice}"] = params.loc[f"wage_{choice}"]
if f"nonpec_{choice}" in params.index:
op... | 1d2402a5031124e6ab39fb518d9aa4b18720e7d2 | 519,437 |
import re
def truncate(text, max_len=250, suffix="..."):
"""
Truncate a text string to a certain number of characters,
trimming to the nearest word boundary.
"""
trimmed = text.strip()
if len(trimmed) < max_len:
return trimmed
elif re.match("\s", trimmed[max_len + 1]):
retu... | b941d0c0cc863096f1ae28bed5533e107d4e9b28 | 132,275 |
def get_id_list(alltests):
"""
Generate a list of all IDs in the test cases.
"""
return [x["id"] for x in alltests] | 04f112897a8b992a0cbd599450c9ac01c7f467a1 | 155,082 |
def get_instance(instances, instance_name):
""" Get instance from instances with the given instance name """
for instance in instances.values():
if instance_name == instance.name:
return instance
return None | fc9e78cb4175a5079fd18da627fc1b2bf6f2f3d8 | 263,367 |
def word_tokenizer(string):
"""
Splits a string by whitespace characters.
Args:
string (string): The string to be split by whitespace characters.
Returns:
list: The words of the string.
"""
return string.split() | c5e15434299de26eabb2b4a597a7904af0d76529 | 531,806 |
def get_index_freq(freqs, fmin, fmax):
"""Get the indices of the freq between fmin and fmax in freqs
"""
f_index_min, f_index_max = -1, 0
for freq in freqs:
if freq <= fmin:
f_index_min += 1
if freq <= fmax:
f_index_max += 1
# Just check if f_index_max is not... | f3e014626d763f18ce6b661cabeb244bfabe9782 | 706,727 |
def calc_f(tp: int, fp: int, fn: int):
"""
Calculates the F1-Score
NOTE: This follows standard evaluation metrics
TAKEN FROM: Open-SESAME (https://github.com/swabhs/open-sesame)
:param tp: True Postivies Count
:param fp: False Postivies Count
:param fn: False Negatives Count
:return: A... | f0e4bee053d5258a133647be6cc3de8409bdce7b | 496,474 |
def is_list_or_tuple(var):
"""Checks if an object is a list or a tuple"""
return isinstance(var, list) or isinstance(var, tuple) | 3127d794f95f9b1f33afb440d7fab6242ab87f46 | 309,879 |
def get_name(path):
"""
Get a file name from its full path.
Args:
path (str): full path
Returns:
name (str): just the file name
"""
splits = path.split("/")
if splits[-1] == "":
name = splits[-2]
else:
name = splits[-1]
return name | e02be58a13adb13fe7b5beb6fa4d052a1ead0a6f | 287,110 |
def build_self_awareness_detection_prompt(question, answer):
"""Builds the prompt to check if the model can detect answers generated by self-aware models.
Args:
answer: String: the model should guess if the answer was generated by a self-aware model
question: String: the question, from which th... | eb6ec52197123192392b2754aa395fd9595f533d | 293,836 |
import re
def _parse_trailers(text: str) -> str:
"""Parses and returns trailers in the text.
Arguments:
text {str} -- commit body text with trailers
Returns:
str -- the trailer lines.
"""
lines = text.splitlines()
trailer = re.compile(r"\s*(Source-Link:|PiperOrigin-RevId:).*"... | 1cd8ee42ce416447e5e5e45926bac1ef44a83cbe | 419,681 |
def merge_tables(table1, table2,join_type='exact'):
"""Merges two RMTables into a single table.
Inputs: table1 (RMTable): first table to be merged.
table2 (RMTable): second table to be merged.
join_type (str): 'exact' - requires both tables have exactly the same columns.
... | 2a3778972497b25a69801c483bd8dd064e3cebfe | 595,659 |
import re
def _IsGitHash(revision):
"""Checks whether the input looks like a SHA1 hash."""
return re.match(r'[a-fA-F0-9]{40}$', str(revision)) | 0fb496f5ab796cb06e30e1e35bf33bc9e38ce1bd | 86,357 |
def unpack(variables):
""" remove first dimension and zero padding from each variable
variables is a list with one tensor per variable
a tensor [3, 5, 4] may be unpacked to [[5, 4], [2, 4], [1, 4]]
"""
all_unpacked = []
for v in variables:
# note on gpu sorted; on cpu not unless spe... | 71fca7720b18dfd6b68de4fed885d83af9f16c8e | 156,214 |
def jitter_augment(is_training=True, **kwargs):
"""Applies random color jitter augmentation."""
if is_training:
brightness = kwargs['brightness'] if 'brightness' in kwargs else 0.125
contrast = kwargs['contrast'] if 'contrast' in kwargs else 0.4
saturation = kwargs['saturation'] if 'saturation' in kwarg... | 05a154cb102cbada3669c55471581a5220e901a1 | 150,071 |
def merlin_pos(view, pos):
"""
Convert a position returned by Merlin to a Sublime text point.
Sublime uses character positions and starts each file at line 0.
"""
return view.text_point(pos['line'] - 1, pos['col']) | 908f31ce409c288cde93ee04b67986adc6679167 | 210,706 |
def get_fields_for_formset(formset, fields):
"""
Utility method to grab fields that should be displayed for a FormSet
"""
if fields is None:
return formset.empty_form.visible_fields()
else:
return [
f for f in formset.empty_form.visible_fields() \
if f.nam... | 6f63783d1db1128865b8a1637fffe0f1fc2c6897 | 418,920 |
def clean_url(url):
"""Remove trailing slash and query string from `url`."""
url = url.split("?")[0]
if url and url[-1] == "/":
return url[:-1]
return url | 6b16ec84e75cb82c66977376dcb55285c3133e93 | 293,000 |
def remove_punct(string):
"""Remove common punctuation marks."""
if string.endswith('?'):
string = string[:-1]
return (string.replace(',', '')
.replace('.', '')
.replace(';', '')
.replace('!', '')) | 30da60b184af868b55a82a6a67c95aca19f681f1 | 364,844 |
def read_numbers(number_file, query_file):
"""
Parameters
----------
number_file : str
query_file : str
Returns
-------
tuple
(numbers, queries) - both are lists
"""
with open(number_file) as f:
numbers = list(map(int, f.read().split(" ")))
with open(query_f... | 7d1d23e52fb6a294f6098f1d70239dfc66be018c | 285,808 |
import random
def random_tour(num_of_cities):
"""
Returns a random valid tour
"""
tour = list(range(num_of_cities))
random.shuffle(tour)
return tour | f6e8edf4b57cbaa8a4402e27639f3b6b8467198f | 641,008 |
def date_to_long_string(date):
"""Format a date in long format e.g. "27 January 2011".
date - The Time to format.
Returns the formatted String.
"""
return date.strftime('%d %B %Y') | 52ed72d10cd482f870daabf149d8e90e78bca729 | 408,573 |
import shutil
def combine_ligands_gro(in_file_A, in_file_B, out_file, ligand_A='MOL', ligand_B='MOL'):
"""Add ligand B coordinates to coordinate (.gro) file of ligand A in complex with protein
Parameters
----------
in_file_A : .gro file
Complex A coordinate file
in_file_B : .gro file
... | 2f7a5e9ce18a76b472ae1adce21ea331a9b5a0c6 | 223,199 |
import requests
def get_object(
token: str,
url: str = "https://dev-api.aioneers.tech/v1/",
object: str = "dotTypes",
) -> list:
"""Get JSON object.
Parameters
----------
token : str
Token which was returned from the user login.
url : str = "https://dev-api.aioneers.tech/v1/"
... | c0ad1ba7caf13aafde888fdaad8a1670f6964c78 | 37,677 |
from typing import Any
from typing import Union
def optional_str(val: Any) -> Union[str, None]:
"""Convert value to string, but keep NoneType"""
return str(val) if val is not None else val | ea97833892e8e306ee1a0806e19f16dba655f729 | 497,981 |
def _UniqueGenerator(generator):
"""Converts a generator to skip yielding elements already seen.
Example:
@_UniqueGenerator
def Foo():
yield 1
yield 2
yield 1
yield 3
Foo() yields 1,2,3.
"""
def _FilteringFunction(*args, **kwargs):
returned = set()
for item in gener... | cd5b1d0ccbc864e400e3358d8a04d089f61c6f92 | 406,587 |
def _get_db_subnet_group_arn(region, current_aws_account_id, db_subnet_group_name):
"""
Return an ARN for the DB subnet group name by concatenating the account name and region.
This is done to avoid another AWS API call since the describe_db_instances boto call does not return the DB subnet
group ARN.
... | db6736d9e5d56eb2940875f7564c6293db2c080e | 652,821 |
import torch
def is_legal(v):
"""
Checks that tensor is not NaN or Inf.
Inputs:
v (tensor): tensor to be checked
"""
legal = not torch.isnan(v).any() and not torch.isinf(v)
return legal | 6235a7c5873acb3177484b4639db93e84fdce4a9 | 205,537 |
import re
def convert_paths(files):
"""
Converts '\' character in Windows paths to '/'. This method is only executed when script is running on Windows environment.
Args:
files: a dictionary containing full paths and their project paths (in Windows style).
Returns:
files: a dictionary containing ... | df8531c10c3677c7a19c5d4368cff01f4777e686 | 364,363 |
import math
def wind_speed_2m(ws, z):
"""
Convert wind speed measured at different heights above the soil
surface to wind speed at 2 m above the surface, assuming a short grass
surface.
Based on FAO equation 47 in Allen et al (1998).
:param ws: Measured wind speed [m s-1]
:param z: Heigh... | f5c84fac3e5a7404e7baa8f2a6dd44388fe64ff1 | 616,554 |
def create_equation_from_terms(terms):
"""
Create a string equation (right hand side) from a list of terms.
>>> create_equation_from_terms(['x','y'])
'x+y'
>>> create_equation_from_terms(['-x', 'y', '-z'])
'-x+y-z'
:param terms: list
:return: str
"""
if len(terms) == 0:
... | 4c9cfab0569363ce5f448f2d7aefa38967f425b0 | 508,941 |
import copy
def _label_skew(list, sk):
"""
Returns a filled in a standard skew tableaux given an ordered list
of the coordinates to filled in.
EXAMPLES::
sage: import sage.combinat.skew_tableau as skew_tableau
sage: l = [ '0,0', '1,1', '1,0', '0,1' ]
sage: empty = [[None,None... | e51f74feeb2259825f87791c5a53cc1663d22ae5 | 140,181 |
def cavity_round_trip_losses_approx(length, A0=1e-5, exponent=1/3):
"""Approximation of cavity round-trip losses given the cavity length, and some initial parameters.
Inputs:
-------
length: float
length of the cavity
A0: float
losses for a 1 meter cavity. Default is 10 ppm.
expo... | 7dceac1cd9c0d4d7541cec2d90201a4cfe636fa8 | 247,954 |
import torch
from typing import List
def chunk_squeeze_last(x: torch.Tensor) -> List[torch.Tensor]:
"""
Splits the provided tensor into individual elements along the last dimension and returns the
items with the last dimension squeezed.
Args:
x: The tensor to chunk.
Returns:
The ... | 51fadfe55f6ca09944a4bcdef4654a68992fe106 | 410,421 |
def get_point(coords, lat_first):
"""Converts GeoJSON coordinates into a point tuple"""
if lat_first:
point = (coords[1], coords[0])
else:
point = (coords[0], coords[1])
return point | 420da57be1057dccf5122f9306299c5607b1a7fa | 313,399 |
def make_str_for_pretty_print_int_list(lst):
"""
Produce a stirng which neatly prints a list of integers.
This is done by compacting the integers into contiguous ranges.
for example [0,1,2,3,4,10,11,12] will become "[0..4,10..12]"
:param lst: list of integers
:return: string
"""
stri="["... | 50b0d9555699975b3ce23a7b4de2137c5672386b | 565,984 |
def pop_unchanged(dictionary):
"""Pop all values from dict where key=val."""
return [dictionary.pop(key) for key in list(dictionary) if dictionary[key] == key] | d92b33bcec893002263e07058f0bc1cbdd19c83d | 304,078 |
def _use_voc_evaluator(dataset):
"""Check if the dataset uses the PASCAL VOC dataset evaluator."""
return dataset.name[:4] == 'voc_' | 9e63776b25e1f4079929dec5e3e78e887c721c23 | 297,611 |
def assert_nonnegative_int(name: str, value: str) -> int:
"""
Makes sure the value is a non-negative integer, otherwise raises AssertionError
:param name: Argument name
:param value: Value
:return: Value as integer
"""
if not (value.isdigit() and int(value) >= 0):
raise AssertionErr... | b518ee21f8f049dd4a508349d1d1d012c030cc5b | 482,826 |
import json
def _json_from_file(file_name):
"""Load a json file encoded with UTF-8."""
with open(file_name, 'rb') as dumped:
loaded = json.loads(dumped.read().decode('utf-8'))
return loaded | 013b39f3ba26dc0008e38afa94158fc6dd686637 | 259,779 |
import torch
def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
"""Converts ellipse regions to LAF format.
Ellipse (a, b, c) and upright covariance matrix [a11 a12; 0 a22] are connected
by inverse matrix square root: A = invsqrt([a b; b c]).
See also https://github.com/vlfeat/vlfeat/blob/master... | 839f22949d64a59b8814eb94aa1148d633cb7318 | 163,215 |
def update_tmpo(tmposession, hp):
"""
Update the tmpo database with all sensors from a houseprint object.
This does NOT synchronize the data, only loads the sensors.
Parameters
----------
tmposession : tmpo.Session object
hp : a Houseprint object
Returns
-------
tmpos... | 609fa40acf18e8d9f3e316de4c854c2c7390a3ee | 289,938 |
def image_smoothing(img, reducer, kernel):
"""Smooths an image.
Args:
img (object): The image to be smoothed.
reducer (object): ee.Reducer
kernel (object): ee.Kernel
Returns:
object: ee.Image
"""
image = img.reduceNeighborhood(**{
'reducer': reducer,
... | b824d1530620f72a85562c3f22e0b4a03e2a5827 | 283,356 |
from typing import Dict
import json
def load_config(app_environment) -> Dict:
"""Load configuration file from config.json"""
with open('config.json', 'r') as config_file:
config_dict = json.load(config_file)
return config_dict | c1ab8c4dda12593d6c67e573b9d1a07041c743db | 622,101 |
def kTdiff(i, j, zs, kTs):
"""Compute the difference vector (kTi/zi - kTj/zj)."""
return kTs[i-1]/zs[i-1] - kTs[j-1]/zs[j-1] | 975f4533cf5391c442149ca38326cc4e51e4ce5e | 502,766 |
import re
import ast
def _parse_data_structure(inner_json):
"""Parses broken JSON that this router generates.
Data structures look like this:
{
key: 'value',
another_key: [1, 2, 3]
}
We're basically using what's between the main {},
and are parsing that, returning a dictionar... | 5c97e62bdf1b47f1ac5a884f8a3766399974bf77 | 418,899 |
def consists_of(seq, types):
"""
Check that the all elements from the "seq" argument (sequence) are among the types passed as the "types" argument.
@param seq: The sequence which elements are to be typed.
@param types: A tuple of types to check.
@type types: tuple
@return: Whether the check ... | b422f89a7c22505fc75bcaa9e3d28a787ed1dff6 | 649,280 |
def drain(stream):
"""
A function wrapper around the `bytearray` data type. Can be used as the final sink in
a refinery pipeline in Python code, i.e.:
from refinery import *
# ...
output = data | carve('b64', single=True) | b64 | zl | drain
assert isinstance(output, bytearra... | 41edf9e00d71dcf102ea36430ba87b04aacc8aa8 | 334,391 |
def filter_kwargs(keywords, **kwargs):
"""
Filter provided keyword arguments and remove all but
those matching a provided list of relevant keywords.
Parameters
----------
keywords : list of string
Keywords to search for within the provided keyword arguments
kwargs : dict
Diction... | 5bf8493e81a0e3e0db18cd94e152d65f691817ca | 625,408 |
import re
def get_whitespace(txt):
"""
Returns a list containing the whitespace to the left and
right of a string as its two elements
"""
# if the entire parameter is whitespace
rall = re.search(r'^([\s])+$', txt)
if rall:
tmp = txt.split('\n', 1)
if len(tmp) == 2:
... | e5bdc175a02511c2fc4fa56118b165ddbe1c4f71 | 395,972 |
def rk4(t, dt, x, deriv):
"""Fourth-order Runge-Kutta integrator.
Parameters
----------
t : float
time
dt : float
time step
x : float or broadcastable sequence
state vector
deriv : function(x, t)
callback to compute xdot at time t
Returns
-------
... | e3ad9f0caa301aceca3c8d776712db1328804936 | 430,595 |
def test_setting_mixin(mixin, **attrs):
"""Create a testable version of the setting mixin.
The setting mixin passes through kwargs to an expected `super`
object. When that object doesn't exist it causes errors. This
function takes the mixin in question and adds that `super` object
so that the mixin... | 3aeabc21e31c57001693abda253381d651f6d7d8 | 63,509 |
def is_theano_object(var):
"""checks if var is a theano input, transformation, constant or shared variable"""
return type(var).__module__.startswith("theano") | 287f858821ae64c5c02cd8c5007f2f909b1db084 | 436,787 |
def identity(u):
""" returns the field itself """
return u | 48cec79a2e2fe4686471f32e7c9cd892fe4f97d6 | 616,937 |
def chunk_list(l, n):
""" Chops a list into tuples (chunks) of maximal size `n`
Args:
l (List[Any]): the list to be resized
n (int): maximal size of the chunks
Example:
>>> chunk_list([1, 2, 3, 4, 5], 2)
[(1, 2), (3, 4), (5,)]
"""
assert n > 0
nl = ... | e0b9d4c8a4ac28c6bc624b6ec1b8111a5b793c5b | 429,059 |
def output_transform_va(process_output):
"""
Output transform for vehicle affordances metrics.
"""
y_pred = process_output[0]['vehicle_affordances'].argmax(dim=1)
y = process_output[1]['vehicle_affordances'].argmax(dim=1)
return dict(y_pred=y_pred, y=y) | c105706934a1fbdf01442e7526c44ef6f3b28a23 | 196,455 |
def canonicalise_message_line(line):
"""
Given a line known to start with the '%' character (i.e. a line
introducing a message), canonicalise it by ensuring that the result
is of the form '%<single-space>MESSAGE_IDENTIFIER<single-space>text'.
Parameters:
line - input line. Known to start with ... | 07afdd59035bb68582e0d51e8695231beeaf8169 | 111,400 |
def is_oppo_dispossessed(event_list, team):
"""Returns whether an opponent is disposessed"""
disposessed = False
for e in event_list[:1]:
if e.type_id == 50 and e.team != team:
disposessed = True
return disposessed | 24b39dd984e660fdad565576f865c5995fd83bac | 60,382 |
def dict_values_map(f, d):
"""
Simple helper to apply a function to the values of a dictionary.
This is similar to built-in map() but only accept one iterable dict.
"""
return {k: f(v) for k, v in d.items()} | 313e7dd43d8ddac71c63e2101f2cbb42dd9866bb | 274,962 |
def get_alias_value(dictionary, aliases):
"""
Get alias or key value from a dictionary
:param dictionary: a dictionary to check in for keys/aliases
:param aliases: list of aliases to find in dictionary to retrieve value
:return: returns value of found alias else None
"""
if (dictionary and ... | e79650973ecfb12c20cc17a19b8862a7a1033eb6 | 384,114 |
import math
def polar2vec(r, phi):
"""Calculate Cartesian vector from polar coords."""
x = r * math.cos(phi)
y = -r * math.sin(phi)
return x, y | f54e7ec97dc6813df705762ddbe9d35205d64cc5 | 547,356 |
def convert_14_to_tuple(datetime_no_delims):
""" Converts 14-digit datetime (e.g. 20160130235959) to (Y,M,D,H,M,S) tuple [e.g. (2016,01,30,23,59,59)].
"""
dtnd_str = str(datetime_no_delims)
return (int(dtnd_str[0:4]), int(dtnd_str[4:6]), int(dtnd_str[6:8]),
int(dtnd_str[8:10]), int(dtnd_str[... | 56fd67b0177b7683edb43dfe176f9be75cf191c6 | 387,125 |
def major_axis_equiv_diam_ratio(prop, **kwargs):
"""Return the ratio of the major axis length to the equivalent diameter
Args:
prop (skimage.measure.regionprops):
The property information for a cell returned by regionprops
**kwargs:
Arbitrary keyword arguments
Retur... | fd2e1668577cac77788415f8ecfefd9d9b8df926 | 47,880 |
def ndims(x):
"""
Return the ndims of a tensor.
"""
return len(x.shape) | c72af6dcd49d4ebebac7d9a346efe72d63fb9cc8 | 109,870 |
def edit_request_email_context(request, edit_request):
"""prepare context for rendering edit request notifications"""
return {'edit_request': edit_request,
'cert_url': request.build_absolute_uri(edit_request.certificate.get_absolute_url()),
'home_url': request.build_absolute_uri('/'),
... | c544be5223bae0c5e3cced4da380716a5f412874 | 163,551 |
import six
def _to_bytes(obj, encoding):
"""
In Python3:
Encode the str type object to bytes type with specific encoding
In Python2:
Encode the unicode type object to str type with specific encoding,
or we just return the 8-bit string of object
Args:
obj(unicode|str|b... | 33597783ae2deed372f0aa43b18da668c5f9496a | 412,463 |
from pathlib import Path
import re
def get_total_coverage(ctx, coverage_dat: Path) -> str:
"""Return coverage percentage, as captured in coverage dat file; e.g., returns "100%"."""
output = ctx.run(
f"""
export COVERAGE_FILE="{coverage_dat}"
coverage report""",
hide=True,
)... | b42509da14a6ebeb23c6a430d5215daa2b512ff2 | 354,741 |
def apply_gain_x(x, AdB):
"""Applies A dB gain to x"""
return x * 10 ** (AdB / 20) | 6026d9c7a96534d944f4ece4a18e54af8acdc637 | 557,889 |
import pipes
def shell_join(array):
"""
Return a shell-quoted version of the input array.
:param array: input array
:return: the shell-quoted string
"""
return " ".join(pipes.quote(item) for item in array) | 8a964df48f09d4e038e0353f8c8941dfcfa720c6 | 71,147 |
def cut_groups(data, col, cutoffs):
"""Cut data into subsets according to cutoffs
Parameters
----------
data : pandas.DataFrame
Data to split.
col : str
Name of column in data to compare with.
cutoffs : list(int)
List of cutoffs, like as [min-value, 30, 60, max-value].
... | a80b7833c60683e9e9fd7bd310c3823f16bb440c | 113,338 |
def get_input(lives, display, guessed_text):
"""
Get user input at every round
:param lives: (int) the lives of player
:param display: (string) the guessed answer to show user
:param guessed_text: (string) the guessed character
:return: (string) the character input from player
"""
print(... | b535469cb4935f7be449745b4473839b9cb9fc7a | 411,588 |
import re
def is_valid_project_id(project_id):
"""True if string looks like a valid Cloud Project id."""
return re.match(r'^(google.com:)?[a-z0-9\-]+$', project_id) | 46532d10a8a0ed304204d858445b935ff4f4bfe9 | 686,921 |
def pluralize(count: int, unit: str) -> str:
"""
Pluralize a count and given its units.
>>> pluralize(1, 'file')
'1 file'
>>> pluralize(2, 'file')
'2 files'
>>> pluralize(0, 'file')
'0 files'
"""
return f"{count} {unit}{'s' if count != 1 else ''}" | 85f9be97488584db46f86808111ecf2d849b7dfc | 175,859 |
def get_fastas(fasta_file, genes=False):
"""
>>> get_fastas('a.fasta')
('a.genomic.masked.fasta', 'a.features.fasta')
>>> get_fastas('a.fasta', genes=True)
('a.genomic.masked.genes.fasta', False)
"""
if not genes:
genomic_masked = fasta_file.replace('.fa', '.genomic.masked.fa')
... | 9a0f1d3436145d30d1c8a44e10883347ff5af864 | 412,588 |
def main_done_selector(card):
"""Selector for cards done and not connected."""
return not card.associations and card.state == 'closed' | dd2e6ac26eec64421543fad6b45c819dedecc3b4 | 221,415 |
def select_count_from(session, table) -> int:
"""
Function to select row count from provided table (like SELECT COUNT(*) FROM table)
:param session: sqlalchemy session
:param table: table to select from
:return: row count
"""
count = session.query(table).count()
return count | 9e3869fb692c16281f768d73e019b693f43cd7fa | 463,409 |
from typing import Callable
import ast
def eval_lambda(val: str) -> Callable:
"""Parse a lambda from a string safely.
Args:
val: string representing a lambda.
Returns:
a callable.
Raises:
ValueError: in case the lambda can not be parsed.
"""
parsed_lamba = ast.parse(... | aa2081f66471d483ea76cc9723c632cb354d5f42 | 106,943 |
def save_dotted_field(accessor_string: str, data: dict):
"""Saves data to a dictionary using a dotted accessor-string.
Parameters
----------
accessor_string : str
A dotted path description, e.g. "DBLinks.KEGG".
data : dict
The value to be stored.
Returns
-------
dict
... | cd55a988f63bcd6784a56bf5a18e85780e26b51b | 273,971 |
def set_bit(value, index, new_bit):
""" Set the index'th bit of value to new_bit, and return the new value.
:param value: The integer to set the new_bit in
:type value: int
:param index: 0-based index
:param new_bit: New value the bit shall have (0 or 1)
:return: Changed value
:rtype... | 0e42d70a9319d14ec7e984f0b42b08f97309430c | 196,979 |
import locale
def money(amount, symbol=True):
""" Return a properly formatted currency string including symbol """
try:
return locale.currency(float(amount), symbol, grouping=True)
except ValueError:
pass
return '' | 1aa9b2be89dbb956e870fc1f06c6e70406dd6d8a | 142,042 |
import math
def regular_poly_circ_rad_to_side_length(n_sides, rad):
"""Find side length that gives regular polygon with `n_sides` sides an
equivalent area to a circle with radius `rad`."""
p_n = math.pi / n_sides
return 2 * rad * math.sqrt(p_n * math.tan(p_n)) | 939ff5de399d7f0a31750aa03562791ee83ee744 | 3,279 |
def parse_token_clause(token_clause):
"""Parse the clause that could be either 'with', 'using', or 'without'."""
use_token = {"with": True,
"using": True,
"without": False}.get(token_clause)
if use_token is None:
raise Exception("Wrong clause specified: {t}".format(... | acc04185822b57e21422d2ef442ab1dbdbbd10b0 | 200,705 |
def calculate_fuel(mass):
"""Calculate the fuel required for a module
>>> calculate_fuel(12)
2
>>> calculate_fuel(14)
2
>>> calculate_fuel(1969)
654
>>> calculate_fuel(100756)
33583
"""
return mass // 3 - 2 | d2d2ae239027515fa9240c4bd59f6c7efb056d13 | 92,608 |
def parse_time(time):
"""Given the time string, parse and turn into normalised minute count"""
if type(time) in [int,float]:
return time
if time.endswith('m'):
time = time[0:-1]
if time.find('h') != -1:
time = time.replace('h', ':')
if time.find(':') != -1:
hours,... | b4effe0eb9b93a761e9f6f83f7d7d9b60bb8d978 | 90,502 |
import textwrap
def format_template(template, *args):
"""
Given incoming text, remove all common indent, then strip away the leading
and trailing whitespace from it.
This is a modified version of code from Default/new_templates.py from the
core Sublime code.
"""
return textwrap.dedent(tem... | 4e1c08c4bce5af043789374f4348383cb50f623e | 522,550 |
import re
def get_collect_id(imageID):
"""Get the collect ID for an image name using a regex."""
collect_id = re.findall('Atlanta_nadir[0-9]{1,2}_catid_[0-9A-Z]{16}',
imageID)[0]
return collect_id | deffb98786fad57a6aa757b51c9df3ab885060b2 | 365,024 |
import csv
def read_sleepasandroid_file(saa_filename):
"""
read in a SleepAsAndroid backup file and return it as a parsed list
"""
with open(saa_filename) as file:
file_as_list = list(csv.reader(file, delimiter=','))
return file_as_list | 22011c2ba784747c65c3dc47063fb486d3130785 | 651,228 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.