content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def for_and_backward(model, batch, maps, optimizer, loss_fn):
"""Does one forward and one backward step, including weight updates, using
the given batch. Returns the loss."""
prediction = model(batch)
loss = loss_fn(prediction, maps)
# Calculate gradients
loss.backward()
# Update model param... | 5d95583173dad8db55196d3a1799656888cad322 | 638,281 |
import grp
def get_group_grp(gid):
"""get group info
Args:
gid (int): gid of the group
Returns:
grp.struct_group
"""
return grp.getgrgid(gid) | bc63b1887fecc7e59b535d0b006b81f3fab36e8a | 638,282 |
import math
def _db2gain(db):
"""Convert 100ths of dB to linear gain."""
return math.pow(10.0, float(db)/1000.0) | afac35b8610e6d80953f343ffdf24e16ca01e3ee | 638,285 |
def parse_is_account_bimodal_response(resp):
"""
Parse a response from RpcIsAccountBimodal.
Returns (True, peer-addr) if the account is bimodal, (False, None)
otherwise.
"""
is_bimodal = resp["IsBimodal"]
ip = resp["ActivePeerPrivateIPAddr"]
if ip.startswith("[") and ip.endswith("]"):
... | d18305ead4bfc349d4ecf44dc057712ab64be887 | 638,289 |
from typing import List
def get_mask_colors(scene: dict) -> List[List[float]]:
"""
Loads the unique mask colors from the scene dictionary
Parameters
---
scene (dict)
Scene dictionary containing info about the scene
Result
---
List[List[float]]
"""
masks = []
for o... | 7a065664d70d23baaa8621977ddb92e77acbc1e9 | 638,291 |
def any2unicode(text, encoding='utf8', errors='strict'):
"""Convert `text` (bytestring in given encoding or unicode) to unicode.
Parameters
----------
text : str
Input text.
errors : str, optional
Error handling behaviour if `text` is a bytestring.
encoding : str, optional
... | 7dbdacd9249ed495594685f379604348f8f6cfb5 | 638,293 |
def bits_to_int(bits):
"""Converts a list of bits into an integer"""
val = 0
for bit in bits:
val = (val << 1) | bit
return val | fe2024817f3659b6304577e7c325168690e74392 | 638,295 |
def parse_hex(string):
"""Parse a string as a hexadecimal value."""
return int(string, 16) | e5ce1ba5b0542d0dcad8855fd352431670f5682b | 638,308 |
import torch
def box_xy_to_wh(x):
"""
Converts co-ordinates from (x1, y1, x2, y2) to
(x, y, w, h)
"""
x1, y1, x2, y2 = x.unbind(-1)
x = (x2 + x1)/2
y = (y2 + y1)/2
w = (x2 - x1)
h = (y2 - y1)
return torch.stack([x, y, w, h], dim=-1) | d728a70c70a65242f76a3041d994efaa93846b85 | 638,310 |
def scalar_eq(a, b, precision=0):
"""Check if two scalars are equal.
Keyword arguments:
a -- first scalar
b -- second scalar
precision -- precision to check equality
Returns:
True if scalars are equal
"""
return abs(a - b) <= precision | e3d3cb091119d38825a37a5e745ab302f976cbb7 | 638,314 |
import re
def identify_url(url):
"""Identify from which site a url is.
Return values:
'letras' for 'letras.mus.br'
'vagalume' for 'vagalume.com.br'
'unknown' if not able to identify.
"""
if not isinstance(url, str):
raise ValueError('url is not a string')
url = url.strip()... | d5f48efb2e7c7d6a0e22641939b379c7a75ca333 | 638,315 |
def flatten_list(_list):
""" [(1,2), (3,4)] -> [1, 2, 3, 4]"""
return sum([list(item) for item in _list], []) | 42caee7ee37fc14fd74eba784ac3b76326754a37 | 638,317 |
def validate_byr(birth_year: str) -> bool:
"""byr (Birth Year) - four digits; at least 1920 and at most 2002."""
return len(birth_year) == 4 and int(birth_year) >= 1920 and int(birth_year) <= 2002 | 5ec2c850a7f48bfdb49d62259689b6b6f87cdec3 | 638,318 |
def is_restart_command(command_text: str) -> bool:
"""
>>> is_restart_command("restart")
True
>>> is_restart_command("restart game")
True
>>> is_restart_command("take lamp")
False
"""
return command_text.startswith("restart") | 5fbfe40e11df015a7d159db6da6d7f213d67330f | 638,319 |
def _strip(string):
"""
Removes unicode characters in string.
"""
return "".join([val for val in string if 31 < ord(val) < 127]) | 12aa6b9ae6c2b3c5283ee837819d48d35be39e74 | 638,322 |
def measurement_ids_and_names(experiment_proto):
"""List all measurement IDs and names for an experiment.
Results are sorted by measurement ID.
Args:
experiment_proto: selection_pb2.Experiment describing the experiment.
Returns:
measurement_ids: tuple of integer IDs for each measurement.
column_n... | c065d0451e8d1b90a34e36c097cc99f9836d728c | 638,324 |
from datetime import datetime
def noclook_last_seen_to_dt(noclook_last_seen):
"""
Returns noclook_last_seen property (ex. 2011-11-01T14:37:13.713434) as a
datetime.datetime. If a datetime cant be made None is returned.
"""
try:
dt = datetime.strptime(noclook_last_seen, '%Y-%m-%dT%H:%M:%S.%... | 88eab5db655c32323004a14bab458962f90fda73 | 638,325 |
def split_dataframe(df, chunk_size):
"""
splits a pandas dataframe into a list of sub-dataframes by size of chunk_size
"""
df = df.iloc[::-1] #reverse the dataframe
chunks = list()
for i in range(len(df)): #for amount of days in df
if len(df[i:i+chunk_size]) is chunk_size:
... | 2d8597d27e2d326298941d0bd38d99a3fa0f3524 | 638,326 |
def _is_dunder(name):
"""Returns True if name is a __dunder_variable_name__."""
return len(name) > 4 and name.startswith('__') and name.endswith('__') | 9dc571eab0f47ab94860bbc56a67140ec1b52498 | 638,327 |
def get_matching_items_from_dict(value, dict_name):
"""
Return all items in a dict for which the label matches the provided value.
@param value: the value to match
@param dict_name: the dict to look in
"""
matches = [dict_name[x]["items"]
for x in dict_name if x.lower() == value]... | 4e2d720ebca42c41a87833ebfa9b502955ec7840 | 638,328 |
def build_entity(key, value):
"""
build_entity return a dict that can be passed back to rasa as an entity
using the given string key and value
"""
return {"entity": key, "value": value, "start": 0, "end": 0} | 3e29ed0d9dc3adad003ff95b75a8c46edd0becce | 638,333 |
def to_float(nmb: str):
"""
convert numbers from rinex files to python floats
rinex floats can either be:
4.391254341941D-09
4.391254341941E-09
that is, the scientific notation can use the ´E´ or ´D´ char
"""
try:
flt = float(nmb)
except ValueError:
nmb = nmb... | 26a92184ed4c78ab0ce90c1b05c513629271f120 | 638,334 |
def get_vertical_layers_centroids_list(vert_layers):
""" Returns a list with points that are the centroids of the heads of all vertical_layers_print_data. The head
of a vertical_layer is its last path. """
head_centroids = []
for vert_layer in vert_layers:
head_centroids.append(vert_layer.head_c... | ae8757778fd10d68cbc4fade18cb44e51de4d677 | 638,336 |
def read(path, as_single_string=False):
"""Read the file at the path and return its contents as a list or string."""
the_file = open(path, 'r')
if as_single_string:
contents = the_file.read()
else:
contents = the_file.readlines()
the_file.close()
return contents | 968eb1bf955f8f08f172ff8cdbce660d28ba24ea | 638,337 |
def _observed_name(field, name):
"""Adjust field name to reflect `dump_to` and `load_from` attributes.
:param Field field: A marshmallow field.
:param str name: Field name
:rtype: str
"""
# use getattr in case we're running against older versions of marshmallow.
dump_to = getattr(field, 'du... | 727ac76fc21d12ea7ad94e91e19d10747cdf769b | 638,347 |
def remove_duplicates(nonunique):
"""Remove duplicate values in a list.
Args:
nonunique (list) - a list of values
Returns:
a list of the unique values in the nonunique list
Example:
unique_values(['a', 'a', 'b', 'c']) --> ['a', 'b', 'c']
"""
un... | 7da75f4e2e51969fb624bdd2c765017fc03b4f30 | 638,348 |
def is_grayscale(image):
"""
Check if given image is in grayscale color space.
:param image: checked image
:return: result of the check (boolean value)
"""
GRAYSCALE_DIMENSION_COUNT = 2
return len(image.shape) == GRAYSCALE_DIMENSION_COUNT | 010c93f593d39858ba334b9d917a6b411e5077de | 638,349 |
def Dutch_Flag(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
Adapted from https://en.wikipedia.org/wiki/Dutch_national_flag_problem
"""
#Null input
if input_list == None:
... | d8e8219f1e2e2e9dbe633295d053d20f26e43424 | 638,351 |
def get_filepath(video_id):
"""
Returns the filepath of the video in the clevrer directory
Args:
video_id(int): The id of the video obtained from the json
Returns:
filepath(string): the path from the dataset directory to the video
Ex: image_00000-01000/video_00428
"""
... | 4d18c856af09f737856e2d2e57c84115ae51a108 | 638,352 |
from typing import Sequence
def _to_list(scalar_or_iter):
"""Convert scalars and iterables to list.
Parameters
----------
scalar_or_iter : str or list
Returns
-------
list
Examples
--------
>>> _to_list("a")
['a']
>>> _to_list(["b"])
['b']
"""
return (
... | cac99f3ecb2c53965d623e7ac95bd47d3cc7a302 | 638,353 |
def construct_runtime_cache_folder(runtime_cache_prefix, ios_version):
"""Composes runtime cache folder from it's prefix and ios_version.
Note: Please keep the pattern consistent between what's being passed into
runner script in gn(build/config/ios/ios_test_runner_wrapper.gni), and what's
being configured for ... | 2da19c5e184ccbbcab5e39cb5794e6ae973a5ade | 638,356 |
def get_dhl_tweet(df, dhl_acc):
"""
Get Tweets by DHL associated accounts
Parameters
----------
df : pandas.core.frame.DataFrame
Tweets data.
dhl_acc : list
List of Twitter account usernames associated with DHL.
Returns
-------
pandas.core.frame.DataFrame
Fi... | ed2758a4f403e4879cf9ef87b866023fec093512 | 638,357 |
def gen_link(name, visual=None, collision=None):
"""
Generates (as a string) the complete urdf element sequence for a `link`
element. This is essentially a string concatenation operation.
If `collision` is not provided, a duplicate of `visual` will be used
instead.
:param name: Name of the lin... | ad71dd3c739d942451166e680038af437f3f81a5 | 638,362 |
import torch
def compose_projection_matrix(K, M):
"""
Compose intrinsics (K) and extrinsics (M) parameters to get a projection
matrix
"""
return torch.matmul(K[:, :3], M) | f685ae4ed40b2b0d284e8a5750b2c471ce041fde | 638,367 |
def add_ul(text, ul):
"""Adds an unordered list to the readme"""
text += "\n"
for li in ul:
text += "- " + li + "\n"
text += "\n"
return text | 580648ca2a3cc89d43400d331e6e91376adc0a77 | 638,370 |
def gen_var_info(var_names: list,
zip_var_name: str = "uZipVars",
offset_name: str = "offset",
enum_name: str = "VAR",
enum_prefix: str = "U",
use_const: bool = True,
enum_start_idx: int = 0,
enum_var_... | b3da9f3e6298e3e37433023cd4fc90fed8931279 | 638,371 |
from typing import Optional
def next_page_checker(
page: dict
) -> Optional[str]:
"""This is the parser for checking "nextParams" from react page data for automatic paging in get*Iter function.
Arguments:
page (:class:`dict`) : Page data from get(Comments, Posts, etc..)
Returns:
... | 780eaed3f8277bc8839c03474ce10e8a84832d46 | 638,374 |
def merge_tensors(tensor_objects, non_tensor_objects, tensor_flags):
"""
Merge two lists (or tuples) of tensors and non-tensors using a mapping of positions in merged list (or tuple).
Parameters:
tensor_objects (list/tuple): Tensors to merge.
non_tensor_objects (list/tuple): Non-tensors to m... | c727d6a568f1c40a18cc8fbd8c80856e224efdf8 | 638,375 |
import base64
import six
def base64_encode(text):
"""Base 64 encodes the UTF-8 encoded representation of the text. In Python
2 either a byte string or Unicode string can be provided for the text
input. In the case of a byte string, it will be interpreted as having
Latin-1 encoding. In Python 3 only a ... | ae599eff5a3fd51e163cae086b55ceba0b491b24 | 638,376 |
def no_op(*args, **kwargs):
"""
No-op function to serve as default ``get_runtime_attrs``.
"""
return None | 3089a28bd2f913787056f3a5e07ce495928f6f3a | 638,377 |
def computeFraction( poi_messages, all_messages ):
""" compute the fraction of messages to/from a person that are from/to a POI """
fraction = 0
if poi_messages == 'NaN' or all_messages == 'NaN':
fraction = 'NaN'
else:
fraction = float(poi_messages)/all_messages
return fraction | 12acfb8bfdbd82637c16dbca78976516da510bf6 | 638,378 |
def CheckForSize(collection, expected_size, equal_flag, unequal_flag,
unexpectedly_empty_flag=None):
"""Check conditions for collection size.
Args:
collection: A collection can be a list, set or dictionary.
expected_size: The expected size.
equal_flag: The value to return if the collec... | 6efcf98f72a8191cf1e07180de62762ae67a2388 | 638,380 |
def numseqstr(seq, sep=',', fmt='%0.2f'):
"""Takes a number sequence or single number and prints it using the given separator and format."""
def gets(s):
"""Returns a number formatting string using fmt if a number, else str() version"""
try: # number
return fmt % s
except Typ... | 7061e6c0b8fb0b2c1158e58ac111d90802648a8f | 638,384 |
def _increment_list_counter(ilvl2count, ilvl: str) -> int:
# noinspection SpellCheckingInspection
"""
Increase counter at ilvl, reset counter at deeper levels.
:param ilvl2count: context['numId2count']
:param ilvl: string representing an integer
:return: updated count at ilvl.
updates c... | c49887a37de5b5a0ff7177d4414e35fbc5273fb6 | 638,388 |
def merge_dicts(list_of_dicts):
"""Merge multipe dictionaries together.
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
Args:
dict_args (list): a list of dictionaries.
Returns:
dict
"""
merge_dict = {}... | 28c763d1f97a1c0abd84993803620748045b2691 | 638,389 |
from typing import Iterable
def apply_ners(query, ners):
"""
Applies each NER model passed in `ners` on `query`, taking the union set of their predictions.
Ignores various types of entities not useful for the business case.
"""
ignore = ['CARDINAL', 'DATE', 'MONEY', 'ORDINAL', 'PERCENT', 'QUANTITY... | 9d7c6293637ca14e815681a71d3264f5c3a7ef83 | 638,392 |
def get_ids(data):
"""
Extracts dataset IDs.
:param data: The input data
:return: IDs
"""
ids = []
for i in data:
ids.append(i.ID)
return ids | c88bccbab4b3af8038cec20c1413b5ef1e0dedbc | 638,393 |
def _convert_space_to_shape_index(space):
"""Map from `feature` to 0 and `sample` to 1 (for appropriate shape indexing).
Parameters
----------
space : str, values=('feature', 'sample')
Feature or sample space.
Returns
-------
return : int, values=(0, 1)
Index location of th... | 20ec5aad29366929973b2bfa8e503a5bcbbb9a3a | 638,398 |
def next_recipe_digits(cur_recipe):
"""Calculate next recipe, based on the cur_recipe."""
if cur_recipe == 0:
return [0]
digits = []
while cur_recipe > 0:
digits.append(cur_recipe % 10)
cur_recipe = cur_recipe // 10
return digits[::-1] | c97e590a456e1d4e0801035fcc89989a45010738 | 638,399 |
import re
def IsGCESlave(slavename):
"""Returns (bool): Whether |slavename| is hosted on GCE.
Args:
slavename: The hostname of the slave.
"""
# The "-c2" suffix indicates that a builder is in GCE (as opposed to
# in the Chrome Golo, which has a -m2 suffix).
return bool(re.search(r'-c\d+$', slavename)... | 613569120fd4390608ba6173ef3686bb1ef1b01f | 638,400 |
def pesos_ady(grafo,vertice):
"""Dado un grafo y un vertice devuelve un diccionario con los vertices adyacentes
como clave y el peso de la arista como valor"""
diccionario = {}
adyacentes = grafo.ver_a_adyacentes(vertice)
for a in adyacentes:
diccionario[a[0]] = a[1]
return diccionario | ad11e0bd022168c6da8a97f1598a3dd985817b19 | 638,401 |
from typing import Optional
import requests
def get_request(url: str, headers: Optional[dict] = None, params: Optional[dict] = None):
"""Return response if request is successful and in JSON format"""
try:
response = requests.get(url, headers=headers, params=params).json()
except:
return
... | 20cd883b39c6b47d893e78d1aba3eaac508f35e7 | 638,403 |
def get_ncattrs(obj):
"""
Returns ncattrs of a netcdf object as a dictionary
:param obj: Object to collect ncattrs from
:return: dictionary representation of those ncattrs
"""
out = {}
for key in obj.ncattrs():
value = obj.getncattr(key)
if hasattr(value, 'tolist'):
... | 2fdd3d2cf847d1e927b50cf9e9b0d8d997e791c3 | 638,406 |
def trans_ledu(ledu):
"""
Translates the level of education code to a human-readable string
"""
retStr = 'unknown or unsupplied'
if ledu == 'p_se':
retStr = 'Ph.D. in STEM'
elif ledu == 'p_oth':
retStr = 'Ph.D. in non-STEM field'
elif ledu == 'm':
retStr = 'Masters or... | c0b8fe645457f32e87928bbe13d6f28716a5e4ac | 638,411 |
def z_score(data2d, axis=0):
"""Standarize the mean and variance of the data axis Parameters.
:param data2d: DataFrame to normalize.
:param axis: int, Which axis to normalize across. If 0, normalize across rows,
if 1, normalize across columns.
:Returns: Normalized DataFrame. No... | 0e8fc71fad9b4cdb55d6d1a88bf814e80b9598ad | 638,412 |
def boolean(value):
"""Parse the string "true" or "false" as a boolean (case insensitive).
Also accepts "1" and "0" as True/False (respectively). If
the input is from the request JSON body, the type is already a native
python boolean, and will be passed through without further parsing."""
if type(va... | 09a6b313a7f85e8d7d480661c257aea194743db6 | 638,413 |
import re
def _linkify_usernames(text):
"""Slack wants @usernames to be surrounded in <> to be highlighted."""
return re.sub(r'(?<!<)(@[\w_]+)', r'<\1>', text) | 1018503583f47187f84615910d327ab8259afb51 | 638,415 |
def difference(first, other, epsilon=0.005):
"""
Calculate the difference between two dictionaries. The difference is
defined as all the values for the keys that are in both ``dict`` and
``other`` which differ. For floating point numbers, the value ``epsilon``
is used to define difference, so two fl... | 7c3c7d5b06ee8b244e734e37667454600193cc96 | 638,416 |
def cut_lc(df, min=-30, max=150):
"""Short summary.
Parameters
----------
df : Pandas DataFrame
The dataframe containing the photometry of all events.
min : float
The minimum phase (relative to trigger) at which to truncate photometry.
max : float
The maximum phase (rel... | a646b4e354a840c64a27485dd42d458b72c3b28e | 638,419 |
from pathlib import Path
from typing import List
import ast
def tests_from_file(path: Path, base: str) -> List[str]:
"""
Returns all the tests in the given file, in format
expected as arguments when running the tests.
e.g.
file_stem
file_stem.TestFunctionality
file_stem.TestFun... | e21cb2c093357dda35b60298ab95793975dc2359 | 638,421 |
import yaml
def load_repositories(repos_file):
"""
Load repository yaml
"""
if repos_file:
try:
file_descriptor = open(repos_file, 'r', encoding='utf-8')
except IOError as error:
print("Error: open file {} failed", repos_file, error)
return None
... | d3f1ae60407f3c9eeebc9ca5326fa753e166c2ba | 638,425 |
def observations(ax, data, label='Observations', future=False, **kwargs):
"""
Plot observed values.
:param ax: The plot axes.
:param data: The NumPy array containing the observation data.
:param label: The label for the observation data.
:param future: Whether the observations occur after the f... | 8b1bc6c9a618db273bd1afb60fc91325b941f931 | 638,427 |
import torch
def compute_accuracy(predictions, labels):
""" Compute the frequency that the label belongs to the predicted set
Args:
predictions (tensor): a batch of topk predictions with shape [batch_size] or [batch_size, k]
labels (tensor): a batch of labels with shape [batch_size]
... | 9f305af250ea272a9c155c32729dd97aea99b7e2 | 638,430 |
def format_timedelta(time_delta):
"""
Convert a datetime.timedelta to str format
example output: "0h:0m:18s"
Parameters
----------
time_delta: datatime.timedelta
Returns
-------
str: formatted timedelta
"""
d = {}
d["hours"], rem = divmod(time_delta.seconds, 3600)
... | 3d41644991ec558ea423f24d426e62b417fc9b48 | 638,431 |
from typing import Tuple
from typing import Any
def snd(tup: Tuple[Any, Any]) -> Any:
""" Return second member of tuple """
return tup[1] | a24632b572474ea3964d4b35422934ca8a40aaa3 | 638,432 |
def create_grant(grant_create_request): # noqa: E501
"""Create a grant
Create a grant with the specified name # noqa: E501
:param grant_create_request:
:type grant_create_request: dict | bytes
:rtype: GrantCreateResponse
"""
return 'do some magic!' | b0d4fad2a955716173279b14abed6ede4b9cae7f | 638,434 |
def mark_metadata(metadata, subcollection, selposts):
"""
Mark all posts corresponding to the current subcollection criteria.
This is done in the form of a label in the subcollection column.
"""
for post in selposts:
postindex = metadata[metadata.filename == post].index[0]
metadata.s... | 5c978d846d2969c81c67d024a9f7e7cac4c8cff7 | 638,436 |
def charOffsetToTuples(charOffset):
""" Splits a comma separated list of character offsets into tuples of integers.
Keyword arguments:
charOffset -- a string in the format "0-2,5-20"
Returns:
A list of tuples of two integers each
"""
tuples = []
ranges = charOffset.split(",")
f... | 2cebe13228b5142b84118da4e561c39db2137b20 | 638,440 |
def is_empty_line(line):
"""
Returns true if a given line is empty.
str -> bool
"""
return len(line) == 0 | 0286ee5e3968036892e281c2c679f8f56e2e7cdf | 638,444 |
def add_slash(url):
"""Add a slash at the end of URL if the slash is not already presented."""
if url and not url.endswith('/'):
url += '/'
return url | a8011372714807abb0a26215b99100fe26025fac | 638,445 |
def getDayOfMonth(date):
"""Extracts the day of the month from a date. The first day of the
month is day 1.
Args:
date (Date): The date to use.
Returns:
int: An integer that is representative of the extracted value.
"""
return date.day | 53d890d032be2acfea014212df6e8f0ca4eba5f9 | 638,448 |
import csv
def into_dict(fIn,delimiter=","):
"""
Read data from file into a dictionary. By default
first element of each row is assigned to the key
and the second element is assigned to the value.
Parameters
----------
fIn : str
Path to input file
delimeter : str (optional)
... | b73b5ffbf3fae1a16159f06336ff2aca22f0983e | 638,449 |
def _parse_percent(perc):
"""Parse percentile"""
return float(perc[:-1]) / 100 | 43933e8e9a64c8d43d35dd72c590c4e7fabfa455 | 638,450 |
def _escapeArg(arg):
"""Escape the given command line argument for the shell."""
#XXX There is a probably more that we should escape here.
return arg.replace('"', r'\"') | 0b1b125edfb21a95f97e6a20a33691d0ad8d16e3 | 638,451 |
def is_valid_name(name):
"""Checks that GitHub user's name is valid"""
return name and len(name) >= 3 and ' ' in name | 7197c0d420cfcd59eb68337e0933c02f00e9f801 | 638,457 |
def build_call(*args):
"""
Create a URL for a request to the OEC API.
Args:
*args (str): strings to be appended to the API call.
Returns:
str: url for the API request.
"""
call_url = 'https://legacy.oec.world/'
for val in args:
call_url += str(val) + '/'
return ... | 72e305bbb598d7d6ceec60e825363647dfc56bfb | 638,460 |
def get_json(nifti_path):
"""
Get associated JSON of input file
"""
return nifti_path.replace(".nii.gz", ".json").replace(".nii", ".json") | 8afa8ff9e5fcceeacfe4fadaee03589fc1edfc81 | 638,463 |
def add_score_line(line: str, value: str) -> str:
"""
String formatting for scoreboard sidebar
:param line: score text
:param value: score
:return: str - formatted score
"""
base_str = f"{line}{value}".center(20)
return_str = '┃' + base_str[1:-1] + '┃'
return return_str | 7825fc206a9ca57a5c657ca182f21aaf1c4ef87d | 638,468 |
def split_data(test_size, df):
"""
Split data into training and testing sets
INPUT:
test_size - size of testing data in ratio (default = 0.2)
df - cleaned and processed dataframe
OUTPUT:
train - training data set
test - testing data set
"""
test_size = test_size
training_si... | cea724ab0d2a1808c93d8b3beae8d81e0485ebd3 | 638,470 |
def augment_segmentation_map(self, segmentation_map, hooks=None):
"""
Augment a single segmentation map.
Parameters
----------
segmentation_map : (H,W,C) ndarray or (H,W) ndarray
The segmentation map to augment.
Expected dtypes are integer-likes, e.g. int32.
hooks : None or ia.... | af0961f56a12bab724fdb6bfee1d83dfb46176dc | 638,471 |
def seabed2aliased(seabed, rlog, tpi, f, c=1500,
rmax={18:7000, 38:2800, 70:1100, 120:850, 200:550}):
"""
Estimate aliased seabed range, given the true seabed range. The answer will
be 'None' if true seabed occurs within the logging range or if it's beyond
the detection limit of the... | 1bbdcabda760fe99b7d0c8d8fa6ff9b9bfdc8af5 | 638,472 |
import math
def lcm(a, b):
""" Calculate and return lowest common multiple for a and b """
return abs(a*b) // math.gcd(a, b) | a299301b5b046ded49b069fadf315b856c630c99 | 638,474 |
def get_unique_name(obj):
"""
Creates a unique name (hopefully) of producer and product.
"""
return obj['producer'].lower() + "_" + obj['product'].lower().replace('/', ' ') | 0ec40aa0f4e60eba4c1c4b0c0886352ef6ce5bfa | 638,475 |
import hashlib
def hash_sha256(b):
"""
Args:
b (:class:`bytes` or :class:`str`): sequence to be hashed
Returns:
:class:`bytes`: sha256 hash
"""
return hashlib.sha256(
b if isinstance(b, bytes) else b.encode('utf-8')
).digest() | 0a816055069971d6ea1d3f0e698e4e789861abc8 | 638,477 |
def extended_euclidean(a, b):
"""Extended Euclidean algorithm. Return s, t and r such that r = gcd(a, b)
and s * a + t * b = r"""
prev_r, r = a, b
prev_s, s = 1, 0
prev_t, t = 0, 1
while r != 0:
q = prev_r // r
prev_r, r = r, prev_r - q * r
prev_s, s = s, prev_s - q * s
... | 9b4c082cf1e68d70af682bb9ff2ba5e49e3f90b1 | 638,480 |
def sendController(msg, q):
"""Communicate with connected controller
Arguments:
msg {str} -- Message to be sent
q {socket.socket} -- Controller's socket
Returns:
int -- Error Code:
0) Error
1) Success
"""
try:
q.send(msg)
... | f0c27aff3ad54903c0a480754bc304d4bd7a5058 | 638,484 |
from typing import get_origin
def _is_type_alias(obj: object) -> bool:
"""Determines whether the given object is (likely) a type alias."""
return get_origin(obj) is not None | 5b72fecd5869492feb7af7097fca184b1cc05786 | 638,486 |
def get_source_attributes(source):
"""
Retreives a dictionary of source attributes from the source class
:param source:
Seismic source as instance of :class:
`openquake.hazardlib.source.base.BaseSeismicSource`
:returns:
Dictionary of source attributes
"""
return {"id": s... | 78cf144f833e8ae8447545ea0608ecb2aa31bd85 | 638,487 |
import re
def get_column_defaults(table):
""" Extract column default value for each column.
If column lacks default, set default to NULL.
Returns: a map(column_name, default_value)
"""
defaults = dict()
regex1 = re.compile(r'default\s+(\(|"|\')(.*)(?=(\)|"|\'))')
regex2 = re.compi... | cd4f3b4d897d0cfec4d5af887131a7b06b0c9ab6 | 638,488 |
def process_one_file(k, a, filename):
"""Return a set of species over thresholds."""
with open(filename) as f:
f.readline()
species = set()
for line in f:
tkns = [tkn.strip() for tkn in line.split('\t')]
abund, _, _, kmers, _, _, _, rank, taxa_name = tkns
... | ec00bf57d67c9fe0b1b54e9644e32415da7855fc | 638,493 |
from typing import Callable
def custom_color(x: int) -> Callable[[], str]:
"""Return an escape string for a color by it's number.
param:
x:
The color code (between 0 and 255).
returns:
Formatted escape sequence for a color
"""
return lambda: "38;5;" + str(x) + "m" | a423dde11a68a317db77ab1e9f7d17464bc6b919 | 638,494 |
def get_connectors(pipe):
"""Get the connector elements of a pipe."""
connector_set = pipe.ConnectorManager.Connectors
connectors = [connector for connector in connector_set.GetEnumerator()]
assert len(connectors) == 2
return connectors | 0e344844b7371d9227bf62e409d3ddee4b04e84b | 638,496 |
def isControlTimestampChanged(prev, latest):
"""\
Checks whether a new (latest) Control Timestamp is different when compared to a old (previous) Control Timestamp.
Note that this does not check equivalency (if two Control Timestamps represent the same mapping between Wall clock time and content time)
... | 550166b8d8637582edb68a21704c69bc79bce0cc | 638,500 |
def too_big(dataset, start, end, dim = 300, cutoff = 620000):
"""
Calculates if a batch consisting of dataset[start:end] is too big based on cutoff. This can be used for constructing dynamic batches.
"""
sizes = [len(x) for x in dataset[start:end]['embeddings']]
max_size = max(sizes)
dim = dim
... | 881ec1a3376722c5a9e18384b1f46b640178c3ea | 638,503 |
def separate_file_from_parents(full_filename):
"""Receives a full filename with parents (separated by dots)
Returns a duple, first element is the filename and second element
is the list of parents that might be empty"""
splitted = full_filename.split('.')
file = splitted.pop()
parents = splitted... | a074e234c931fa816ca17864af1710e396a5a263 | 638,507 |
def v_sub(v, w):
"""Performs componentwise subtraction on two vectors. Returns a list."""
return [vi - wi for vi, wi in zip(v, w)] | 8014d580553299fbd187e8c8ebe7e5670aa3aec7 | 638,508 |
def generate_filename(blob_name: str, message_index: int) -> str:
"""Strip the file type suffix from the blob name, and append message index."""
fname = blob_name.split("/")[-1]
fname, _ = fname.rsplit(".", 1)
return f"{fname}-{message_index}" | da075bec5b52c429b651ecf87b76d050fc062492 | 638,509 |
def _is_type(t):
"""
Factory for a type checking function of type ``t`` or tuple of types.
"""
return lambda x: isinstance(x.value, t) | 4c2768f0a818b24227e96c705eace42550c8a4f6 | 638,510 |
def calc_diff(prev, curr):
"""Returns percentage difference between two values."""
return ((curr - prev) / prev * 100.0 if prev != 0 else float("inf") *
abs(curr) / curr if curr != 0 else 0.0) | e9f53bca8007157208dd40c265140082817f423f | 638,511 |
def k2e(k, E0):
"""
Convert from k-space to energy in eV
Parameters
----------
k : float
k value
E0 : float
Edge energy in eV
Returns
-------
out : float
Energy value
See Also
--------
:func:`isstools.conversions.xray.e2k`
"""
return ((1... | 2999eedff5135999f4a062c8eb83b0fddea6138f | 638,514 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.