content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_vf_res_scale_down(width: int, height: int, res_limit='FHD', vf: str = '') -> str:
"""generate 'scale=<w>:<h>' value for ffmpeg `vf` option, to scale down the given resolution
return empty str if the given resolution is enough low thus scaling is not needed"""
d = {'FHD': (1920, 1080), 'HD': (1280, 7... | 7b2e4095aedba22dc9f0b8484c52aad0cf61eb82 | 586,219 |
def get_line_nr(view, point):
"""Return 1-based line number for `point`.
"""
return view.rowcol(point)[0] + 1 | d853be89861c0f05a332dcdc0676a46f5472d8a2 | 586,227 |
def prepare_csv(element, delimiter=';'):
"""
Receives a tuple ('CE',2015,11, 0.4, 21.0)
Return a limited string "CE;2015;11;0.4;21.0"
"""
return f"{delimiter}".join(element) | 3d81055a8597a342c358a973827f822987e4be1b | 586,234 |
def checksave(save_all, pix_list, save_ratio, save_count_annotated, save_count_blank):
"""
Checks whether or not an image chip should be saved
:param save_all: (bool) saves all chips if true
:param pix_list: list of pixel values in image mask
:param save_ratio: ratio of annotated chips to unannotate... | 766144b91ec7c8e9cc7126127f07a5f9cd942640 | 586,239 |
import pytz
def build_tzinfo(tzname, tzsign='+', tzhour=0, tzmin=0):
"""
create a tzinfo instance according to given parameters.
tzname:
'Z' ... return pytz.UTC
'' | None ... return None
other ... return pytz.FixedOffset
"""
if tzname is None or tzname == '':
r... | 4959e26d4933879e31ae55da7fd1f174b8039f5b | 586,240 |
def modinv(a, b):
"""Returns the modular inverse of a mod b.
Pre: a < b and gcd(a, b) = 1
Adapted from https://en.wikibooks.org/wiki/Algorithm_Implementation/
Mathematics/Extended_Euclidean_algorithm#Python
"""
saved = b
x, y, u, v = 0, 1, 1, 0
while a:
q, r = b // a, b % a
... | dc68357521b8c8f4947f863ef1f930b9b0cdb262 | 586,243 |
import pickle
def unpickle_data(filename):
""" load the metrics from a file """
with open(filename, 'rb') as handle:
obj = pickle.load(handle)
return obj | 70da711fd07a6b393d1f75d137dbbba04b4c512c | 586,244 |
def _get_bin(value, bins):
"""Returns the smallest index i of bins so that
bin[i][0] <= value < bin[i][1], where
bins is a list of tuples, like [(0,20), (20, 40), (40, 60)]
"""
for i in range(0, len(bins)):
if bins[i][0] <= value < bins[i][1]:
return i
return -1 | 83890a87e5a6fb1d44c7db67beaf03f7ac780ccf | 586,247 |
def compute_multipliers(tokens):
"""
Determine the multiplier based on the tokens at the end of
a number (e.g. million from "one thousand five hundred million")
"""
total = 1
for token in tokens:
value, label = token
total *= value
return total | 20205cd104bab6b49d68512133eafec042ed4d87 | 586,249 |
def format_interconnector_loss_coefficients(INTERCONNECTORCONSTRAINT):
"""Re-formats the AEMO MSS table INTERCONNECTORCONSTRAINT to be compatible with the Spot market class.
Examples
--------
>>> INTERCONNECTORCONSTRAINT = pd.DataFrame({
... 'INTERCONNECTORID': ['X', 'Y', 'Z'],
... 'LOSSCONSTA... | 54f3eb300b7920422c69fa7569c262226d05ad7d | 586,251 |
from urllib.parse import urljoin
def safe_join(base, *paths):
"""
A version of django.utils._os.safe_join for S3 paths.
Joins one or more path components to the base path component
intelligently. Returns a normalized version of the final path.
The final path must be located inside of the base pa... | 428f94ca2895c40d88d5b3ac4e2d83115148dc7c | 586,257 |
def get_multiplexer(num):
"""
Get max decimal multiplexer.
"""
m = 1
while num % 10 == 0:
num = num / 10
m *= 10
return m | 7164209c83a80ebf39931fb7bcbef3ee5163d416 | 586,258 |
def max_acc(zmax,T,f0):
"""
To obtain the maximum acceleration 'detectable' by PRESTO.
zmax - (expected) maximum number of Fourier bins that the pulsar frequency
f0 drifts
T - observation duration (s)
f0 - pulsar's frequency (Hz)
"""
c = 299792458 #speed of light in m/s
return zmax... | 4a999156a3aa90c9d74c878ba9f55c34bfb38b7d | 586,260 |
def calculate_precision_recall(tp_totals, fp_totals, fn_totals):
"""
Calculate list of precision and recall values from lists of true pos.,
false pos., false neg. values.
"""
precision = [tp / (tp+fp) if (tp+fp)>0 else 0 for (tp, fp) in zip(tp_totals, fp_totals)]
recall = [tp / (tp+fn) if (tp+f... | 23b8ab79fb32c11e5f432e89496dd7d63f5edd3f | 586,262 |
import cmath
def explt(l, t): # pragma: no cover
"""Complex exponenital as used in solution to schrodinger equation.
"""
return cmath.exp((-1.0j * t) * l) | 64f70afc1954aee7a2bd0b233c025ab834ba065b | 586,268 |
import math
def liters_to_bars(liters, bottle_size, round=False):
"""returns the bars corresponding to a given volume in a given bottle_size in liters"""
if round:
return math.ceil(liters / bottle_size)
else:
return liters / bottle_size | feaec7a7249d0bcacb0a96cda1078e60ef2e2456 | 586,269 |
def contains(a1,a2,b1,b2):
"""
Check whether one range contains another
"""
return ((a1 >= b1) & (a2 <= b2)) | 6d24151cca362bdda3698f0813ed785d311fc040 | 586,270 |
def index(lst, trunc):
"""
Converts an n-ary index to a 1-dimensional index.
"""
return sum([lst[i] * trunc**(len(lst)-i-1) for i in range(len(lst))]) | 0df82084ff01c703e780e4a43924965ed398da3e | 586,271 |
def _get_column_index(i, inputs):
"""
Taken from https://github.com/onnx/sklearn-onnx/blob/9939c089a467676f4ffe9f3cb91098c4841f89d8/skl2onnx/common/utils.py#L50.
Returns a tuples (variable index, column index in that variable).
The function has two different behaviours, one when *i* (column index)
i... | 9a46a6314777ef1538a7056f998110d615abcd8c | 586,279 |
import collections
def from_cards(cards, sideboard=()):
"""
Create a deck from an iterable of cards with an optional sideboard.
* cards : an iterable of cards
* sideboard : an optional iterable of cards for the deck's sideboard
"""
return {
u"cards" : collections.Counter(card.name f... | 78f4ef730d4f47fe64d20377f810e5c15ad65ecb | 586,285 |
def getSessionTypes(assoc_type):
"""Return the allowed session types for a given association type"""
assoc_to_session = {
'HMAC-SHA1': ['DH-SHA1', 'no-encryption'],
'HMAC-SHA256': ['DH-SHA256', 'no-encryption'],
}
return assoc_to_session.get(assoc_type, []) | 740fc6ec10aa1127a7bd8366a045974bcba08671 | 586,290 |
from typing import Dict
from typing import Any
from pathlib import Path
import json
def read_json_data_from_file(data_path: str, encoding: str = 'utf-8'):
"""Reads the contents of a json file into a dict object.
Args:
data_path (str): Path to the file.
encoding (str): Inspected encoding of th... | 15656ba303f902383976cf78a6f8a82b51676f08 | 586,296 |
def _read_name_charge(data):
""" Build the species dictionary relating ChemKin name to charge.
If the charge is missing for a given species, the dictionary
element will be set to zero, assuming a neutral species.
:param data: information from input species.csv file
:type data: panda... | 791e7805f53791ee0e28f1bfaf01467b7abcf6f4 | 586,298 |
import torch
def normalize_embeddings(embeddings: torch.Tensor, epsilon: float = 1e-6) -> torch.Tensor:
"""
Normalize N D-dimensional embedding vectors arranged in a tensor [N, D]
Args:
embeddings (tensor [N, D]): N D-dimensional embedding vectors
epsilon (float): minimum value for a vect... | 3ba85b09e5cd6eae9921ed0be79a9fcc7af8f741 | 586,299 |
def get_attrib_url(attrib):
"""
Create a string suitable for a URL from the dict attrib
"""
tag_string = '='.join([attrib['name'], attrib['value']])
return tag_string | e0c55f6d0e102467855da65df17f2e6401f5be5f | 586,302 |
def vLength(v):
""" Return Vector length """
return (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) ** 0.5 | 22b4243cb38fa15cf33e531c572ab0d7feb87f59 | 586,305 |
def populate_metadata(case, config):
""" Provide some top level information for the summary """
return {"Type": "Summary",
"Title": "Performance",
"Headers": ["Proc. Counts", "Mean Time Diff (% of benchmark)"]} | b20e08f764f79e3cf2fb76fdf5980577431bfefe | 586,306 |
def merge_endpoints(defaults, additions):
"""
Given an existing set of endpoint data, this will deep-update it with
any similarly structured data in the additions.
:param defaults: The existing endpoints data
:type defaults: dict
:param defaults: The additional endpoints data
:type default... | 327853930237c79e9c24ed5768c1ecb6033a6122 | 586,307 |
def get_sep_type(input_lines):
"""
Return the Content-Type of the input. "text/plain" is the default.
Return ``None`` if the input is not a SEP.
"""
sep_type = None
for line in input_lines:
line = line.rstrip().lower()
if not line:
# End of the RFC 2822 header (first... | a1623d08a1dd767c7d81c8c19128eed2ddcd01e5 | 586,316 |
def bow(lst_mots):
"""
Transforme une liste de mots en dictionnaire bag of words qui associe chaque
mot à son nombre d'occurence dans le texte.
Entrée : une liste de mots (et de liens)
Sortie : le dictionnaire bag of words
"""
d = { s : lst_mots.count(s) for s in set(lst_mots) }
return d | 966d745fcb876a2a687a1bf2d98de73ebf6b4248 | 586,326 |
def scrub(content):
"""Replaces triple back ticks with triple grave accents."""
return content.replace(
"\N{GRAVE ACCENT}" * 3, "\N{MODIFIER LETTER GRAVE ACCENT}" * 3
) | d58fb1df2c8618ea534ece7147bab3eb089c0e0c | 586,327 |
from typing import OrderedDict
def dict_isect(*args):
"""
Dictionary set extension for :func:`set.intersection`
Constructs a dictionary that contains keys common between all inputs.
The returned values will only belong to the first dictionary.
Args:
*args (List[Dict[KT, VT] | Iterable[KT... | 16105161c0178e45da7f3179bc6bd988343c7b00 | 586,328 |
def get_rules(rest_client):
"""
api call to get all rules for the resilient organization
:param rest_client:
:return: json formatted rule list
"""
url = "/actions"
return rest_client.get(url) | 4a01123c8c0d80ef9e237649c0e3d4b08839dbd7 | 586,329 |
def extract_data(env):
"""Extracts the data from the envment of a POST request."""
try:
length = int(env.get('CONTENT_LENGTH', '0'))
except ValueError:
length = 0
if length != 0:
return env['wsgi.input'].read(length)
return "" | d26ee953bd74792a83305edb26d9bd3ae862309b | 586,331 |
import re
def parse_show_ip_bgp(raw_result):
"""
Parse the 'show ip bgp' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show ip bgp command in a \
list of dictionaries of the form:
::
[
{
... | 69cb90bedbcf60d218f8fcf6ab76b7b8435e9f1e | 586,337 |
def engine_version(connection):
"""
Return string representation of oVirt engine version.
"""
engine_api = connection.system_service().get()
engine_version = engine_api.product_info.version
return '%s.%s' % (engine_version.major, engine_version.minor) | ac038ee0d812cde0d4d50e34510e0c8004562ecf | 586,340 |
def list_get(list_obj, index, default=None):
"""Like ``.get`` for list object.
Args:
list_obj (list): list to look up an index in
index (int): index position to look up
default (Optional[object]): default return value. Defaults to None.
Returns:
object: any object found at ... | efc243845057d59e237fef588222926cc439092d | 586,342 |
def moving_averages(df, start_step, window_size=None):
"""Compute averages of every feature over moving time windows.
Args:
df (Dataframe): Input features as a dataframe
start_step (Integer): Starting time step of rolling mean
window_size (Integer): Windows size of rolling mean
Ret... | d64172e591e9469703ffc89312c761fbf4efa8db | 586,343 |
def _plot_overlay_pointcloud(fig, pointcloud, name: str, marker_color: str, **kwargs):
"""Overlay the plot with another pointcloud.
Args:
fig (plotly.graph_objects.Figure): The original plot.
pointcloud (PointCloud): The PointCloud to overlay.
name (str): Name of the pointcloud to overl... | e21c9f64794263e8428031cc4bfbd5134ff3e448 | 586,348 |
def __check_md(res, cond, msg):
"""
Helper function used to validate metadata.
If cond is false, return False, and display message
"""
if not cond:
print("Metadata validation failed: '{}'".format(msg))
return False
return res | 305f8542c7a80d25d8634969a8c3c7179446fb66 | 586,350 |
def need_blank(opt, lines):
"""Helper function to get blank line flag.
Returns True if:
* ``opt`` is ``True``
* ``opt`` is ``None`` and ``lines`` has more than one line.
Args:
opt: Option.
lines: Block lines.
Returns:
Boolean value.
"""
return opt is True or (... | c818547feff2b4c25869ac9f392e869c3283d799 | 586,353 |
import typing
import re
def dedupilicate(value: str, existing_values: typing.Iterable[str]):
"""
If <value> is present in <existing_value>, returns '<value>(1)'. If '<value>(1)' is present in <existing_values>,
returns '<value>(2)' and so on. A typical use would run <value> through this function and then ... | 4cd792e334ee3b1519a70ca83f774078ec921e4b | 586,355 |
def secure_compare(actual, expected):
"""
Returns True if the two strings are equal, False otherwise
The time taken is dependent on the number of characters provided
instead of the number of characters that match.
When we upgrade to Python 2.7.7 or newer, we should use hmac.compare_digest
instea... | aa7a66368f29fb4b9f81033957d75a08ee453a28 | 586,360 |
import base64
def b_to_b64s(b: bytes) -> str:
"""convert bytes to base 64 string
:param b: input bytes
:type b: bytes
:return: output base 64 string
:rtype: str
"""
b64s = base64.b64encode(b).decode('utf8')
return b64s | d86603405b3a92b82cadf02db8c548b2ccc8c0b4 | 586,363 |
def generate_one_or_none(generator, enforce=True):
"""
Return first item from a generator.
Optionally check that nothing else was generated.
Return None if nothing was generated.
"""
result = None
for item in generator:
result = item
break
if enforce:
for item i... | 6888082b16895c55feeaccf71c747d76264bfa89 | 586,367 |
def pytest_funcarg__confoverrides(request):
"""
Confoverrides for the current test as dict, extracted from the keyword
arguments to the ``confoverrides`` marker.
"""
confoverrides_marker = request.keywords.get('confoverrides')
if confoverrides_marker:
return confoverrides_marker.kwargs
... | b8020108297b8c6049a46d2b13a4fc7899a99fa0 | 586,373 |
def predicateFormat(predType, *values):
"""
.. versionadded:: 0.3.0
Converts inputs into predicates, creating examples and facts in predicate-
logic format.
:param predType: The action which relates one or more values.
:type predType: str.
:param \*values: Values which are related to one a... | ad86b4309f13b3640c2612d61d355bc696acee81 | 586,378 |
def readFile(fullPathToFile):
"""A generic function to read the content of a file.
Args:
fullPathToFile: The full filename for the file
Return:
The content
"""
fileHandler = open(fullPathToFile, "r")
content = fileHandler.read()
fileHandler.close()
return content | 28de1f839156200d368e9f19b915fdda548cebf8 | 586,382 |
import hashlib
from pathlib import Path
def get_md5(path: Path):
"""
Get the MD5 value of a path.
"""
with path.open("rb") as fin:
data = fin.read()
return hashlib.md5(data).hexdigest() | de03387b08aea17593f33cefe67fbe8723710254 | 586,384 |
def convert2MSAcenter(xin, yin, xtin, ytin, arcsec):
"""
This function is a python translation of Tonys IDL equivalent function. It converts the
measured coordinates of each star into the frame relative to the center of the MSA.
Args:
xin: numpy array of the measured V2s
yin: numpy array... | 96e0bbcbab09a1c6c87043ca9c2f60ece62c66bd | 586,385 |
def name_from_scope_name(name):
"""Returns the name of an op given the name of its scope.
Args:
name: the name of the scope.
Returns:
the name of the op (equal to scope name minus any trailing slash).
"""
return name[:-1] if (name and name[-1] == "/") else name | 7cfbbcaf7c2e3cfe68b39c6e2d379d55e017d330 | 586,392 |
def align(text, size, char=" "):
"""
Format text to fit into a predefined amount of space
Positive size aligns text to the left
Negative size aligns text to the right
"""
text = str(text).strip()
text_len = len(text)
if text_len > abs(size):
text = f"{text[:size-3]}..."
offset = "".join(char * (abs(size)... | 1a45b0ee0fe2e16aaec67d765622c1e22d7a442a | 586,393 |
def generate_manifest_table_name(
database_name, base_table_name, import_source, export_source
):
"""Returns the qualified manifest table name.
Arguments:
database_name (string): The name of the database
base_table_name (string): The base name of the table
import_source (string): "s... | 2fee20d3d82fe6d3547087971a6066432b6ec18a | 586,394 |
import requests
def get_file(url):
"""
Download file without saving from url and return the bytes
"""
return requests.get(url) | b772e6d88392bd257e0139309947a2dc75bddd51 | 586,395 |
def nipsa_filter(userid=None):
"""Return an Elasticsearch filter for filtering out NIPSA'd annotations.
The returned filter is suitable for inserting into an Es query dict.
For example:
query = {
"query": {
"filtered": {
"filter": nipsa_filter(),
... | c9b16d30ea6fb5f442ea7a5a08fe4aea1f49279f | 586,398 |
def nestList(f,x,n):
"""
return [x,f(x),f(f(x)),...,f(f(...f(x)))]
[nest(f,x,0) to nest(f,x,n)]
"""
result = [x]
for i in range(n):
x = f(x)
result.append(x)
return result | 644ed58812d88c0aff7710d7ed7fe0b990652269 | 586,399 |
def combine_name(name1, name2):
""" Function used to combine team and project name """
return f'{name1} ({name2})' | 608d747ef1eb36b2f6df86f15cf2f57b7134d451 | 586,407 |
def swap_upstairs_list(id1, id2, li):
"""Swap list element id1 with the next until reaches id2 (id1 < id2)."""
for i in range(id2 - 1, id1 - 1, -1):
li[i], li[i+1] = li[i+1], li[i]
return li | f0bdf3daa8423547502bcadae6d80a90a68ecc31 | 586,408 |
def _traverse(graph, node, visited=[]):
"""Returns list of all direct/indirect adjacent nodes for a given node"""
nodes = []
if node in visited:
return nodes
visited.append(node)
nodes.append(node)
for adjacent in graph[node]:
nodes.extend(_traverse(graph, adjacent))
return n... | 9c10a58c96e69627fe2a6e4bfcb1fb3c9e750781 | 586,410 |
import requests
def query_graph(url: str, query: str) -> dict:
"""Helper methods for querying graphql api. [Source: https://thegraph.com/en/]
Parameters
----------
url: str
Endpoint url
query: str
Graphql query
Returns
-------
dict:
Dictionary with response da... | 9dea44e4269e4de875f3e8796578f2b33e07a622 | 586,412 |
def bytes_adapter(obj, request):
"""Convert bytes objects to strings for json error renderer."""
if isinstance(obj, bytes):
return obj.decode('utf8')
return obj | 32d69eb1c7d2b9772960ed93f9b9866cc79d18a7 | 586,414 |
def split_component_view(arg):
"""
Split the input to data or subset.__getitem__ into its pieces.
Parameters
----------
arg
The input passed to ``data`` or ``subset.__getitem__``. Assumed to be
either a scalar or tuple
Returns
-------
selection
The Component sel... | de50b4c079f1a6223bc1ec48a1ceea922fe352a6 | 586,419 |
def decompressish(s):
"""
returns tuple (X, S) where X is the size of the decompressed parts,
and S is the remaining string to decompress
"""
count = 0
while s[0] != '(':
count += 1
s = s[1:]
if len(s) == 0:
return (count, "")
s = s[1:... | fe5c30862d4a741e3907d0da51fcf052085bb061 | 586,426 |
def merge(L1, L2):
"""Merge to sorted lists into a sorted list"""
i = 0
j = 0
res = []
while i<len(L1) and j<len(L2):
if L1[i] < L2[j]:
res.append(L1[i])
i += 1
else:
res.append(L2[j])
j += 1
if i >= len(L1):
res.extend(L2[j... | 2350ab189bfed9ecaeadf051905082d8270ad21f | 586,428 |
def handy_ruler(pkg_name):
"""Create a handy ruler.
Parameters:
----------
pkg_name : {str}
Name of program
Returns
-------
list
Returns single element list with 'handy ruler'.
"""
ruler_intend = len(pkg_name) * ' '
ruler_start = '|-----handy-ruler' # 17 chars
... | 7544e0480564ca41c4f09ce53b73f8fc0a9936ee | 586,432 |
def prettyprinter(d, indent=0):
"""Makes a string with nice formatting out of a dictionary"""
s = '\n'
for key, value in d.items():
s+='\t' * indent + str(key) + ':' + '\t' + str(value) + '\n'
return s | 6476534029050395437fac8e2dc8a9335bc762a8 | 586,434 |
def get_diff(instrs):
"""Returns a list of triplets of the form (ea, orig, new)."""
diff = []
for ins in instrs:
for i, (orig, new) in enumerate(zip(ins.bytes, ins.cbytes)):
if orig != chr(new):
diff.append((ins.addr + i, orig, chr(new)))
return diff | 32968d25e521e73ed29f4700b91940d4ac1b6744 | 586,441 |
import struct
def _decode_plen(reader):
"""
Reads and decodes event's payload length.
Parameters
----------
reader : apptrace.Reader
Trace reader object.
Returns
-------
int
decoded value.
"""
plen = 0
b0, = struct.unpack('<B', reader.read(1))
if b0 & ... | 84c4f84d0f17832f073521c9c885d4494a014ceb | 586,442 |
from warnings import warn
def reshape_data(data, shape):
"""
Reshape data or return 1D data after warning.
"""
try:
return data.reshape(shape)
except ValueError:
warn(str(data.shape) + "cannot be shaped into" + str(shape))
return data | 791c059ba147147c9431cb23f5f5a11779730016 | 586,443 |
import torch
def rotmat(a,b):
"""
Adapted from http://www.netlib.org/templates/matlab/rotmat.m
Compute the Givens rotation matrix parameters for a and b.
"""
c = torch.zeros_like(a)
s = torch.zeros_like(a)
temp = torch.zeros_like(a)
mask = (b.abs()>a.abs())
temp[mask] = a[mask] / b[mask]
s[mask] = 1.0 / t... | 9170c832ccf4e0203b22938e39a4eca67c3f3a4f | 586,445 |
def calculate_performance(tps, fps, fns, tns):
"""
Calculate the performance/evaluation metrics given the confusion matrix (TP, FP, FN, TN)
The evaluation metrics are:
Recall/Sensitivity, Precision, Specificity, F1-score, F0.5-score, F1-recall-specificity, F0.5-recall-specificity.
"""
recall, pr... | e042ab5d56ab3c6254fbdad14904d82f12205bfb | 586,448 |
def neighboursList(data):
"""
Return the same dataframe containing the list of neighbors for each junction.
Parameters:
-----------
data: pandas dataframe
data must contain at least one column named neighbors.
Returns:
--------
data: pandas dataframe
The input data b... | 295a89b8bec971a28507326900f2ac339c6c8699 | 586,449 |
import math
def exponential_easein(pos):
"""
Easing function for animations: Exponential Ease In
"""
if pos == 0:
return pos
return math.pow(2, 10 * (pos - 1)) | 036338b65971393263a9469f5e442f5a0191d958 | 586,450 |
import hashlib
def hash_file(fn):
""" Compute a SHA-256 hash for the file fn and return a hexdigest of the hash """
sha = hashlib.sha256()
with open(fn, "rb") as f:
while True:
data = f.read(65536)
if not data:
break
sha.update(data)
return... | cb13b0d581facd44c4fd1bed5518643b2488d922 | 586,451 |
def get_synopsis_from_soup(soup):
"""Get the synopsis from a book page.
Parameters
----------
soup : BeautifulSoup
BeautifulSoup object created from a book page.
Returns
-------
str
Book synopsis.
None
Synopsis not found.
"""
try:
return soup.fin... | e3b7e36c1483c2a4774298d023424c6c3ae2c21b | 586,454 |
def trunc(x):
"""Implementation of `trunc`."""
return x.__trunc__() | 806fd517f587375d4958f53bb8b9c4ca8c7b1117 | 586,456 |
def format_instances(instances, features):
"""
Convert a list of instances into a header list and datarows list.
`header` is just `features` e.g. ['username', 'email']
`datarows` is a list of lists, each sublist representing a row in a table
e.g. [['username1', 'email1@email.com'], ['username2'... | 90a53722f72ffa5fd747e8cc8130a9c0b154e63a | 586,458 |
def find_range_ix_in_point_list(start, end, point_list):
"""Returns the index range all points inside the given range.
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
point_list : sortedcontainers.SortedList
A ... | 2d043db246166e7584a1f085847aaaf458b4d2e2 | 586,461 |
def nice_bytes(number, lang='', speech=True, binary=True, gnu=False):
"""
turns a number of bytes into a string using appropriate units
prefixes - https://en.wikipedia.org/wiki/Binary_prefix
spoken binary units - https://en.wikipedia.org/wiki/Kibibyte
implementation - http://stackoverflow.com/a/1094... | 89680dabf2e71c15769e2d1c33b54f6a10cdec67 | 586,462 |
def _get_go2nt(goids, go2nt_all):
"""Get user go2nt using main GO IDs, not alt IDs."""
go_nt_list = []
goids_seen = set()
for goid_usr in goids:
ntgo = go2nt_all[goid_usr]
goid_main = ntgo.id
if goid_main not in goids_seen:
goids_seen.add(goid_main)
go_nt_... | bea4c6a825b5720340fe8043dbe1d842399ba632 | 586,463 |
import csv
def read_csv_to_dictionary(csvfile, delimiter=';'):
"""Reads a csv file and returns a dictionary with the respective keys
specified in the first row of the csv file.
Parameters
----------
csvfile : str
The path to csv file.
delimiter : str, optional
The character us... | 5d66f74959f054dc0a83a077e550d0f354bb3ac2 | 586,465 |
def hidden_field(key, value):
"""
Generates a hidden field from the given key and value
"""
return f'<input type="hidden" name="{key}" value="{value}">' | b254c02c0ee780f9e872a67c9c7a4fa912328672 | 586,476 |
def IsValid(G,degree):
"""
Method checks if a graph is valid, i.e. the real
degree of the vertices matches the character
in the lgi-string.
G -- Graph.
degree -- Expected degree
Return:
True if all degrees match the character in the string.
"""
for idx in range(G.number_of_n... | 2fd0e43d17b512340444838b32a86b435db0f977 | 586,478 |
def mm2cin(arg):
"""
Convert millimeters to 1/100 in.
Arguments:
arg: Number or sequence of numbers.
Returns:
Converted number or sequence.
"""
if not type(arg) in [list, tuple]:
return float(arg) * 100.0 / 25.4
return [float(j) * 100.0 / 25.4 for j in arg] | 0e0b9b084fbdf0b51418bda029e8ce37d9237fa9 | 586,480 |
import logging
def time_difference(h1:int, m1:int, s1:int, h2:int, m2:int, s2:int=0) -> int:
"""
Description:
function get difference between 2 times times
Arguments:
h1 {int} : integer which contains the value of the current hour
m1 {int} : integer which contains the value of ... | 041c15f9a7b266a60c3bc3291d0ddb3f1398a0bf | 586,482 |
def _augment_segmentation_maps(self, segmentation_maps, random_state, parents, hooks):
"""
Augment multiple segmentation maps.
This is the internal variation of `augment_segmentation_maps()`.
It is called from `augment_segmentation_maps()` and should usually not
be called directly.
It has to be... | 9e9ee13a676403e12d96a7003f035daa3de1952f | 586,483 |
from typing import OrderedDict
def expand_src_param(values, shp_params):
"""
Expand hazardlib source attribute (defined through list of values)
into dictionary of shapefile parameters.
"""
if values is None:
return dict([(key, None) for key, _ in shp_params])
else:
num_values =... | 3540045ac386dac842781d715f1ad693a9285940 | 586,486 |
def _conv_type(s, func):
"""Generic converter, to change strings to other types.
Args:
s (str): String that represents another type.
func (function): Function to convert s, should take a singe parameter
eg: int(), float()
Returns:
The type of func, otherwise str
""... | e72cab10a0256cb57cddfad7da7f5f1239476852 | 586,488 |
def imageAddReversed(imgs: list):
"""Make a loop by adding a reverst set of images to the back of the input list."""
temp = imgs.copy()
temp.reverse()
imgs_reversed = imgs.copy()
imgs_reversed.extend(temp)
return imgs_reversed | 1e12cb3ff05614f0418b8f6408da685b8159166e | 586,493 |
def handle_discover_response(msg): # pylint: disable=useless-return
"""Process an internal discover response message."""
msg.gateway.is_sensor(msg.node_id)
return None | a127b1df8e8977960a58fec6b09c589297c0d874 | 586,495 |
import re
def middle_name_initials(middle_name):
"""
Given a middle name value parse it to middle initials
Example inputs: S, S., Smith, Smith Doe, Smith-Doe, S-D, S D, SD, S.D., S. D.
Example outputs: S, S, S, SD, S-D, S-D, SD, SD, SD, SD
"""
initials = ""
# Keep onl... | 44a9ec735e298bc13784da96ce56c816853fbd67 | 586,504 |
import json
import base64
def decode_transaction_base64(value):
"""Decode a transaction from Base64."""
return json.loads(base64.b64decode(value.encode('utf8')).decode('utf8')) | 46e283dd94f354ef4a01d5742c168048cc607416 | 586,505 |
import uuid
import base64
def decode(slug):
"""
Returns the uuid.UUID object represented by the given v4 or "nice" slug
"""
return uuid.UUID(bytes=base64.urlsafe_b64decode(slug + '==')) | f3e7e943f804722a457ee8ef5102340aa3328d23 | 586,510 |
def five(ls):
"""
returns first five of list
"""
return ls[:5] | 07215d55495096be76a0af8708dc6247b4ec49f5 | 586,511 |
import torch
def radial_gaussian(distances, r0s, alpha=1.):
"""
Evaluates Gaussians on the radial values of the distances.
"""
gauss_arg = distances.unsqueeze(-1) - torch.unsqueeze(r0s, dim=-2)
basis_fxn = torch.exp(-alpha * gauss_arg**2)
return basis_fxn | efcd4960862ec9eb5df9020ad88dbac84d4b7649 | 586,512 |
import inspect
def view_namespace(view, cls_name=None):
"""
Create the namespace from the view
:param view: object (class or instance method)
:param cls_name: str - To pass the class name associated to the view
in the case of decorators that may not give the real class name
:return: st... | 46239aebe05befd5169cbc386d0cd4922f84c3c1 | 586,520 |
def get_choice_from_cli(options,
repeat_until_correct=True,
return_key=False,
title="Select one option from the list:",
prompt="Selection > ",
redo_text="Not a valid selection, try again."):
""" l... | d37d99f021028cce943eb3f60b3552eecac4e056 | 586,521 |
import requests
def make_request(endpoint, payload=None):
"""
Make a request to a specific endpoint on the weather API
passing headers and optional payload.
Parameters:
- endpoint: The endpoint of the API you want to
make a GET request to.
- payload: A diction... | 9c5a64c693036ca3ae244b2aa46180a09bac0fd3 | 586,529 |
from typing import OrderedDict
import inspect
def inspect_fn(fn):
"""
Inspect arguments of a function
Args:
fn: a function to inspect
Returns:
- an ordered dict with arguments and defaulted values
"""
args = OrderedDict()
signature = inspect.signature(fn)
for key, val... | 49b499f71bbc917b173d37035dc58b429a2cdd45 | 586,530 |
import json
def get_run_json(source: str):
"""Get the json resultant of a run"""
with open(source) as fd:
# File is a one liner
for line in fd:
return json.loads(line) | 6548c50a1d56b9eb2af1a966a20e53ccbad8f14c | 586,531 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.