content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def func(x, a, b, c):
"""
Second degree polynomial function of the form
f(x) = ax^2 + bx + c
:param x: input variable
:param a: second deg coeff
:param b: first deg coeff
:param c: zeroth deg coeff
:return: f(x)
"""
return a*x**2 + b*x + c | bedc9b41013e47aecfee779589b6e3e7b22b96cd | 646,988 |
def hex_to_bool(val):
"""Converts hex string or boolean integer to a clean boolean value.
Returns a boolean data type True or False
"""
if type(val) == str:
val = val.strip("0x").rstrip("0")
if val:
return True
else:
return False | 2bbd08688f654e93a8c8769c23ce4cc122562b6c | 646,989 |
import torch
def describe(x: torch.Tensor):
"""
Describe the distribution of numbers in the input tensor.
This function mimics the behavior of DataFrame and Series
describe method in pandas.
Parameters
----------
x : torch.Tensor
Input tensor to be described
Returns
----... | fa1d9a2d711d9668235e49480c6a94f2c0e96093 | 646,990 |
def dictify(dict_, dict_type=dict):
"""Turn nested dicts into nested dict_type dicts.
E.g. turn OrderedDicts into dicts, or dicts into OrderedDicts.
"""
if not isinstance(dict_, dict):
return dict_
new_dict = dict_type()
for key in dict_:
if isinstance(dict_[key], dict... | 11202e5bcdca72fba06e6aad080dd48a4f271589 | 646,991 |
def iou(fx, y):
""" Intersection over Union"""
inter = (fx * y).sum()
union = fx.sum() + y.sum()
return inter/(union - inter + 1) | 99e34d299daf70c9ad2f3baed6901db890bc86a4 | 646,992 |
def checkNewFollowers(new_list, old_list):
"""
Checks if elements in the new list are present in the old one
if not present, saves it into a list of new users (that is, new followers)
:param new_list: A list of followers generated in this execution
:param old_list: A list of followers generated ... | db46dd9c05dc08836aab57ca8a5d020fa2cc05ac | 646,993 |
import torch
def average_aggregator(embedding_batch, embed_dim=0):
"""
aggregates by averaging embedding lists in each of the n batch entries
:param embedding_batch: python list of n tensors of m x K-dim embedding vectors (m can vary)
:param embed_dim: K, used if the embedding_lists is empty (n = 0) t... | c4fbb0e67035246a6f585ce140c99f1dfc6cc7c0 | 646,994 |
def is_property_rel(rel_type):
# type: (str) -> bool
"""Test for string indicating a property relationship
Arguments:
rel_type {str} -- relationship type
Returns:
bool -- relationship is a property
"""
return rel_type.endswith('-properties') | b8258ab602f0b3e6dffc7bb29727b3177cc0b349 | 646,995 |
def get_value_from_return_json(json, name1, name2):
"""
get value by key
:param json:
:param name1:
:param name2:
:return:
"""
info = json['info']
group = info[name1]
value = group[name2]
return value | ac00e831b8e762a1ca843f6d1090794d74c2107c | 646,996 |
def prepare_ground_truth(json_data, im_height=1 , im_width=1):
"""
:param json_data: The json file that holds the ground truth content
:return A dictionary with the filenames from the json_data as keys
and the corresponding and prepared annotation data.
"""
gt_dict = dict()
for element i... | 8bbe16adb68dcbb2f0dca53fc9513d830584242a | 646,997 |
def int_to_roman(input):
""" Convert an integer to a Roman numeral. """
if not isinstance(input, type(1)):
raise TypeError("expected integer, got %s" % type(input))
if not 0 < input < 4000:
raise ValueError("Argument must be between 1 and 4000")
ints = (1000, 900, 500, 400, 100, 90, 50,... | 35bdebee545660a5c3608e3fc32de998813c0393 | 646,998 |
def number_to_latex(number_as_string):
"""usage as ``number_to_latex(num2str(1.023e-12)) == "'-1.0\\times10^{-12}'"``"""
s = number_as_string
if s.find('e') > 0:
if s.startswith('1e') or s.startswith('-1e'):
s = s.replace('1e', '10^{')
else:
s = s.replace('e', '\\time... | 61a57755436ac6b0d858970c712a5e43e2228b0b | 646,999 |
import re
def handle_exception(traceback_format_info: str, function_name: str):
"""
这里传入 traceback.format_exc() 就好了
:param traceback_format_info : traceback.format_exc()
:param function_name: 当前传入函数.__name__
:return --> 报错行,报错文件路径,报错类型,报错详细介绍
"""
results = traceback_format_info.split('\n')... | 93197a99f955cddbdcd774c432b9fc2e3e508c84 | 647,000 |
def post_statement(config, migration, statement):
"""
Called on SQL migrations only. Called after individual statement execution.
Accepts config dict, migration dict, and statement string as arguments.
Overide this function in your config file for custom action.
"""
return None | 7fa2a59b6129bbdc717a1e6e06d156f7f36d619d | 647,001 |
import torch
def box_nms(boxes, scores, threshold):
"""Non maximum suppression.
Args:
boxes: (tensor) bounding boxes, sized [N,4].
scores: (tensor) bbox scores, sized [N,].
threshold: (float) overlap threshold.
Returns:
keep: (tensor) selected indices.
Reference:
https://... | bf877bdd9640facdfc59fea6c25728e6d810ec58 | 647,002 |
from datetime import datetime
def get_playlist_items(handle, playlist_id, from_date, until_date, max_videos):
""" Returns list of video IDs for given Playlist ID and filters.
Parameters:
handle(object): Youtube handle for authorizing requests to the
Youtube API. See function `get_handle`... | 069680be188e820979704f2407a602057354d567 | 647,003 |
def valid(guess):
"""
This is a predicate function to check whether a user input is a letter and with only one letter.
:param guess:
:return: bool
"""
if guess.isalpha() and len(guess) == 1:
return True
return False | c66e1a4b0da64ac53644f23099077955a942bd71 | 647,004 |
def validate_play(player, card, pile, message):
"""
Validates each subsequent play in the round, first play will dictate what can be played
"""
valid_play = False
#if player has the first suit played, they can only play that suit
has_suit = False
#gets the suit of the first card played, wh... | ea7186daaa79f15de166a99ffc1be916a789becc | 647,006 |
def findall_with(node, path, func):
"""Find all func(n) for n in node.findall(path).
"""
return [func(n) for n in node.findall(path)] | f1ca028013078c47923f3a62ee2691a6bec6bb2d | 647,007 |
def _split_table_name(table_name):
"""Split 'schema_name.table_name' to (schema_name, table_name)."""
table_name_items = table_name.split(".")
if len(table_name_items) == 1:
schema_name = None
elif len(table_name_items) == 2:
schema_name, table_name = table_name_items
else:
r... | 9538acb70b7d6bd5f035481d164e5fce0fe3e68b | 647,008 |
def ell_max_from_resolution(resolution):
"""Returns the maximum degree for a spherical input of given resolution."""
return resolution // 2 - 1 | 7ef887fa4dfacff0476a1d5f4d98a49f5db076c1 | 647,009 |
import glob
import os
def get_hmm_paths(indirpath):
"""Returns a list of all .hmm files in a given directory.
"""
return glob.glob(os.path.join(indirpath, '*.hmm')) | 0e163a7b32d03f9013e340e03fb43b427d21fa4c | 647,010 |
def check_args(**kwargs):
"""
Check function input arguments from the command via discord message.
"""
# Already deprecated
return []
# errors = []
# for key, value in kwargs.items():
# if value:
# if key.count('name'):
# if not re.match(regex.is_name, val... | 78266fa9741cbc1f358f2edce2d2b8cb0dd5c794 | 647,011 |
def buscar_vuelos_escala(vuelos: dict, origen: str, destino: str) -> list:
""" Buscar vuelos (con escala)
Parámetros:
vuelos (dict): Es un diccionario de diccionarios con la información de los vuelos.
origen (str): El código del aeropuerto de origen
destino (str): El código del aeropuerto de d... | 2231d18c60b1bf6d0553e75dc449ea27688ba21d | 647,012 |
import time
def datetime_to_timestampms(dt):
"""Converts datetime object to unix timestamp in milliseconds.
Keyword arguments:
date -- Datetime object to convert
"""
if dt is None:
return dt
return int(time.mktime(dt.timetuple())) * 1000 | f2c0e575f53248b879627849e10c07cef4ab24a3 | 647,013 |
import torch
def normalize(x, eps=1e-6):
"""Apply min-max normalization."""
x = x.contiguous()
N, C, H, W = x.size()
x_ = x.view(N*C, -1)
max_val = torch.max(x_, dim=1, keepdim=True)[0]
min_val = torch.min(x_, dim=1, keepdim=True)[0]
x_ = (x_ - min_val) / (max_val - min_val + eps)
out ... | 738311825bb64c562c018acd1bdaa0500ea4fee8 | 647,015 |
import torch
def raycast(rays, env, h, w):
"""Raycast in an environment to black-out any non-visible tiles"""
image = torch.zeros((2, env.shape[0], env.shape[1]))
for ray in rays:
# assert isinstance(ray, tuple)
for (rh, rw) in ray:
v = int(env[h + rh, w + rw].item())
... | 61075abf1743fe0e71da580944c31e9d7733d8d7 | 647,016 |
def most_common_v1(lst):
"""Great way to find return the most common item in a list. Unfortunately,
the result is unpredictable in case of a tie. This can be avoided by using
the Counter function in the collections module.
Args:
lst (list): The list to seach in for the most common item.
Returns:
The most co... | 4eb375aaf625d2263407de4764d1ab2d4da8dbc9 | 647,018 |
import sys
def printable_length_where(w):
""" Returns the printable length of the substring """
if sys.version_info[0] >= 3: # pragma: no cover
stype = str
else:
stype = unicode
sub = w.string[w.character:w.character_end]
# return len(stype(sub, 'utf-8'))
# I am not really sur... | a0db57327c3705a4ef80bcbd1257b8ce272415ba | 647,019 |
def filter_par(name):
"""Filter parenthesis away from a name."""
if name.endswith(")"):
return name.split("(")[0]
else:
return name | a72967b2bc8e3c52aa17169aa69cbad74605dbf5 | 647,020 |
def fermi_energy_parser(vasp_dir):
"""
Parses fermi energy from DOSCAR file.
:param vasp_dir: string containing path to VASP-file.
:return: float containing fermi energy.
"""
# Open DOSCAR file.
outcar_file = vasp_dir + '/DOSCAR'
try:
with open(outcar_file, "r") as f:
... | 07297e5194d59b8d78a852524ac9c63502a423e0 | 647,021 |
def vocab(name):
"""
Given a property such as 'rel', get its fully-qualified URL in our
JSON-LD vocabulary.
"""
return "http://api.conceptnet.io/ld/conceptnet5.7/context.ld.json#" + name | e46dcdc8648eb8b8a6085f7fa1a2a51eafca3987 | 647,022 |
def unconvert_from_RGB_255(colors):
"""
Return a tuple where each element gets divided by 255
Takes a (list of) color tuple(s) where each element is between 0 and
255. Returns the same tuples where each tuple element is normalized to
a value between 0 and 1
"""
un_rgb_color = (colors[0]/(2... | 637f9e03e17f4fae17f0f023f486e24d5ca6e745 | 647,023 |
def triangle_recursion(n: int) -> int:
"""
slowest method
Three times slower than other two methods.
"""
if n == 1:
return 1
else:
return triangle_recursion(n - 1) + n | 7898f8b706a6d3f4f07d9f36005debcd27eaa369 | 647,024 |
def get_total_nodes(load_bal):
"""
Returns the number of nodes attached to the load balancer.
Regardless if they are in the scaling group or not.
"""
return len(load_bal.nodes) | 570809488bd800d8bfc41ce564929e13b1d3f013 | 647,025 |
def stakes(result):
"""
:param result: ensemble des valeurs affichées dans le terminal par une fonction du package
sportsbetting
:return: Dictionnaire des mises
"""
return result.split(
"Répartition des mises (les totaux affichés prennent en compte les éventuels freebets):\n")[
1... | ddf4a1967b070798c102b2ff27c077c2d81a4ec2 | 647,026 |
from unittest.mock import Mock
def mock_job_run_syncupstream():
"""
job_run mock value
"""
mock_rep = Mock()
mock_rep.ok = True
mock_rep.json.return_value = {
"Success": "Job created and logged. "
"URL: http://localhost:8080/jobs/log/e41ee603-9bdc-4640-83f3-aa8c82263... | f1349480120af2925ce550511e494dd3ba45234f | 647,027 |
def convert_to_int(s):
"""Convert any object to int if possible, otherwise return original object."""
try:
return int(s)
except (ValueError, TypeError):
return s | aec494493aba265ea91cf11225a2a09aeda3fa4e | 647,028 |
import functools
def login_not_required(func):
"""
Dummy decorator. @login_required will inspect the method
to look for this decorator
Use this decorator when you want do not require login in a "@login_required" class/method
:param func:
:return:
"""
@functools.wraps(func)
def dec... | a0d7942f6a28698ac248992ed0e635e063c8c064 | 647,029 |
def txt_contrast(txtname1, txtname2):
"""
Verify that the txt are the same
"""
with open(txtname1, "r", encoding="utf-8") as fp:
file1 = fp.read()
with open(txtname2, "r", encoding="utf-8") as fp:
file2 = fp.read()
if(file1 == file2):
return 1
else:
r... | 2ab491195b648dc10279244c02fc3ac2d75e4aeb | 647,030 |
import torch
def backproject_points(p, fx, fy, cx, cy):
"""
p.shape = (nr_points,xyz)
"""
# true_divide
u = torch.round((torch.div(p[:, 0], p[:, 2]) * fx) + cx)
v = torch.round((torch.div(p[:, 1], p[:, 2]) * fy) + cy)
if torch.isnan(u).any() or torch.isnan(v).any():
u = torch.tens... | b0aeb8de2087dd68684a495e2234d0a983bebec0 | 647,031 |
import os
import sys
def load_aa_codes(code="default"):
"""Loads in the aa_codes.txt file and finds the right codes"""
aa_code = {}
with open(os.path.join(sys.path[0], "aa_codes.txt"), "r") as f:
found_code = False
for line in f:
line = line.strip()
if found_code:
... | 7b40b173df65d58145e46c4d3d9952719daaf941 | 647,032 |
import json
def load_config_file(file_path):
""" reads a json file and returns a dict obj
throws an exception if the file is misssing """
with open(file_path, 'r') as f:
return json.load(f) | fa9b97e7fc9adfff58ab4b5623df752724063b81 | 647,033 |
def superpack_name(pyver, numver):
"""Return the filename of the superpack installer."""
return 'numpy-%s-win32-superpack-python%s.exe' % (numver, pyver) | 5c234119923961c98b6f036df21cc9cd9a8ca0d8 | 647,034 |
def riffle(*args):
"""riffle(*args)
Riffles lists of equal length.
The resulting list alternates between elements of each of the input lists.
"""
n = len(args)
# Verify that all lists are the same length
for i in range(1, n):
if len(args[0]) != len(args[i]):
raise Val... | 3cb156c2d42479ced434438effee614908e08a0a | 647,035 |
from typing import Any
def is_false(expression: Any):
"""Returns true if the input expression evaluates to false"""
return expression is False | 1ddda5f3d3ea0666598a6562d2dae2d7ff8e1533 | 647,036 |
def expanduser(path):
"""On Unix and Windows, return the argument with an initial component of ``~`` or
``~user`` replaced by that *user*'s home directory."""
return '' | c0b5cc245f000e1b27fd544c3af636b5f8a1d555 | 647,038 |
import pandas as pd
def GeoBound(Hnum, Hurricane_name, Data, Data_Location):
"""Find the boundary of the trajectory of the hurricane (in longitude and latitude form)
"""
Latitude = []
Longitude = []
for i in range(Hnum):
CSV = pd.read_csv(Data_Location + Data[i])
lon = CSV['Lo... | 21f827b356685fe26200f293cc4af87cfde27bed | 647,040 |
def get_gazed_at_multiplier(person_of_interest, looking_at, add_to_multiply=.5, base_multiple=1):
"""Creates a 'per-frame' multiplier based on the # of people looking at the person_of_interest
frame_multiplier = base_multiple + (add_to_multiply * [# of people looking at that person])
note: Doesn't include... | b9b14cd3ecd735cb6ea0f1d77aebf20b7d1571b9 | 647,041 |
def DictInvert(aDict):
"""\\
Inverts a dictionary; {(key,value)} is turned into {(value, [key1, key2, ...])}.
For example, {(1,'a'), (2,'b'), (3,'a')} is turned into {('a',[1,3]), ('b',2)}
"""
invDict = {};
for k,v in aDict.items():
invDict[v] = invDict.get(v, []);
invDict[v].app... | 6df641ad8a28c9bf98fef748325db8ab6e4cf430 | 647,042 |
def _get_min_overlap_timestamp(df1_timestamps, df2_timestamps):
"""
Get the minimum overlapping timestamp from two series
"""
try:
if df1_timestamps.max() < df2_timestamps.min() or df1_timestamps.min() > df2_timestamps.max():
raise IndexError("No overlapping data. Dataset ranges are:... | 3acb862525beb084cfed161704cc965e83db8f69 | 647,044 |
def filter_gene(rec, gene=None):
"""
Filters BioPython SeqRecords by name
"""
return True if not gene else rec.__gene__ == gene | 78432f697d574415644cc1c288669e3edc56c128 | 647,045 |
import os
def get_files(dir_name):
"""
Takes a directory name and returns a list of all files inside of it.
"""
return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)] | dc52ca2a2c1ae117c8430f639a6e614219bb55d1 | 647,047 |
def is_delayed_game(event_list, team):
"""Looks further back due to paused game"""
is_delayed = False
for e in event_list[:2]:
if e.type_id == 28:
is_delayed = True
return is_delayed | 61874846f2d018a3128ec0a4eb0e5364c1fa45e5 | 647,048 |
def set_nreg(reg):
"""
Set number of extra parameters due to regularization
"""
if reg is not None:
if reg == 'Tikhonov':
N = 1
elif reg == 'GP':
N = 3
elif reg == 'GP2':
N = 2
else:
print("%s is not a valid regularization m... | 9c8094bf7d3e61d520791cc002f16298c5d6e0c4 | 647,049 |
import math
def gen_gaussian_list(a, b, n=1000):
"""gen_gaussian_list(a, b, n=1000)
Generate a discrete approximation of a Gaussian function, including its
domain and range, stored as a pair of vanilla python lists.
Args:
a (float) : Lower bound of domain
b (float) : Upper bound o... | babea372bb98c659b54ef20ca043f27bb14365e2 | 647,050 |
def is_panchromatic_product(xml_node):
"""Checks whether a satellite product is panchromatic."""
for child in xml_node:
if child.text == 'Pan':
return True
return False | 81c61c84955aab5984fb4a391ae44991a8db00e4 | 647,051 |
def center_kernel_low_rank(G):
"""
Center a the feature matrix such that :math:`\mathbf{G}_c \mathbf{G}_c^T` is centered.
.. math::
\mathbf{G}_c = (\mathbf{I} - \dfrac{\mathbf{11}^T}{n})\mathbf{G}
:param G: (``numpy.ndarray``) Low-rank approximation of the feature matrix of shape ``(n, k)``.
... | 200a3aed74b8b3aff7ac88a0daeb03f31159a2f8 | 647,052 |
import os
def get_python_source_paths(root_path):
"""Get a list of all python sources appearing recursively under the given root path."""
results = []
for dir_path, _, file_names in os.walk(root_path):
for filename in file_names:
if filename.endswith('.py'):
results.app... | cf555c36ffc53a9bb3abdaedf74b9d5bc9106943 | 647,053 |
def quota_parse(quota_dict):
"""
Parse the output of ``SESConnection.get_send_quota()`` to just the results.
"""
return quota_dict['GetSendQuotaResponse']['GetSendQuotaResult'] | 36d44e539b969b8e4ef26b738ad59fc47ce12f66 | 647,054 |
import fileinput
def read_from_stdin():
"""Collect piped elements in set."""
s1 = set()
for line in fileinput.input():
s1.add(line.strip())
return s1 | c996e9364a0609081cc0da8d28308d839092b086 | 647,055 |
import os
import json
def _get_vcap_services(vcap_services = None):
"""Retrieves the VCAP Services information from the `ConfigParams.VCAP_SERVICES` field in the config object. If
the field is a string, it attempts to parse it as a dict. If the field is a file, it reads the file and attempts
to parse the ... | 85dfa374300bd347f0b537a49b306233b212f55c | 647,056 |
def pack_offset(plane_index, offset=None):
"""
Get MSR value that writes (or read) offset to given plane
:param plane: voltage plane index
:param offset: voltage offset as hex string (omit for read)
:return value as long int ready to write to register
# Write
>>> from undervolt import pack_... | 99d68472e7a4a392912d01521d4ddcd6f20625e6 | 647,057 |
from unittest.mock import patch
def class_mock(q_class_name, request, autospec=True, **kwargs):
"""
Return a mock patching the class with qualified name *q_class_name*.
The mock is autospec'ed based on the patched class unless the optional
argument *autospec* is set to False. Any other keyword argumen... | 448ab8aff578bbdb6ab8a9b3130fdf0fac1f113b | 647,058 |
def hexstr_to_int(value, base=16):
"""
Convert hex string to int.
:param value:
:param base:
:return:
"""
return int(value, base=base) | 6098a710c268efe6374ac4744094542618092277 | 647,059 |
import os
def get_rpt_path(jmx_path):
"""
获取生成报表文件路径.
:param jmx_path: string--> jmeter脚本路径
:return: rpt_path: string--> 报表文件路径
"""
rpt_path = os.path.join(os.path.dirname(jmx_path), 'report')
return rpt_path | 41f41ca01eceb68029e0be01109ce895ad4bab25 | 647,060 |
def abstractmethod(funcobj):
"""Decorator used to identify an abstract method that must be implemented in any subclasses."""
funcobj.__isabstractmethod__ = True
return funcobj | 755cda1b6a58c6cda7a6dd7828148951302db0d8 | 647,061 |
from typing import Type
from enum import Enum
from typing import Sequence
def create_choices(enum_type: Type[Enum]) -> Sequence[str]:
"""Create choice strings.
Args:
enum_type: enum
Returns:
a collection of strings describing the choices in enum.
"""
# mypy wants type annotation... | 4a3dda90048bebeafeb71049cfb7e28a530f0461 | 647,062 |
def p_maxlh(n,k):
"""
Calculates the maximum likelihood estimator for the kth sample
of n total samples.
Args:
n: the number of samples from the random variable, X
k: the hierarchical position of the sample when ordered
k in [0,n)
Returns:
the maximum likelih... | 29d709124b6bd8d86ef01cb7603297b8cfc774c5 | 647,063 |
def try_config(config, heading, key):
"""Attempt to extract config[heading][key], with error handling.
This function wraps config access with a try-catch to print out informative
error messages and then exit."""
try:
section = config[heading]
except KeyError:
exit("Missing config se... | 6c10fd8ec356cf5ad2b6c09314a3ea00e7af08f5 | 647,064 |
def yup():
"""
Afformative
"""
return "yes" | 592e6d0fe4007c94afe958a83842ebf0be353332 | 647,066 |
def ma_apply_nb(ts, window, ewm, adjust, cache_dict):
"""Apply function for `vectorbt.indicators.basic.MA`."""
h = hash((window, ewm))
return cache_dict[h] | 46b5ab6ca89946be1080553b50e2eac0c50c3f2c | 647,067 |
def custom_colors():
"""
define some colors in BGR, add more if needed
:return: return a list of colors
"""
colors = []
colors.append([0, 255, 255]) # yellow
colors.append([245, 135, 56]) # light blue
colors.append([0, 255, 0]) # green
colors.append([255, 0, 255]) # m... | b67ab3767f499d32aa80fcd4674e4e843c172e96 | 647,068 |
import re
def humanize(word):
"""
Capitalize the first word and turn underscores into spaces and strip a
trailing ``"_id"``, if any. Like :func:`titleize`, this is meant for
creating pretty output.
Examples::
>>> humanize("employee_salary")
"Employee salary"
>>> humanize(... | 22ef47a7112a2ac2b0ae14ce1822f3de3c3477c6 | 647,069 |
def add_xy_grid_meta(coords):
"""Add x,y metadata to coordinates"""
# add metadata to x,y coordinates
if "x" in coords:
x_coord_attrs = dict(coords["x"].attrs)
x_coord_attrs["long_name"] = "x coordinate of projection"
x_coord_attrs["standard_name"] = "projection_x_coordinate"
... | 8f82e52b62930178d6c445d9929bc9bf9bfb0260 | 647,071 |
import hmac
import hashlib
def hmac_sha256(key, data):
"""Generate pseudo-random-keyed (PRK-keyed) hash-block"""
return hmac.new(key, data, hashlib.sha256).digest() | d63c776b28cc30afefd0361a744c79f469b64327 | 647,072 |
def total_heat_sum_error(spf_heat_data):
"""Total values for heating and overall heating spf.
Uses heating operational data. Calculate total heat extracted from
ground and absolute error. Also calculates spf and fractional error.
Parameters
----------
spf_heat_data : pd.Dateframe
Heatp... | c15c07c984a11b2732ee7ed47c6263db18156e10 | 647,073 |
def id(value):
"""extract(entity)
extracts a string unique ID from a opencue entity or
list of opencue entities.
"""
def _extract(item):
try:
return item.id()
# pylint: disable=bare-except
except:
pass
return item
if isinstance(value, (tup... | 75ee72c7dcbe0f5d3e01314bea29a0be49a70133 | 647,074 |
def sumarSensores( readings ):
"""
Determine the weight of the user on the board in hundredths of a kilogram
"""
weight = 0
#weight = sum(calibrations.next())
#print("Peso")
#print(weight)
for sensor in ('right_top', 'right_bottom', 'left_top', 'left_bottom'):
reading = readings[... | 7797540f612beaa0773b49cabd32467f80f14b93 | 647,075 |
def _is_a_url(input_element):
"""
-----
Brief
-----
Auxiliary function responsible for checking if the input is a string that contains an url.
-----------
Description
-----------
Some biosignalsnotebooks functions support a remote access to files. In this situation it is
importa... | a468ff4b5c0cd75baec6205d9e4fa94248130daf | 647,076 |
def get_download_url_from_commit(package, commit):
"""
Return the download URL for this commit
@package - :user/:repo combination
@commit - commit hash
"""
return "https://codeload.github.com/%s/legacy.tar.gz/%s" % (package, commit) | cb1a7b60f7bb6ba873644b2914cffc67a758f85e | 647,077 |
def OR(bools):
"""Logical OR."""
if True in bools:
return True
return False | 200e78e6ef1ce91ad36301cea0b8f56dc7301219 | 647,078 |
import math
def Magnitude(a):
"""Magnitude returns the square root of the sum of the numbers of a list squared."""
c = 0
for i in range(len(a)):
c = c + a[i]**2
return math.sqrt(c) | b4b28190f41a7c52ff0446fe551b665f06db5299 | 647,079 |
import torch
def make_directed(nbr_list):
"""
Check if a neighbor list is directed, and make it
directed if it isn't. Contributed by saxelrod
Args:
nbr_list (torch.LongTensor): neighbor list
Returns:
new_nbrs (torch.LongTensor): directed neighbor
list
directed (... | d6d1de47b01b0e74d23785325d1d8a7d0dcfb738 | 647,080 |
import uuid
def get_guid(path):
"""
Return a GUID which is reproducibly tied to a file path
"""
return uuid.uuid5(uuid.NAMESPACE_DNS, 'quantiphyse.org/' + path) | d63fa9a35f36ddc9bac248bddb235ee3614e035b | 647,081 |
def calculator(value, operation):
"""Template-based calculator."""
value1, operator, value2 = operation.split(" ")
if value1 == "{}":
value1 = float(value)
value2 = float(value2)
elif value2 == "{}":
value2 = float(value)
value1 = float(value1)
if operator == "+":
... | f8d5e0c15a6fde09c4d56a14ed2c5ba4279c6d10 | 647,082 |
def _rca_division(val1, val2, val3, val4):
"""Multi-step division."""
return (val1 / val2) / (val3 / val4) | f7dcfd649b2d7495c248b73dc788300f9660eaef | 647,083 |
def _stringify_cols(df, cols):
"""
Stringify some cols - useful since many methods erquire code column to be a string
"""
for col in cols:
df[col] = df[col].astype(str)
return df | 17d6b520bed97e34b0e4a53051a81dd0f1aaef4a | 647,084 |
def list2dict(lst):
"""Takes a list of (key,value) pairs and turns it into a dict."""
dic = {}
for k,v in lst: dic[k] = v
return dic | 55c6bb953ee5e0341f25bd1e2a0994ef73fd1ca5 | 647,085 |
def min_max_normalize(X):
"""Min-Max normalization function
X = (X - Xmin)/(Xmax - Xmin)"""
samples, features = X.shape
for i in range(features):
xmin = X[:, i].min()
xmax = X[:, i].max()
X[:, i] = (X[:, i] - xmin)/(xmax - xmin)
return X | cf23a0254559487a77010a6c8942e52959afa4aa | 647,086 |
def is_ascii(s):
"""
Checks if the string (s) has any non-askii character.
:param s: The string which is checked
:return: True, is the string consists of all ascii characters, else returns False.
"""
return all(ord(c) < 128 for c in s) | fcaece0e42a70af81f2198fbea9ecdf79052df40 | 647,087 |
import os
def get_classes(data_folder, number=None):
"""
Return the object detection classes. If a number is specified, return the class defined by the number.
:param data_folder: folder of the data.
:param number: optional. Specifies a class.
:return: a list of classes or a precise one.
"""
... | f2cc58bd4896ec0fc0cbb5cdca116f9d1f640751 | 647,088 |
def calc_percentages(df):
""" Build dataframe with percent changes day to day. """
df_pct = df[df.columns.difference(['date', 'stato', 'note', 'note_it', 'note_en',
'note_test', 'note_casi',
'casi_da_sospetto_diagnostico', 'casi_da_s... | b74bb4dd549494ff602a173c99a220fb7f83f7ac | 647,090 |
import random
def get_random_appointment(_appointment_schedule):
"""
Custom method to get random appointment from _appointment_schedule
:param _appointment_schedule: The AppointmentSchedule object
:type _appointment_schedule: AppointmentSchedule
:return: Random appointment ID
:rtype: str
"... | e3af457ed21ca24ce0551a2d231997b054023698 | 647,092 |
def floor_finder(df):
"""#For a DataFrame with column Cabin, returns list of floor the passanger is staying on.
"""
cabins=df.Cabin.values #Convert to array
floor=[]
for c in cabins:
try:
floor.append(c[0])
except:
floor.append(c)
return floor | 771e18d7eb052d641cc252451e80fcd88451ed6a | 647,093 |
import yaml
def load_config(path):
"""
Loads config file:
Args:
path (str): path to the config file
Returns:
config (dict): dictionary of the configuration parameters, merge sub_dicts
"""
with open(path, 'r') as f:
cfg = yaml.safe_load(f)
config = dict()
for... | 7ab52ac2180ad3d688e12e275d7e7ad1a5aa0814 | 647,094 |
def common(expected_payload, data):
"""
The expected payload is the expected data and we compare it
to the json data
"""
for key in data.keys():
if key not in expected_payload:
msg = 'The field {} is not required'.format(key)
return {"Status":400, "Message":msg}... | 1276e5c458ad4ee78a24df756bb1a262dbe9481b | 647,095 |
def count_floats(param: dict) -> int:
"""Count how may floats there are in a nested dictionary."""
n_floats = 0
for key, value in param.items():
if isinstance(value, dict):
n_floats += count_floats(value)
else:
if not hasattr(value, "__iter__"):
raise ... | deb2f8c6aab520f74b9bebd8ddcf9433ad5b2754 | 647,096 |
from typing import Union
import os
from typing import Any
from pathlib import Path
def get_default_layer(path: Union[str, "os.PathLike[Any]"]) -> str:
"""
Get the default layer name to be used for a layer in this file.
This is the stem of the filepath.
Args:
path (Union[str,): The path to th... | c9cfc0e7aab2e08f7bec471132c1905d91954178 | 647,097 |
from typing import Optional
from typing import Dict
from typing import BinaryIO
def urlopen(url: str, auth: Optional[tuple] = None, **kwargs: Dict) -> BinaryIO:
"""Thin wrapper around requests get content.
See requests.get docs for the `params` and `kwargs` options.
"""
# Ignoring type checks here b... | 1cfa382c19c6248fc08dbc5562b59340ab2649d1 | 647,098 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.