content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def validate_sample_name(query_name: str, sample_list):
"""
Function will validate the query name with a sample list of defined names and aliases
"""
verified_sample_name = [key for key, value in sample_list.items() if query_name.lower() in value['aliases']]
if verified_sample_name:
return... | e2fe6274a4d543229ce131cf9060ccf1d3833669 | 208,582 |
def compareThresh(value,threshold,mode,inclusive, *, default=False):
"""Returns a boolean only if value satisfies the threshold test. In case of failure of any sort, returns the default value (which defaults to 'False').
Accepted mode values are '<', '>', '<=' and '>='."""
#normalizing input
i... | ea3b4fc683c7940996d42c27962217a1ebec7efe | 664,919 |
import re
def _opts_to_list(opts):
"""
This function takes a string and converts it to list of string params (YACS expected format).
E.g.:
['SOLVER.IMS_PER_BATCH 2 SOLVER.BASE_LR 0.9999'] -> ['SOLVER.IMS_PER_BATCH', '2', 'SOLVER.BASE_LR', '0.9999']
"""
if opts is not None:
li... | 5befb8447bed48a81e339c8811f58765c3c34182 | 133,174 |
def differenclists(list1, list2):
"""
Returns list1 \ list2 (aka all elements in list 1 that are not in list 2)
"""
return list(set(list1).difference(list2)) | c7309f1463eb567851f88016ce2cbeb8aba45fa3 | 189,882 |
def determine_upgrade_actions(
repo, format_upgrades, optimizations, sourcereqs, destreqs
):
"""Determine upgrade actions that will be performed.
Given a list of improvements as returned by ``find_format_upgrades`` and
``findoptimizations``, determine the list of upgrade actions that
will be perfor... | 67aa8ff65e4a795e7feb7fa7296811071592e144 | 497,863 |
def stata_string_escape(text: str) -> str:
"""Escape a string for Stata.
Use this when a string needs to be escaped for a single line.
Args:
text: A string for a Stata argument
Returns:
A quoted string.
"""
new_text = text
new_text = new_text.replace('\n', ' ')
new_tex... | 247f974272a3019fe6d6b8991ad2eb508f717ece | 259,075 |
def _gather_results(tree):
"""Convert the XML tree into a map of pod types to tuples (title, value).
"""
result = {}
for pod in tree.findall('.//pod'):
pod_type = pod.attrib['id']
title = pod.attrib['title']
val = None
for plaintext in pod.findall('.//plaintext'):
... | f4f58c296043772c91dc5a6fd72a070dba7c7f62 | 228,431 |
def find_last_reaction_index(species_reaction_sets, srs_idx):
"""Returns the index in species_reaction_sets where the reaction set at
srs_idx ends.
:param species_reaction_sets: list of species-specific CoMetGeNe reaction
sets
:param srs_idx: index of a reaction set in species_reaction_sets
... | 14f7a9a4c44c74a1f39fb6a9597eaa10bcc64783 | 150,754 |
import re
def _progress_stdout_handler(progress_cb):
"""
:return: stdout handler which looks for percentage done reports
and makes an appropriate call to the progress callback.
The handler uses a regex to look for a 'percentage'
output and calls the progress handler with the number
f... | d8a4446c793e44b30ecd1f261d190c037ea562b6 | 587,673 |
import torch
def cropToFrame(bbox, image_shape):
"""Checks if bounding boxes are inside frame. If not crop to border"""
array_width = torch.ones_like(bbox[:, 1]) * image_shape[1] - 1
array_height = torch.ones_like(bbox[:, 2]) * image_shape[0] - 1
bbox[:, 1:3] = torch.max(bbox[:, 1:3], torch.zeros_lik... | 7bfaff063005c4ac40488f9eaebdebdda722f0d6 | 210,692 |
def calc_ttr(df_ttr):
"""Calculates travel time reliability.
Args: df_ttr, a pandas dataframe.
Returns: df_ttr, a pandas dataframe with new ttr column.
"""
# Working vehicle occupancy assumptions:
VOCt = 1
df_ttr['VOLt'] = df_ttr['pct_truck'] * df_ttr['dir_aadt'] * 365
df_ttr['ttr'] = df... | cee9b22dd1866458dfd7ec849c9dccc20da5c92b | 658,040 |
import json
def get_creds(file):
"""
Loads simple json file stored elsewhere with credentials.
See the sample_creds.json folder for the expected format.
:param file: json file containing key/value cres
:return:
client_id, client_secret, user_agent for Reddit api
"""
file = "E:/... | 9e70fc000f65992045971543cf99511280105ebb | 195,460 |
def clip(s, n=1000):
""" Shorten the name of a large value when logging"""
v = str(s)
if len(v) > n:
v[:n]+"..."
return v | b6a56d2fcab1a99371acf9d28847e0de9f717338 | 424,725 |
def has_tag(tags, target) -> bool:
"""
Verifies that the `target` tag is present in a query set.
@param tags: tags to be checked
@param target: the tag searched for
@return: True if the target is present, False otherwise
"""
for tag in tags:
if tag.tag == target:
return T... | a6e46b7e09aa61fe4f2d6ebe2dcb3f8aad14964e | 501,127 |
import math
import torch
def log_prob_standard_normal(x):
"""
Computes the log-probability of observing the given data under a (multivariate) standard Normal
distribution. Although this function is equivalent to the :code:`log_prob` method of the
:class:`torch.distributions.MultivariateNormal` class, ... | 3560b5f95648fa3009b562021e6fc8612b681c37 | 168,510 |
def print_time(time):
"""Format a datetime object to be human-readable"""
return time.astimezone(tz=None).strftime('%m/%d') | d75deefac5f2326637fe73757b8baee95d0ac42b | 684,879 |
from datetime import datetime
def date_check(y, m, d):
"""Ensure that a date is valid."""
try:
test = bool(datetime.strptime(f"{y}{m}{d}", "%Y%m%d"))
except:
test = False
return test | 5816510baffb4dba7c736a261cff2d7ba259f908 | 410,171 |
def moeda(n=0, moeda='R$'):
"""
-> Formata os valores monetários
:param n: (opcional) Valor a ser formatado
:param moeda: (opcional) Moeda a ser utilizado na formatação
:return: Valor 'n' formatado
"""
return f'{moeda}{n:.2f}'.replace('.', ',') | 8205cb444b9592cb1f2fce2ca0db7a5d4119bc18 | 403,389 |
def add_right_title(ax, title, **kwargs ):
"""Add a centered title on rigth of the selected axis.
All :func:`~matplotlib.Axes.annotate` parameters are
accessible.
:param ax: Target plot axis.
:type ax: :class:`~matplotlib.Axes`
:param str title: Title text to add.
:return: :class:`~matplo... | 64839e785945c473b9bfb08d276dc209ff45ce90 | 207,174 |
import json
def read_notebook(file, store_markdown= False):
"""Reads a notebook file and returns the code"""
code = json.load(open(file))
# file = getBaseNameNoExt(file)
py_file = "" # open(f"{file}.py", "w+")
for cell in code['cells']:
if cell['cell_type'] == 'code':
for lin... | 1a5ff7073be822dd5db972389384277d6b552ad8 | 313,328 |
import re
def get_valid_filename(s):
"""Sanitize string to make it reasonable to use as a filename.
From https://github.com/django/django/blob/master/django/utils/text.py
Parameters
----------
s : string
Examples
--------
>>> print get_valid_filename(r'A,bCd $%#^#*!()"\' .ext ')
... | a8161a16d0bd8ad0c5d9ff20c56b52fbdba2d859 | 701,397 |
def alert_data_to_xsoar_format(alert_data):
"""
Convert the alert data from the raw to XSOAR format.
:param alert_data: (dict) The alert raw data.
"""
properties = alert_data.get('properties', {})
formatted_data = {
'ID': properties.get('systemAlertId'),
'Kind': alert_data.get('... | fdffb0016cc49fe0240cacfcc7735bf7f09404b4 | 509,431 |
def read_labeled_image_list(image_list_file):
"""Reads a .txt file containing pathes and labeles
Args:
image_list_file: a .txt file with one /path/to/image per line
label: optionally, if set label will be pasted after each line
Returns:
List with all filenames in file image_... | 7541c3db7bfa6bc9697b541fbe925b53c989b959 | 335,725 |
from typing import Dict
from typing import Any
def dict_argmax(d: Dict[Any, Any]) -> Any:
""" Compute argmax for a dictionary with numerical values. """
argmax = None
best_val = None
for arg, val in d.items():
if argmax is None or val > best_val:
argmax = arg
best_val ... | 163fef049713645711228624fe98a81bdef3bdac | 455,298 |
def subset_by_iqr(df, column, iqr_mult=3):
"""Remove outliers from a dataframe by column, including optional
whiskers, removing rows for which the column value are
less than Q1-1.5IQR or greater than Q3+1.5IQR.
Args:
df (`:obj:pd.DataFrame`): A pandas dataframe to subset
column (st... | ee34ca064c605fe1c1ff36131c8351dfe95321ef | 637,290 |
def chars_different(box1, box2):
"""Count the number of characters that differ between box1 and box2"""
diff = sum(
1 if i != j else 0 for i, j in zip(box1, box2)
)
return diff | b9cfa5ba9a97bb48e60c46918953b1daba6d2f61 | 585,099 |
def _leading_space_count(line):
"""Return number of leading spaces in line."""
i = 0
while i < len(line) and line[i] == ' ':
i += 1
return i | b28daa2845618df5030a79129bb7cec1167b149a | 3,089 |
def by_time(elem):
"""
Returns associated times field of elem (elem assumed to be an instance of SPATLocation.
"""
return elem.times | 25f1230a3adfa0e43b3940cca32b596801ce2234 | 545,378 |
def find_pivot(unsorted, start, end):
"""
Find the pivot value using the Median of Three method in a Python list
Expected Complexity: O(1) (time and space)
:param unsorted: an unsorted Python list to find the pivot value in
:param start: integer of starting index to find the pivot value in
:par... | 2a27ac28f60e46011d086d329b5ab32461f4d801 | 145,142 |
def findpower2(num):
"""find the nearest number that is the power of 2"""
if num & (num-1) == 0:
return num
bin_num = bin(num)
origin_bin_num = str(bin_num)[2:]
near_power2 = pow(10, len(origin_bin_num))
near_power2 = "0b" + str(near_power2)
near_power2 = int(near_power2, base=2)
... | 14f32842d94ffbb5eb4ef4be70fcbf006a7854dd | 388,505 |
def to_gradepoint(grade):
# write an appropriate and helpful docstring
"""
convert letter grades into gradepoint
:param str grade: A, A-, B+, B, B-, C+, C, C-, D, F
:return: float
"""
gradepoint = 0 # initial placeholder
# use conditional statement to set the correct gradepoint
gradepoint = 4 if grade... | 47dd2f053de0f456f642c8391c92346e36d9b943 | 320,382 |
import random
def _random_selection(*args):
"""
Random selection for the genetic algorithm.
This function randomly removes a solution from the population and returns it.
:param args: list where args[0] is the population
:rtype: Solution
:returns: a solution from the population
"""
r... | b428be98a4d0b3beeee277194b5d749fcae7bfcc | 339,476 |
def align_bbox(src, tgt):
"""
Return a copy of src points in the coordinate system of tgt by applying a
scale and shift along each coordinate axis to make the min / max values align
Inputs:
- src, tgt: Torch Tensor of shape (N, 3)
Returns:
- out: Torch Tensor of shape (N, 3)
"""
sr... | a0805a012914460b625537c6fdb84770fe6a326c | 264,230 |
def is_mark(codepoint):
"""Returns true for diacritical marks (combining codepoints)."""
return codepoint.general_category in ("Mn", "Me", "Mc") | 8fb84f7a1b39fa1ce6504a31f6cc902b2d4ab7c8 | 602,825 |
def PZapTable (inUV, tabType, tabVer, err):
""" Destroy specified table
Returns 0 on success
inUV = Python UV object
tabType = Table type, e.g. "AIPS AN"
tabVer = table version, integer
err = Python Obit Error/message stack
"""
###########################################... | b927cabfac51353bc44ea693d4dc7b8687fa6d4e | 600,071 |
import socket
def is_port_open(port_num):
""" Detect if a port is open on localhost"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return sock.connect_ex(('127.0.0.1', port_num)) == 0 | 8ee5e4674a2c4444448208d0e8194809665c8014 | 688,584 |
from functools import reduce
def deepgetattr(obj, attr, default=None, raise_if_missing=False):
"""Recurses through an attribute chain to get the ultimate value."""
if isinstance(attr, str):
attr = attr.split('.')
try:
return reduce(getattr, attr, obj)
except AttributeError:
if ... | d7d6080277af6f9b00b7717f41135c838a3b7af9 | 568,390 |
def sign(value):
"""
Returns an integer that indicates the sign of a number.
Parameters:
value (int): The number to get the sign of
Returns:
-1 if the number is negative, 0 if the number is 0, or 1
if the number is positive.
"""
if value < 0:
return -1
elif... | 71997a571fcdbadf45fa1dd3b8d2b6c54eafdd61 | 43,652 |
def inp_replace_token_value(lines,token,replace):
"""replace the value of a token in a list"""
if type(lines)!=list:
return False
replaced=False
for i in range(0, len(lines)):
if lines[i]==token:
if i+1<len(lines):
lines[i+1]=replace
replaced=True
break
return replaced | 22c50ee9dad7b3f85b339260d6d4b75c37f0efc9 | 282,866 |
from sympy.ntheory import primefactors
def A001221(n: int) -> int:
"""omage(n).
Number of distinct primes dividing n.
"""
return len(primefactors(n)) | a8ffa15d07da753846b37963dc348b5f7ea1d05d | 460,152 |
def escape_leading_slashes(url):
"""
If redirecting to an absolute path (two leading slashes), a slash must be
escaped to prevent browsers from handling the path as schemaless and
redirecting to another host.
"""
if url.startswith('//'):
url = '/%2F{}'.format(url[2:])
return url | 108ce47cd51550d5d847f54ea0b88c83eeae8e24 | 381,276 |
import re
def get_lines_with(input_list, substr) -> list:
"""
Get all lines containing a substring.
Args:
input_list [str]: List of string to get lines from.
substr (str): Substring to look for in lines.
Returns:
lines [str]: List of lines containing sub... | d7562fc3cd8d830279eeedbf421b515d1a7c2ce2 | 488,077 |
def compare_h(new, high):
"""
Compare the latest temperature with the highest temperature.
If higher, replace it. If not, remain the same.
:param new: Integer, new!=EXIT, The lasted temperature input
:param high: Integer, high!=EXIT, the highest temperature of all time
:return: high
"""
if new > high:
high =... | b665cd2cb724d8ddaa95f0ce61f00a9265331543 | 430,950 |
def inclusion_one_param_from_template(arg):
"""Expected inclusion_one_param_from_template __doc__"""
return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg} | 9c4e4f842faaf87f7d328515fbe96ef9d1be2208 | 623,431 |
def is_valid_bbox(rect):
"""Left/top must be >= 0, W/H must be > 0"""
return rect[0] >= 0 and rect[1] >= 0 and rect[2] > 0 and rect[3] > 0 | 8e0661482172e6ca4fc71ae5596903ece69ff570 | 584,081 |
import random
def _shuffle(x):
"""
Shuffles an iterable, returning a copy (random.shuffle shuffles in place).
"""
x = list(x)
random.shuffle(x)
return x | 662627b2b4ae79f630c975cdb8d86837524579ab | 67,677 |
def get_command() -> str:
""" __author__ = "Trong Nguyen"
Prompt the user for a valid command and return the command input as
uppercase.
>>> get_command()
"""
command = input(
"L)oad image S)ave-as"
"\n2)-tone 3)-tone X)treme contrast T)int sepia P)osterize"
... | c8573f03bf2383d5ef6856ff71087b33bb5babb9 | 267,363 |
import inspect
def is_static_method(klass, name: str) -> bool:
"""
Check if the attribute of the passed `klass`
is a `@staticmethod`.
Arguments:
klass: Class object or instance to check for the attribute on.
name: Name of the attribute to check for.
Returns:
`True` if the... | 5ee84883d6ad52b6c0dd69f7123f80fd553313ea | 688,732 |
def bend_stress(mom, y, i):
"""
bend_stress(mom, y, i)
Returns the bending stress given the applied moment, distance to the
centroid, and moment of inertia.
"""
return mom * y / i | 76f5d2f8120d355c69995b5e7edc1f4258084d33 | 453,871 |
import torch
def calc_parameter_sparsity(p):
"""Calculates the sparsity percentage of a torch parameter.
Args:
p: torch parameter
Returns: sparsity percentage (as float) with range [0.0, 1.0]
"""
x = torch.sum((torch.flatten(p) == 0).float())
return float(x) / p.numel() | 3f4a7c171c5dd68d7e5040430fc74a0d529ab458 | 223,655 |
def _args_or_none(arg):
"""Return None if the arg is 'None' or the arg."""
if arg == 'None':
return None
return arg | ffcd8995b97269a4367f1b41bbae54c0e98aa5c1 | 283,222 |
def special_structures(input_string):
"""
Replace some special structures by space.
"""
input_string = input_string.replace("'", " ")
input_string = input_string.replace("(", " ")
input_string = input_string.replace(")", " ")
input_string = input_string.replace("1er ", " ")
input_string ... | b15b289ee36ea21a61db908e42876ed3b3135e34 | 189,528 |
import itertools
def get_subsets(itemset, length):
""" Gets subsets of an itemset with the specified length.
:param itemset: Set of items
:param length: Length
:return: list of sets
"""
tuple_list = list((itertools.combinations(itemset, length)))
set_list = []
for element in tuple_lis... | 908d22fe9876b505137e642ff8566b497772d9db | 395,336 |
def nonneg(s):
"""Returns all non-negative values."""
return filter(lambda x: x>=0, s) | 3cbdf9ee64be450143ca28418613514f3b11e0ca | 508,802 |
def join_rows(row_list_1, row_list_2):
"""Returns a list of list, in which element is the concatenation of the
elements in the same position of row_list1 and row_list."""
if not row_list_1:
return row_list_2
if not row_list_2:
return row_list_1
row_list = []
for (row1, row2... | 0d414e66e9959250b88f5419355616d128759bd5 | 219,475 |
def _calculate_PSF_amplitude(mag):
"""
Returns the amplitude of the PSF for a star of a given magnitude.
Parameters
----------
`mag`: float
Input magnitude.
Returns
-------
amp : float
Corresponding PSF applitude.
"""
# mag/flux relation constants
amp = 10*... | dea6bfb12bfbd548dad4512194b7e3d08b761adc | 464,627 |
def girder_job(title=None, type='celery', public=False,
handler='celery_handler', otherFields=None):
"""Decorator that populates a girder_worker celery task with
girder's job metadata.
:param title: The title of the job in girder.
:type title: str
:param type: The type of the job in ... | 789c5e97cac2676731eaddeae15a3469d6cd0030 | 440,515 |
import time
def format_time(timestamp=None, format=r"%Y%m%d-%H%M%S"):
"""
Return a formatted time string
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock)... | 91486e08e9c21b36cfbdd7303bf99b4c5b1f78ed | 528,636 |
def min_rotation(target_degrees, source_degrees):
"""
Return the smallest rotation required to move
from source angle to target angle::
min_rotation(20, 10) => 10
min_rotation(-340, 10) => 10
min_rotation(20, 370) => 10
"""
return (target_degrees - source... | 8e60a325ff6a169458f7f425e06e080552f5039b | 276,344 |
def coerce_tuple(item):
"""Return item converted to tuple if not already tuple.
:param Union[str, IKey, Iterable] item: item to coerce to tuple.
:returns: coerced value of item as tuple.
:rtype: Tuple[Any].
.. Usage::
>>> coerce_tuple('test')
('test',)
>>> coerce_tuple(('... | b6b0ed565562f37f596cf0aa148bb59d9416d9bb | 606,881 |
def int_to_rgb(rgb_int):
"""
Given an integer, converts to to RGB value. Any integer outside
the range of (0, 16777215) will raise an invalid
>>> int_to_rgb(-1)
Traceback (most recent call last):
...
ValueError: Integer must be in range [0, 16777215], got -1.
>>> int_to_rgb(0)
(0, 0,... | c23eef48c564dcb18eec81c1890add55d77fd3a5 | 619,346 |
import itertools
def SplitNone(l):
"""Split a list using None elements as separator.
Args:
l: a list which may contain some None elements.
Returns:
A list of non-empty lists, each of which contains a maximal
sequence of non-None elements from the argument list.
"""
groups = itertools.groupby(... | 794eccdb6764b6d607e415ea9eab146e0dc0e947 | 573,893 |
import importlib
def class_from_str(str_class):
"""
Imports the module that contains the class requested and returns
the class
:param str_class: the full path to class, e.g. pyspark.sql.DataFrame
:return: the class requested
"""
split_str = str_class.split('.')
class_name = split_str[... | 7571feb9a7d8dca332554c7fcacdb513c3b8e6de | 145,395 |
def _expand_total_pairs(total_pairs):
"""Expands total_pairs so that it has one key per direction.
e.g., 'breitbart-foxnews' and 'foxnews-breitbart' exist as keys.
If expansion is skipped, then total_pairs only has one key per pair of (unordered) elements.
e.g., 'breitbart-foxnews' exists as a key but ... | 74aa6b0475061a480b2a3c098e0cf7f981aa6221 | 409,930 |
def count_rounds(half):
"""
Counts how many rounds were won in the half.
"""
rounds = 0
for img in half.find_all("img"):
if not "emptyHistory.svg" in img["src"]:
rounds += 1
return rounds | 1e80018ae944746783c51e9e58725ef6ce470f86 | 455,440 |
def format_tag(template, tag_name, attrs):
"""
Format a template of a tag with attributes, so that:
>>> format_tag('<{} {}>', 'span', {'id': 'foo'})
>>> '<span id="foo">'
Note: use `klass` instead of the `class` attribute.
"""
return template.format(tag_name, ' '.join(['{}="{}"'.format(key.r... | 195e8fc1d88f1a2ccdae557ba578e22e91ec942f | 249,604 |
def lookup_expr(collection, key):
"""
Lookup a value in a Weld vector. This will add a cast for the key to an `I64`.
Examples
--------
>>> lookup_expr("v", "i64(1.0f)").code
'lookup(v, i64(i64(1.0f)))'
>>> lookup_expr("[1,2,3]", "1.0f").code
'lookup([1,2,3], i64(1.0f))'
>>> lookup_e... | 4bb0d46dc1bc3f6cc206634ea5d5c03167d564c7 | 293,927 |
from typing import List
def fill(index: int, item: float, length: int) -> List[float]:
"""
Make an array that contains `length` 0s, but with the value at `index` replaced with `item`.
"""
a = [0.0 for _ in range(length)]
a[index] = item
return a | bee2c15fc844eae32344b44a7767ce2445e24e90 | 488,325 |
def starts_with_five_zeros(md5_hash: str) -> bool:
"""Whether the given md5 hash starts with five zeros."""
return md5_hash.startswith('00000') | e004fde4485dfddb4d9062dc9b786ce59ae3dbdc | 561,409 |
def _ReplaceVariables(data, environment):
"""Replace all occurrence of the variable in data by the value.
Args:
data: the original data string
environment: an iterable of (variable name, its value) pairs
Returns:
the data string which replaces the variables by the value.
"""
result = data
for ... | 480774fe48844d02a9a74cf2211bd262d9bda150 | 453,831 |
def read_experiment_lines(readme_lines, start_marker_a="TGA",
start_marker_b="###", end_marker="###"):
"""
This function iterates over a list of strings and searches for information
about a desired experiment. The information is found by looking for
sub-strings (markers) that e... | e80cd6213ba703f970db8f9b6b42704c179c4fdd | 39,985 |
import math
def A000108(i: int) -> int:
"""Catalan numbers: C(n) = binomial(2n,n)/(n+1) = (2n)!/(n!(n+1)!).
Also called Segner numbers.
"""
return (
math.factorial(2 * i)
// math.factorial(i)
// math.factorial(2 * i - i)
// (i + 1)
) | bfc0b3b23fd758fb0ff43936c525c7b5c24dfd6f | 328,938 |
def getFileInfo(filename: str):
"""Get file information from filename.
Parameters
----------
filename : str
Filename of CSV file
Returns
-------
date : str
Date of the file
time : str
Time of the file
folder : str
Measurement folder of the file
f... | da81360d7425e27c67465cacbaaf096d6fae7d55 | 609,677 |
def point_within_bounds(x,y, bounds):
"""
Function for checking if a point is within a bounds
from a raster
:param x: x-coordiante
:param y: y-coordinate
:param bounds: raster bounds
:return:
boolean
"""
if (bounds.left < x) & (bounds.right > x):
if (bounds.bottom < y) &... | 9b9fe6a76ef1eb8dd039de2ca8bc2e8fef2f5a6e | 435,652 |
def name_generator(nn_name, nn_name2id):
""" 生成paddle.nn类op的名字。
Args:
nn_name (str): 名字。
nn_name2id (dict): key为名字,value为名字出现的次数-1。
"""
if nn_name in nn_name2id:
nn_name2id[nn_name] += 1
else:
nn_name2id[nn_name] = 0
real_nn_name = nn_name + str(nn_name2id[nn... | a1788af5a9df1618d161ce725ab7839405faef66 | 595,997 |
def stringify_list(list_: list,
quoted: bool = False
) -> str:
"""Converts a list to a string representation.
Accepts a list of mixed data type objects and returns a string
representation. Optionally encloses each item in single-quotes.
Args:
list_: The li... | 7f390283de9ee6c136cb4eedff561a505522e58d | 306,306 |
def rename_modified_residues(mol):
"""
Renames residue names based on the current residue name, and the found
modifications. The new names are found in
`force_field.renamed_residues`, which should be a mapping of
``{(rename, [modification_name, ...]): new_name}``.
Parameters
----------
... | 4b9eee42e071fb42b7cde5d647fb497eb4ca3730 | 478,339 |
import socket
def resolve_fqdn_ip(fqdn):
"""Attempt to retrieve the IPv4 or IPv6 address to a given hostname."""
try:
return socket.inet_ntop(socket.AF_INET, socket.inet_pton(socket.AF_INET, socket.gethostbyname(fqdn)))
except Exception:
# Probably using ipv6
pass
try:
... | 2e7680fe3a4ea174f3f7b22e4991a3a65e5e4995 | 29,516 |
async def check_tags(problem_tags, tags):
"""
To check if all tags are present in the problem tags.
"""
count = 0
for tag in tags:
if "'" + tag + "'" in problem_tags:
count += 1
return count == len(tags) | ad757eadbc7cd74854901a1da55a5f941dbec668 | 386,035 |
import json
def jsonRead(path):
"""Abre un archivo JSON y devuelve los datos del archivo.
Argumentos:
path (str): Ruta relativa hacia el archivo.
Returns:
data (Any): Datos contenidos en el JSON.
"""
with open(path) as json_file:
try:
data = json.load(json_f... | 5be4df247b253c53ab8c555fd61ffd1f3353b555 | 414,125 |
import glob
def get_bridges(vnic_dir='/sys/devices/virtual/net'):
"""Return a list of bridges on the system."""
b_regex = "%s/*/bridge" % vnic_dir
return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)] | 685ffe3ccae18306c49eb4091c360e966674e606 | 653,850 |
from datetime import datetime
def isdate(s_date: str, if_nan=False):
"""Check whether the date string is yyyymmdd format or not."""
if len(s_date) != 8:
return False
try:
datetime.strptime(s_date, "%Y%m%d")
return True
except ValueError:
return False
except TypeErro... | f11e6ea3387a99dbe905c6dee249365074f2bd10 | 262,771 |
def _get_lines(filepath):
""" Given a filepath, return a list of lines within that file. """
lines = None
with open(filepath) as file:
lines = file.readlines()
return lines | 5762459d6455c3133936fe4dda93059d3e9d17eb | 248,331 |
def _calculate_padding(kernel):
"""
Calculate padding size to keep the output matrix the same size as the input matrix.
Parameters
----------
k: ndarray
Convolution kernel
Returns
-------
out: tuple of tuple of int
(row_pad_count_top, row_pad_count_bottom), (col_pad_cou... | 8636975a6aaaeb18f52d547d213f70d94d6aca0c | 333,038 |
def cents_to_hz(F_cent, F_ref=55.0):
"""Converts frequency in cents to Hz
Notebook: C8/C8S2_FundFreqTracking.ipynb
Args:
F_cent (float or np.ndarray): Frequency in cents
F_ref (float): Reference frequency in Hz (Default value = 55.0)
Returns:
F (float or np.ndarray): Frequency... | c73c67bb931d07743ee3b53a662485924b0c3f56 | 45,816 |
def ident(tensor_in):
"""
The identity function
:param tensor_in: Input to operation.
:return: tensor_in
"""
return tensor_in | 9ae521af8ab501e3b5694af9325f3dc2a9ed399f | 460,951 |
def evaluate_coefficients(coefficients,x):
"""Take a list of coefficients and return the corresponding polynomial evaluated at x-value x
"""
return sum(pair[1]*(x**pair[0]) for pair in enumerate(coefficients)) | b46bce35f4275c71f8f1f7ab59d5fee3e6a58b55 | 542,766 |
def integrate(x_dot, x, dt):
"""
Computes the Integral using Euler's method
:param x_dot: update on the state
:param x: the previous state
:param dt: the time delta
:return The integral of the state x
"""
return (dt * x_dot) + x | b2cc59a953f28b4ce8ceecf3dd154b98c34aa274 | 532,761 |
def merge(d1, d2):
"""Merges d2 into d1 without overwriting keys."""
left = d1.copy()
right = d2.copy()
for key in right.keys():
if key in left:
left_is_dict = isinstance(left[key], dict)
right_is_dict = isinstance(right[key], dict)
if left_is_dict and right... | 568254522547b47687cdfaab54bfc21e0b535f93 | 665,456 |
def _format_links(link_x):
"""
Format links part
:param link_x: list, which has several dicts in it
:return: formatted string
"""
try:
pairs = ""
for _dict in link_x:
pairs += _dict['rel'] + '-> ' + _dict['href'] + '\n'
return pairs[:-1]
except Exception:... | ea47e3c9d509dc127ae9089c0b410702e1f58a57 | 96,797 |
def condition_flush_on_every_write(cache):
"""Boolean function used as flush_cache_condition to anytime the cache is non-empty"""
return len(cache) > 0 | 5fa7d2d7a43e510fae7ebe545e973f7ab3831666 | 293,056 |
def ensure_dict(x):
"""Make sure ``x`` is a ``dict``, creating an empty one if ``x is None``.
"""
if x is None:
return {}
return dict(x) | 35eb7b7c2e7be7bd5630135d5a803790d8c5589e | 189,622 |
def __get_node_types(args: dict):
"""
Given the parsed arguments, returns a dictionary of flags
representing the node types to be processed
:param dict args: dictionary of parsed args
:return: dictionary of node types
"""
out = dict(pose=False, hand=False, face=False)
# check if only fac... | 7b4e72d1e9747654201a6b3ad2b17d9cef37a66e | 215,407 |
import re
def regex_escape(string: str) -> str:
"""Escape the given string for use as a regex."""
return re.escape(string) | 7ac2d1c7a8dd3eeeb9f907c39757f7a936e735f9 | 247,793 |
def sequence(left_validator, right_validator):
"""Given two validators, attempt to validate the first
If successful, attempt to validate with the second
"""
def callback(value):
"""Accept a value to validate, return validation results"""
okay, result = left_validator(value)
if ok... | e0a89f1a1a4f78ccd545ce3b78e8f02fa46e4ff5 | 191,345 |
def get_valid_classes_phrase(input_classes):
"""Returns a string phrase describing what types are allowed
"""
all_classes = list(input_classes)
all_classes = sorted(all_classes, key=lambda cls: cls.__name__)
all_class_names = [cls.__name__ for cls in all_classes]
if len(all_class_names) == 1:
... | 8361ad8bfc43c882d4cdc7f08707a0c948230ca0 | 283,825 |
import random
def mutate_guess_i(old_guess, i):
"""randomly mutate single element in string"""
ls_old_guess = list(old_guess)
rand_value = str(random.randint(0, 9))
ls_old_guess[i] = rand_value
return ''.join(ls_old_guess) | 9116f87d9f9a85017fafffe55a5ae640cce13eb7 | 90,567 |
def page_query_with_skip(query, skip=0, limit=100, max_count=None, lazy_count=False):
"""Query data with skip, limit and count by `QuerySet`
Args:
query(mongoengine.queryset.QuerySet): A valid `QuerySet` object.
skip(int): Skip N items.
limit(int): Maximum number of items returned.
... | 2aef61019b67f2d9262ad8f671a9991e0915ddcf | 672,272 |
def ensure_leading_slash(path: str) -> str:
"""
Ensures that the given path has a leading slash.
This is needed as mock paths are stored in the database with a leading slash, but flask passes the path parameter
without one.
"""
if path[0] != "/":
return "/" + path
return path | 8f059b4d420ba7409993c2c324a302e993d2259a | 94,730 |
def get_dtype_str(dtype, byteorder="little"):
"""Parses dtype and byte order to return a type string code.
Parameters
----------
dtype : `numpy.dtype` or `str`
Either a dtype (e.g., ``numpy.uint32``) or a string with the type code
(``'>u4'``). If a string type code and the first charact... | 01c19b606abdd7a641384b5564c520cdfe5b6a02 | 456,583 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.