content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def isiterable(var):
"""
Check if input is iterable.
"""
return hasattr(var, "__iter__") | 53bf8048f3c8c109badd232f44656f392b5d4aad | 584,367 |
def get_font_face(font_name: str, part: str, unicode: str, subset_filename: str):
"""Format @font-face string.
Parameters:
font_name: Font name
part: subset part
unicode: unicode range of the part
subset_filename: woff2 filename of the subset
Returns:
css string of ... | 8d129dda5d87dbe2b8163503682d75a21095cd68 | 584,372 |
import struct
def read_plain_int32(fo):
"""Reads a 32-bit int using the plain encoding"""
tup = struct.unpack("<i", fo.read(4))
return tup[0] | 3fdb182165243b225387b5f7226a3b50dd858a0a | 584,380 |
def sieve_of_eratosthenes(end):
"""Enumerates prime numbers below the given integer `end`.
Returns (as a tuple):
- `is_prime`: a list of bool values.
If an integer `i` is a prime number, then `is_prime[i]` is True.
Otherwise `is_prime[i]` is False.
- `primes`: a list of pri... | a39a56b7ad7fddf2844023af523e9b9be312c2bd | 584,381 |
def Decode(data, codec):
"""Decode the data with the given codec
Args:
data: buffer of data encoded with the given codec
codec: codec name
Returns:
data: decoded data if codec valid
None: codec failed to decode data
"""
try:
decoded_data = data.decode(codec)
return decoded_data
excep... | 19ecd21fbd628211412279a1d4e6c403180a20dd | 584,382 |
def MapPath(path, path_mappings):
"""Maps path into a new path through path_mappings.
Note that the order in path_mappings matters, different order might end up
different result.
"""
if not path or not path_mappings:
return path
for path_mapping in path_mappings:
path = path_mapping(path)
retur... | 5bcef6d7a98cf514bfd86547d061f4e3bca33ff2 | 584,386 |
def split_vectors(vectors):
"""Splits vectors into their x, y and z components."""
return vectors[..., 0], vectors[..., 1], vectors[..., 2] | 2fbd6f1b6b315ab92e2a14c04e03c3a32213f01f | 584,390 |
from typing import Sequence
from typing import List
def normalize_sum(foo: Sequence[float]) -> List[float]:
"""
Normalize by sum. Supports any number of dimensions.
:param foo: list/tuple, any number of floats
:return: list of floats
"""
LLL = sum(foo)
return [t / LLL for t in foo] | e2032d3f74350722e0dc535c7cad7a7611a603a5 | 584,391 |
def _attrgetter_with_default(attr, default):
"""
It returns a function that can be called with an object to get the value
of attr or the default.
Useful to convert None values to ''.
"""
def _getter(obj):
return getattr(obj, attr) or default
return _getter | f0283d879135b7633aa625cec6c99d10d529b436 | 584,394 |
async def ping():
"""
Route for checking if the server is up
:return: a string saying "pong"
"""
return "pong" | 3bc242e3cc84d30929cb3c8e4c7ce0f3319d234e | 584,396 |
import click
def prepare_instance_authentication(ctx, session, public_key):
"""
Sends an ephemeral public key to the target instance used to authenticate the SSH session.
"""
click.echo("sending public key to target instance...")
client = session.client("ec2-instance-connect")
return client.se... | 53c2a51f6715bed4729598c61170f80d415f3f72 | 584,401 |
def main(request, response):
"""
Simple handler that sets a response header based on which client hint
request headers were received.
"""
response.headers.append("Access-Control-Allow-Origin", "*")
response.headers.append("Access-Control-Allow-Headers", "*")
response.headers.append("Access-Contro... | 8491db343947777c3c060cef9e024a852e36b0c1 | 584,410 |
def file_get_contents(path_to_file):
""" Function get content of file (analog of php file_get_contents()) """
fh = open(path_to_file, 'r')
content = fh.read()
fh.close()
return content | 35ce52bdf33aa22c4359fe3aab8085e24780071b | 584,411 |
import json
def load_json(json_path):
"""Try to load a JSON file, or return an empty dictionary."""
try:
with open(json_path, 'r') as jsonf:
parsed = json.load(jsonf)
except FileNotFoundError:
parsed = dict()
return parsed | 374a12f66ec6d2844e62c04d3fcd7191e703a4c7 | 584,414 |
import six
import fnmatch
import re
def filter_by(prop_name, kwargs, objs):
"""
Utility method for filtering a list of objects by a property.
If the given property has a non empty value in kwargs, then
the list of objs is filtered by that value. Otherwise, the
list of objs is returned as is.
"... | 92492ddcb7d9054039adaf8a5c2b9829f09bd0c2 | 584,416 |
def get_group(inventory, groupname):
"""Get group from inventory, return group or None."""
groups = inventory.keys()
found = None
for g_name in groups:
group = inventory[g_name]
if g_name == groupname:
found = group
else:
if "children" in group:
... | a3d100a79858dec50ba53f5a1551330599f4c754 | 584,417 |
import inspect
def get_class_init_kwargs(cls):
"""
Helper function to return a list of all valid keyword arguments (excluding "self") for the given @cls class.
Args:
cls (object): Class from which to grab __init__ kwargs
Returns:
list: All keyword arguments (excluding "self") specifi... | 1954d3c530366a644a373ba8a59ff5dcaf0fc4b5 | 584,419 |
def get_qualifier_without_prefix(feature, qualifier_key, prefix):
"""
Generic function to get the first BioPython feature qualifier value that starts with a given prefix.
For example to get 'PF01234' from qualifiers of {'db_xref': ['PFAM: PF01234']}
you can use get_qualifier_without_prefix(feature, 'db_... | c267fd2f69e7eace3236c7b1d6fa5910278b30c3 | 584,420 |
def r_vis_b(t_vis):
"""The visible light reflectance for the back surface.
Args:
t_vis: The visible transmittance
Returns:
double: The visible light reflectance for the back surface
"""
return -0.7409 * t_vis ** 3 + 1.6531 * t_vis ** 2 - 1.2299 * t_vis + 0.4547 | ef8075e5b39552702fdfdcb67cbd1f2d0f8f543c | 584,422 |
import re
def parse_points(lines):
"""Parse lines to points with position and velocity."""
points = []
for line in lines:
position, velocity = [
[int(num) for num in part.split(', ')]
for part in re.findall(r'<(.*?)>', line)]
points.append({'position': position, 've... | 21342f903cd259f3cf3bf13bfa92f10a6c93ddd5 | 584,424 |
def isolate_path_filename(uri):
"""Accept a url and return the isolated filename component
Accept a uri in the following format - http://site/folder/filename.ext and return the filename component.
Args:
uri (:py:class:`str`): The uri from which the filename should be returned
Returns:
... | 5b04e36bc8a1b47c8b7af3892d083f73528e7391 | 584,425 |
def is_fully_implemented(cls):
"""
Returns True if a ``cls`` is a fully implemented derivate of an ABC.
"""
return not getattr(cls, '__abstractmethods__', False) | 1d3edb66daaeb0af53f3a40619dee340c1fe3ca9 | 584,432 |
def nameval(in_string):
"""
converts given string to key, value and separator triplets
:param in_string: key/value pair
:type in_string: str (unicode)
:return: key, value and separator triplet
:rtype: tuple
"""
idx = in_string.find("=")
separator = '='
if idx >= 0:
name ... | 7bab48c45a1067d40d9dd714993f4fb947f998e6 | 584,433 |
import copy
def kfold_cross_validation(X, n_splits=5):
"""Split dataset into cross validation folds.
Args:
X(list of list of obj): The list of samples
The shape of X is (n_samples, n_features)
n_splits(int): Number of folds.
Returns:
X_train_folds(list of list of int)... | c4e0dbf4c10e5cb36022e66bcc30a2def15bee77 | 584,436 |
def entity_char_to_token(entity, sentence):
"""
Takes Stanza entity and sentence objects and returns the start and end tokens for the entity
:param entity: Stanza entity
:param sentence: Stanza sentence
:return (int, int): Returns the start and end locations indexed by tokens
"""
start_token, end_token = ... | f12dcdf304fad3e1919d74c185b665df3f56dda5 | 584,439 |
import inspect
def _is_model_ndb(ds_model):
"""Return whether or not the model is ndb."""
for cls in inspect.getmro(ds_model):
if 'google.appengine.ext.ndb' in cls.__module__:
return True
return False | 9f3b1818b1cc5472ecf3072a70623b57ced57a15 | 584,441 |
def xyz_to_lab(c: float) -> float:
"""Converts XYZ to Lab
:param c: (float) XYZ value
:return: (float) Lab value
"""
if c > 216.0 / 24389.0:
return pow(c, 1.0 / 3.0)
return c * (841.0 / 108.0) + (4.0 / 29.0) | ab5361d36d5c778fbcd5e5494cb3aa1110b0cef8 | 584,444 |
def should_skip_request(pin, request):
"""Helper to determine if the provided request should be traced"""
if not pin or not pin.enabled():
return True
api = pin.tracer.writer.api
return request.host == api.hostname and request.port == api.port | fe10521efda0bc6803e02a76d20e8e0f4038e20f | 584,445 |
def imagelabel(path):
"""
Get label (detph) related to image name from the readme file.
:param path: absolute path to the readme file (str)
:return: dictionary of label with the image name for key (dct)
"""
labels = {}
with open(path, "r") as f:
for lines in f:
name, dep... | 344dbc40a35b3ccb44d3fa1da63f0ba2dae9e59e | 584,450 |
import json
def is_json(myjson):
"""
tests if a string is valid JSON
"""
try:
json_object = json.loads(myjson)
except ValueError:
return False
return True | c76d679897dae28c8a8e8d12683ccbe0109ddbbd | 584,464 |
def get_sec_cases_in_window(sim, r, t0, t1):
"""
Helper function to extract the number of secondary cases from a simulation
summary object `sim` within interval [t0, t1) for the random repeat `r`.
"""
# Get the indices of new infections (both asymptomatic and symptomatic)
new_inf_indices = (
... | 8bd1db80231837fc6b3521a73430548c255ecec5 | 584,466 |
def replace_defined_interaction(interaction, defines):
"""
Given an `interaction` check if parameters
are defined in a list of defines and replace
by the corresponding numeric value.
Parameters
-----------
interaction: :tuple:`vermouth.molecule.Interaction`
defines: dict
dictiona... | 7e7312460a23e852f38a52aee64cb1cc4d163461 | 584,470 |
from pathlib import Path
def pathify_by_key_ends(dictionary):
"""Return a dict that has had all values with keys marked as '*_PATH' or '*_DIR' converted to Path() instances."""
for key, value in dictionary.items():
if isinstance(value, dict):
pathify_by_key_ends(value)
elif key.end... | 2f998cb13c9f75744ab554d6517ce2f0ebdd21e6 | 584,471 |
def getmonth(record):
"""
function to extract yearmonth in YYYYMM format
"""
crimedate = record.split(",")[3].split(" ")[0]
crimemonth = crimedate.split("/")[1]
crimeyear = crimedate.split("/")[2]
return str(crimeyear+crimemonth) | 8bbf327c66ca1ec56080b33660c3f4aee1b42124 | 584,474 |
import requests
def load_page(url):
"""Load web page. Return HTML."""
r = requests.get(url)
return r.text | db3588114ef229738382268ad4862238390a9557 | 584,479 |
import torch
def _compl_mul_conjugate(a: torch.Tensor, b: torch.Tensor):
"""
Given a and b two tensors of dimension 4
with the last dimension being the real and imaginary part,
returns a multiplied by the conjugate of b, the multiplication
being with respect to the second dimension.
"""
#... | 3beda88d9c032fa7434bc363ecd3381effaca3ac | 584,483 |
def get_precision(input_number):
"""
Return precision of input number.
:param input_number: input number
:type input_number: float
:return: precision as int
"""
try:
number_str = str(input_number)
_, decimalpart = number_str.split(".")
return len(decimalpart)
exc... | 2b80f9556c23c28183bfbf473583a3943d079c09 | 584,486 |
def _read_measurements(f):
"""Read measurements from a file.
Returns {'a': [1.0, 2.0, 3.0], 'b': [5.0, 5.0, 5.0]} for a file containing
the six lines: ['a 1', 'a 2', 'a 3', 'b 5', 'b 5', 'b 5'].
"""
measurements = {}
for line in f:
label, value = line.split(None, 1)
measurements... | 3be0b349eeaac83fe093bfcaa774ea3895028128 | 584,488 |
def get_confidence_outcome(tps, fps, fns, negative_ids):
"""
Determines whether prediction with a given confidence is true or false based on the TPs and FPs lists
Parameters
----------
tps, fps : list of tuple
A list of predicted TP(FP)s in format (slice_id, Adhesion, confidence)
fns : li... | 8db305b0b9edabc1f8949570514c518d01cdc400 | 584,490 |
async def is_rpan_guild(ctx) -> bool:
"""
Checks if the guild is an RPAN discord guild.
:return: Whether or not it is (as listed in the settings).
"""
if not ctx.guild:
return False
return ctx.guild.id in ctx.bot.core.settings.ids.rpan_guilds | e5b2a9f19c5785638809a9e67b00df8f347d9482 | 584,492 |
def turning_radius(speed):
"""Minimum turning radius given speed."""
return -6.901E-11 * speed**4 + 2.1815E-07 * speed**3 - 5.4437E-06 * speed**2 + 0.12496671 * speed + 157 | 8c8a01523c2fbf7478dc915cb878c523f1f3aef2 | 584,494 |
from pathlib import Path
import yaml
def get_config(filename=None):
"""Load YAML configuration file and return contents as dict."""
if filename is None:
project_root = Path(__file__).parents[1]
filename = project_root / "config.yaml"
with open(filename, encoding="utf-8") as file:
r... | 2051b552a4acba467fae174ee53ab43fc1a44574 | 584,497 |
from typing import Union
from typing import Callable
from typing import Iterable
def adapt_object(obj, adapters: Union[Callable, Iterable]):
"""
Applies adapter or adapters to an object. An object is usually a state or a reward.
Parameter adapters can be a function or an iterable. If adapters are None the... | ac6438039b0ed24a0f40e2893c877e9c82b9e3bb | 584,498 |
import types
import typing
def _frames_from_traceback(tb: types.TracebackType) -> typing.List[types.FrameType]:
"""Extract frames from traceback object"""
output = []
current = tb
while 1:
output.append(current.tb_frame)
if current.tb_next:
current = current.tb_next
... | 6c11a2d3c8fd7e911b5984f7ef0976b28ce5d5a5 | 584,500 |
import html
def html_highlight_text(weights, tokens, color=(135, 206, 250), intensity=1):
"""
Return HTML code of highlighted tokens with different intensity color.
Arguments:
weights: (`obj`:list):
List of attentions scores for each token.
tokens: (`obj`:list):
L... | d28928ab383f4230df57b0b6eb3a1c10b81ccbb4 | 584,501 |
def normalise_unreserved(string):
"""Return a version of 's' where no unreserved characters are encoded.
Unreserved characters are defined in Section 2.3 of RFC 3986.
Percent encoded sequences are normalised to upper case.
"""
result = string.split('%')
unreserved = ('ABCDEFGHIJKLMNOPQRSTUVWXY... | 510f0d86cd6951f1d9424eb4e6d4209be551384c | 584,502 |
def disabled(func):
"""Decorator: do nothing. Use this to enable/disable other decorators."""
return func | a903278bcab259e7d2df82e2e0d0f5119b50f7de | 584,507 |
def _create_price_offering(
client,
header,
description,
final_url,
final_mobile_url,
price_in_micros,
currency_code,
unit,
):
"""Creates a PriceOffering instance and returns it.
Args:
client: an initialized GoogleAdsClient instance.
header: The header of the pri... | 836d3fcc041b9d74f5e9c6aa227248eebcf23227 | 584,512 |
def ib_commission(quantity, price):
"""Compute the commission charged by Interactive Brokers."""
c = 0.005 * quantity
maximum = 0.005 * quantity * price
minimum = 1.0
if c < minimum:
# The commission may not be less than one dollar.
c = minimum
elif c > maximum:
# The c... | f2c033e36b88c9e91d4bc98689e761430d250278 | 584,513 |
def num_to_dashes(n: int) -> str:
"""Create a string of hyphens with length n."""
return "-" * n | 40b6ebd342eb2df2108d210ee5abdf8a6e27905a | 584,522 |
import math
def log_add(log_x, log_y):
"""Given log x and log y, returns log(x + y)."""
# Swap variables so log_y is larger.
if log_x > log_y:
log_x, log_y = log_y, log_x
# Use the log(1 + e^p) trick to compute this efficiently
# If the difference is large enough, this is effectively log ... | c8fe9b80b4a456a7f2ea0ec7b411fc288f16085a | 584,524 |
def assert_listener_item_equal(test_case, item1, item2, msg=None):
""" Assertion function for comparing two instances of ListenerItem.
"""
def get_msg(name, msg):
return "{name} mismatched. {msg}".format(
name=name,
msg="" if msg is None else msg
)
test_case.ass... | ed02cc13bc2de74beecdd4d4c3a11dace7b7072c | 584,526 |
def graphFormatter(source):
"""Formats the data as the Pie Chart creator requires for graphing."""
formatted = []
for i in source.items():
formatted.append({
'label': i[0],
'data': i[1],
})
return formatted | 2550b2ebfd2683e125759e4bca49b76661bcf6d7 | 584,527 |
import math
def latex_table_line(xparam, yparam, fit_results_dict):
"""
Format a fit result as an entry for the fit results table in the paper.
Parameters
----------
xparam: string
name of parameter on x-axis
yparam: string
name of parameter on y-axis
fit_results_dict: d... | 20a738148fdad5857c6fd395a2c79f23d429ad42 | 584,532 |
def missing_number_xor(nums: list[int]) -> int:
"""
Complexity:
Time: O(n)
Space: O(1)
Args:
nums: array containing n distinct numbers
taken from the range [0,n]
(n+1 possible numbers)
Returns: the single missing number in the range [0,n] missing fr... | 19da2865ab72d691363ea62c0a08d0bfc52b5f58 | 584,533 |
def _hessian(d, positions):
"""Compute the non-redundant 3D Hessian terms at the requested positions.
Source: "Anatomy of the SIFT Method" p.380 (13)
"""
p0 = positions[..., 0]
p1 = positions[..., 1]
p2 = positions[..., 2]
two_d0 = 2 * d[p0, p1, p2]
# 0 = row, 1 = col, 2 = octave
h... | 37bc07711bd0d10ccc93abe8aeb49bbb05fb777c | 584,534 |
import random
def _dictionary_sample(dic):
"""_dictionary_sample(dic) -> key
Returns a weighted random sample key from a dictionary.
The dictionary is assumed to consist of key/weight pairs.
Positional arguments:
dic (dict) -- dictionary of key/weight pairs (weights given as floats)
Returns... | 16f37c1438ac39298b962229e2c20415a443f11c | 584,535 |
def get_frequency_dictionary(data):
"""
Takes a string or list of strings and returns a dictionary of unique
members and their abundance. Similar to itertools.Counter.
"""
return {k: data.count(k) for k in set(data)} | cfd097875bf18be7845c2f734dd0c72ec21576cd | 584,539 |
import re
import requests
def execute_sparql_query(prefix='', query='', endpoint='http://localhost:8282/proxy/wdqs/bigdata/namespace/wdq/sparql',
user_agent="User Agent Name"):
"""
Static method which can be used to execute any SPARQL query
:param prefix: The URI prefixes required... | 99c99e08363b6bb9577b370a0b7be7db5b0953ec | 584,540 |
def get_euler_solution(derivative, numsteps, upper, initial):
"""
Returns an explicit Euler's method solution to a given differential equation,
called `derivative`, of the form dy/dx = f(x, y)
Can operate on numpy vectors
Runs with `numsteps` iterations, from x = 0 to x = `upper`
Uses `initial` ... | e00c0411c854f31d71bc552f0361ead876a282f0 | 584,542 |
import torch
def sample_generalized_normal(mean: torch.Tensor, lbd: float, p: int, shape):
"""Sample from a generalized Normal distribution.
Modified according to:
https://www.tensorflow.org/probability/api_docs/python/tfp/distributions/GeneralizedNormal
Args:
mean: Mean of the distribution.
... | 7827b45c828a86d674592abe13f9bc8750b2a561 | 584,543 |
def line_parameters_xy(pt_1, pt_2):
"""
Used in lines_intersection
from:
https://stackoverflow.com/questions/20677795/how-do-i-compute-the-intersection-point-of-two-lines-in-python
"""
a=(pt_1[1]-pt_2[1])
b=(pt_2[0]-pt_1[0])
c=(pt_1[0]*pt_2[1]-pt_2[0]*pt_1[1])
return a, b,-c | f59ba6bdcfb0acbce95df7a4c96e5c7fe6560b1b | 584,547 |
def UC_Q(Q_mmd, A_catch):
""" Convert discharge from units of mm/day to m3/day
Args:
Q_mmd: Float. Discharge in mm/day
A_catch: Float. Catchment area in km2
Returns:
Float. Discharge in m3/day
"""
Q_m3d = Q_mmd*1000*A_catch
return Q_m3d | 3082e71cc8b8af0456ff4e1f53fec292099a6ae4 | 584,548 |
from typing import Tuple
import math
def _quantize_bounding_rect(
xMin: float,
yMin: float,
xMax: float,
yMax: float,
factor: int = 1,
) -> Tuple[int, int, int, int]:
"""
>>> bounds = (72.3, -218.4, 1201.3, 919.1)
>>> _quantize_bounding_rect(*bounds)
(72, -219, 1202, 920)
>>> _... | b8a618584acd60d55a56d1e62e3b61772d01c6f1 | 584,549 |
def summarize_text(text, max_length=100, marker="[...]"):
"""Truncate text and add a marker, if the length is above `max_langth`"""
if not text:
return ""
if len(text) < max_length:
return text
return text[:max_length] + marker | 8fe45d3a4672c4381cb2323d3e2a598bf07e9791 | 584,552 |
def setup_parser(parser):
"""
Setup argument parser.
:param parser: argument parser
:return: configured parser
"""
parser.add_argument('--scheduler', required=False, default="local",
help="Dask scheduler ip:port for remote scheduler,'local' "
... | f253de7e38a11dbb1fb5059f890eea087a2ff9bd | 584,553 |
import re
def str_to_dict(input_list: list) -> list:
"""
Analyze a list of strings and return a list of dict with all found fields
example:
from:
['eyr:2028 iyr:2016 byr:1995 ecl:oth pid:543685203 hcl:#c0946f hgt:152cm cid:252']
to:
[{'byr': '1995', 'iyr': '2016', '... | 7e2c7b314f0449ffd4fabeaad34632f7eed3419f | 584,554 |
def cargar_tablero_goles(ruta_archivo: str) -> list:
"""
Esta función carga la información de un tablero de goles
a partir de un archivo CSV.
La primera fila del archivo contiene la dimensión del tablero (cuadrado).
Parámetros:
ruta_archivo (str): la ruta del archivo que se quiere cargar.
... | f982dbbbb29c79e3764f0da7d5f88b57250805a5 | 584,555 |
def filter_for_five_on_five(df):
"""
Filters given dataframe for 5v5 rows
:param df: dataframe, columns HomeStrength + RoadStrength or TeamStrength + OppStrength
:return: dataframe
"""
colnames = set(df.columns)
if 'HomeStrength' in colnames and 'RoadStrength' in colnames:
fives = ... | 291063e07a443d5e73d7893bf2b4ab3277b58039 | 584,561 |
from bs4 import BeautifulSoup
def strip_html(text):
"""
Strips HTML from a text using BeautifulSoup4.
:param text: The text that is to be stripped of HTML tags.
:return: The text without HTML tags.
"""
return BeautifulSoup(text, "html5lib").get_text() | b24ef7d5d150bf99cbed10ea795635bf57edeac7 | 584,564 |
def compute_chirpmass(m1, m2):
"""Compute binary chirp mass from component masses."""
return (m1 * m2)**(3./5.) / (m1 + m2)**(1./5.) | 2d58e3c925f0eee62b8682ecfe1dbe174a6ceb95 | 584,572 |
def populate_array_id(arr, spots):
"""
receives an empty array
populates the array with values corresponding to spot ID:
ID like : "spot-1-2", "spot-2-4", "spot-3-3-", etc...
:param arr: np.ndarray
numpy array generated from "create_array"
:param spots: dict
dict from "creat... | 63840bf061a3653e1b1ec5c0014453ea0f408a9c | 584,573 |
def calc_z_shifts(zphase, zsubstrate, margin):
"""Calculate shifts from z = 0 for each phase."""
shifts = {}
shifts['sub_bottom'] = margin
sub_bottom_upper_margin = shifts['sub_bottom'] + zsubstrate
shifts['phase'] = sub_bottom_upper_margin + margin
phase_upper_margin = shifts['phase'] + zph... | 6798fc6b4fff552103fe9d7abdfd7e1ef12181d1 | 584,574 |
def reverse_probs(probs):
"""
Reverses the conditional probability assuming that variables are uniformly distributed
Parameters
----------
probs : probs[x][y] = Pr(Y=y | X=x)
Returns
-------
reverse : reverse[y][x] = Pr(X=x | Y=y) assuming X is uniform
"""
reverse = {}
for ... | 20a0b189027c76bbd4bbd1938778399a08a5d981 | 584,577 |
def is_number(c):
"""
Checks if the given character is a number.
:param c: The character to check.
:return: True if the character is a number, False otherwise.
"""
return '0' <= c <= '9' | 4c115405d46e878863de4bf84b058fce586df331 | 584,579 |
import math
def convert_index_to_x_y(index, dim):
"""
Converts an index to an x, y coordinate.
Used when mapping from 1-D space to 2-D space.
:param index: the index to convert from
:param dim: the x dimension of the matrix
:return: a tuple of integers containing the x and y coordinates
... | 6905d9ae217b5645ab0079e9e05fba55e38ff849 | 584,584 |
import warnings
import pickle
def cpickle_load(filename):
"""Load object written by ``cPickle.dump()``. Deprecated, use
:func:`~pwtools.io.read_pickle` instead."""
warnings.warn("cpickle_load() is deprcated, use io.read_pickle() instead",
DeprecationWarning)
return pickle.load(open(... | 07faba702ee79bf8ae74d0d88c9619a558f896dc | 584,586 |
def digits(n,B=10):
"""
Number of digits of n in base B
"""
n = abs(n)
ctr = 0
while n != 0:
n //= B
ctr += 1
return ctr | 2d569c5667ceeb9dca0fb139435a37a98248c564 | 584,593 |
def _get_randomized_range(val,
provided_range,
default_range):
"""
Helper to initialize by either value or a range
Returns a range to randomize from
"""
if val is None:
if provided_range is None:
return default_range
... | c317adf7f850e89694f523cd499f58e6d87981ae | 584,597 |
from typing import OrderedDict
def transform_object_tree(f, o, key_transform=lambda k: k):
"""
Apply a function (f) on all the values in the given document tree, returning a new document of
the results.
Recurses through container types (dicts, lists, tuples).
Returns a new instance (deep copy) w... | ce0941c4eaa75bf0672b50e1fff37664c3bdced9 | 584,598 |
def profile_filter(rec):
"""
Filter records without profiles.
Filter records without profiles, which are additional numerical data associated with each position in the sequence.
These are added by the user and can correspond to things like the output of language models like UniRep or AminoBert.
Pa... | 4c26f11e97c25db375918ad5fc8ddf2f7411d701 | 584,599 |
def _is_cookie_marked_for_deletion(request):
"""
Returns whether the session cookie has been designated for deletion
in the given request object.
"""
return getattr(request, 'need_to_delete_cookie', False) | da731d8d5b9f261334fc8ee85dc40eaf3d47199d | 584,601 |
def format_mac(mac):
"""Format a MAC address."""
return ":".join([format(octet, "02x") for octet in mac]) | 4371947570768d17fc8e0a2ecf4a402f66695a15 | 584,604 |
import hashlib
def actual_hash(path):
"""Hash the file at path and return it."""
hasher = hashlib.sha256()
with open(path, 'rb') as ins:
hasher.update(ins.read())
return hasher.hexdigest() | 964c9c872ad2f6ea91753de756caaf82adbd802b | 584,607 |
from typing import Optional
def _dash_empty(s: str) -> Optional[str]:
"""
Several fields use a dash to indicate the field has no value.
"""
return None if s == '-' else s | 54b203fd11fa942631735354bafa1e425d7eb5c4 | 584,609 |
import hmac
import hashlib
def compare_digest(a, b):
"""Intended to be a constant-time comparison."""
if hasattr(hmac, 'compare_digest'):
return hmac.compare_digest(a, b)
return hashlib.sha1(a).digest() == hashlib.sha1(b).digest() | 66b32bb3535faf30bc437f7ed054d2b151e92ef8 | 584,611 |
import hashlib
def md5sum(filename):
"""Compute the MD5 checksum of a given file"""
blocksize = 65536
hasher = hashlib.md5()
with open(filename, "rb") as fp:
buf = fp.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = fp.read(blocksize)
return hash... | 713224fb77e0509ada1f58bc5b7eb6eb8f07824d | 584,614 |
def exptimewarning(bin_ix, events, verbose=0, ratio=0.5):
"""
Passes a warning if the effective exposure time within a bin is
significantly less than the raw exposure time, which might produce
anomalous values due to counting statistics or be a symptom of a problem
in the exposure time c... | bd3372b046db193d5af2eda7e3b283130b1f4846 | 584,615 |
def filter_with_email(df, col):
""" Filter any boxes that contain emails. These are (almost?) always addresses or disclaimers"""
df['has_email'] = df[col].str.contains(r'([\w.\-]+@[\w\-.]+[.]([\w\-.]+)?[\w])', regex=True)
return df[~df.has_email] | 6401e6487dd264e0ced49cfca676399eead613ea | 584,616 |
import inspect
def get_lineno_from_deeper_in_stack(n_frames_offset, original_lineno, func_name=None):
"""
Given a line number, find the frame in the stack that it refers to,
and return the line number from a frame deeper in the stack.
If `func_name` is passed, change the line number only if the origin... | 17abb7ec3758cb0f2491100d37ff9232496f82d9 | 584,617 |
def _directory_element(elem_type, name, dot_path=None):
"""instantiate directory element dictionary"""
element = {
'type': elem_type,
'name': name,
'dot_path': dot_path,
'sub_elements': []
}
return element | 13480a3e74508c0c1f12ef5c1519d528973a3ab0 | 584,618 |
def erase_loop_in_image(image, istart, jstart, width, xloop, yloop):
"""
Makes all the points in a loop and its vicinity as zero in the original
image to prevent them from being traced again.
Parameters
----------
image : `numpy.ndarray`
Image in which the points of a loop and surroundi... | 958c88ba4b172da1969bfc9341a17a68ecb80179 | 584,622 |
def map_float(to_float) -> float:
"""Maps value to float from a string.
Parameters
----------
to_float: various (usually str)
Value to be converted to float.
Returns
-------
mapped_float: float
Value mapped to float.
Examples
--------
>>> number_one = "1"
... | 476bf50b52d7317f8c120a34dc3cd870b512b074 | 584,624 |
from typing import List
def selection_rule_fn(l1: int, l2: int, lmax=None, lfilter=None) -> List[int]:
"""
selection rule according to the triangle inequality:
\|l1 - l2\| <= l <= l1 + l2.
This inequality is euqivalent to the following inequality system:
(1) l1 + l2 >= l
(2) l2 + l >= l1
... | 0aeb8d25b1b5c487d833bce2dd23684bff147981 | 584,625 |
def intersperse(lst, item):
""" Insert item between each item in lst.
Copied under CC-BY-SA from stackoverflow at:
https://stackoverflow.com/questions/5920643/
add-an-item-between-each-item-already-in-the-list
"""
result = [item] * (len(lst) * 2 - 1)
result[0::2] = lst
return result | fa3dd575cca6360bc5d49bc804eba7ce6cfdf0a5 | 584,630 |
import click
def _parse_ip_input(ip_input):
"""Parse the IP address input, return the IP address and port.
The user may have either (1) added spaces in the IP address , or
(2) included the port number (delimited by a colon). In both cases, this
is likely due to copy/pasting from previous output of th... | 2e101112942e15d652965f354fe8845beaa84973 | 584,631 |
def distance_between(agents_row_a, agents_row_b):
"""
define distance_between function to calculate distance between 2 agents
"""
return (((agents_row_a._y - agents_row_b._y)**2) + ((agents_row_a._x - agents_row_b._x)**2))**0.5 | 81431d42c9bb00d200772a9b1163f4aa138f7528 | 584,632 |
def do_use_container(**kwargs):
"""
Decide whether to use a container or not.
:param kwargs: dictionary of key-word arguments.
:return: True is function has decided that a container should be used, False otherwise (boolean).
"""
return True | cdb684e97e4c691dde8e599e7b9ac8c23cb8493a | 584,633 |
def _get_pairs_of_neighbours(graph, node):
""" For a given node, return all possible pairs of neighbours.
Returns a list of tuple pairs. Each tuple has the smallest element
first. The list is also sorted.
"""
neighbours = list(graph.edge[node].keys())
pairs = []
n = len(neighbours... | 1b81007a3c8e593bb442d93010d2f5b80dd09732 | 584,635 |
def precision_recall_etc(classification, actual_classification):
"""Given a pair of classifications and actual classifications,
calculates various assessment parameters of the classification
Parameters calculated: precision, recall, specificity, NPV, f1,
tp (true positive), tn (true negative), fp ... | 6127f4724dcc1b86da03552f05fc40fe02f7b6c2 | 584,636 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.