content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def make_desc_dict(ecfp):
"""
Format tuple of fingerprint information into dictionary
:param ecfp: Tuple of fingerprint features and values
:return: dictionary of fingerprint features and values
"""
ecfp_feat, ecfp_val = zip(*ecfp)
return ecfp_feat, ecfp_val | 5925cda8d428fad5c9bfd46a7a26276e34256569 | 34,002 |
def extract_tags(tags):
""" Extract the tag names from tag list"""
return [tag['display_name'] for tag in tags] | 2c07a66ac3ddf1291fd0dab803fd4310c2e80941 | 34,004 |
def get_orders(value):
"""
Return a list of orders for context tiers.
Parameters
----------
value : int or string
The maximum context length or a string in the set "bigram" (for
context 1, and 2), "trigram" (for context 1, 2, and 3), or
"fourgram" (for contexts 1, 2, 3, and ... | 7f473e50a9fbb0ec0927016994367150aee7aa70 | 34,005 |
def clean_env(env):
"""Make a copy of env without game."""
new_env = env.copy()
del new_env["game"]
return new_env | dc7356a271c6f82ba8fe06a600302f6bc1eae963 | 34,008 |
def _num_clips(
duration_sec: float,
fps: float,
stride_frames: int,
window_size_frames: int,
backpad_last: bool = True,
) -> int:
"""
Utility to calculate the number of clips for a given duration, fps, stride & window_size
"""
num_frames = round(duration_sec * fps)
N = num_frame... | f13cec1dd9ced5a4a446b24524646a2e6db3479e | 34,010 |
import csv
def load_review_data(path_data):
"""
Returns a list of dict with keys:
* sentiment: +1 or -1 if the review was positive or negative, respectively
* text: the text of the review
"""
basic_fields = {'sentiment', 'text'}
data = []
with open(path_data) as f_data:
for dat... | e19e51a37007ad308893c190a3629beef9e57f90 | 34,011 |
def days_per_month(leap=False):
"""Return array with number of days per month."""
ndays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if leap:
ndays[1]+= 1
return ndays | e8efeab08bc82344792a3956df91e53767be81c9 | 34,013 |
def linear_annuity_mapping_func(underlying, alpha0, alpha1):
"""linear_annuity_mapping_func
calculate linear annuity mapping function.
Annuity mapping function is model of $P(t, T) / A(t)$
so that it's value is positive.
linear annuity mapping function calculates following formula:
.. math::
... | 3c4f780c8bc90ac2e6e2b3a1f9b930cbd291c9a7 | 34,017 |
def xy_to_wcs(xy, _w):
"""
Convert pixel coordinates (xy) to astronomical
coordinated (RA and DEC)
"""
_radec = _w.wcs_pix2world(xy, 1)
return _radec[:, 0], _radec[:, 1] | 0d82fadee33a783ec6f1f202b74f9e6345ff827e | 34,021 |
def format_month_day(dt, month_fmt="%b"):
"""
Formats the month and day of a datetime
Args:
dt (datetime.datetime): The datetime to be formatted
month_fmt (Optional[str]): The strftime-compatible month format
Returns:
str: The formatted month and day
"""
# NOTE: This fu... | 19e7862e49d998b48b1c2f404e24af4eaf5bf73c | 34,024 |
def capitalize(text):
"""capitalizes a word, for use in rendering template
Args:
text (str): word to capitalize
Returns:
capitalized (str): capitalized word
"""
return text[0].upper() + text[1:] | 63248f2f0477c56ca1032aaefde69dd3398970fd | 34,025 |
def string_to_maya_value(string):
""" Convert a value saved in string to a numerical type understood by maya
"""
if string.isdigit():
return int(string)
if '.' in string or ',' in string:
if string.replace(',', '').replace('.', '').isdigit():
return float(string)
return s... | eeac4948225f496c3ad224f149b7eca2b1572e9e | 34,027 |
def get_arg(*args, index: int):
"""Get the argument at index."""
if args:
return args[index]
return None | 7f0e3ad04affdceb4ed02cb88a79f1c7b00e6ad2 | 34,033 |
import torch
def sqrt(x):
"""Apply sqrt function."""
return torch.sqrt(x) | e6e7421f27ba44dc91d3c2162d6846d2b6427626 | 34,034 |
def check_api_key(tmdb) -> bool:
"""
Checks for the presence of the TMDB API Key.
"""
return False if not tmdb.api_key or "" else True | 8a6c4c59448c761d548de3ba66b089beb814f839 | 34,040 |
from datetime import datetime
def start_and_end_of_the_month(dt: datetime):
"""Get first of month and first of next month for a given datetime.
"""
start = dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
if start.month == 12:
end = start.replace(year=start.year + 1, month=1, day=1... | 9f1001c325d04a4754b666477292788f620596f7 | 34,047 |
def has_any_permissions(user, permissions):
""" Retuns `True` if the user has any of the permissions """
for perm in permissions:
if user.has_perm(perm):
return True
return False | 2de21fcb3f5a4984365185216f45ed2814fd13e4 | 34,053 |
def weighing_function(orig_length, cur_length):
"""
Function to generate the weight value given the predicted text-length and the expected text-length
The intuition is that if the predicted text-length is far from the expected text-length then weight should be
small to that word-bbox.
:param orig_length: Length o... | 09afb649952039e0d7f7b776d43cc0b0307329ee | 34,054 |
def _parse_text_with_command(text: str):
""" Parse string that is passed when bot command is invoked. """
if after_bot_name_text := text.split('</at>')[-1].rstrip().strip():
return after_bot_name_text.split()
else:
return '', [] | 03559b81e696064fee90c8818cb2825a93cbe719 | 34,057 |
from typing import Mapping
from typing import Optional
def _parse_obsolete(obsolete_file_path: str) -> Mapping[str, Optional[str]]:
"""Parses the data file from PDB that lists which pdb_ids are obsolete."""
with open(obsolete_file_path) as f:
result = {}
for line in f:
line = line.strip()
# Fo... | c4e3f3a04d3349d6752d133d079a1bb3aa34e13f | 34,060 |
def compact_date(date):
"""
Converts an ISO 8601 format date string into a compact date.
Parameters
----------
Date: a string date in iso format.
Returns
----------
A string date without hyphens.
"""
return date.replace('-', '') | e377096d2f0ce9404835968627e9b4e3f9d4b252 | 34,062 |
import torch
def calculate_accuracy(inputs: torch.Tensor, targets: torch.Tensor) -> float:
"""
A function that calculates accuracy for batch processing.
Returns accuracy as a Python float.
Args:
inputs (torch.Tensor): shape == [N, n_class]
targets (torch.Tensor): shape == [N]
Ret... | 53eff3901d675370a9ed0f260d1230c2c5badb79 | 34,064 |
import hashlib
def hash100(s: str):
"""
Hash a string into 1~100.
Useful when you split a dataset into subsets.
"""
h = hashlib.md5(s.encode())
return int(h.hexdigest(), base=16) % 100 + 1 | 0686d599e42c104d487462682340f04bd3fe94b4 | 34,069 |
def _get_union_type_name(type_names_to_union):
"""Construct a unique union type name based on the type names being unioned."""
if not type_names_to_union:
raise AssertionError(
"Expected a non-empty list of type names to union, received: "
"{}".format(type_names_to_union)
... | f72f6a5212aa97eba32a3da7249087c97ce471b3 | 34,071 |
def is_clinical_in_cases(clinical_obj, cases):
"""Checks to see if clinical object representation is part of cases to assess
Example:
>>> clin_obj = xml_to_raw_clinical_patient("Test_Data/nationwidechildrens.org_clinical.TCGA-MH-A562.xml")
>>> cases = set(["ad7ba244-67fa-4155-8f13-424bdcbb12e5"... | ecff8e7e4697b0b89f5cf5e45de8e6515e2c0ea9 | 34,072 |
def get_blanks(nrows, ncols, plot_set):
"""Return a list of plot locations that should remain blank."""
assert type(plot_set) == set
nplots = nrows * ncols
plot_numbers = range(1, nplots + 1)
return list(set(plot_numbers) - plot_set) | e2049d16b7ff1f3e5d9d3628881f2574febffe16 | 34,074 |
def _qualified_names(modname):
"""Split the names of the given module into subparts
For example,
_qualified_names('pylint.checkers.ImportsChecker')
returns
['pylint', 'pylint.checkers', 'pylint.checkers.ImportsChecker']
"""
names = modname.split(".")
return [".".join(names[0 : i... | 97c614bbcc0997ab95a8535bf02489291d9d1c11 | 34,075 |
def find_index(x,y):
"""
find the index of x in y, if x not in y, return -1
"""
for index, item in enumerate(y):
if x == item:
return index
return -1 | 2e454c97155bd9d52851a1e20a0c795e8a485a46 | 34,083 |
def get_user_action(message, options):
"""
Reads user input and returns value specified in options.
In case user specified unknown option, returns default value.
If default value is not set, returns None
:param message: The message for user.
:type message: string
:param options: Options ma... | 207e0a64ff1b5e9e638fc449c6782ae3bf3b8f5f | 34,087 |
def byte_pos(text, line, col):
""" Return position index of (line, col)
line is line index, col is column index
The returning byte position __includes__ all '\n's.
Text is unicode.
"""
if type(text) != list:
lines = text.splitlines(True)[:line+1]
else:
lines = text[:line+1... | 8bd545b76569861a0c23d6a23cb70fdfcbad0475 | 34,092 |
import re
import copy
def _select_allowed_items(item_dict, allow_patterns, disallow_patterns):
"""
Creates the dictionary of items selected from `item_dict` such that item names
satisfy re patterns in `allow_patterns` and not satisfy patterns in `disallow_patterns`.
The function does not modify the di... | c56d9b6bf7db0f7a26da42c6da808de8fb8b7341 | 34,096 |
def scale_lr_and_momentum(args, cifar=False, skip=False):
"""
Scale hyperparameters given the adjusted batch_size from input
hyperparameters and batch size
Arguements:
args: holds the script arguments
cifar: boolean if we are training imagenet or cifar
skip: boolean skipping the... | abe65febe2538218db67470b1c2919ae7dd08cb2 | 34,097 |
def _py_lazy_or(cond, b):
"""Lazy-eval equivalent of "or" in Python."""
return cond or b() | 965c831da37e79cc22caaf20bc9edd8677e86be6 | 34,098 |
def get_printable_table(class_name: str, class_info: dict) -> str:
"""
Creates and returns a string displaying the class info in a
format that is easily read in a table.
:param class_name: The name of a class owning the data.
:type class_name: str
:param class_info: The data in the class to dis... | 7734537c4f68df0cc755c51661fd63d5ddb46978 | 34,099 |
def get_geometry_type(gi):
""" Return the geometry type from a __geo_interface__ dictionary """
if gi["type"] == "Feature":
return get_geometry_type(gi["geometry"])
elif gi["type"] in ("FeatureCollection", "GeometryCollection"):
return get_geometry_type(gi["geometries"][0])
else:
... | 6e1292863dd45933c59e84cc465d3ade53248c08 | 34,102 |
def ListToString(alist, useAssert=False):
"""Convert a list of strings into a single string
alist is the list to be converted into a string
if useAssert is True, then the function checks whether all elements of alist are strings before proceeding"""
if useAssert:
assert all([isinstance(x, str) for x in alist]), "... | 29b4329df4f4e97c571240076f7f3571e91f970e | 34,105 |
def is_number_offset(c_offset):
"""
Is the offset a number
"""
return 0x66 <= c_offset <= 0x6f | 6606048314047de7f59e77e01f48e438d4113159 | 34,107 |
def inbound_degrees(adj_list: dict) -> dict:
"""Calculate the inbound degree of each node in a graph.
Args:
adj_list (dict): An adjacency list. Can be from an undirected or directed graph.
Returns:
dict: A dictionary where the key is a graph node \
and the value is the number of in... | 0580e29e4f21dcc33ee6ef74717bda4250dca8c7 | 34,111 |
def sizes (im):
"""
Return the dimensions of an image as a list.
Arguments:
im the image whose dimensions are to be returned
"""
return im.shape | 3bddd044a103b11a7c2e3eef46efb8b83c7f44d6 | 34,113 |
def _range_to_number(bucket_string):
"""Converts "X-Y" -> "X"."""
return int(bucket_string.split('-')[0]) | 1bc40f88cfabec19d8f9e5e14e7de03cec825f58 | 34,114 |
import torch
def compute_input_lengths(padded_sequences: torch.Tensor) -> torch.Tensor:
"""
Parameters
----------
padded_sequences
(N, S) tensor where elements that equal 0 correspond to padding
Returns
-------
torch.Tensor
(N,) tensor where each element corresponds to the... | 44640410704c2118a09b3c0490bc854fde93269a | 34,115 |
def calc_swath_at_nadir_cross(gsd_cross,
pixels_cross):
"""
Calculate the swath at nadir cross track.
https://en.wikipedia.org/wiki/Swathe
Returns
-------
double : meters
"""
return gsd_cross * pixels_cross | c5cdd2f08ea64884624bae6ae0497f850fe7d815 | 34,118 |
def matchAPIProfile(api, profile, elem):
"""Match a requested API & profile name to a api & profile attributes of an Element"""
match = True
# Match 'api', if present
if ('api' in elem.attrib):
if (api == None):
raise UserWarning("No API requested, but 'api' attribute is present with... | 147e8174d57fb05f43869075f7826c9a0fd4d484 | 34,121 |
def _plain_value_to_html(dict_, html=None):
"""Convert plain JSON-LD value to HTML."""
if html is None:
html = []
html.append(dict_['@value'])
return html | 8579318b1ada26e1259550ff925d400bc5c5fa15 | 34,123 |
def angular_velocity(v, r):
"""
Calculates the angular velocity of an
object whose linear velocity is 'v'
and radius of the path traced is 'r'
Parameters
----------
v : float
r : float
Returns
-------
float
"""
return v / ... | f24c43711044d3a3ed5d10b3590eeb19dcd1820e | 34,124 |
def list_neighbors(cfg):
"""List neighbors from config.
Args:
cfg (dict): config from config_load.
Returns:
list: list of string with neighbor names.
Examples:
>>> list_neighbors(cfg)
['192.168.0.2', '192.168.0.1']
"""
return [neighbor["name"] for neighbor in c... | c341ef5aa63fce5bf1f11ea8e615f70037448410 | 34,127 |
from typing import Counter
def CalculateSharedAddresses(symbols):
"""Checks how many symbols share the same memory space. This returns a
Counter result where result[address] will tell you how many times address was
used by symbols."""
count = Counter()
for _, _, _, _, address in symbols:
count[add... | ed7872872e9d538edb08957a5268b6ab21948534 | 34,128 |
def create_dt_hparams(max_depth=None, min_samples_split=2):
"""
Creates hparam dict for input into create_DNN_model or other similar functions. Contain Hyperparameter info
:return: hparam dict
"""
names = ['max_depth','min_samples_split']
values = [max_depth, min_samples_split]
hparams = dic... | 7b0ddc46bdd5ace23402dc8d8f8a338a82c86cf9 | 34,130 |
def sizestr(s):
"""
Parses a CHANNELSxHEIGHTxWIDTH string into a tuple of int.
"""
return tuple(map(int, s.split('x'))) | bc7f21a5340792d5fd85ef9b420562dc39ea2f81 | 34,132 |
def calculate_area_per_pixel(resolution):
"""
Takes a resolution in metres and return the area of that
pixel in square kilometres.
"""
pixel_length = resolution # in metres
m_per_km = 1000 # conversion from metres to kilometres
area_per_pixel = pixel_length**2 / m_per_km**2
return... | 375b376cc9c2104d3298334b718cf51c9bbd23ab | 34,137 |
def exp_transformation(data, orig_col, new_col, power):
"""
Performs feature transformation by raising the indicated feature column to
the given power.
Parameters:
_________________
data: dataframe containing training data
orig_col: (str) column in data to be transformed
new_col: (... | 0fb10d848d3bec1c6a8b2a3a0776a3f0bb501b0d | 34,139 |
import math
def tan(degrees) -> float:
"""Calculate the tangent of the given degrees."""
return math.tan(math.radians(degrees)) | 90d21f4618eed7ac5eefa6a7868f2bc25322e252 | 34,140 |
def transpose(xss):
"""
Transpose a list of lists. Each element in the input list of lists is
considered to be a column. The list of rows is returned.
The nested lists are assumed to all be of the same length. If they are not,
the shortest list will be used as the number of output rows and other ro... | 655465216e3190c9ae08900c8790d46b65be0401 | 34,147 |
import uuid
def generate_uuid_filename(instance, filename):
"""
Generate a uuid filename keeping the file extension.
"""
extension = filename.split(".")[-1]
return "{}.{}".format(uuid.uuid4(), extension) | b7846db99992d019c63b87cbb680d1d0b941dacf | 34,148 |
def convert_bounding_boxes(bboxes):
"""Accepts a list of bounding boxes in format (xmin,ymin,xmax,ymax)
Returns the list of boxes in coco format (xmin,ymin, width, height)
"""
coco_boxes = []
all_tokens = []
for b, tokens in bboxes:
ymin, ymax, xmin, xmax = b
h = ymax - ymin
... | 873adfe784e39cbb4e0bcbd4eca966abc76221dd | 34,149 |
def defval(val, default=None):
"""
Returns val if is not None, default instead
:param val:
:param default:
:return:
"""
return val if val is not None else default | eb945de18a125b3465fb5716df4f87487a5d7205 | 34,152 |
def fixup(ocr_text, pattern):
"""Fix spacing and numerics in ocr text"""
cleaned_pattern = pattern.replace("4", "A").replace("1","l").replace(" ","")
#print(f"{pattern}\t\t{cleaned_pattern}")
#print("{0:<30} {1:<10}".format(pattern, cleaned_pattern))
return ocr_text.replace(pattern, cleaned_patter... | 8aaef7a24a7599a5ddbfc5d3b2af3b6377bbe749 | 34,153 |
def true_text(variable):
"""
Deal with variables that should be True or False even when a string
(defaults to False)
i.e. returns True if variable = True, 1, "True", "T", "t", "true" etc
:param variable:
:return:
"""
# if variable is a True or 1 return True
if variable in [True, 1... | aafd64921aa64d0e2d66e2e429005f91f1e53b9c | 34,156 |
def minimum(evaluator, ast, state):
"""Evaluates "min(left, right)"."""
res = min(evaluator.eval_ast(ast["left"], state), evaluator.eval_ast(ast["right"], state))
return res | c64e9444bff000a2ae73caf6efb717ea6164ad81 | 34,157 |
def pad_list(orig_list, pad_length):
"""
Pads a list with empty items
Copied from http://stackoverflow.com/a/3438818/3710392
:param orig_list: the original list
:param pad_length: the length of the list
:return: the resulting, padded list
"""
return orig_list + [''] * (pad_length - len(o... | 89c2f1d0908fcfaf7fc699bf095e2faff7a7b987 | 34,160 |
import ast
from typing import Any
def json_to_py(json: dict, replace_comma_decimal: bool = True, replace_true_false: bool = True) -> Any:
"""Take json and eval it from strings. If string to string, if float to float, if object then to dict.
When to use? - If sending object as parameter in function.
Args... | f4929ef26ac3d69ad124180dada8994e5873e842 | 34,162 |
def format_quantum_numbers(info: tuple):
"""Takes an expression like
('S', 1, 0, 2, ('3b', 1), ('y', 2/3))
and returns a string like
S(3, 3, 2/3)(3b: 1)
"""
lorentz, su3_up, su3_down, su2, *charges = info
su3_dim = lambda m, n: 0.5 * (m + 1) * (n + 1) * (m + n + 2)
# For now just add... | 6fa8835fdbf4fe3d3c914dec10e12573070b58ad | 34,167 |
def rename_table_clause(old_table, new_table):
""" Create a RENAME table clause string for SQL.
Args:
old_table: The table to be renamed.
new_table: The new table name.
Returns:
A string with the crafted clause.
"""
return 'ALTER TABLE {} RENAME ... | d984cbce2b6c0b3451c8927a61e40fbdbc330c7c | 34,170 |
from typing import List
def median(lst: List[int]) -> float:
"""Takes an ordered list of numbers, and returns the median of the numbers.
If the list has an even number of values, it computes the mean of the two
center values.
Args:
lst - an ordered list of numbers
Returns:
the me... | 830c5122536c73ec154be3e231d1bf54a66d977c | 34,172 |
def get_word_length(word):
""" Returns number of letters in the word
:param word: word
:return: int
"""
return len(word) | 0e9eeca8f3cb35178484575303a4bddae7d08adb | 34,173 |
def split_rowcol(matrix_dim):
"""
Split the input matrix dimensions into row and columns
matrix_dim: String
Input concatenated string with row and column
return: Tuple
Row and column split based on suffix
"""
k = str(0) * 3
M = str(0) * 6
replace_M = matrix_dim.replace('M', st... | e5d27349c0cf9db28841f4bdd6e606257ecd9ca5 | 34,174 |
from typing import List
import glob
def get_html_files(src: str) -> List[str]:
"""Get all the HTML file names in the source directory"""
_html_files = glob.glob(f"{src}/*.html")
return _html_files | 7c8f48166f28eb51dcc6d31ed6bdd9ca25b7218c | 34,177 |
def RGBDimtoRGB(R, G, B, Dim):
""" convert RGBDim to RGB color
:warning: When Dim is 0, no more color component information encoded
:warning: Prefer RGBDimtoHSV function
:param R: red value (0;255)
:param G: green value (0;255)
:param B: blue value (0;255)
:param Dim: brightness value (0.0;1... | c1996c8c27a445f623ef5566497318bf90cd3c97 | 34,179 |
def _format_datetime_for_js(stamp):
"""Formats time stamp for Javascript."""
if not stamp:
return None
return stamp.strftime("%Y-%m-%d %H:%M:%S %Z") | a305c9c64f1ec9de0bd99181f14dedebae8cf940 | 34,182 |
def constrain(value, min_value, max_value):
"""
Constrains the `value` to the specified range `[min_value, max_value]`
Parameters
----------
`value` : The value to be constrained
`min_value` : The lower limit of range (inclusive)
`max_value` : The upper limit of range (inclusive)
Ret... | 230cb07a564f78c75ebe7978e6c3877722efd34a | 34,183 |
def get_news(soup):
"""Gets bs object, returns list of bs object representing the articles in
the news section of the webpage"""
results = soup.find_all("article", class_="clanek col-12 mb-3 mt-3")
return results | c6b55f49f468fd3cf93895cac13bd7a8683de2b9 | 34,185 |
import pickle
def load_ranks_from_file(filename):
"""
Given a pickled rank file, returns ranks and inverse_ranks.
"""
with open(filename, 'rb') as f:
content = pickle.load(f)
return content['ranks'], content['inverse_ranks'] | ff6823241c16bcc5f51dc788366291e47a9c1142 | 34,188 |
import json
def global_extent(tiles):
"""
Compute the global raster extent from a list of tiles
Args:
tiles: list of config files loaded from json files
Returns:
(min_x,max_x,min_y,max_y) tuple
"""
min_x = None
max_x = None
min_y = None
max_y = None
# First lo... | 81e16f22fc1fce75b9583c5037a10d19851097ec | 34,189 |
import yaml
def read_yaml_data(yaml_file):
"""
read yaml file.
Args:
yaml_file: yaml file
Returns:
dict: yaml content of the yaml file
"""
with open(yaml_file, 'r', encoding="utf-8") as file:
file_data = file.read()
data = yaml.safe_load(file_data)
return da... | 225c3caa8a8060eb3eab7af3b2e556dffb4c1a6f | 34,190 |
def get_unique_peptides(peptides:list) -> list:
"""
Function to return unique elements from list.
Args:
peptides (list of str): peptide list.
Returns:
list (of str): list of peptides (unique).
"""
return list(set(peptides)) | 15ad1a70c0bf4269ce2f6d08032b384080e7c655 | 34,191 |
import logging
def get_log_level(ll):
"""Get the logging level from the logging module. Defaults to ERROR if not found.
:param ll: `str` The log level wanted.
:returns: `int` The logging level.
"""
return getattr(logging, ll.upper(), logging.ERROR) | 6fbb3ab5cdbef507faa883121a49a12529008441 | 34,195 |
def date_parser(dates):
"""Date Parser - changes dates to date format 'yyyy-mm-dd'
Parameters
----------
dates: list of dates and times strings in the format 'yyyy-mm-dd hh:mm:ss'
Returns
-------
list:
A list of only the dates in 'yyyy-mm-dd' format.
"""
data_for... | 20a91662129edc38a3bd36ea4f39cd4dcb966ab3 | 34,196 |
def intfloat(x):
"""int . float (for convenience in command-line specification)"""
return int(float(x)) | 9b75d32e209f30415d826ac7ea2e59f7a162cad7 | 34,198 |
def create_health_check(lock):
"""
Return health check function that captures whether the lock is acquired
"""
def health_check():
d = lock.is_acquired()
return d.addCallback(lambda b: (True, {"has_lock": b}))
return health_check | fc77f8c42f271fd98051f91771d99ccc8aec7a9e | 34,199 |
def check_batch_state(state, max_len, pad_token):
"""Check batch of states and left pad or trim if necessary.
Args:
state (list): list of of L decoder states (B, ?, dec_dim)
max_len (int): maximum length authorized
pad_token (int): padding token id
Returns:
final (list): li... | c4b4f16fe71daa61ac6afba4935ae94b51a3516d | 34,200 |
def get_clicked_pos(pos, rows, width):
"""
Identify spot which was clicked on.
Basically we need to find the position of mouse on the screen
in the terms of our grid.
:param pos: position of click from pygame
:param rows:
:param width:
:return:
"""
gap = width // rows
y, x = ... | def409071e95b5a48f287be6d3c7d4e2b7c4adf3 | 34,201 |
def target_label_split(label):
"""
Split a target label into a tuple of it's parts: (fsname, target type, index)
"""
a = label.rsplit("-", 1)
if len(a) == 1:
# MGS
return (None, a[0][0:3], None)
return (a[0], a[1][0:3], int(a[1][3:], 16)) | 58e7333f555712f3a1afffe3d31e35db4bb8c40b | 34,204 |
def _ResolveMsg(msg_type, msg_map):
"""Fully resolve a message type to a name."""
if msg_type in msg_map:
return msg_map[msg_type]
else:
return '[Unknown message %d (0x%x)]x' % (msg_type, msg_type) | b8bd2b9aa29bbb88ee6f70038f5f97cf2bea908e | 34,205 |
def round_digits(
v: float, num_digits: int = 2, use_thousands_separator: bool = False
) -> str:
"""
Round digit returning a string representing the formatted number.
:param v: value to convert
:param num_digits: number of digits to represent v on
None is (Default value = 2)
:param ... | 38873d5dd6d1cee6cf48b9ff2f046e59007822fa | 34,206 |
from typing import Sequence
from typing import Hashable
def filter_dict(src: dict, keys_to_filter: Sequence[Hashable]) -> dict:
"""
Filters dictionary by keys_to_filter set.
Parameters
----------
src: dict
Source dictionary.
keys_to_filter: Sequence[Hashable]
Set of keys that should be in the final diction... | 92ee67c92e07b110122a2adb0b0084991e978415 | 34,208 |
def oct_to_decimal(oct_string: str) -> int:
"""
Convert a octal value to its decimal equivalent
>>> oct_to_decimal("12")
10
>>> oct_to_decimal(" 12 ")
10
>>> oct_to_decimal("-45")
-37
>>> oct_to_decimal("2-0Fm")
Traceback (most recent call last):
...
ValueError: Non-oc... | ef933850d533c499b126d024d1cae1f86944248e | 34,209 |
def crop_image_nparts(input_image, n_parts_x, n_parts_y=None):
"""
Divide an image into n_parts_x*n_parts_y equal smaller sub-images.
"""
# if n_parts_y not specified, assume we want equal x,y
if not n_parts_y:
n_parts_y = n_parts_x
xsize, ysize = input_image.size
x_sub = int(xsize ... | f12e4f1ee85411f1f2b38042d47894f3d8dafda6 | 34,210 |
from typing import Union
from typing import Sequence
def format_as_iter(vals: Union[int, Sequence[int]], iters_per_epoch: int, time_scale: str):
"""Format data to be at iteration time scale.
If values are negative, they correspond to the opposite time scale.
For example if `time_scale="epoch"` and `val=-... | f9971ad6227b497834e4667f101a56c49b71507e | 34,216 |
import math
def deg2rad(degrees):
"""Degrees to radians
"""
radians = math.pi * degrees/180.0
return radians | ffb796655e1181310d222297071187c2865b1d24 | 34,219 |
def get_value(config, key):
"""Get value from (possibly nested) configuration dictionary by using a
single string key as used for the commandline interface (list of keys
delimited by '-' or '_').
"""
keys = key.replace('-', '_').split('_')
for key in keys[:-1]:
config = config[key]
r... | d0ef4c16cb3fb202956c0ab14d8ade843d68d7cc | 34,222 |
import re
def check_domain_valid(submission):
"""
Check if a submission is a valid domain.
:param submission: The submission to be checked
:return: True if 'submission' is a valid domain, otherwise False
"""
return re.match("^([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*(?:\\.[A-Za-z]{2,}))$", submissi... | c6f011242cad39d187cbc723f006ae0cb3087dea | 34,223 |
def compute_chi_eff(m1,m2,s1,s2):
""" Compute chi effective spin parameter (for a given component)
--------
m1 = primary mass component [solar masses]
m2 = secondary mass component [solar masses]
s1 = primary spin z-component [dimensionless]
s2 = secondary spin z-component [d... | ee7d619c282a2d48a68651b896024c3c2e3b4d72 | 34,224 |
def appropriate_partition(distance):
"""Find appropriate partition of a distance into parts.
Parameters
----------
distance : float
Traveled distance in meters
Returns
-------
segment_distance : float
Appropriate length of segments in which we split the total distance
"... | 35d7888166ea416d470e106fbbfc3e07af6671e1 | 34,227 |
import itertools
def all_subsets(A, strict=True, null=True):
"""
Return all subsets of A (list/tuple/etc). If strict is False, result
includes A, if null is True, includes ().
"""
n = len(A)
min = 0 if null else 1
max = n if strict else n + 1
out = []
for m in range(min, max):
... | c26e035d6d1b38c6a6ac153ee883566d8ed513fb | 34,228 |
from typing import Mapping
from typing import Tuple
def mapping_sort_key(prediction: Mapping[str, str]) -> Tuple[str, ...]:
"""Return a tuple for sorting mapping dictionaries."""
return (
prediction["source prefix"],
prediction["source identifier"],
prediction["relation"],
pred... | ce506f536ea2321f7c67b2703cbf09fde9d13275 | 34,232 |
import base64
import hashlib
def compute_md5_for_string(string):
"""Compute MD5 digest over some string payload"""
return base64.b64encode(hashlib.md5(
string.encode('utf-8')).digest()).decode('utf-8') | 6f4af502ec5a14551ba5a22cd7df048ccd7fcc8a | 34,233 |
def fits_identify(origin, *args, **kwargs):
"""Check whether given filename is FITS."""
return (isinstance(args[0], str) and
args[0].lower().split('.')[-1] in ['fits', 'fit']) | 10257681795a4f0979caf33775e700b1666e156a | 34,236 |
def copy_column(column, schema):
"""
Safely create a copy of a column.
"""
return column.copy(schema=schema) | 1842db07939a3d2aee7923e72230819afacd7751 | 34,238 |
def _unembed(tree_list):
"""Unembeds (or deletes) extra spaces at the end of the strings."""
unembedded = []
for line in tree_list:
unembedded.append(line.rstrip())
return unembedded | c692f2f440b88a2a079b48f7ee1928f529136a15 | 34,247 |
def get_py_type(json_type):
"""
Given a JSON type return a corresponding Python type.
If no type can be determined, return an empty string.
"""
if json_type in ("enum", "string", "File"):
return "str"
elif json_type == "boolean":
return "bool"
elif json_type == "array":
... | bf738c5257022019ec26ac89a45ba098e129afcd | 34,252 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.