content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import time
def spi_command(spi, message, get_result):
"""Write the specified message to the serial peripheral interface
and return the result if get_result is true."""
spi.writebytes(message)
time.sleep(0.001)
return spi.readbytes(4) if get_result else None | 1c28addfb1d9ef72217e04fa25272c2a15f35973 | 598,274 |
from typing import Union
def bool_value(s: Union[str, int]) -> bool:
"""
Convert a string or int to a boolean value. Raises ValueError if the string
isn't boolean.
:param s: the string
:return: the boolean
"""
if isinstance(s, bool):
return s
if isinstance(s, int):
r... | c2ea4e354203f849f4be4445dfc03c02a840af72 | 598,276 |
def get_dns_classification(self) -> list:
"""Get application definition for DNS from Cloud Portal. This
generates a lot of data and require longer response time.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - spPortal
- GET... | 7261ab56274e52e35cdb96921d9e6e160f86a1a9 | 598,282 |
def arithmetic_series(a, d, n):
"""Find the sum of arithmetic series.
a = first term
d = Common Difference
n = number of terms
"""
sum_ = (n/2) * (2 * a + (n-1) * d)
return sum_ | 083a52f818cb07e2561692026d49ef00963841e9 | 598,284 |
import random
def get_batch(source, i, args, train=True):
"""
get_batch subdivides the source data into chunks of length args.bptt.
If source is equal to the example output of the batchify function, with
a bptt-limit of 2, we'd get the following two Variables for i = 0:
┌ a g m s ┐ ┌ b h n t ┐
... | 53d86f02eff38a5c41b78264d96fd0a28d87a854 | 598,285 |
import string
def get_format_keys(format_str: str) -> list:
""" Get keys from format string. Unnamed placeholders are returned as empty strings."""
return [t[1] for t in string.Formatter().parse(format_str) if t[1] is not None] | 419165c392cc8e92d6daafa8a7d3f78a9a537530 | 598,292 |
def alias_map(aliased, aliases, required=()):
"""For each key in ``aliases``, find the item in ``aliased`` matching
exactly one of the corresponding items in ``aliases``.
Parameters
----------
aliased : list of str
Input keys, will be values in output map.
aliases : dict of sets
... | ba8341fbcff7ac61f44195d1dd799d6c128b9280 | 598,295 |
def ito_to_neuprint(ito_name):
"""Map Ito region name to equivalent hemibrain neuprint region(s)."""
mapping = {'AL_R': ['AL(R)'],
'AOTU_R': ['AOTU(R)'],
'ATL_R': ['ATL(R)'],
'ATL_L': ['ATL(L)'],
'AVLP_R': ['AVLP(R)'],
'BU_R': ['BU(R)'],... | eb433c919a5b1ed143f3a79b47af060b4f8b85ed | 598,296 |
import torch
def laplace_attention(queries, keys, values, scale, normalise=True):
"""
Here we compute the Laplace exponential attention. Each value is weighted by an amount that depends
on the distance of the query from the corresponding key (specifically, w_i ~ exp(-||q-k_i||/scale))
:param queries: ... | b322d66d95ce9e10de4d0ed73f086aefe5b85235 | 598,300 |
import operator
def trim_vocab(word_frequency, vocab_size):
"""Given the max vocab size n, trim the word_frequency dictionary to only contain the
top n occurring words
Args:
word_frequency (Dictionary): dictionary of word, frequency pairs.
vocab_size (Integer): the maximum number of vocabulary allowed.
... | e0dce524c6b58c707de2af3b30c0a5c989bf10a3 | 598,302 |
def print_class(klass):
"""Return the class name as used in text reports.
"""
return klass.lstrip('0') | a04b8b41870e4a76f6d0425d771bf37a0d35c026 | 598,312 |
import math
def gam_prophoto(rgb):
"""
Convert an array of linear-light prophoto-rgb in the range 0.0-1.0 to gamma corrected form.
Transfer curve is gamma 1.8 with a small linear portion.
"""
et = 1 / 512
result = []
for i in rgb:
# Mirror linear nature of algorithm on the nega... | 8c9f599ad25b17e98c611521763227db8a8aed3a | 598,317 |
def fibonacci_at_position(position):
"""Return Fibonacci number at specified position"""
current_position = 0
previous_number, current_number = 0, 1
while current_position < position:
current_position += 1
previous_number, current_number = current_number, previous_number + current_number... | 45d4abd8a0bfd1d2259e839bd939352874ccbdee | 598,318 |
def _cmp_zorder(lhs, rhs) -> bool:
"""Used to check if two values are in correct z-curve order.
Based on https://github.com/google/neuroglancer/issues/272#issuecomment-752212014
Args:
lhs: Left hand side to compare
rhs: Right hand side to compare
Returns:
bool: True if in corre... | 821b7421664db069eba63528eeecf9c55ee7f4c1 | 598,320 |
def between(x1: float, x2: float, x3: float) -> bool:
"""Checks if x2 is between x1 and x3."""
return x1 < x2 < x3 or x1 > x2 > x3 | 1f585718b0a2a9df44c248928e676cad47852bd0 | 598,324 |
import random
def crossover(x, y):
""" simple one-point crossover """
random_point = random.randint(1, len(x) - 1)
return x[0:random_point] + y[random_point:len(x)], \
y[0:random_point] + x[random_point:len(x)] | 7f66a47e460d47afc65c0f080accb3bf269535f9 | 598,325 |
def firehose_alerts_bucket(config):
"""Get the bucket name to be used for historical alert retention
Args:
config (dict): The loaded config from the 'conf/' directory
Returns:
string: The bucket name to be used for historical alert retention
"""
# The default name is <prefix>-strea... | 543aff4b722aed87adb21ff5096b0e573b6af0a3 | 598,327 |
def _compute_slice_dim_and_shape(full_shape, slicing):
"""Computes which dimension is being sliced and the typical slice shape."""
slice_shape = [0] * len(full_shape)
slice_dim = None
for dim, num_slices in enumerate(slicing):
dim_size = full_shape[dim]
if num_slices <= 0 or dim_size < num_slices:
... | 9ad2a219aa1f89663c1afbd0914c5b4d7bcaaac0 | 598,334 |
import re
def _get_cmds_inputs(ctx, ci):
"""Parse and return commands and TOSCA inputs."""
cmds = []
inputs = {}
pipe = False
i = 0
while i < len(ci):
if ci[i].startswith('--'):
# Parse TOSCA inputs in the two possible format:
# --key value or --key=value
... | 53db2dcaae86ae3d72a52057208e6a90d0de35dd | 598,335 |
def sample(*args, **kwargs):
"""Convenience method that calls into pandas DataFrame's sample method"""
return lambda df: df.sample(*args, **kwargs) | 7a49ea863848e97ee6d3c98472375f17f8fd5a35 | 598,338 |
import random
import torch
def _interval_based_sampling(vid_length, vid_fps, target_fps, clip_idx, num_clips, num_frames, interval,
minus_interval=False):
""" Generates the frame index list using interval based sampling.
Args:
vid_length (int): The length of the whole vid... | 8a0aa51ca063bf251c689a72f97fba3cb1e046b3 | 598,340 |
def water_dielectric_const(T):
"""Return water dielectric constant for temperature 253.15K < T < 383.15K.
Uses interpolation equation (eq. 9) for static dielectri constant found in
the doucment by The International Association for the Properties of
Water and Steam from 2011
<http://www.iapws.org/rel... | 760e29451e8fc3c8fd78df41deceaf80e044948e | 598,346 |
def invert_dictionary(dictionary):
"""Invert a dictionary.
NOTE: if the values of the dictionary are not unique, the function returns the one of the mappings
Args:
dictionary (dict): A dictionary
Returns:
dict: inverted dictionary
Examples:
>>> d = {"a": 1, "b... | 28f3aef9b4f377f40cb68f87277d34f2e2817eda | 598,348 |
def mahalanobis_squared(xi, xj, VI=None):
"""Computes the pair-wise squared mahalanobis distance matrix as:
(xi - xj)^T V^-1 (xi - xj)
Args:
xi (Tensor): xi input matrix.
xj (Tensor): xj input matrix.
VI (Tensor): The inverse of the covariance matrix, default: identity
... | 6651523378e870e24352c03242150671079b0a2a | 598,349 |
def _no_convert(_, start, end=None):
"""Dummy function for when no conversion is needed."""
if end:
return start, end
else:
return start, start | 623d229f0d09396cf00ba684fe4020d6450c722c | 598,350 |
def rx_band(freq):
"""
Associate a waveguide band with a frequency
"""
# Which front end channel is this for?
if freq < 2000.:
band = 'L'
elif freq < 5000.:
band = 'S'
elif freq < 10000.:
band = 'X'
elif freq < 40000.:
band = 'Ka'
else:
band = None
return band | 41098e6afa42dbf30f16e74eb102f986c8998d81 | 598,351 |
from typing import Iterable
def to_list(item_or_list):
"""
Convert a single item, a tuple, a generator or anything else to a list.
:param item_or_list: single item or iterable to convert
:return: a list
"""
if isinstance(item_or_list, list):
return item_or_list
elif isinstance(ite... | fe81e6e142120d2247c548e16dfd85634280dfe9 | 598,353 |
def num_to_string(num):
"""Formats a number as a string"""
if int(num) == num:
return str(int(num))
else:
return str(num) | 91aa0a903e89dacffb319aef8108c0eb71cdac8f | 598,357 |
def get_abort_running(db_cur, schedule_id):
"""Get abort_running status"""
sqlquery = f"""
SELECT abort_running
FROM schedules
WHERE schedule_id = '{str(schedule_id)}'"""
db_cur.execute(sqlquery)
row = db_cur.fetchone()
abort_running = row[0]
if abort_running == 0:
return F... | c6246242c8f0d4b8548b318f5f4a16f17bc439b7 | 598,360 |
def replace_python_tag(wheelname, new_tag):
# type: (str, str) -> str
"""Replace the Python tag in a wheel file name with a new value."""
parts = wheelname.split('-')
parts[-3] = new_tag
return '-'.join(parts) | cd71fccbbf9b0dd26bd04fc6d6294c91a38781ec | 598,362 |
def _starts_with_vowel(char) -> bool:
"""Test to see if string starts with a vowel
Args:
char: character or string
Returns:
bool True if the character is a vowel, False otherwise
Examples:
>>> _starts_with_vowel('a')
True
>>> _starts_with_vowel('b')
Fal... | 5bc3c31e9d604ee3319360145d81f93d5148d414 | 598,368 |
def freq(mylist, item):
"""Return the relative frequency of an item of a list.
:param mylist: (list) list of elements
:param item: (any) an element of the list (or not!)
:returns: frequency (float) of item in mylist
"""
return float(mylist.count(item)) / float(len(mylist)) | 5d00eb08bd2225b0e2433876bb3d6202aa9b5d05 | 598,370 |
from typing import Tuple
def _identify_additional_columns(
schema_field_names: Tuple[str, ...],
column_names: Tuple[str, ...],
) -> Tuple[bool, ...]:
"""Returns boolean mask of column names not in schema field names."""
return tuple(column not in schema_field_names for column in column_names) | 80cf4767372fdf1205c949c5bb5b7cdd48b4feb8 | 598,371 |
def from_doi(doi_identifier):
"""
Make an ISBN out of the given DOI.
.. note::
Taken from
https://github.com/xlcnd/isbnlib/issues/30#issuecomment-167444777.
.. note::
See https://github.com/xlcnd/isbnlib#note. The returned ISBN may not be
issued yet (it is a valid on... | aecef95f29e41f2aa8051a18bae48261ea33bf7d | 598,372 |
import requests
import json
def get_jsonparsed_data(url):
"""
Sends a GET request to API and returns the resulting data in a dictionary
"""
# sending get request and saving the response as response object
response = requests.get(url=url)
data = json.loads(response.text)
return data | dd415a712e79a40b411ebdbac2472d1bac1b9ec7 | 598,373 |
def revcompSeq(seq):
"""
Get reverse complementary sequence
"""
return seq.translate(str.maketrans("ACGTN", "TGCAN"))[::-1] | 96de52ef4dd9d543a2d5d7828724c24446066d72 | 598,376 |
def test_areas(root, printerror=False):
"""Verifies if the Lattes CV contains actuation areas.
Args:
root: the Lattes CV that has been parsed with the ElementTree
language.
flag: if 0, then the Lattes CV contains actuation areas.
If 1, the Lattes CV doesn't contain actuation area... | aec370fdc79171a941d107f7bf8b247fd57632ed | 598,384 |
def pe8(fname="../../res/pe8.txt", n=5):
"""
Discover the largest product of five consecutive digits
in the 1000-digit number.
>>> pe8()
40824
"""
with open(fname, 'r') as f:
s = f.read()
s = s.replace('\n', '')
ls = len(s)
if ls < n:
raise ValueError
m = 0
... | 7ec5c99658dfe977947e9746d4daa430f7025add | 598,386 |
from typing import Iterable
import ast
def _contains_node(elts: Iterable[ast.AST], node: ast.AST) -> bool:
"""Given a list of assignment targets (elts), return whether it contains the given Name node."""
for elt in elts:
if isinstance(elt, (ast.List, ast.Tuple)):
if _contains_node(elt.elts... | f490225a1e41b410600ada99c5757baf7d2ef33f | 598,390 |
def rebuild_text_passim(page, string=None):
"""The text rebuilding function.
:param page: a newspaper page conforming to the impresso JSON schema
for pages.
:type page: dict
:param string: the rebuilt text of the previous page. If `string` is not
`None`, then the rebuilt text is appende... | 57278cca90adab779205bbe4dae6ed6116b9a2b8 | 598,394 |
def _grid_list_uuid_list(model):
"""Returns list of uuid's for the grid objects in the cached grid list."""
uuid_list = []
for grid in model.grid_list:
uuid_list.append(grid.uuid)
return uuid_list | f9548d45527f491c043419a4d459dc1485a0b129 | 598,396 |
def create_analogy_templates(all_analogies):
"""For each analogy, create a template using each word pair.
Each template contains two special tokens: "[A]" and "[B]". These correspond
to the first and second word of the analogies provided in the original
analogies file, and will be substituted in during the ra... | 8210a32be69844f68cfdda351edc74fc9490b0d9 | 598,397 |
def error_response(error_message):
"""Return a well-formed error message."""
return {
"success": False,
"test_name": "s3_png_metadata",
"error_message": error_message,
} | bae8c59adb1ca9b0f90d8df94dcf66fdbf965bf1 | 598,398 |
import re
def escape_for_file(s):
"""Take out invalid characters for a filename."""
return re.sub('/', '-', s) | 42c664a5300a350b0dc38b355a42e8a3ae5bb0dc | 598,401 |
def checkPhone(phone: str) -> bool:
"""
Checks if a phone number is valid
Expected Countrycode<space>Number +91 12345678901
Parameters
----------
phone: str
The string to be Tested
Returns
-------
bool
True/False according to the validity of the phone number
"""... | 2145bb081900da51ff63ed22cf66ca3fb7a35776 | 598,409 |
import re
def get_field_name_from_mongoengine_error(exc):
"""
Try to extract field name from mongoengine error.
If field name is unable to be extracted, original exception is returned instead.
"""
msg = str(exc)
match = re.match('Cannot resolve field "(.+?)"', msg)
if match:
ret... | a23cde820fd66b60d984a90ab23398f15c2e4dc0 | 598,416 |
def query_df(data, col_name, col_value):
"""
Create a new subset of a given DataFrame() by querying it.
Parameters:
- data: The base DataFrame().
- col_name: The name of the column.
- col_vale: The values to match in that column.
Returns:
A DataFrame() object.
"""
... | f75290e09c887a312e07fa62015fcdf0c19d5803 | 598,419 |
def _get_unique_symmetry_elements(sym1, sym2, check_subgroups=False):
"""Compute the unique symmetry elements between two `Symmetry`
instances, defined as `sym1.outer(sym2).unique()`.
To improve computation speed some checks are performed prior to
explicit computation of the unique elements. If `sym1 =... | 8693abfcffed1f935cf6bb7b3d084ffc03a25200 | 598,421 |
def to_sir(scale, decay, n):
"""
Return the parameters of the equivalent SIR model.
Parameters
----------
scale : float
See the corresponding parameters in :meth:`exp_intensity` for more
information.
decay : float
See the corresponding parameters in :meth:`exp_intensity`... | 4d46cc8036a51370d2d35c8c48bc60cfb7fdbff0 | 598,429 |
import re
def extract_r(rmd_content):
"""Extract the actual R code from the given Rmd script"""
return "\n".join(re.findall(r"^```\{r[ \}].*?$(.+?)^```", rmd_content, flags=re.MULTILINE|re.DOTALL)) | 6b737f5faf20d3bfe880f237b94e028f51fdc8a6 | 598,431 |
import re
def process_url_id(url: str):
"""
Process the URL and return the giveaway ID
:return: string ('https://playr.gg/giveaway/WPfCGl-') --> 'WPfCGl-'
"""
return re.split("/", url)[-1] | 4f64ee68378aadf4e836e5bef1686e029e676d9f | 598,432 |
def _make_click_callback(function):
"""
Given a `function`, returns a callback function that can be used for a
click option's `callback=` to apply `function` to the value before passing
the argument to the command
"""
def callback(ctx, param, value):
return function(value)
return c... | bb7f1ec151d7e0c734dce21f0cfc01b624cc868a | 598,435 |
def load_file(filename: str) -> list:
"""Load the list of lanternfish from filename
:param filename: Location of the input file
:return: List of lanternfish
"""
with open(filename) as f:
fish = [int(n) for n in f.readline().split(',')]
return fish | 3761850d9450c72792ab0de9619592694d777cb5 | 598,440 |
from typing import Union
import logging
def _convert_logging_level(level: Union[int, str]) -> int:
"""Convert the user-provided level to a logging level integer."""
if isinstance(level, int):
assert 0 < level <= 50, 'Logging level must be between 0 and 50.'
return level
assert hasattr(logg... | b381294e25194031e0d2eb95b4f93b590c5dc2bc | 598,441 |
def parse_header_variable(line):
"""
Parses a line that follows:
Variable Code Value Description
Returns:
key, value, description, in_automesh
"""
x = line.split()
key = x[0]
if x[1] == 'A':
in_automesh = True
s = x[2]... | f52e0d19d41cf89fc428e82545217a8e8da1d2b2 | 598,443 |
def is_sequence(arg):
"""
Returns true if arg behaves like a sequence,
unless it also implements strip, such as strings.
"""
return (not hasattr(arg, "strip") and
hasattr(arg, "__getitem__") or
hasattr(arg, "__iter__")) | f0adf35d974e3c033a7b3de2cb735f3da5afbba1 | 598,451 |
async def root():
"""Home page."""
return {"message": "Hello Harper"} | ef64dbaba05c7fd804a632f12473d7f1724f2892 | 598,455 |
from typing import Tuple
def _get_effective_bandwidth(
lo: int, hi: int, transpose: bool, symmetrise: bool
) -> Tuple[int, int]:
"""
Given that a matrix has bandwidth (lo, hi) but may be treated
transposed or symmetrised, return the dimension of the matrix effectively used.
"""
if transpose:
... | 72fd23b4d9d402489037300666116fa87d1282c4 | 598,458 |
def is_snapshot_version(version):
"""
Check whether the given version is a snapshot version
:param version: The version to check
:return: whether the given version is a snapshot version
"""
return version.endswith("-SNAPSHOT") | 72fd47434b4490770d4b408ad7f579886f9f9fdc | 598,460 |
def is_di_repeat(kmer):
"""
Return true if kmer represents a di-nucleotide repeat (e.g. ATATAT).
"""
if not len(set(kmer)) == 2:
return False
return bool(len(set(kmer[::2])) == 1 and len(set(kmer[1::2])) == 1) | 752f1500ab5ff4840b651de60551020ea3da9866 | 598,469 |
def cap_feature(s):
"""
Capitalization feature:
0 = low caps
1 = all caps
2 = first letter caps
3 = one capital (not first letter)
"""
if s.lower() == s:
return 0
elif s.upper() == s:
return 1
elif s[0].upper() == s[0]:
return 2
else:
return 3 | 70e76d476c1202a74697af552ea2b22f0c3b0eac | 598,470 |
import itertools
def repeat(make_source):
"""Yield elements from a source, re-initializing it when empty."""
return itertools.chain.from_iterable(make_source() for _ in itertools.count()) | 6fcbe691e7778d6d98014cbf70e86895469dacdf | 598,471 |
def get_segment_length(linestring, p, q=None):
"""
Given a Shapely linestring and two Shapely points,
project the points onto the linestring, and return the distance
along the linestring between the two points.
If ``q is None``, then return the distance from the start of the
linestring to the pr... | c3dcacd3be1bc2251129700897371b444f0f3ac1 | 598,472 |
def strip_comment(line):
"""
Remove comment from input line.
"""
comment = line.find('#')
if comment != -1:
line = line[:comment]
return line.strip() | 10dea3cd6acf6240e01ceb39650de2f3dd6ab625 | 598,474 |
def request_args(args):
"""Decorator for request arguments.
Defines fields that should be passed to the controller action.
:param args: The arguments of the request.
:type args: dict
:return: The decorator.
:rtype:
"""
def _decorator(f):
f.args = args
return f
ret... | 0ade1d8a3e9da0904ff71ca19c6138b102020d1c | 598,475 |
def _pyval_find_struct_keys_and_depth(pyval, keys):
"""Finds the keys & depth of nested dictionaries in `pyval`.
Args:
pyval: A nested structure of lists, tuples, and dictionaries.
keys: (output parameter) A set, which will be updated with any keys that are
found in the nested dictionaries.
Return... | 0590851fca096be3d56d7b8cb69b18f0fd46ff9f | 598,476 |
import math
def generate_pareto_distribution_from_CDF(rand, lambda_pareto):
"""
Generate numbers following Pareto distribution using its CDF and a random number uniformly generated
"""
# We use beta = 2 (Pareto Parameter from distribution)
return (1/math.sqrt(1-rand) - 1)/lambda_pareto | e0a54ed1a462808a7e5cb50fe25085e3d409d833 | 598,477 |
def test_cutoff(labels,
scores,
cutoff,
metric = "accuracy"):
"""
-- DESCRIPTION --
Function to calculate accuracy or false positive rate for a specific cutoff
value.
PARAMS:
- labels (list of strings): list of labels ("active" or "inactive"... | 2aa63d0d52aecc00526d34ee96f56bb14c195ef9 | 598,479 |
def _proto_path(src, proto):
"""proto_path returns the string used to import the proto. This is the proto
source path within its repository, adjusted by import_prefix and
strip_import_prefix.
Args:
src: the proto source File.
proto: the ProtoInfo provider.
Returns:
An impor... | 1f96df0e59e5aface712bea625484c627c46fc5e | 598,481 |
def generate_path_dict(images_path, labels_path, partial_f_name):
"""
Generate split data path dict, also contains the corresponding label directories.
:param images_path: str - image top path
:param labels_path: str - label top path
:param partial_f_name: str - ending annotation name
:return: D... | e7cbdc86700aa7d3aea902f39d153e7ac1979398 | 598,485 |
def read_datasets_h5(h5):
"""
Simple read datasets from h5 handle into numpy arrays
"""
d = {}
for k in h5:
d[k] = h5[k][:]
return d | 1b11dcd3383a4cbf68b34726f5c4e04c40664d78 | 598,489 |
import math
def getDistance(x_data_row1, x_data_row2):
"""calculates distance between two rows of data (based on Euclidean distance)"""
distance = 0
length = len(x_data_row1)
for i in range(length):
distance += (x_data_row1[i] - x_data_row2[i])**2 # differences... | c5d14e0781436a5c3c7ebfe93f7482cc2d449899 | 598,490 |
def bowtie2_index_from_prefix(prefix):
"""
Given a prefix, return a list of the corresponding bowtie2 index files.
"""
return (
[
'{prefix}.{n}.bt2'.format(prefix=prefix, n=n)
for n in range(1, 5)
] + [
'{prefix}.rev.{n}.bt2'.format(prefix=prefix, n=n)... | c20d095f603a387048018c414f5d895d05061529 | 598,495 |
import base64
def base64url_decode(src):
"""
Decode URL-safe base64-encoded string without padding.
:param src:
:return:
"""
return base64.urlsafe_b64decode(src + '=' * (len(src) % 4 )) | 5f3508eefa99408bbb746e2c69f892f0fa9ba7ae | 598,496 |
def reorder(order, tag, reverse=False):
"""
Relocate the tag column to be the last bin of the order.
:param order: iterable order.
:param tag: string
:param reverse: True to put it at the beginning, false to be the last
:return: ordered order
"""
order = list(order)
others_index = o... | f5aef57b722c59ed2d2d83574a7c1d030b01adc7 | 598,498 |
def lines(s):
"""
Split a string in lines using the following conventions:
- a line ending \r\n or \n is a separator and yields a new list element
- empty lines or lines with only white spaces are not returned.
- returned lines are stripped.
Because of these constraints "".split() cannot be use... | 8a446927e83b68b267986461dc55410a2fad3de0 | 598,502 |
def normal_name(name: str) -> str:
"""Make first letter uppercase and replace spaces with underscores"""
if name == "":
return ""
name = str(name)
return (name[0].upper() + name[1:]).replace(" ", "_") | e81b03f977f566607dc952de160c88d81af343ed | 598,505 |
def find_alias_target(ast):
""" If "ast" is an alias type, return its target.
If "ast" is a type instance, go to the constructing type first.
"""
try_again = True
while try_again:
try_again = False
if ast.name == 'type_instance':
ast = ast.the('target').the('type')
try_again = True
while ast.name == ... | 9a75305984eb5ce963236ec81366c476c028bcbd | 598,507 |
def image(
src="http://placehold.it/200x200",
href=False,
display=False, # [ rounded | circle | polaroid ]
pull="left", # [ "left" | "right" | "center" ]
htmlClass=False,
htmlId=False,
thumbnail=False,
width=False,
height=False,
onPhone=T... | ef8243e300b3cad5a714904891ecc1fc47396435 | 598,508 |
import torch
def swish(x):
"""
Swish activation function,
from Ramachandran, Zopf, Le 2017. "Searching for Activation Functions"
"""
return x * torch.sigmoid(x) | f630c0851e1afe0ac72ff2f5dd06d787fa556194 | 598,510 |
import random
def pick_max(distribution):
"""Pick the value with the max weight from a list of (element, weight) pairs."""
distribution = list(distribution) # Reify potential generator
max_w = max(w for x, w in distribution)
opts = [x for x, w in distribution if w == max_w]
return random.choice(opts) | c53d091a74e696a03a9e7587733b32c958da6ae8 | 598,514 |
from pathlib import Path
from typing import Dict
def insert_high_priority(value: Path, fpaths: Dict[int, Path]) -> Dict[int, Path]:
"""Adds a high-priority file path to ``fpaths``."""
max_priority = max(fpaths.keys())
max_priority += 1
fpaths[max_priority] = value
return fpaths | 93d15112341becb164dea6ad138cadcc3fc35e62 | 598,524 |
import glob
def get_algorithms() -> list[str]:
"""Returns a list of all available algorithms
Returns:
list[str]: Gathered algorithms from the folder
"""
files = glob.glob("algorithms/*.py")
return [
file.split("\\")[-1].split(".")[0].replace("_", " ").title() for file in files
... | 2de8241a4e8d7d5c125982b41534eb9ee75b99b1 | 598,526 |
def parse_benchmark_full_name(name: str):
"""
Returns the benchmark full name including the template types.
>>> parse_benchmark_full_name('BM_Insert_Random<int64_t, int64_t, std::unordered_map>/1000')
'BM_Insert_Random<int64_t, int64_t, std::unordered_map>'
"""
return name[0: name.find('/')] | ecc7ae6b6abff4828ba4e2a079c2e77451a52065 | 598,529 |
def gdx_isnan(val,gdxf):
"""
Utility function for equating the GDX special values that map to None or NaN
(which are indistinguishable in pandas).
Parameters
----------
val : numeric
value to test
gdxf : GdxFile
GDX file containing the value. Provides np_to_gdx_svs map.
... | 915baa0f7d00bc8b4121005a92519e0d5a052f91 | 598,531 |
def get_prediction(data,model):
"""
Predict the class of a given data point.
"""
return model.predict(data) | e7839a96e5fa9f085489a5cd6acfa01e6f8b14ff | 598,532 |
def format_span_id(span_id: int) -> str:
"""Format the span id according to b3 specification."""
return format(span_id, "016x") | 597325a69d357c033d1540528339c2952ef4651e | 598,535 |
def volume_tetrahedron(xyz, A, B, C, D):
"""
Returns the volume for tetrahedras volume specified by the indexes A to D.
:param numpy.ndarray xyz: X,Y,Z vertex vector
:param numpy.ndarray A,B,C,D: vert index of the tetrahedra
:rtype: numpy.ndarray
:return: V, volume of the tetrahedra
Algori... | 1ab1b800d38cd0b33c50b33772eeb2f4f2d9361f | 598,536 |
def capitalization_helper(original: str, replacement: str) -> str:
"""
helper function to return appropriate capitalization
:param original: original word from the sentence
:param replacement: replacement for the given word
:return: replacement word matching the capitalization of the original word
... | 42f8b3bd070a22567f27b787db5128f72f8755c9 | 598,537 |
def get_role( trans, id ):
"""Get a Role from the database by id."""
# Load user from database
id = trans.security.decode_id( id )
role = trans.sa_session.query( trans.model.Role ).get( id )
if not role:
return trans.show_error_message( "Role not found for id (%s)" % str( id ) )
return r... | b58ef0e6f82c22062f775e7368bf9511f342df66 | 598,538 |
def to_list(df):
"""
Create list of track & artists
"""
combined = df['combined']
track_artist = combined.tolist()
return track_artist | 6fd2a8b12b307bd2cef28e7c82ad6b1e086a669b | 598,540 |
def _map_range(value, in_min, in_max, out_min, out_max):
"""Map an integer value from a range into a value in another range."""
result = (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
return int(result) | 298ea457798b6f6f34552d8e24d4cc6c1614b390 | 598,541 |
def z_score(point, mean, stdev):
"""
Calculates z score of a specific point given mean and standard deviation of data.
parameters:
point: Real value corresponding to a single point of data
mean: Real value corresponding to the mean of the dataset
stdev: Real value corresponding to the standard deviation of the... | 38682129cbad9f6a1db2bcb949a915e33a12b254 | 598,542 |
def split_ref( ref ):
"""Splits a database reference into a db name and an accession number
"""
( db_name, acc_id ) = ref.split( ':' )
return ( db_name, acc_id ) | 01f84c290b180a031b8bb9ff67e072ce0a233a0d | 598,546 |
def dmp_copy(f, u):
"""
Create a new copy of a polynomial ``f`` in ``K[X]``.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.densebasic import dmp_copy
>>> f = ZZ.map([[1], [1, 2]])
>>> dmp_copy(f, 1)
[[1], [1, 2]]
"""
if not u:
retu... | 935c937e7a3944506afebee70574a1028c789f58 | 598,550 |
def split_pdb_atom_lines(lines):
"""
Extract PDB atom properties
for a list of strings and
return a list of dictionaries.
Parameters
----------
lines : list of str
list of PDB atom strings
Returns
-------
list of dict
list of PDB atom properties
"""
retu... | 6d06fdb30dd950cbc9f4c25a30539d79b2b99e75 | 598,551 |
def _get_files_excluded(copyright):
"""Returns an iterable of all Files-Excluded patterns"""
return map(str.strip, copyright.header['Files-Excluded'].strip().splitlines()) | edbb61e44906fc21fd8129dea1a2488616f569fa | 598,553 |
def _to_bool(value):
"""Transform string value to bool.
Return `True` is input `value` is "yes" or "true", or "1" or "on",
return `False` for all other cases.
For example:
.. code-block:: python
>>> _to_bool('yes')
True
>>> _to_bool('no')
False
>>> _to_boo... | 43f8188b115428461a92597ed5d8a560a1fef32f | 598,555 |
def valid_delimiter(request):
"""
Fixture that yields valid delimiter strings.
"""
return request.param | f0dfe8b297936e5b9661153270db78a1197d87a5 | 598,557 |
def parse_cmd(cmd):
"""This function converts a list to str.
If a command is passed as list it is converted to str.
For pyrpipe v0.0.5 onwards the get_shell_output function uses shell=True
"""
if isinstance(cmd,list):
return " ".join(cmd)
return cmd | 1141034750299d7dc05a4975b7deb299a041d588 | 598,561 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.