content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _func_overhead(q, p, n):
"""
Model function to calculate the overhead.
:param q: Actual overhead parameters values
:param p: Numbers of cores used on model data
:param n: Problems size used on model data
:return: calculated overhead value
"""
return q[0]+(q[1]*p)/pow(q[2], n) | 7c6e41fdb829bb3c653887df0a565c3b406afdd8 | 672,689 |
def _f1(precision: float, recall: float) -> float:
"""
Compute f1.
:param float precision
:param float recall
:return: f1
:rtype: float
"""
if precision == recall == 0:
return 0
return 2 * precision * recall / (precision + recall) | f1e19ef9ed614355166989a18d556d4afd11af16 | 672,690 |
def CleanIndent(text, prefix=''):
"""Remove extra indentation from comments or code.
This allows code to be written as triple-quoted strings with natural
indentation in the python file, and that indentation will be removed
and replaced with the provided prefix.
Args:
text: Input code
prefix: will be... | b980dae9f18dac6681fe3955d94cc27d95f4fabb | 672,691 |
def escape(v):
"""
Escapes values so they can be used as query parameters
:param v: The raw value. May be None.
:return: The escaped value.
"""
if v is None:
return None
elif isinstance(v, bool):
return str(v).lower()
else:
return str(v) | 304079292532ef905099f1fd047ddb95df231076 | 672,692 |
def _css_select(soup, css_selector):
""" Returns the content of the element pointed by the CSS selector,
or an empty string if not found """
selection = soup.select(css_selector)
if len(selection) > 0:
if hasattr(selection[0], 'text'):
retour = selection[0].te... | 5b9dc2c2a26957e32aab1ac86dde85a8efd39bcf | 672,695 |
import re
def is_compatible(source_version, compat_versions):
"""
Compare a source version string to a set of target version string specifications. Supports semantic versioning
comparison via setuptools version comparison logic (http://setuptools.readthedocs.io/en/latest/setuptools.html#id7).
:param ... | 05c2df2282685e44c482afb9cbbfc7646b806fe7 | 672,696 |
def edge_color_weight(G,edgelist=None):
"""Automatically calculate a normalized reasonable color for
a weighted graph
Parameters:
-----------
G: A networkx Graph
edgelist: A list
Edges to calculate the weights for if None, uses all edges
Returns:
--------
weight_dict: A dictio... | 1d408538df26ad937e3c8964539833d95aed1081 | 672,704 |
import csv
def env_reader(infile: str) -> list:
"""
Read environment list from infile.
Parameters
----------
infile : str
Name of the file containing the environment list.
Returns
-------
list
Nested (2D) list of the environment.
"""
with open(infile, 'r') as ... | 3923df8630b5f2dcbc9ba14ab29af88ab07a8316 | 672,712 |
def axis_list(n_axes: int, reverse=False) -> str:
"""Returns a comma-separated list of axis TypeVar short names.
Args:
n_axes: Maximum number of axes to include in the list.
n_axes=1 -> 'A1', n_axes=2 -> 'A1, A2', etc.
reverse: If False, the returned list starts from A1 and counts up to An.
... | d86752bc637b3ce9a6e9440449319dac4b18e9a5 | 672,716 |
def mult_saturate(a, b, upper_bound, lower_bound):
"""
Returns the saturated result of a multiplication of two values a and b
Parameters
----------
a : Integer
Multiplier
b : Integer
Multiplicand
upper_bound : Integer
Upper bound f... | fa6b379860f18aa2e09b91086e6cfe129588f4cc | 672,717 |
def _GetReleaseTracks(release_tracks):
"""Returns a string representation of release tracks.
Args:
release_tracks: API versions to generate release tracks for.
"""
release_tracks_normalized = '[{}]'.format(', '.join(
[track.upper() for track in sorted(release_tracks)]))
return release_tracks_normal... | 2d4a66996844fe27144eb22d8eb7832d4ed9dd7f | 672,719 |
def get_wsgi_header(header):
"""Returns a WSGI compliant HTTP header.
See https://www.python.org/dev/peps/pep-3333/#environ-variables for
information from the spec.
"""
return 'HTTP_{}'.format(header.upper().replace('-', '_')) | c4a41a07b53f4b2b63c7e9c197a7995a3993d20d | 672,720 |
def proportion_of_traffic_from_top_users(tweets, users_with_freq, n):
"""
Return the percentage of the traffic that comes from the n most active accounts in a list of tweets.
:param tweets: the list of tweets, represented as dictionaries.
:param users_with_freq: a Counter of usernames with the num... | 7f8226c8e7dce4fccd74a7b2ac375d8fb86213ce | 672,721 |
def is_valid_lindblad_paramtype(typ):
"""
Whether `typ` is a recognized Lindblad-gate parameterization type.
A *Lindblad type* is comprised of a parameter specification followed
optionally by an evolution-type suffix. The parameter spec can be
"GLND" (general unconstrained Lindbladian), "CPTP" (cp... | 9b82f2ffabde8eeb1fe6275b592e7db46f691e3e | 672,722 |
def make_GeoJson(geoms, attrs):
"""
Creates GeoJson structure with given geom and attribute lists; throws exception if both lists have different length
:param geoms: list of geometries (needs to be encoded as geojson features)
:param attrs: list of attributes
:return: dict in GeoJson structure
"... | 87ad4e7a883cf192f74f96410a723eaec91af7c8 | 672,723 |
def combine_bytes(reorder):
"""Combine list of bytes into one binary sequence"""
o = b''
for r in reorder:
o += r
return o | 8014302a48e839edf4fcb6a1cd8f978d5bfa92e5 | 672,725 |
def adjust_error_on_warning_flag(flag, step, language):
"""
Adjust a given compiler flag according to whether this is for configure or make.
"""
assert language in ('c', 'c++')
assert step in ('configure', 'make')
if language == 'c' and flag in ('-Wreorder', '-Wnon-virtual-dtor'):
# Skip... | 112bfe55f6bbd77ef2ac5aa70ec23d56f46bacd0 | 672,727 |
def x_to_ab(x, p, q):
"""
Given some integer x mod pq, returns the CRT representation (x mod p, x mod q)
(CRT -> Chinese Remainder Theorem).
"""
return x % p, x % q | 2d8d5c4cb60c490e04f9d3bec47652afc2ee9638 | 672,729 |
def is_number(num):
"""Checks if num is a number"""
try:
float(num)
except ValueError:
return False
return True | 28e5d8d96e324bd2690f06a7681999f37b1d42af | 672,732 |
def ok_for_raw_triple_quoted_string(s, quote):
"""
Is this string representable inside a raw triple-quoted string?
Due to the fact that backslashes are always treated literally,
some strings are not representable.
>>> ok_for_raw_triple_quoted_string("blah", quote="'")
True
>>> ok_for_raw_tr... | bb86e5720ec91a5ce0e15ce342563cfa03ba6319 | 672,733 |
import json
def read_fps(json_file_path):
"""
Open json file, read the fps the data was recorded at.
input: json file path
output: int (fps)
"""
with open(json_file_path) as f:
data = json.load(f)
fps = data['fps'][0]
return fps | 28d55b554b339d49920cf046230fd77b1c6ca2e3 | 672,734 |
def separate_artists_list_by_comparing_with_another(
another_artists_list, compared_artist_list
):
"""
Input: Two list of artists_id
Return two lists containing:
- Every artist in compared_artist_list that are in another_artists_list
- Every artist in compared_artist_list that are not in anothe... | 330fae7901e4600a0ecfad00b9f55db6a0358a36 | 672,737 |
def _is_items(lst):
"""Is ``lst`` an items list?
"""
try:
return [(a, b) for a, b in lst]
except ValueError:
return False | 1a8362cd5c91dd799469682d729d2f9c735dd795 | 672,738 |
from typing import List
def get_drop_columns_binary(categoricals: List[str], columns: List[str]) -> List[str]:
"""
Selects the columns which can be dropped for one-hot-encoded dfs without drop_first.
Is mainly needed to transform into drop_first encoding
Parameters
----------
categoricals: n... | b20ce71b7b44ac48f3850e58223d58ec871623fd | 672,739 |
def process_predictions(lengths, target, raw_predicted):
"""
Removes padded positions from the predicted/observed values and
calls inverse_transform if available.
Args:
lengths: Lengths of the entries in the dataset.
target: Target feature instance.
raw_predicted: Raw predicted/... | 7bdebe64779bd2972ba9e1f6549193c033a81ccb | 672,740 |
def get_start_end_from_string(start_end):
""" 111.222 => 111, 222 """
start, end = start_end.split(".")
start = int(start)
end = int(end)
return(start, end) | 43af0d52c492b083be01a97aeca8999ba78e3bdc | 672,742 |
def get_weighted_mean(distribution: list, weights: list) -> float:
"""
:param distribution: list of int or float to calculate the weighted mean
:param weights: weights list
:return: the weighted mean of distribution list
"""
numerator = sum([distribution[i] * weights[i] for i in range(len(distri... | a9f67af2c1e492348dc2693531b3641e0decbc5b | 672,743 |
from typing import List
def cross_over(input_data: List, value: int):
"""return true if input_data crossed over value otherwise false"""
return input_data[-1] > value > input_data[-2] | 94a60dcb1ade37825812c307f70091cff0643822 | 672,748 |
def prod_nadate_process(prod_df, prod_col_dict, pnadrop=False):
"""
Processes rows of production data frame for missing time-stamp
info (NAN).
Parameters
----------
prod_df: DataFrame
A data frame corresponding to production data.
prod_df_col_dict: dict of {str : str}
A d... | 20381ef0cbeabae67d738f17ecd349513006e81e | 672,752 |
def wrap_seq_string(seq_string, n=60):
"""Wrap nucleotide string (seq_string) so that each line of fasta has length n characters (default n=60)
Args:
seq_string (str): String of DNA/protein sequence
n (int): Maximum number of characters to display per line
Returns:
(str): String o... | 6987d3066b8907ad6ec44a374a3d86c6a2bb7b4c | 672,757 |
def jib(foot, height):
"""
jib(foot,height) -> area of given jib sail.
>>> jib(12,40)
240.0
"""
return (foot*height)/2 | 5097252deffe96f8d4fc32e5f26b8be3cadcd1cc | 672,758 |
def _mac_to_oid(mac):
"""Converts a six-byte hex form MAC address to six-byte decimal form.
For example:
00:1A:2B:3C:4D:5E converts to 0.26.43.60.77.94
Returns:
str, six-byte decimal form used in SNMP OIDs.
"""
fields = mac.split(':')
oid_fields = [str(int(v, 16)) for v in fiel... | 5bf5d6a1b3e5bf3afcf8d00553e668d8d8fd2309 | 672,764 |
def get_amr_line(input_f):
"""
Read the file containing AMRs. AMRs are separated by a blank line.
Each call of get_amr_line() returns the next available AMR (in one-line form).
Note: this function does not verify if the AMR is valid
"""
cur_amr = []
has_content = False
for line in input... | 60e22230748f9b849b460b465415a82d0af7c909 | 672,768 |
def read_obs(obs_file):
"""
Function to read in observation data from text file
each line should be formatted as "T ill V J"
"""
f = open(obs_file, 'r' )
f.readline() # there's a header with column labels
obs_T, obs_ill, obs_V, obs_J = [], [], [], []
for line in f:
l=line.s... | 40b2bd9d56e85ebbfe86f1221104e6c1fd194934 | 672,769 |
def fake_answer_questionnaire(input_str, answer_options, multiple_choice_questions):
"""Imitates the ability of a self-aware model to answer questions about itself, as in answer_questionnaire subtask
Args:
input_str: String. The model's input, containing a question about the model
answer_option... | 1d459c52b7b949bfed2ad7cf18c489db58a4387e | 672,771 |
import math
def make_jc_matrix(t, a=1.):
"""
Returns Juke Cantor transition matrix
t -- time span
a -- mutation rate (sub/site/time)
"""
eat = math.exp(-4*a/3.*t)
r = .25 * (1 + 3*eat)
s = .25 * (1 - eat)
return [[r, s, s, s],
[s, r, s, s],
[s, s, r, s],... | 12f0c30732db909930201ba7ff26c78c38ea4f4a | 672,772 |
def parse_ipmi_sdr(output):
"""Parse the output of the sdr info retrieved with ipmitool"""
hrdw = []
for line in output:
items = line.split("|")
if len(items) < 3:
continue
if "Not Readable" in line:
hrdw.append(('ipmi', items[0].strip(), 'value', 'Not Reada... | 7525b21926ced8dc44f4730c283432b869905786 | 672,778 |
from pathlib import Path
def repository(tmp_path: Path) -> Path:
"""Fixture for a repository."""
path = tmp_path / "repository"
path.mkdir()
(path / "marker").write_text("Lorem")
return path | d334be1f1bda43f3c7c46c8b79dd3024029618a9 | 672,780 |
def latest_actions_only(items):
"""Keep only the most recent occurrence of each action, while preserving the order"""
used = set()
res = []
for item in reversed(items):
if item not in used:
res.append(item)
used.add(item)
return reversed(res) | 56e8dd5b0b2bfab2da91c1070252ba6574f50fed | 672,782 |
def planet(armageddon):
"""Return a default planet (exponential atmosphere)"""
return armageddon.Planet() | 2f5f3b1dbd4b88d1362d8670a4bb9aebb1753e8a | 672,783 |
def mult_with_submatrix(A, columns, x):
"""Computes :math:`b = A[:, I] x`
"""
A = A[:, columns]
return A @ x | 7b2c9eab55a18f4c0de13cc0cbe6038f7fb0c573 | 672,784 |
def set_cover(X, subsets):
"""
This algorithm finds an approximate solution
to finding a minimum collection of subsets
that cover the set X.
It is shown in lecture that this is a
(1 + log(n))-approximation algorithm.
"""
cover = set()
subsets_copy = list(subsets)
while True:
S = max(subsets_co... | afbcded0a24e1bffcad4e6c01f844edcef673fb7 | 672,786 |
def _validate_float(value):
""" Convert an arbitrary Python object to a float, or raise TypeError.
"""
if type(value) is float: # fast path for common case
return value
try:
nb_float = type(value).__float__
except AttributeError:
raise TypeError(
"Object of type ... | 5cd57b9b557ef5c3a56365152eb95fbea2a8b098 | 672,787 |
def lr_lin_reduction(learning_rate_start = 1e-3, learning_rate_stop = 1e-5, epo = 10000, epomin= 1000):
"""
Make learning rate schedule function for linear reduction.
Args:
learning_rate_start (float, optional): Learning rate to start with. The default is 1e-3.
learning_rate_stop (float, op... | 75809150725bcaa8216dfec8958957101dfc01b2 | 672,789 |
def split_conn_port(connection):
"""Return port number of a string such as 'port0' as an
integer, or raise ValueError if format is invalid"""
try:
return int(connection.split('port', 1)[1])
except (ValueError, IndexError):
msg = "port string %s does not match format 'port<N>' for integer... | 60ea8508920158a99fda3fa69c9b0c2bdd221919 | 672,790 |
def tail(list, n):
""" Return the last n elements of a list """
return list[:n] | bef68bbe0f4fc3ace24306ba6e01c6c1dd9aab8c | 672,791 |
import torch
def categorical_focal_loss(y_true, y_pred):
"""
Reference: https://github.com/umbertogriffo/focal-loss-keras
Softmax version of focal loss.
m
FL = SUM -alpha * (1 - p_o,c)^gamma * y_o,c * log(p_o,c)
c=1
where m = number of classes, c = class and o = observa... | d5a9224dbfedaf10f9f27fb3872b2178bd6e7b5b | 672,794 |
def compute_loss(logits, target, criterion):
"""
logits shape: [seq-len, batch-size, output_dim]
target shape: [batch-size, seq-len]
"""
loss = criterion(logits, target)
return loss | 791bfeab27b8264b4d72331c2b43cd22f6f4d480 | 672,797 |
def _add(a: int, b: int) -> int:
"""Add two numbers together.
Args:
a (int): First number.
b (int): Second number.
Returns:
int: A sum of two numbers.
"""
return a + b | 60372a3916a7337b1bdd401de0165bc46fabeee3 | 672,803 |
def _parse_list_file(path):
"""
Parses files with lists of items into a list of strings.
Files should contain one item per line.
"""
with open(path, 'r') as f:
items = [i for i in f.read().split('\n') if i != '']
return items | 2c1203cd76e6b4382d8407d5d4197a2b8489f92a | 672,804 |
def first_elem(s):
""" Extracts first element of pandas Series s, or returns s if not a series. """
try:
return s.iloc[0]
except AttributeError:
return s | 6b6bcf84c07ced25d797bc022d4713543deaeafb | 672,806 |
import glob
def get_images(path):
"""
Checks the folder for images
:param path: The folder in which we will check for images
:return: An array of all images found
"""
path = path
images = glob.glob(path + "**/**/**/*.jpg", recursive=True)
images.extend((glob.glob(path + "**/**/**/*.png... | dcb805a010af1c277f54b9dee1342b3eb6207d69 | 672,807 |
from itertools import chain, repeat
from typing import Iterable
from typing import Iterator
def ncycles(it: Iterable, n: int) -> Iterator:
"""
Returns the sequence elements n times
>>> [*ncycles(range(3), 3)]
[0, 1, 2, 0, 1, 2, 0, 1, 2]
"""
return chain.from_iterable(repeat(it, n)) | f6d4f5f14615dd2d170922a349bb3f0f4b6e4c0d | 672,809 |
import re
def get_audio_paths(dataset_root_path, lst_name):
"""Extract audio paths."""
audio_paths = []
with open(dataset_root_path / "scoring" / lst_name) as f:
for line in f:
audio_path, lang = tuple(line.strip().split())
if lang != "nnenglish":
continue
... | fb7256c994d928462152f6c9d85480d4b4a0d918 | 672,811 |
def foreground_color(bg_color):
"""
Return the ideal foreground color (black or white) for a given background color in hexadecimal RGB format.
"""
bg_color = bg_color.strip('#')
r, g, b = [int(bg_color[c:c + 2], 16) for c in (0, 2, 4)]
if r * 0.299 + g * 0.587 + b * 0.114 > 186:
return '... | ae41ce30e820c160f1c9c88dd34496905f6a3bd6 | 672,813 |
def count_trajectories(n: int) -> int:
"""
The Grasshopper is in position 1.
The Grasshopper may jump to +1, +2 or +3.
How many possible trajectories does the grasshopper have to get to position n?
If n<=1, consider that the Grasshopper has 0 possible trajectory.
>>> count_trajectories(0)
0... | d9c0127e2a21346872783d6b4b9ea44fc2bde285 | 672,815 |
import requests
def get_request(url, max_tries=10):
""" Get JSON data from BiGG RESTful API.
Args:
url (str): url request
max_tries (int): maximum number of communication attempts (default: 10)
Returns:
dict: json data
"""
resp, data = None, None
for i in range(max_... | 3a8752538cef2f33e4c3979e92f8a69d3c2c3d13 | 672,817 |
def ubfx(value, lsb, width):
"""Unsigned Bitfield Extract"""
return (value >> lsb) & ((1 << width) - 1) | bba3b92deea9105acc6554d235230711d1979c5f | 672,818 |
def interleaved2complex(data):
"""
Make a complex array from interleaved data.
"""
return data[..., ::2] + 1j * data[..., 1::2] | 78d7eeb385232757f4feddc757b6766ef91b1c23 | 672,819 |
import inspect
import gc
def gc_objects_by_type(tipe):
"""
Return a list of objects from the garbage collector by type.
"""
if isinstance(tipe, str):
return [o for o in gc.get_objects() if type(o).__name__ == tipe]
elif inspect.isclass(tipe):
return [o for o in gc.get_objects() if ... | 9f2baa59818b4e495703fbda3b095e46dde97b2a | 672,820 |
from typing import Optional
from typing import List
def _nt_quote_args(args: Optional[List[str]]) -> List[str]:
"""Quote command-line arguments for DOS/Windows conventions.
Just wraps every argument which contains blanks in double quotes, and
returns a new argument list.
"""
# Cover None-type
... | 6939cb7d8e0b967d9bb629fc8785a42d130fd683 | 672,823 |
def sign_extend(value: int, orig_size: int, dest_size: int) -> int:
"""
Calculates the sign extension for a provided value and a specified destination size.
:param value: value to be sign extended
:param orig_size: byte width of value
:param dest_size: byte width of value to extend to.
:return:... | 2b3b545f5b7362f1a67bb95ce82265132f050c6f | 672,824 |
def identity(*args):
"""
Return whatever is passed in
Examples
--------
>>> x = 1
>>> y = 2
>>> identity(x)
1
>>> identity(x, y)
(1, 2)
>>> identity(*(x, y))
(1, 2)
"""
return args if len(args) > 1 else args[0] | e0ffb84b8685c562d9b05c4880553d4b8ea9678c | 672,827 |
def _convert_to_index_name(s):
"""Converts a string to an Elasticsearch index name."""
# For Elasticsearch index name restrictions, see
# https://github.com/DataBiosphere/data-explorer-indexers/issues/5#issue-308168951
# Elasticsearch allows single quote in index names. However, they cause other
# p... | 4ce052c19e97ed0d528890f3a444e05b88344753 | 672,829 |
import re
def coerceColType(colType):
"""
Given a colType, coerce to closest native SQLite type and return that, otherwise raise a ValueError.
Parameters:
colType (str): column type from DBML specification.
Returns:
str: valid SQLite column type.
"""
colType = colType.upper()
n... | acff9fac321b26b1a3591eb81f2ce24997a130fd | 672,832 |
from typing import Any
import importlib
import ast
def load_cli(import_str: str) -> Any:
"""Load the cli object from a import name. Adapted from gunicorn.
Examples:
flask.cli:cli
pipx.cli:create_parser()
"""
import_name, _, obj = import_str.partition(":")
if not (import_name and ... | 23f3e8107446c205834ed3cc7bd3384718ea797e | 672,836 |
def parse_regex_string(string):
"""
Parse header string according to wappalizer DB format
strings follow the below format:
<string>[\\;version:\\\d][\\;confidence:\d]
"string" is a mandatory regex string followed by 0 or more parameters (key:value), can be empty
parameters are divided by a \\;... | 41a11b9099abcd03f87f14aefe85dbe9e6ccc45b | 672,839 |
from math import pi as π, radians
def theoretical_peak_angle_velocity(stride_freq_Hz: float = 3.,
total_angle_deg: float = 180.,
disp: bool = True):
"""Cheetah leg moves from 0⁰ -> 90⁰ -> 0⁰ in about 1/3 of a second. Ie, follows the shape:
... | 48fe8201bf56200598963f4fa58b6405e9836a65 | 672,841 |
def Courant(alpha, h, c):
"""
Computes the courant condition.
Parameters
----------
alpha: Scaling parameter (generally 0.4)
h: array of h's
c: array of speeds of sound
Returns
-------
float: min. time step according to courant condition... | c6783f8dd8f0dea204ab076a1badfed1eadbff9a | 672,843 |
def cal_iou(box1, box2):
"""
computing IoU
:param box1: (y0, x0, y1, x1), which reflects
(top, left, bottom, right)
:param box2: (y0, x0, y1, x1)
:return: scala value of IoU
"""
cx1, cy1, cx2, cy2 = box1
gx1, gy1, gx2, gy2 = box2
# 计算每个矩形的面积
S_rec1 = (cx2 - cx1) * (cy... | f58bd3be9d507c3f3e0814194b04a359aced233f | 672,845 |
import textwrap
def _get_embl_wrapper(embl_key, indent=5, subsequent_indent=None, width=80):
"""Returns a textwrap.TextWrapper for embl records (eg, write
<key> <string> by providing embl key and a string. Wrap text to
80 column"""
# define the string to prepen (eg "OC ")
prepend = '{key:<{in... | c6b142233bb870dda812a01f31924b8f938cb316 | 672,849 |
def find_worst(list_of_values, quantity):
"""
auxiliary function to changeworst,
finds the indexes of the worst performing members
:param list_of_values: list of values relative to the members of the candidate
used to determine which is the worst performing ones
:param quantity: the quantity... | efb47dca893cc6f20f7ae4c13d45b3b15e20153c | 672,850 |
def get_resource_file(entity, resource_info, base_url):
"""
Create a file object from which resource data can be read.
resource_info is a value returned by `find_fixed_resource` or `find_entity_resource`
base_url is a base URL that may be used to resolving relative references in the
... | 3b21e4a6288e29bc7bef97ebb5549b10ebc0ab8c | 672,853 |
def field_eq(p, e):
"""
Checks the field values of a parsed message for equality against
some ground truth value.
Parameters
----------
p : object with dict-like attributed access
Parsed field contents.
e : object with dict-like attributed access
Expected field contents.
Returns
----------
... | e6e9410a72e93c8f587bb6ee365d941ae5271ae3 | 672,855 |
def _format_list(elems):
"""Formats the given list to use as a BUILD rule attribute."""
elems = ["\"{}\"".format(elem) for elem in elems]
if not elems:
return "[]"
if len(elems) == 1:
return "[{}]".format(elems[0])
return "[\n {},\n ]".format(",\n ".join(elems)) | 37c1b2d6558d8d96dc3381d73fafaf9c7e489e92 | 672,857 |
def footer() -> str:
"""
Return the footer of the LaTeX document.
:return: LaTeX document footer.
"""
return "\\end{tikzcd}\n\\end{document}" | f3d6615d089e489a88e6eba3c87a0fa9a655c20c | 672,859 |
def ReformatForLog( data ):
"""
Change all non printable characters into something human readable.
Arguments:
data -- The raw data that may contain unprintable characters
Example: 0x0D will show up as <D>
"""
output = ''
for char in data:
o = ord( char )
if( o < 32 ): # Unprintable control character... | 0ed1f657bf1afbb495c09c6e3db4bdba30628449 | 672,860 |
def read_text_file(filename):
"""
Read .txt file
Args:
:param: filename(str): the name of .txt file
Returns:
:param: text(str): text in .txt file
"""
with open(filename, "r", encoding="utf-16") as file:
text = file.readlines()
return str(text) | e76e7922aaccd5b5c7971dbb6bfe34125425aa03 | 672,861 |
def _filterobsoleterevs(repo, revs):
"""returns a set of the obsolete revisions in revs"""
return {r for r in revs if repo[r].obsolete()} | 1471f9c3818965c42080947a7f96390d668e0a5b | 672,866 |
def parse_mode(new_mode):
"""Function to parse a mode give in input to chmod function.
Parameters
----------
new_mode --> str, the new resource permissions, in the form of [0-7][0-7][0-7]
Returns
-------
(own,grp,others) --> tuple(int,int,int), the permissions parsed
"""
#t... | 49bb96475b8b78e4550ddae6e17ee079056e8beb | 672,868 |
def iseven(n):
"""
Return True if n is an even number and False otherwise.
"""
return (n % 2 == 0) | c3139d5b11d83f1d4e98d0575472bf817610b5c8 | 672,869 |
import inspect
def get_object_classes(classes_or_instances, expected_base_class=None):
"""Given a list of instances or class objects, return the list of their classes.
:param classes_or_instances: mixed list to parse
:type classes_or_instances: list[type or object]
:param expected_base_class: if give... | 738b99224111d940c0a14c753fad69eb66f16271 | 672,871 |
def d(b, a, bnds):
"""
Calculate difference between two images
Parameters:
b (ee.Image): 'before' image
a (ee.Image): 'after' image
bnds (ee.List<str>): band names included in calculation
Returns:
ee.Image: difference image with original bands
"""
... | 9a08abccd84ab39da7f8f4fad04f1e9d9beb4fa7 | 672,872 |
def find_nth_natural_number(i, limit):
"""Returns the ith natural number and the number containing it"""
assert i >= 1
number_map = {}
nums = []
prev_len = 0
for num in range(1, limit + 1):
nums.append(num)
new_len = len(str(num)) + prev_len
number_map.update({j: (prev_le... | dd06e37f34e48c327494b0f6c1ab19012d672836 | 672,874 |
import re
def form_date_parameter(date: str, name: str) -> str:
"""Form the date parameter for the API query after checking whether given date is valid.
Args:
date (str): date in format YYYY-MM-DD
name (str): either 'startDate' or 'endDate', used to differentiate API query parameters
Rai... | 1a229254731ca43748e1f6939a54cd2d029fee3a | 672,876 |
import torch
def matvec(mat, vec, out=None):
"""Matrix-vector product (supports broadcasting)
Parameters
----------
mat : (..., M, N) tensor
Input matrix.
vec : (..., N) tensor
Input vector.
out : (..., M) tensor, optional
Placeholder for the output tensor.
Return... | aa866fe9e3bf893c74ecac2b5c4c7cff3beebdb3 | 672,877 |
def acquire_title(soup):
"""
Take a BeautifulSoup content of a book page.
Return the title of the book.
"""
title = soup.h1.string
return title | a3d661430d1516142a720b8981999db0ea5970a5 | 672,878 |
def find_samples(data):
"""
Parse a list of raw packages into a list of raw samples
:param data: List of raw packages (int)
:return: samples, fail_count.
samples: List of raw samples
fail_count: number of samples that could not be decoded
"""
sample = None
looking_... | 9cd1351acba500a4615b42a5db5482d36cb48b19 | 672,879 |
def load_room_descrips(data, room_names):
"""
Loading each rooms respective main description.
Parameters:
data(dict): Nested dictionaries containing
all information of the game.
room_names(list): List containg room names.
Returns:
room_descrips(list): Returns list o... | 078762791ca9d10533dda0d5f86443b0693d36e7 | 672,880 |
def lines2paragraphs(lines):
"""
Return a list of paragraphs from a list of lines
(normally holding the lines in a file).
"""
p = [] # list of paragraphs to be returned
firstline = 0 # first line in a paragraph
currentline = 0 # current line in the file
lines.insert(l... | 2f6cf177ac3fe93edc3df3b8ffbe11763e395558 | 672,883 |
def bytes_as_char_array(b): # type: (bytes) -> str
"""
Given a sequence of bytes, format as a char array
"""
return '{ ' + ', '.join('0x%02x' % x for x in b) + ' }' | 980f1b57d2cc9b1b2b054843d54a24c5257d2996 | 672,884 |
def get_cpubind(cpu_binding):
"""Convert aprun-style CPU binding to PALS-style"""
# First check for keywords
if not cpu_binding or cpu_binding == "cpu":
return "thread"
if cpu_binding == "depth":
return "depth"
if cpu_binding == "numa_node":
return "numa"
if cpu_binding =... | 5c0bbdedb3aca3580ca712d7af25a0b7e1ab4c2b | 672,888 |
def info_to_name(display):
"""extract root value from display name
e.g. function(my_function) => my_function
"""
try:
return display.split("(")[1].rstrip(")")
except IndexError:
return "" | d01ce91fe18a57f1788feefa7fff37e4ec38a66e | 672,889 |
def get_x_minmax(start_times, end_times):
"""Determine the horizontal (x) min and max values.
This function adds 1% to either side for padding.
Args:
start_times (np.array): First packet unix timestamps of all pcaps.
end_times (np.array): Last packet unix timestamps of all pcaps.
Retur... | 95f95a281a626b0eefbbabf457a23303926c927b | 672,892 |
def get_busco_score(short_summary):
"""get busco Complete score from short_summary.txt"""
with open(short_summary) as f:
for line in f:
line = line.strip()
if line.startswith(("#", "*")) or line == "":
continue
elif line.startswith("C:"):
... | ddafc7092f7f6d0821aacc75b0acbd940626098e | 672,894 |
def rgb_to_hex(rgb):
"""
Covert RGB tuple to Hex code
"""
return f'0x{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}' | 6b2e0cfeee567dd42635a69903e2317605c0fe87 | 672,899 |
def is_managed_by_cloudformation(physical_resource_id: str, resource_array: list) -> bool:
"""
Given a physical resource id and array of rources - returns if the resource is managed by cloudformation
Parameters:
physical_resource_id (string): The identifier of the resource - eg igw-09a7b4932e331edb... | 49e4bd6d704df37824bde273b1e78079ca7e679d | 672,901 |
def combine_QUBO_storage(QUBO_storage, solved_QUBOs, column_solutions):
"""
Merges previous QUBO storage with new solutions.
Parameters
----------
QUBO_storage : list
Input QUBO storage list.
solved_QUBOs : dict
The QUBOs that were solved in this latest iteration.
column_sol... | 6a8c217f75c4b3c3f51a6292ce4179a165276fd5 | 672,905 |
from datetime import datetime
def get_week_format_from_timestamp(timestamp_millis: int) -> str:
"""Get week format from timestamp in milliseconds. The week number
returned will follow ISO-8601 standard
:param timestamp_millis: Timestamp in milliseconds.
:type timestamp_millis: int
:return: Return... | e9cbd2ffcde5bef2ef02fa5a670a4fdba9fd7934 | 672,907 |
def counting_sort(array, maxval):
"""
Sorts the list 'array' using counting sort
>>> from pydsa import counting_sort
>>> a = [5, 6, 1, 9, 3]
>>> counting_sort(a, 9)
[1, 3, 5, 6, 9]
"""
count = [0] * (maxval + 1)
for a in array:
count[a] += 1
i = 0
for a in range(max... | 9f40f270b5974a80d2d46db5896ecf34b80b8568 | 672,908 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.