content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def has_no_overlap(r1, r2):
"""Returns True if the two reads overlap.
"""
r1_start, r1_end = r1.reference_start, r1.reference_end
r2_start, r2_end = r2.reference_start, r2.reference_end
return (r2_end <= r1_start) or (r1_end <= r2_start) | 54e5c50ed37c8d3ca473dc62a0fd3c21318d4df0 | 673,426 |
def pick(*args):
"""
Returns the first non None value of the passed in values
:param args:
:return:
"""
for item in args:
if item is not None:
return item
return None | acbdf1a47050303c0d2c033f64d793b8821bbbc9 | 673,428 |
def get_dataframe_name(s):
"""
Split dataframe and variable name from dataframe form field names (e.g. "___<var_name>___<dataframe_name>__").
Args:
s (str): The string
Returns:
2-tuple<str>: The name of the variable and name of the dataframe. False if not a properly formatted string.
... | 20b3a72b19717d6c428d2c41a98ab3fa001b8536 | 673,432 |
from typing import Iterable
from typing import Any
def count_bool(blist: Iterable[Any]) -> int:
"""
Counts the number of "truthy" members of the input list.
Args:
blist: list of booleans or other truthy/falsy things
Returns:
number of truthy items
"""
return sum([1 if x else... | 25c0e1d06ce059f39d5238364ea6a59f93876af8 | 673,437 |
import re
def WrapWords(textlist, size, joiner='\n'):
"""Insert breaks into the listed strings at specified width.
Args:
textlist: a list of text strings
size: width of reformated strings
joiner: text to insert at break. eg. '\n ' to add an indent.
Returns:
list of strings
"""
# \S*? is a... | 8fba790437b643da960897ecf00d6c4ba24c1c5f | 673,438 |
def _format_param_value(key, value):
"""Wraps string values in quotes, and returns as 'key=value'.
"""
if isinstance(value, str):
value = "'{}'".format(value)
return "{}={}".format(key, value) | c6989a4ac03a94e7c680f6cd2ea5f3570812f02d | 673,440 |
def echo_args(*args, **kwargs):
"""Returns a dict containng all positional and keyword arguments.
The dict has keys ``"args"`` and ``"kwargs"``, corresponding to positional
and keyword arguments respectively.
:param *args: Positional arguments
:param **kwargs: Keyword arguments
:rtype:... | 383c36b6a8c0d7ae3dbecbbcfc59808106a8ce1e | 673,447 |
from pathlib import Path
def resolve_import(import_: str, location: str, file: Path) -> str:
"""Resolve potentially relative import inside a package."""
if not import_.startswith('.'):
return import_
import_parts = import_.split('.')
up_levels = len([p for p in import_parts if p == ''])
i... | aed1b736a84f2fb3670e89e4f3a2dfd529162a95 | 673,454 |
def time2int(float_time):
"""
Convert time from float (seconds) to int (nanoseconds).
"""
int_time = int(float_time * 10000000)
return int_time | 7fd785ac7eade1336ddf08d4c6c4ac1116287380 | 673,456 |
def fp_rate(FP, neg):
"""
Gets false positive rate.
:param: FP: Number of false positives
:type FP: `int`
:param: neg: Number of negative labels
:type neg: `int`
:return: false positive rate
:rtype: `float`
"""
if neg == 0:
return 0
else:
return FP / neg | afb9e78dd601c3f9f559001c8f0f2727ccdb0c5f | 673,459 |
def cmd_automation_event_lost(msg):
"""
(From protocol docs) Panel's automation buffer has overflowed.
Automation modules should respond to this with request for Dynamic
Data Refresh and Full Equipment List Request.
"""
return { } | 9394a98c3b1eb81cf16946252cd82c60cda2bbb5 | 673,462 |
def columns_to_nd(array2reshape, layers, rows, columns):
"""
Reshapes an array from columns layout to [n layers x rows x columns]
"""
if layers == 1:
return array2reshape.reshape(columns, rows).T
else:
return array2reshape.T.reshape(layers, rows, columns) | 4fb11743406ca1f1c099e7783381fe0463141683 | 673,465 |
def convert_none_type_object_to_empty_string(my_object):
"""
replace noneType objects with an empty string. Else return the object.
"""
return ('' if my_object is None else my_object) | 52d0cb756f85adba0cd537c0f1b7b74b4c0d23b8 | 673,466 |
import re
def is_weight(word):
"""
is_weight()
Purpose: Checks if word is a weight.
@param word. A string.
@return the matched object if it is a weight, otherwise None.
>>> is_weight('1mg') is not None
True
>>> is_weight('10 g') is not None
True
>>> is_weight('78 mcg') ... | 45bafa2176056babbbd5bc18d93ed6f96c341b6e | 673,471 |
import re
def get_locus_info(locus):
""" Returns chrom, start and stop from locus string.
Enforces standardization of how locus is represented.
chrom:start_stop (start and stop should be ints or 'None')
"""
chrom, start_stop = locus.split(':')
if chrom == 'None':
chrom = None
star... | b09efb7c8c8433c12c7738bbe926df0dad04d9e8 | 673,476 |
def gameboard(level):
"""
This function will generate a gameboard, determined by the level size parameter.
To keep the rows equivalent for both the user and the player, the board_size is
guarenteed to be a multiple of two.
Parameters:
-----------
level: required parameter. Level determin... | 538120cf0e5789074c1f2e0c6e16f6440d0a4524 | 673,481 |
import time
def convert_time(longTime):
"""
Ignore time of day to help with grouping contributions by day.
2018-01-03 00:00:00 --> 2018-01-03
"""
try:
t = time.strptime(longTime, "%Y-%m-%d %H:%M:%S")
except ValueError:
return longTime
ret = time.strftime( "%Y-%m-%d", t)
... | d27f66ec817af5a35a0d406de3f922af1a4f9c6a | 673,485 |
def computeRR(self):
"""
Compute the rectangularity ratio (RR) of the max-tree nodes. RR is defined as the
area (volume) of a connected component divided by the area (volume) of its bounding-box.
"""
xmin,xmax = self.node_array[6,:], self.node_array[7,:] + 1
ymin,ymax = self.node_array[9,:], s... | 745413a672dcdcdb2717c8c45b12ce66f1a0b258 | 673,486 |
def shape3d_to_size2d(shape, axis):
"""Turn a 3d shape (z, y, x) into a local (x', y', z'),
where z' represents the dimension indicated by axis.
"""
shape = list(shape)
axis_value = shape.pop(axis)
size = list(reversed(shape))
size.append(axis_value)
return tuple(size) | 72282a25629ecb864efde13f5c8eb238120d74e5 | 673,489 |
def orsample(df):
"""
Return the bitwise-OR of every value in the data frame.
>>> orsample(empty)
0
>>> result = 1 | 3 | 5 | 6 | 8
>>> assert result == orsample(sample)
"""
if len(df) == 0:
return 0
result = 0
for val in df.iloc[::, 0]:
if val > 0:
re... | d027397953cff1939fe5218b7ae345d6dd4a80b2 | 673,492 |
def camels_to_move(camel_dict, space, height):
"""Getting information about camels that need to move
Parameters
----------
camel_dict : nested dict
Dictionary with current camel positions
space : int
Space the camel is on
height : int
Height of the camel
Returns
... | cc8737d6a7d544775af32b90a3c9486e7ffb3060 | 673,493 |
def make_feasible(x_0, c):
""" Returns a feasible x with respect to the constraints g_3, g_4, g_5, and g_6.
:param np.array x_0: (n,) Initial, infeasible point.
:param dict c: Constants defining the constraints.
:return np.array: (n,) Initial, feasible point.
Notes:
- x_0 should follow: x0... | b4a04ccb25d29962b32601593fd3f2bb7582348a | 673,494 |
def binary_sum(S, start, stop):
"""Return the sum of the numbers in implicit slice S[start:stop]."""
if start >= stop: # zero elemetns in slice
return 0
elif start == stop - 1:
return S[start] # one element in slice
else: # two or more ... | 3d21dfe3afcf47f29d95ae67dc46a5970ed39515 | 673,495 |
from typing import List
def gen_string(i: int, base: int, digits: List[str]):
"""Returns a string representation of an integer given the list of digits.
Args:
i (int): The integer to generate
base (int): The base representation of the number. (based on the length of the list)
digits (... | ad7fe50db1f72fdc4bc5e53e09a6abdea5ff1bd7 | 673,499 |
import math
def round_up_to_multiple(x: int, base: int) -> int:
"""
Round a positive integer up to the nearest multiple of given base number
For example: 12 -> 15, with base = 5
"""
return base * math.ceil(x / base) | c7e9d1442e198e995511193f631e666a1fdd344b | 673,501 |
def module_name_join(names):
"""Joins names with '.'
Args:
names (iterable): list of strings to join
Returns:
str: module name
"""
return '.'.join(names) | 873eb6281f2de5da1fa17f5d89e17a1de4202b4f | 673,503 |
def splitf(delim):
"""
Returns a function that splits string with a given delimiter.
Examples
--------
>>> f = splitf(", ")
>>> f('apples, pears, oranges')
['apples', 'pears', 'oranges']
"""
return lambda x: x.split(delim) | 16bc8a15f356971042ab3472253604cba7807915 | 673,505 |
def _calculate_texture_sim(ri, rj):
"""
Calculate texture similarity using histogram intersection
"""
return sum([min(a, b) for a, b in zip(ri["texture_hist"], rj["texture_hist"])]) | 62168687a737446a77a9a90e3f7227007f23088b | 673,509 |
def pp_value(TP, FP):
"""
Gets positive predictive value, or precision.
:param: TP: Number of true positives
:type TP: `int`
:param: FP: Number of false positives
:type FP: `int`
:return: positive predictive value
:rtype: `float`
"""
if TP == 0 and FP == 0:
return 0
... | 73486b177d9da992777c5f90b98909341467899d | 673,510 |
def _no_pending_images(images):
"""If there are any images not in a steady state, don't cache"""
for image in images:
if image.status not in ('active', 'deleted', 'killed'):
return False
return True | e39b5e3959095599a64a43d517ea206a0b12bc9c | 673,514 |
def get_data(fname: str) -> list:
"""
Read the data file into a list.
"""
with open(fname) as f:
return [int(line) for line in f] | 077dd25a97e61a9bd4abbd76746b1bc7503d068f | 673,515 |
def format_skills(text: str, ents: list) -> list:
"""
Get the list of skills according to the HrFlow.ai Job format
@param text: text description of the job
@param ents: list of entities in the text
@return: list of skills
"""
skills = [{ "name": text[ent["start"]:ent["end"]].lower(), "value"... | 852e340574e5017792aabb51608bd2d66b2e047a | 673,518 |
import csv
def write_csv(f, extract, fields=None):
""" Writers extract to file handle
Parameters
__________
f : file handle (string mode)
extract: list of dicts
fields: list of str
Field names to include in CSV.
Returns
_______
f : file handle (string mode)
"""
key... | c54b797a71af725eace6958950b5d91bce7e64fb | 673,519 |
from typing import List
def _replace_with(items: List[int], value: int) -> List[int]:
"""Replaces all values in items with value (in-place)."""
length = len(items)
del items[:]
items.extend(length * [value])
return items | 4983459883cc34f8d1bf0ca1bfb289e07fc17116 | 673,520 |
import requests
def token(code, redirect_uri, client_id, client_secret):
"""Generates access token used to call Spotify API
Args:
code (str): Authorization code used to generate token
redirect_uri (str): Allowed redirect URL set in Spotify's developer dashboard
client_id (str): Appli... | a834a0361972fe0828d11d2ff8a29464a30b34c6 | 673,521 |
import torch
def broadcast_backward(input, shape):
"""Sum a tensor across dimensions that have been broadcasted.
Parameters
----------
input : tensor
Tensor with broadcasted shape.
shape : tuple[int]
Original shape.
Returns
-------
output : tensor with shape `shape`
... | f81140f7be710435ad1c65b848e0a5d1b7d56bb2 | 673,524 |
def _getrawimagelist(glance_client):
"""Helper function that returns objects as dictionary.
We need this function because we use Pool to implement a timeout and
the original results is not pickable.
:param glance_client: the glance client
:return: a list of images (every image is a dictionary)
... | 86aff3f3508bf3da5fa9f97f9caa1a87b63c0e2c | 673,528 |
import uuid
def prefixUUID(pre: str = "PREFIX", max_length: int = 30) -> str:
"""
Create a unique name with a prefix and a UUID string
:param pre: prefix to use
:param max_length: max length of the unique name
:return: unique name with the given prefix
"""
if len(pre) > max_length:
... | 3ff15b23f768cb138bce291defb288395c25609e | 673,533 |
import re
def _make_safe_id_component(idstring):
"""Make a string safe for including in an id attribute.
The HTML spec says that id attributes 'must begin with
a letter ([A-Za-z]) and may be followed by any number
of letters, digits ([0-9]), hyphens ("-"), underscores
("_"), colons (":"), ... | 81a4e7bec5a87d9588f303033c7960a8a24e9aba | 673,535 |
def is_pickup(df):
"""Return if vehicle is a pickup truck, per NHTSA convention."""
yr = df['YEAR']
body = df['BODY_TYP']
return ((yr.between(1975, 1981) & (body == 50)) |
(yr.between(1982, 1990) & body.isin([50, 51])) |
((1991 <= yr) & body.between(30, 39))) | 29925316fb1b744f36bf7506866bb036f4ccf2f6 | 673,539 |
def _num_items_2_heatmap_one_day_figsize(n):
""" uses linear regression model to infer adequate figsize
from the number of items
Data used for training:
X = [2,4,6,10,15,20,30,40,50,60]
y = [[10,1],[10,2],[10,3],[10,4],[10,6],[10,8],[10,10],[10,12],[10,15],[10,17]]
Parameters
--... | 5fb398c753acb159ed3139588634825024d74acb | 673,542 |
import itertools
def split_mosaic(image, tile_size):
"""
Returns image after splitting image to multiple tiles of
of tile_size.
Args:
image: str an image array to split
tile_size: tuple size each image in the split is resized to
Returns:
Returns list of images
"""
... | b4c38c04f8473afe97179dd8968f59bc785b3f3e | 673,544 |
def skolemize_one(bnode: str, url: str) -> str:
"""Skolemize a blank node.
If the input value is not a Blank node, then do nothing.
Args:
* value: RDF Blank node to skolemize.
* url: Prefix URL used for skolemization.
Returns:
The skolemized blank node, or the value itself if it was... | 9d1ab0abff892f294e0b612d1f236c002fcb2d7e | 673,545 |
def search_datastore_spec(client_factory, file_name):
"""Builds the datastore search spec."""
search_spec = client_factory.create('ns0:HostDatastoreBrowserSearchSpec')
search_spec.matchPattern = [file_name]
return search_spec | aead60178b4a595bb9ca6d1213c3934b2678f185 | 673,546 |
def artist_src_schema_to_dw_schema(df):
"""
Rename the event src columns to dimensional and fact tables format.
dim_artist columns: artist_id, name, location, latitude, longitude
"""
df = df.withColumnRenamed("artist_name", "name")
df = df.withColumnRenamed("artist_location", "location")
df ... | 11e69be3a535949af85a19fa6c255669953e81b2 | 673,549 |
def get_file_lines(filename):
"""
Inputs:
filename - name of file to read
Output:
Returns a list of lines from the file named filename. Each
line will be a single line string with no newline ('\n') or
return ('\r') characters.
If the file does not exist or is not readable, th... | 7d5335838f1fd510705b86ec6716610654f43790 | 673,550 |
def get_lines(text_string, sub_string):
"""Get individual lines in a text file
Arguments:
text_string {string} -- The text string to test
sub_string {string} -- The conditional string to perform splitting on
Returns:
{list} -- A list of split strings
"""
lines = [line for line in text_string.split("\... | 69c7f05167b2a4423011a44ec5b7e40045463d4e | 673,551 |
def tag(accessing_obj, accessed_obj, *args, **kwargs):
"""
Usage:
tag(tagkey)
tag(tagkey, category)
Only true if accessing_obj has the specified tag and optional
category.
If accessing_obj has the ".obj" property (such as is the case for
a command), then accessing_obj.obj is use... | ac5db92d562e78fa98f114202dd0658cecb8823f | 673,553 |
import re
def get_filename_components(filename):
"""Decomposes a standard note filename
A standard filename has the form of
2_03_04a_5_Some_Topic_fb134b00b
Where 2_03_04a_5 define the order within
the hierachy of notes (in this case 4 levels),
Some_Topic is the base of the filename
and fb... | a98abee89eb0644781e4187ba28d9896e74a7622 | 673,555 |
def get_label_from_directory(directory):
"""
Function to set the label for each image. In our case, we'll use the file
path of a label indicator. Based on your initial data
Args:
directory: string
Returns:
int - label
Raises:
NotImplementedError if unknow... | 1e7a8c3066f813ad5f2aca1eb580de2673638fdb | 673,558 |
import math
def euclidean_distance(x0, y0, x1, y1):
"""
Regular Euclidean distance algorithm.
:param x0: x value of the first coordinate
:param y0: y value of the first coordinate
:param x1: x value of the second coordinate
:param y1: y value of the second coordinate
:return: euclidean dis... | ae5e57b855a45d3353649cc50f098839642171ef | 673,560 |
def GetExtent(ds):
""" Return list of corner coordinates from a gdal Dataset """
xmin, xpixel, _, ymax, _, ypixel = ds.GetGeoTransform()
width, height = ds.RasterXSize, ds.RasterYSize
xmax = xmin + width * xpixel
ymin = ymax + height * ypixel
return (xmin, ymax), (xmax, ymax), (xmax, ymin), (xmi... | 5dfcb2074b2fd5efb4019cf403bd026296079efc | 673,564 |
def filter_request_parameters(field_name, msg, look_in_response=False):
"""
From an event, extract the field name from the message.
Different API calls put this information in different places, so check a few places.
"""
val = msg['detail'].get(field_name, None)
try:
if not val:
... | a45f721fd4e2b344230d6b8f82403ba45a60fc60 | 673,565 |
from typing import List
import random
def randboolList(len: int) -> List[bool]:
"""Returns a list of booleans generated randomly with length `len`"""
finalList: List[bool] = []
for _ in range(len):
finalList.append(random.choice([True, False]))
return finalList | 1b3f8e3753ff3f61b5b292a91e2728ce889942e6 | 673,566 |
import mpmath
def mean(p, b, loc=0, scale=1):
"""
Mean of the generalized inverse Gaussian distribution.
The mean is:
K_{p + 1}(b)
loc + scale --------------
K_p(b)
where K_n(x) is the modified Bessel function of the second kind
(implemented ... | 0e08c1f9275520b64a591b684ae0b369fe6fa3ba | 673,569 |
from typing import Dict
def with_type(d: Dict, kind) -> Dict:
"""
Add or overwrite the key "type", associating it with kind, while not mutating original
dict.
:param d: dictionary to add "type": kind to
:param kind: the kind of object dict represents
:return: d | {"type": kind}
>>> with_t... | 46d65c863eb0891727e9aa5f9901b924c434dae6 | 673,573 |
def Dir(v):
"""Like dir(v), but only non __ names"""
return [n for n in dir(v) if not n.startswith('__')] | eca5c032a5483778d1e56164967c60bd11b9a4bd | 673,578 |
import re
def splitFastaHeader(name):
"""
Split a FASTA/FASTQ header into its id and metadata components
"""
nameParts = re.split('\s', name, maxsplit=1)
id_ = nameParts[0]
if len(nameParts) > 1:
metadata = nameParts[1].strip()
else:
metadata = None
return (id_, metadat... | 5fdb03606af766923969051c726d4b9cc42af95d | 673,581 |
def selectGenes(df, selection):
"""
Remove all rows (gene_ids) from a data frame which can not be found in
selection.
Parameters
---------
df : DataFrame
The data frame to work with.
selection : set
All ids to keep.
Return
------
df : DataFrame
The clean... | f6d81fe7f9489f2ed0a9f8d597405319ea222151 | 673,585 |
def move_to_same_host_as(source, destin):
"""
Returns source or a copy of `source` such that `source.is_cuda == `destin.is_cuda`.
"""
return source.cuda(destin.get_device()) if destin.is_cuda else source.cpu() | 7e6337be37d5e7ae54b60c86bb270e7d93c6f8f6 | 673,590 |
def subdict(d, keep=None, drop=None):
"""Compute the "subdictionary" of a dict, *d*.
A subdict is to a dict what a subset is a to set. If *A* is a
subdict of *B*, that means that all keys of *A* are present in
*B*.
Returns a new dict with any keys in *drop* removed, and any keys
in *keep* stil... | 4ff6e3d7470891eba190a5aca19f94f87724dc90 | 673,591 |
def any_heterozygous(genotypes):
"""Determine if any of the genotypes are heterozygous
Parameters
----------
genoytypes : container
Genotype for each sample of the variant being considered
Returns
-------
bool
True if at least one sample is heterozygous at the varia... | 1ed57835f84ebf8f609a6addba5b922003a5588e | 673,594 |
import operator
def get_operator_function(op_sign):
"""
Get operator function from sign
Args:
op_sign (str): operator sign
Returns:
operator function
"""
return {
'>': operator.gt,
'<': operator.lt,
'>=': operator.ge,
'<=': operator.le,
... | 6b3a3f23335d499400e12071b421a4f34b1acffc | 673,595 |
import unittest
import operator
def create_datecalctestcase(start, duration, expectation):
"""
Create a TestCase class for a specific test.
This allows having a separate TestCase for each test tuple from the
DATE_CALC_TEST_CASES list, so that a failed test won't stop other tests.
"""
class T... | 3148c057992e13a64da9ca33340cd80ea68fb12f | 673,596 |
def true_positives(truth, pred, axis=None):
""" Computes number of true positive
"""
return ((pred==1) & (truth==1)).sum(axis=axis) | 8112b2d719702e1aa0964555d9cd9327e0b295fb | 673,597 |
def merge_dicts(create_dict, iterable):
"""
Merges multiple dictionaries, which are created by the output of a function and
an iterable. The function is applied to the values of the iterable, that creates dictionaries
:param create_dict: function, that given a parameter, outputs a dictionary.
:param... | c4d8165c07b268be8ee892bb64405d5ef1480ba2 | 673,600 |
def hs2_text_constraint(v):
"""Constraint function, used to only run HS2 against uncompressed text, because file
format and the client protocol are orthogonal."""
return (v.get_value('protocol') == 'beeswax' or
v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').c... | 5fc055d6cd0f79a8f12fdfeff8d24399f3b74b9f | 673,601 |
import random
def recursive_back_tracker_maze(bm_edges, full_mesh=False):
"""trace a perfect maze through bm_edges
input:
bm_edges: list of BMEdges - needs to be pre-sorted on index
full_mesh: does bm_edges include the whole mesh
output:
maze_path: list of BMEdges
maze_vert... | 21cb3e22c9a37d94d30a3ed41de358b5e536e284 | 673,604 |
def get_trunk(py):
"""helper function that returns name of df column name for particular percentile (py) of latency"""
p_col_name = {
"P50_latency(ms)": "P50ms",
'P90_latency(ms)': "P90ms",
'P95_latency(ms)': "P95ms",
'P99_latency(ms)': "P99ms"
}
return p_col_name[py] | e9ccd17ff734441c8b1bfa963265642746eee67f | 673,605 |
def isBuildConfFake(conf):
"""
Return True if loaded buildconf is a fake module.
"""
return conf.__name__.endswith('fakeconf') | a27a2bb844cf928e75a073e8c731079aa940c281 | 673,609 |
def is_palindrome(n):
"""Checks if n is a palindrome"""
n = str(n)
return n == n[::-1] | 4f1fab3178b1e0b35a08611298e8baaa00562bb7 | 673,610 |
import torch
def load_model(filename, model):
"""Load the model parameters in {filename}."""
model_params = torch.load(str(filename))
model.load_state_dict(model_params)
return model | 14cb058d61dedc1ad4b41b0aab09a4ce56db37a1 | 673,612 |
def table(lst):
"""
Takes a list of iterables and returns them as a nicely formatted table.
All values must be convertible to a str, or else a ValueError will
be raised.
N.B. I thought Python's standard library had a module that did this
(or maybe it was Go's standard library), but I'm on an a... | b85fba6bd376810e4dfe206f7e7e053955ebec54 | 673,619 |
def push_variable_on_stack(assembler, stack_offset,
value, value_array):
"""Push a value on a specified location on stack
Args:
assembler (Assembler): the assembler to use
stack_offset (int): the offset relative to the current stack pointer
value (bytearray): ... | 5e62baf9410bd60a017929fae44f52e604a4dc1b | 673,620 |
from typing import Mapping
def signature(signages):
"""
Creates Signature HTTP header item from signages list
RFC8941 Structured Field Values for HTTP
Returns:
header (dict): {'Signature': 'value'} where value is RFC8941 compliant
(Structured Field Values for HTTP) formatted str of ... | 8934f913d79a6f49fd1dd9bd5fa08eb1d01c4ed6 | 673,621 |
def get_file_content(fpath: str, **kwargs) -> str:
"""Get content from a file given a path
Parameters
----------
fpath : str
file path
Returns
-------
str
file content
"""
with open(fpath, **kwargs) as f:
txt = f.read()
return txt | aaea3135d9f32df22d79ff4efb3decbffde06310 | 673,622 |
def multiples(s1, s2, s3):
"""Show multiples of two numbers within a given range."""
result = []
for i in range(s3):
if i % s1 == 0 and i % s2 == 0 and i:
result.append(i)
return result | cb6acc4eb372fff232190022e5a1d4b4938fc7f0 | 673,630 |
def avg(array):
"""
Makes the average of an array without Nones.
Args:
array (list): a list of floats and Nones
Returns:
float: the average of the list without the Nones.
"""
array_wo_nones = list(filter(None, array))
return (sum(array_wo_nones, 0.0) / len(array_wo_nones)) i... | dea25aa24dbe53b0d3974d16f5b3ae3bf93ffcdc | 673,633 |
def pms_to_addrportsq(poolmembers):
""" Converts PoolMembers into a list of address, port dictionaries """
return [{'address': p._node.name, 'port': p._port} for p in poolmembers] | fa24338856f383b1d8dcab3a499a6dddbb45adcb | 673,635 |
def qualify(ns, name):
"""Makes a namespace-qualified name."""
return '{%s}%s' % (ns, name) | 98cc677f4e149d2f515f844fa69e4164442241b1 | 673,640 |
import difflib
def simple_merge(txt1, txt2):
"""Merges two texts"""
differ = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
diff = differ.compare(txt1.splitlines(1), txt2.splitlines(1))
content = "".join([l[2:] for l in diff])
return content | db353b9fd73a130b8fa6014968546345f66c2aec | 673,641 |
def encoding_fmt(request):
"""
Fixture for all possible string formats of a UTF encoding.
"""
return request.param | 53bc76ee4e5f4188cb5f6bce669d6ea3387a6bca | 673,642 |
import math
def sph2cart(theta, phi, r=1):
"""Converts spherical coords to cartesian"""
x = r * math.sin(theta) * math.cos(phi)
y = r * math.sin(theta) * math.sin(phi)
z = r * math.cos(theta)
vect = [x, y, z]
return vect | cf793f0a81baefa80c96863d1b765fdd8d30b637 | 673,643 |
import base64
def convert_img_to_b64_string(img_path):
""" Converts medical image to b64 string
This function takes the image filepath as an input and outputs it as a b64
string. This string can be sent to the server and then the database.
Args:
img_path (str): the name of the file path contai... | b9d1e2077ae2e7f9c8e027a56c25e79d0262cb27 | 673,644 |
import random
import math
def randomLogGamma(beta,seed=None):
"""
Generate Log-Gamma variates
p(x|beta) = exp(beta*x - x)/gamma(beta)
RNG derived from G. Marsaglia and W. Tsang. A simple method for generating gamma variables. ACM Transactions on Mathematical Software, 26(3):363-372, 2000.
See http... | 3a1afeb59fbb2f6ad969e16de3ca1c58faa747c5 | 673,645 |
def _fmt_cmd_for_err(cmd):
"""
Join a git cmd, quoting individual segments first so that it's
relatively easy to see if there were whitespace issues or not.
"""
return ' '.join(['"%s"' % seg for seg in cmd]) | 4b201ec9ba9f1f27df18913f1104bee4f98dcc49 | 673,647 |
def get_slices_by_indices(str, indices):
"""Given a string and a list of indices, this function returns
a list of the substrings defined by those indices. For example,
given the arguments::
str='antidisestablishmentarianism', indices=[4, 7, 16, 20, 25]
this function returns the list::
['... | e69bd33abfd3f9f423ed33c3b46841ad0ed1a30e | 673,648 |
def _read_pid_file(filename):
"""
Reads a pid file and returns the contents. PID files have 1 or 2 lines;
- first line is always the pid
- optional second line is the port the server is listening on.
:param filename: Path of PID to read
:return: (pid, port): with the PID in the file and the p... | afccae64451ab50c0bb1e179095e4cac23730526 | 673,651 |
def col_variables(datatype):
"""This function provides a key for column names of the two
most widely used battery data collection instruments, Arbin and
MACCOR"""
assert datatype == 'ARBIN' or datatype == 'MACCOR'
if datatype == 'ARBIN':
cycle_ind_col = 'Cycle_Index'
data_point_col =... | 004d851de05c2d0e07ced93a454b6c0377407f31 | 673,652 |
def uri_to_id(uri):
""" Utility function to convert entity URIs into numeric identifiers.
"""
_, _, identity = uri.rpartition("/")
return int(identity) | 1578a3a6716e20cede81aeebf04a8da6455413d1 | 673,657 |
def centimeter2feet(dist):
""" Function that converts cm to ft. """
return dist / 30.48 | f943b322760696d42d45e20da3565cb6e7c20ddb | 673,659 |
import struct
def char(c):
"""
Input: requires a size 1 string
Output: 1 byte of the ascii encoded char
"""
return struct.pack('=c', c.encode('ascii')) | 355303fdd2bbfbb77ec59e8adb14c6f01841fc90 | 673,661 |
import torch
def covariance_z_mean(z_mean):
"""Computes the covariance of z_mean.
Borrowed from https://github.com/google-research/disentanglement_lib/
Uses cov(z_mean) = E[z_mean*z_mean^T] - E[z_mean]E[z_mean]^T.
Args:
z_mean: Encoder mean, tensor of size [batch_size, num_latent].
Returns:
... | f9b82a6bb3c08c3ca59381c3f877cfbf0542aeb1 | 673,663 |
import socket
def inet_to_str(inet):
"""Convert inet object to a string
:param inet: inet network address
:type inet: inet struct
:return: str of printable/readable IP address
"""
try:
return socket.inet_ntop(socket.AF_INET, inet)
except ValueError:
return socket.inet_nto... | 313864b214fda7cccf2781fc049381ea998a93b2 | 673,664 |
import torch
def get_idxs(results, test_targets, device):
"""
Args:
results (tensor): predictions
test_targets (tensor): Ground truth labels
Returns:
miss_index: index of misclassifier images
hit_index: index of correctly classifier images
"""
miss_index = torch.where((results.argmax... | 9c194b7b97c19ab5ff05412de7079bd16f5c2eb3 | 673,665 |
def trailing_zeros(value: int) -> int:
"""Returns the number of trailing zeros in the binary representation of
the given integer.
"""
num_zeros = 0
while value & 1 == 0:
num_zeros += 1
value >>= 1
return num_zeros | bcb760be12e1b918647a017c04d5b46d87035510 | 673,673 |
def getAverageVectorForWords( word_list, model, np ):
"""Calculates average vector for the set of word.
Parameters
----------
word_list : array
Array of words in format [word1, word2, ...].
model : object
Word2Vec model.
np : object
numpy library.
Return... | 5ee60efff539ec1b46728a7c16d1f5b4cf00db1b | 673,675 |
def is_ethiopia_dataset(name):
"""Names with 'TR' at start or Ethiopia"""
return name.upper().startswith('TR') or \
name.lower().find('ethiopia') > -1 | 81f9981a4389f9c9fe7a19f23f8a66541116b04d | 673,676 |
from pathlib import Path
def exhaustive_directory_search(root, filename):
"""Executes an exhaustive, recursive directory search of all downstream
directories, finding directories which contain a file matching the provided
file name query string.
Parameters
----------
root : os.PathLike
... | cf6ded7ccce0af81190c1337dd511c44d45c3557 | 673,680 |
def dot(v1,v2):
"""Dot product of two vectors"""
n = len(v1)
prod = 0
if n == len(v2):
for i in range(n):
prod += v1[i]*v2[i]
return prod | 569ad317cf8d875a0c0592a576c3987b02b54f95 | 673,683 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.