content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def sign(input, *args, **kwargs):
"""
Returns a tree of new tensors with the signs of the elements of input.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.sign(ttorch.tensor([12, 0, -3]))
tensor([ 1, 0, -1])
>>> ttorch... | 768b4a6a4d12d4f7de5854c060fe1d7a494e8e6a | 21,396 |
def _get_included_folds(folds, holdout_index = None):
"""
Returns a list that contains the holds to include whe joining.
If a holdout index is specified, it will not be included.
:param folds: the folds to join
:param holdout_index: an index to holdout
:return: the folds to use when joining
... | f6715734620d3acbb43fc1146b84d312199ad741 | 21,398 |
def determine_colors(percentage):
"""
Determine the color of the duplicated section.
The color depends on the amount of code duplication.
"""
colors = []
if 3 >= percentage > 0:
colors.append("rgb(121, 185, 79)")
elif 5 >= percentage > 3:
colors.append("rgb(255, 204, 5)")
... | 3b9aa1071476a34c30fef274fb2a0d86f3eeb687 | 21,399 |
def equal_near(item_1: float, item_2: float, thresold: float = 0.1) -> bool:
"""Is two item close to equl?
Return True is difference less than thresold.
Args:
item_1 (float): First item.
item_2 (float): Second item.
thresold (float, optional): Thresold for compare. Defaults to 0.01.... | e9d61f1e14d7c09a42444d32da19e0d81be56af2 | 21,403 |
import itertools
def reject(iterable, conditional=None):
"""
Returns the values in list without the elements that the truth test (predicate) passes. The opposite of filter.
params: iterable, conditional
iterable -> list, sequenece, set, dictionary, generator etc
conditional -> a lambda... | 02baa409454d20c07e328b669014768fdd971e5c | 21,407 |
def build_msg(request, msg_type, name, drink):
"""Personalize SMS by replacing tags with customer info"""
msg = request.form.get(msg_type)
msg = msg.replace('<firstName>', name)
msg = msg.replace('<productType>', drink)
return msg | 2a22f1b48717d9a874e2397791f734fce483e703 | 21,410 |
def _pascal_case_to_underscore_case(value: str) -> str:
"""
Converts a pascal case string (e.g. MyClass)
into a lower case underscore separated string (e.g. my_class).
"""
result = ""
state = "initial"
partial = ""
for char in value:
if "A" <= char <= "Z":
if state ==... | 540d4b7525424d3e2f40f52d357fcb6c94b77d52 | 21,416 |
import struct
def read_uint32(fp, pos):
"""Read 4 little-endian bytes into an unsigned 32-bit integer. Return value, position + 4."""
fp.seek(pos)
val = struct.unpack("<I", fp.read(4))[0]
return val, pos + 4 | 2b2f4fa99bc480aae5eb8bc8602f1c11aa775031 | 21,418 |
import collections
def process_types(mrsty_file):
"""Reads UMLS semantic types file MRSTY.2019.RRF.
For details on each column, please check: https://www.ncbi.nlm.nih.gov/books/NBK9685/
"""
cui_to_entity_types = collections.defaultdict(set)
with open(mrsty_file) as rf:
for line in rf:
... | b20b26f5015abb2ee5ce718eaa83895d4cb4f5e2 | 21,422 |
def week_of_year(date):
"""
Our weeks starts on Mondays
%W - week number of the current year, starting with the first
Monday as the first day of the first week
:param date: a datetime object
:return: the week of the year
"""
return date.strftime("%W") | 6de546b23e5cc717b3b0fc357da3af6b4fa1305b | 21,425 |
def append_hostname(machine_name, num_list):
"""
Helper method to append the hostname to node numbers.
:param machine_name: The name of the cluster.
:param num_list: The list of nodes to be appended to the cluster name.
:return: A hostlist string with the hostname and node numbers.
"""
hos... | d2ff25273a21682ec31febc1e63fbc2f562017c3 | 21,430 |
def objsize(obj):
"""
Returns the size of a deeply nested object (dict/list/set).
The size of each leaf (non-dict/list/set) is 1.
"""
assert isinstance(obj, (dict, list, set)), obj
if not obj:
return 0
if isinstance(obj, dict):
obj = obj.values()
elem = next(iter(obj))
... | 66c792c4799df530cded59c5a006ae251032a2b9 | 21,433 |
def reduceDictionary(data: dict):
"""
This function reduce a dictionary in the case of one only element dict.
Eg. a = {"key": value} -> value
"""
if len(data) == 1:
return data[list(data.keys())[0]]
else:
return data | 9165a12bf04601d903fb1b6caed120a193279e30 | 21,435 |
from typing import Dict
from typing import Any
def merge_dict(dict1: Dict[str, Any], dict2: Dict[str, Any]
) -> Dict[str, Any]:
"""Merge two dictionaries into a third dictionary.
Args:
dict1: First dictionary to be merged.
dict2: Second dictionary to be merged.
Returns:
A dictionary ... | baa64359ab740fcf9689305d091a75fb7c7a0cbc | 21,436 |
def normalise_error_asymptotic(absolute_error: float, scaling_factor: float) -> float:
"""
Given an error in the interval [0, +inf], returns a normalised error in [0, 1]
The normalised error asymptotically approaches 1 as absolute_error -> +inf.
The parameter scaling_factor is used to scale for magnit... | a3a2a99390acf65b334fc7b2b1d0792c042582fd | 21,439 |
def inverse_clamp(value, liveband):
"""
Ensures value is in (-β, -liveband] βͺ [liveband, β)
liveband must be a positive value
"""
if value > 0:
value = max(value, liveband)
if value < 0:
value = min(value, -liveband)
return value | 07b0b617e1658bf6534b92360087bd0b150ef731 | 21,443 |
import math
def normalize_value(x, exponent_min, exponent_max):
"""
Normalize the input value. Note that this assumes that `allocation: lg2` is used for the color space in
the OpenColorIO configuration.
:param x: Input value
:param exponent_min: Smallest exponent for the input values
:param ex... | 808f70446a2e450fd7dfe1df480c696ed38163dd | 21,447 |
def first_word(str):
"""
returns the first word in a given text.
"""
text=str.split()
return text[0] | 73f1efc24c6c68e92b2af824358b0656cfbe278b | 21,448 |
import torch
def sinc(x: torch.Tensor):
"""
Implementation of sinc, i.e. sin(x) / x
__Warning__: the input is not multiplied by `pi`!
"""
return torch.where(x == 0, torch.tensor(1., device=x.device, dtype=x.dtype), torch.sin(x) / x) | 2b7fd194a0e5ef8449b88f711312fce9a2d0ba84 | 21,455 |
def collisions(distance_list, distance_cutoff):
"""
Determine if there are any collisions between non-bonded
particles, where a "collision" is defined as a distance shorter than 'distance_cutoff'.
:param distance_list: A list of distances.
:type distance_list: List( `Quantity() <htt... | cab45e8a2da21b9096656cce7eedce74fdae4d76 | 21,462 |
def _get_comparable_seq(seq_i, seq_j, start_phase, end_phase):
"""
Return the residues of the exon/subexon that can be shared.
It takes into account that first/last residue could be different
if the start/end phase is different from 0 or -1.
>>> _get_comparable_seq("ASMGSLTSSPSSL", "TSMGSLTSSPSSC"... | 0d309f2c2081e84f7285485577b4edd84aba9635 | 21,463 |
from typing import Dict
def csv_pep_filter(p, **kwargs) -> Dict[str, str]:
"""
CSV PEP filter, that returns Sample object representations
This filter can save the CSVs to files, if kwargs include
`sample_table_path` and/or `subsample_table_path`.
:param peppy.Project p: a Project to run filter o... | 8cadf3f1cf292e6b511bf7d2489ffaa0edf22191 | 21,464 |
import torch
def onehot_labels(labels: torch.Tensor, n_classes: int):
"""Convert loaded labels to one-hot form.
:param labels: tensor of shape (batch_size x n_cells) with integers indicating class
:param n_classes: number of classes
:return: tensor of shape (batch_size x n_cells x n_classes) with one... | 3e27693b62eacf19d1bd996a79e18b82addc91e6 | 21,465 |
def list_encoder_factory(type_callable):
"""
Creates a function encoder that iterates on the elements of a list to apply the specified type_callable format.
:param type_callable: type to apply to data
:return: function that applies type_callable to a supplied list of data
"""
def inner(data):... | 6a892956d94e88e24ad738de6a19e2394aa34842 | 21,470 |
def hex_to_rgb(value):
"""Given a color in hex format, return it in RGB."""
values = value.lstrip('#')
lv = len(values)
rgb = list(int(values[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
return rgb | 274725a7f6695e190d3590565c935fbe1f6c7676 | 21,471 |
def determine_input_arg(arg_val, default_arg_val):
""" if arg_val exists, use it, else return default_arg_val """
if arg_val:
return arg_val
else:
return default_arg_val | c15500b7869a5b4c5a0c687228c926bfa4568f74 | 21,474 |
def _dict_depth(d):
"""
Get the nesting depth of a dictionary.
For example:
>>> _dict_depth(None)
0
>>> _dict_depth({})
1
>>> _dict_depth({"a": "b"})
1
>>> _dict_depth({"a": {}})
2
>>> _dict_depth({"a": {"b": {}}})
3
Args:... | 0c6fd91ed64b25ff023edbfbf210c6b354cd3af8 | 21,478 |
def inherit_function_doc(parent):
"""Inherit a parent instance function's documentation.
Parameters
----------
parent : callable
The parent class from which to inherit the documentation. If the
parent class does not have the function name in its MRO, this will
fail.
Example... | 0d22610e66118363fdeda6139eab0a8065e6c354 | 21,481 |
import re
def check_files(files, count_limit, size_limit):
"""
Check if uploaded files are conforming given requirements.
"""
if len(files) == 0:
return False, "No file was uploaded"
elif len(files) > count_limit:
return False, "Limit on amount of files exceeded"
for file in f... | 25ccb7641b9f4b8b3f71f25dbcbf5f73be8de6b0 | 21,484 |
import math
def distance_between_points(p0, p1):
""" Distance between two points (x0, y0), (x1, y1)
Parameters
----------
p0 : tuple
Point 0
p1 : tuple
Point 1
Returns
-------
distance : value
Distance
"""
return math.sqrt((p0[1] - p1[1])... | 58ee3b4536c912846704c581fa42065cd1b2f0a1 | 21,487 |
def _stocknames_in_data_columns(names, df):
"""Returns True if at least one element of names was found as a column
label in the dataframe df.
"""
return any((name in label for name in names for label in df.columns)) | 30eee497f7a21755eda7e1915bf84dc800a09abc | 21,488 |
import six
def to_bytes(value, encoding='utf-8'):
"""
Makes sure the value is encoded as a byte string.
:param value: The Python string value to encode.
:param encoding: The encoding to use.
:return: The byte string that was encoded.
"""
if isinstance(value, six.binary_type):
retu... | c4f0e24d39ee565135326550006a3d5311adbb40 | 21,491 |
import requests
def get_team(team_id, gw):
""" Get the players in a team
Args:
team_id (int): Team id to get the data from
gw (int): GW in which the team is taken
Returns:
(tuple): List of integers, Remaining budget
"""
res = requests.get(
'https://fantasy.premier... | 295c46628c14ad64715ee4a06537598878a8ef2e | 21,495 |
def get_indexes(start_index, chunk_size, nth):
"""
Creates indexes from a reference index, a chunk size an nth number
Args:
start_index (int): first position
chunk_size (int): Chunk size
nth (int): The nth number
Returns:
list: First and last position of indexes
... | a8dba6fef788b542b502e1e0ce52ce57f2372485 | 21,498 |
def _get_request_wait_time(attempts):
""" Use Fibonacci numbers for determining the time to wait when rate limits
have been encountered.
"""
n = attempts + 3
a, b = 1, 0
for _ in range(n):
a, b = a + b, a
return a | 91e4c165fee5b821e8654468e954786f89ad1e0b | 21,502 |
def GetProblemIndexFromKey(problems, problem_key):
"""Get a problem's index given its key and a problem list.
Args:
problems: Iterable of problems in the current contest.
problem_key: String with the problem key that must be searched.
Returns:
The index of the requested problem in the problem list. ... | 08e84afe65695c0d0aedb391975b37c7b42f22af | 21,508 |
from typing import List
from pathlib import Path
def get_core_paths(root: str) -> List[str]:
"""Return all the files/directories that are part of core package.
In practice, it just excludes the directories in env module"""
paths = []
for _path in Path(root).iterdir():
if _path.stem == "envs":... | 96b9e6391fa8aabbec947a88c4f142b8007eaddc | 21,509 |
import re
def get_symbol_name(module, symbol_id):
"""Return a pretty printed name for the symbol_id if available.
The pretty printed name is created from OpName decorations for the
symbol_id if available, otherwise a numerical ID (e.g. '%23') is
returned.
Names are not unique in SPIR-V, so it is... | b82ec2e06e289a58d1a4dc6ebd858a74a4c07ca6 | 21,510 |
import struct
def unpack_uint32(byte_stream, endian="<"):
"""Return list of uint32s, (either endian) from bytes object.
Unpack a bytes object into list of 32-bit unsigned integers.
Each 4 input bytes decodes to a uint32.
Args:
byte_stream (bytes): length is a multiple of 4
endian (ch... | 87f7bd12607e9be193098a407b51cbc01bdbe3c4 | 21,511 |
def tag_to_rtsip(tag):
"""Convert tag to relation type, sense, id, and part."""
rel_type, rel_sense, rel_id, rel_part = tag.split(":")
return rel_type, rel_sense, int(rel_id), rel_part | 38237836cd16d34a594296c5077eee062600d899 | 21,519 |
def _clean_name(s: str) -> str:
"""
>>> _clean_name("Residual x ")
'residual_x'
"""
return str(s).strip().lower().replace(" ", "_") | 15bce66826a7caa76f4f25810369047de451c276 | 21,520 |
import torch
def sample_points(rays_o, rays_d, near, far, num_samples, perturb=False):
"""
Sample points along the ray
Args:
rays_o (num_rays, 3): ray origins
rays_d (num_rays, 3): ray directions
near (float): near plane
far (float): far plane
num_samples (int): num... | 28adc68aa8a6d8cf0fd54fa62d23bc2e7a1dc296 | 21,529 |
def html(html_data):
"""
Builds a raw HTML element. Provides a way to directly display some HTML.
Args:
html_data: The HTML to display
Returns:
A dictionary with the metadata specifying that it is to be
rendered directly as HTML
"""
html_el = {
'Type': ... | 898100fe5eef22fb7852b5991b1927ac4b3bf8f6 | 21,530 |
def distance_sqr_2d(pt0, pt1):
""" return distance squared between 2d points pt0 and pt1 """
return (pt0[0] - pt1[0])**2 + (pt0[1] - pt1[1])**2 | 23820a4e5f396ddda9bea0a0701c26d416e6567b | 21,532 |
def wlv_datetime(value):
"""Default format for printing datetimes."""
return value.strftime("%d/%m/%Y %H:%M:%S") if value else "" | c8bf50d239c7bad195e65f6036c7bcf522d38feb | 21,533 |
def get_diff_sq(a, b):
"""
Computes squared pairwise differences between a and b.
:param a: tensor a
:param b: tensor b
:return: squared pairwise differences between a and b
"""
aa = a.matmul(a.t())
bb = b.matmul(b.t())
ab = a.matmul(b.t())
diff_sq = -2 * ab + aa.diag().unsqueez... | fcaec3db6316c8872c24a89ee56e1b6e6b83787b | 21,535 |
from typing import List
def D0_dd( phi: List[float], s: List[float] ) -> float:
"""
Compute the central difference approximation of the second order derivative of phi along the same dimension, as in [3].
:param phi: List of the 3 upwind-ordered phi values (i.e. [\phi_{i-1}, \phi_i, \phi_{i+1}]).
:param s: List of... | 20c012098827e929b08770fe159d87cf29eb15c2 | 21,537 |
def separate_categories(data):
"""
Separate the rows concerning "script-identifiable edits" from those
concerning "other edits".
Also, in each categry, and for each line, calculate the sum of
levenshtein distances across all edits for that line.
Return two separate DataFrames.
"""
# Line... | 6d7b844bd69402fc32c2deb4c0ee3df131fdf6aa | 21,538 |
import math
def calculate_distance(coord1, coord2, box_length=None):
"""
Calculate the distance between two 3D coordinates.
Parameters
----------
coord1, coord2 : list
The atomic coordinates [x, y, z]
box_length : float, optional
The box length. This function assu... | 954bdf6dc66ca4edf58b1b96aa63343930e1a604 | 21,539 |
def practice_problem2a(sequence, delta):
"""
What comes in:
-- A sequence of integers, e.g. ([2, 10, 5, -20, 8])
-- A number delta
What goes out:
-- Returns a new list that is the same as the given list,
but with each number in the list having had the given
delta
... | 31cc3f1272f5563db0f2edcb5c1f5f7052b10751 | 21,542 |
import torch
def compute_tv_norm(values, losstype = "l2"):
"""Returns TV norm for input values.
Source: regnerf/internal/math.py
Args:
values: [batch, H, W, *]. 3 or more dimensional tensor.
losstype: l2 or l1
Returns:
loss: [batch, H-1, W-1, *]
"""
v00 = values[:, :-1, :-1]
v01 = values[... | 34088d342cac0f1d4ee0ec4946f73aec9cc92639 | 21,543 |
import re
def is_sale(word):
"""Test if the line is a record of a sale"""
cattle_clue = r'(bulls?|steers?|strs?|cows?|heifers?|hfrs?|calf|calves|pairs?|hc|sc)'
price_clue = r'[0-9,]+'
has_cattle = any(bool(re.search(cattle_clue, this_word, re.IGNORECASE)) for this_word in word)
has_price = any(bo... | f4b53e28b18f7f7fdffeebf8884076224660ae48 | 21,545 |
import re
def word_count(text: str) -> int:
"""
Counts the total words in a string.
Parameters
------------
text: str
The text to count the words of.
Returns
------------
int
The number of words in the text.
"""
list_words = re.split(' |\n|\t', text) #Splits a... | 869afd06172c9ffb61430489804cac20706ca245 | 21,551 |
def tobin(i):
"""
Maps a ray index "i" into a bin index.
"""
#return int(log(3*y+1)/log(2))>>1
return int((3*i+1).bit_length()-1)>>1 | a32bf5895071ac111bbd0c76a3fa8b630feb252d | 21,552 |
def get_model_path(model):
"""Return the qualified path to a model class: 'model_logging.models.LogEntry'."""
return '{}.{}'.format(model.__module__, model.__qualname__) | ab6b631aa4fb3acac0355c587f792441ecf25702 | 21,553 |
def get_image_data(image):
"""
Return a mapping of Image-related data given an `image`.
"""
exclude = ["base_location", "extracted_to_location", "layers"]
image_data = {
key: value for key, value in image.to_dict().items() if key not in exclude
}
return image_data | 684cd2a358599b161e2311f88c3e84c016ad2fef | 21,558 |
def proceed() -> bool:
"""
Ask to prooceed with extraction or not
"""
while True:
response = input("::Proocced with extraction ([y]/n)?")
if response in ["Y", "y", ""]:
return True
elif response in ["N", "n"]:
return False
else:
continu... | 6d4c93ee7a216d9eb62f565657cf89a2e829dd30 | 21,559 |
def clean_input(text):
"""
Text sanitization function
:param text: User input text
:return: Sanitized text, without non ascii characters
"""
# To keep things simple at the start, let's only keep ASCII characters
return str(text.encode().decode("ascii", errors="ignore")) | 974a24e4d516faac650a9899790b66ebe29fc0a2 | 21,560 |
import requests
def get_player_stats_from_pfr(player_url, year):
"""
Function that returns the HTML content for a particular player
in a given NFL year/season.
:param player_url: URL for the player's Pro Football Reference Page
:param year: Year to access the player's stats for
:return: Strin... | d6e4b34de9498dd8dff80bf5e6bd0bdc9f44255b | 21,564 |
def euclidean_rhythm(beats, pulses):
"""Computes Euclidean rhythm of beats/pulses
From: https://kountanis.com/2017/06/13/python-euclidean/
Examples:
euclidean_rhythm(8, 5) -> [1, 0, 1, 0, 1, 0, 1, 1]
euclidean_rhythm(7, 3) -> [1, 0, 0, 1, 0, 1, 0]
Args:
beats (int): Beats of t... | c1ded4891dfc658a4ba1e92db7b736c70f25f4f5 | 21,566 |
import csv
def get_device_name(file_name, sys_obj_id, delimiter=":"):
"""Get device name by its SNMP sysObjectID property from the file map.
:param str file_name:
:param str sys_obj_id:
:param str delimiter:
:rtype: str
"""
try:
with open(file_name) as csv_file:
csv_re... | 3074dffc5274d882bb99c13a0e642b05fd68cb9c | 21,568 |
def get_replaces_to_rule(rules):
"""Invert rules dictionary to list of (replace, rule) tuples."""
replaces = []
for rule, rule_replaces in rules.items():
for replace in rule_replaces:
replaces.append((replace, rule))
return replaces | de3fd8235eb8926682544def49de500412ee3084 | 21,569 |
def query_epo_desc_table(src_table: str):
"""
Return the query generating the aggregate table to compute descriptive statistics on the EPO
full text database
:param src_table: str, table path to EPO full-text database on BigQuery e.g.
'project.dataset.table'
:return: str
"""
query = f"""... | 20f114cc4c54e03261362458140b2f7bc7318ea4 | 21,570 |
def _get_metadata_map_from_client_details(client_call_details):
"""Get metadata key->value map from client_call_details"""
metadata = {metadatum[0]: metadatum[1] for metadatum in (client_call_details.metadata or [])}
return metadata | 1d0b843b41f2777685dad13b9269410033086b02 | 21,571 |
def snake_to_camel_case(name: str, initial: bool = False) -> str:
"""Convert a PEP8 style snake_case name to CamelCase."""
chunks = name.split('_')
converted = [s.capitalize() for s in chunks]
if initial:
return ''.join(converted)
else:
return chunks[0].lower() + ''.join(converted[1:... | 1669c0a1065da8133771d83ebbc7ed4c393d4a8f | 21,572 |
def filter_default(input_dict, params_default):
"""
Filter input parameters with default params.
:param input_dict: input parameters
:type input_dict : dict
:param params_default: default parameters
:type params_default : dict
:return: modified input_dict as dict
"""
for i in params... | 5cae639c2a18c6db7a858ebe4ce939bf551088c2 | 21,577 |
def is_even(n):
"""Determines whether `n` is even
"""
# even = n % 2 == 0
even = not(n & 1)
return even | cfb0d961bf456fe84b99ba3dd81ec34b2bdd4f2f | 21,579 |
import time
def minutesTillBus(busTimepoint, nowTime = None):
""" given a bus timepoint record from getTimepointDepartures, return the number of minutes until that bus, as a float. nowTime is the current time since unix epoch, but leave it out to just use the system time. """
t = busTimepoint["DepartureTime"]
if ... | b26f194fd07160a2e7b2d5a059a6242af636d1fe | 21,580 |
import base64
def read_file_as_b64(image_path):
"""
Encode image file or image from zip archive to base64
Args:
image_path (bytes or str): if from a zip archive, it is an image in
bytes;
if from local directory, it should be a
... | 516200ba2c7a129f236c92dbf7952592f449b6e3 | 21,581 |
from typing import Iterable
import functools
def prod(iterable: Iterable[int]) -> int:
""" Calculates the product of an iterable. In Python 3.8 this can be replaced with a call to math.prod """
return functools.reduce(lambda x, y: x * y, iterable) | 219aec67b87fb1b4b16e6d4e70f8d1deca3a4388 | 21,582 |
def return_int(user_input):
"""Function to check and return an integer from user input"""
try:
user_int = int(user_input)
except ValueError:
print("Oops! Not a valid integer format.")
else:
return user_int | 01dccefb92e3b854029ec6100a11d02bc51af240 | 21,585 |
def get_clusterID(filename):
"""given a file name return the cluster id"""
return filename.split(".")[0] | 43de7ab212d41d4e7c1d40e6dadb988c178db1f4 | 21,586 |
import json
def to_json(value):
"""A filter that outputs Python objects as JSON"""
return json.dumps(value) | 386a27290c2f9e1f0a926143bc7e54e2ca98912b | 21,594 |
def get_mac_addr_from_dbus_path(path):
"""Return the mac addres from a dev_XX_XX_XX_XX_XX_XX dbus path"""
return path.split("/")[-1].replace("dev_", '').replace("_", ":") | a8603f2f7b6202ab9bafe5f911606efd8dc54358 | 21,599 |
import typing
def compute_parent(
tour_edges: typing.List[int],
) -> typing.List[typing.Optional[int]]:
"""Compute parent from Euler-tour-on-edges.
Args:
tour_edges (typing.List[int]): euler tour on edges.
Returns:
typing.List[typing.Optional[int]]:
parent list.
... | 5887a22faf42fae32b81fab902de9490c5dc4b00 | 21,600 |
from typing import Optional
def build_netloc(host: str, port: Optional[int] = None) -> str:
"""Create a netloc that can be passed to `url.parse.urlunsplit` while safely handling ipv6 addresses."""
escaped_host = f"[{host}]" if ":" in host else host
return escaped_host if port is None else f"{escaped_host}... | 56e44584b2f5e76142c40b639919951772f75aed | 21,602 |
def error404(e):
"""
404 error handler.
"""
return ''.join([
'<html><body>',
'<h1>D20 - Page Not Found</h1>',
'<p>The only endpoint available on this entropy micro-service is <a href="/api/entropy">/api/entropy</a>.</p>',
'<p>For more information including the complete source code, visit <a href="https://gi... | 35ab121b88e84295aaf97e2d60209c17acffd84d | 21,607 |
import string
import random
def id_generator(
size=6,
chars=string.ascii_uppercase + string.ascii_lowercase + string.digits
):
""" Creates a unique ID consisting of a given number of characters with
a given set of characters """
return ''.join(random.ch... | 9a6bf02c63e5ad933340be70e95c812683a69dee | 21,609 |
def convert_hubs_to_datastores(hubs, datastores):
"""Get filtered subset of datastores as represented by hubs.
:param hubs: represents a sub set of datastore ids
:param datastores: represents all candidate datastores
:returns: that subset of datastores objects that are also present in hubs
"""
... | 14e7231f9c6a1e273c217bf77b8a7d3b3632709c | 21,611 |
def inspect_chain(chain):
"""Return whether a chain is 'GOOD' or 'BAD'."""
next_key = chain.pop('BEGIN')
while True:
try:
next_key = chain.pop(next_key)
if next_key == "END":
break
except KeyError:
return "BAD"
if len(chain) > 0:
... | 083886aa31fa81cc90d4c7bd30149c5575a5a675 | 21,613 |
def hex(string):
"""
Convert a string to hex.
"""
return string.encode('hex') | 66ff8fe8797c840d5471dbb4693e0ae6ef32fb8e | 21,624 |
import ast
def literal(str_field: str):
"""
converts string of object back to object
example:
$ str_literal('['a','b','c']')
['a', 'b', 'c'] # type is list
"""
return ast.literal_eval(str_field) | 25d23f55e52cdb4727f157a3db13614932bcbec7 | 21,626 |
def tail_logfile(logfile=''):
"""Read n lines of the logfile"""
result = "Can't read logfile: {}".format(logfile)
lines = 40
with open(logfile) as f:
# for line in (f.readlines()[-lines:]):
# print(line)
result = ''.join(f.readlines()[-lines:])
return result | 61a4046d2a7bfb8be907a325253424b2d425b410 | 21,627 |
from typing import Dict
from typing import Any
from typing import Optional
import requests
def request_data(url: str, params: Dict[str, Any]) -> Optional[str]:
"""Request data about energy production from Entsoe API.
Args:
url (str): Entsoe API url.
params (Dict[str, str]): Parameters for the... | 187d134f3457616d830ec5c78b02a11f880c981e | 21,629 |
def minimum_katcp_version(major, minor=0):
"""Decorator; exclude handler if server's protocol version is too low
Useful for including default handler implementations for KATCP features that
are only present in certain KATCP protocol versions
Examples
--------
>>> class MyDevice(DeviceServer):
... | bcaefb29af78400cd283895fef0d4fd94f175112 | 21,631 |
def newick_to_json(newick_string, namestring = "id", lengthstring = "branch_length", childrenstring = "children", generate_names=False):
"""Parses a newick string (example "((A,B),C)") into JSON format accepted by NetworkX
Args:
newick_string: The newick string to convert to JSON. Names, branch lengths and named
... | b116869f46467390b6dd2463bf2b982f01a95a13 | 21,633 |
def __str2key(_):
"""Make string a valid jinja2 template key e.g. dictionary.key
Ref: https://jinja.palletsprojects.com/en/3.0.x/templates/#variables
"""
return _.replace('.', '') | 7980e8d38576211f9bd02bcedd817c5d0087e415 | 21,635 |
import re
def compile_re(pattern):
""" Compile a regular expression with pattern
Args:
pattern (str): a string representing the pattern
e.g. "NoviPRD-.*" means strings that start with "NoviPRD-"
e.g. ".*\.csv" means strings that end with ".csv"
e.g. ".*xxx.*" means strings that... | f5fa043b9472bf19e350c880bbaf6200739234f5 | 21,636 |
import warnings
def check_args(parsed_args):
""" Function to check for inherent contradictions within parsed arguments.
For example, batch_size < num_gpus
Intended to raise errors prior to backend initialisation.
Args
parsed_args: parser.parse_args()
Returns
parsed_args
"""
... | 160f4bacc40d6187191c6b8ec18e0bc214856d4d | 21,640 |
def email_associated(env, email):
"""Returns whether an authenticated user account with that email address
exists.
"""
for row in env.db_query("""
SELECT value FROM session_attribute
WHERE authenticated=1 AND name='email' AND value=%s
""", (email,)):
return Tr... | 4f5ff9954cf7a73eca17529f74f3004835c6a07d | 21,641 |
def _ListOpToList(listOp):
"""Apply listOp to an empty list, yielding a list."""
return listOp.ApplyOperations([]) if listOp else [] | 1c6aefacdbadc604a2566b85483894d98d116856 | 21,644 |
def calc_rectangle_bbox(points, img_h, img_w):
"""
calculate bbox from a rectangle.
Parameters
----------
points : list
a list of two points. E.g. `[[x1, y1], [x2, y2]]`
img_h : int
maximal image height
img_w : int
maximal image width
Returns
-------
dict
corresponding bbox. I.e. `... | 45be9537c80d54e26a54dc4a04ece3759d988feb | 21,646 |
def __en_omelete(soup):
"""
Helper function to get Omelete News
:param soup: the BeautifulSoup object
:return: a list with the most read news from a given Omelete Page
"""
news = []
anchors = soup.find('aside', class_='c-ranking c-ranking--read').find_all('a')
for a in anchors:
... | 3c18168ca3f4656182e09c5dbde98ce1665b425d | 21,647 |
def trailing_zeros(n):
"""Count trailing zero bits in an integer."""
if n & 1: return 0
if not n: return 0
if n < 0: n = -n
t = 0
while not n & 0xffffffffffffffff: n >>= 64; t += 64
while not n & 0xff: n >>= 8; t += 8
while not n & 1: n >>= 1; t += 1
return t | dd25d3f855500ae4853130c3b84601c51b64d9f0 | 21,651 |
def extract_node_attribute(graph, name, default=None):
"""
Extract attributes of a networx graph nodes to a dict.
:param graph: target graph
:param name: name of the attribute
:param default: default value (used if node doesn't have the specified attribute)
:return: a dict of attributes in form ... | 5ec1b7124ecbe048107d4d571c18fe66436d0c7b | 21,653 |
import struct
def Rf4ceMakeFCS(data):
"""
Returns a CRC that is the FCS for the frame (CRC-CCITT Kermit 16bit on the data given)
Implemented using pseudocode from: June 1986, Kermit Protocol Manual
https://www.kermitproject.org/kproto.pdf
"""
crc = 0
for i in range(0, len(data)):
c = ord(data[i])
q = (crc ... | 81add4f980ded4e26b78252257933a191be8721c | 21,654 |
def _best_streak(year_of_commits):
"""
Return our longest streak in days, given a yeare of commits.
"""
best = 0
streak = 0
for commits in year_of_commits:
if commits > 0:
streak += 1
if streak > best:
best = streak
else:
streak... | 3d0f042dc9565d5ef7002b6729550a76d01d3b00 | 21,655 |
def labels_to_clusters(X, labels):
"""Utility function for converting labels to clusters.
Args:
X (ndarray[m, n]): input dataset
labels (ndarray[m]): labels of each point
Returns:
clusters (list, ndarray[i, n]): list of clusters (i denotes the size o... | d3e316f8563d0e8c4853754bddb294b51462d724 | 21,661 |
import requests
def get_page(url):
"""
Get a single page of results.
"""
response = requests.get(url)
data = response.json()
return data | d7d31ea8abbaa13523f33aa9eb39fca903d5cb21 | 21,662 |
def lst_to_ans(ans_lst):
"""
:param ans_lst: list[str], contains correct guesses the user entered and undeciphered character.
:return: str, turns the list into string.
"""
ans = ''
for i in range(len(ans_lst)):
ans += ans_lst[i]
return ans | b1f0c196a53dc88e76967481d573bdff591597b9 | 21,665 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.