content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _str_to_str(value: str) -> str:
"""Convert ``str`` to ``str``"""
return value | 3237651c783cb7e2223ea2f78cd2a13ff554d7ea | 637,012 |
import string
def sanitise_string_for_stream_id(unsafe_string):
"""
Removes any unhelpful characters (e.g. #,/,<space>,%) from a string.
We pass:
-Letters ([A-Za-z])
-digits ([0-9]),
-hyphens ("-"),underscores ("_"), colons (":"), and periods (".")
-Plus symbol ('+')
... | 7d70534682259e583bdaacd84f9b94ecebcdbf87 | 637,014 |
import unicodedata
def normalize_string(string):
"""Normalize string for tokenization and matching.
Characters can come in composed or decomposed varieties.
We normalize to decomposed characters in order to allow
fine-grained control of accent patterns. The string is
converted to lowercase.
... | 1159b54d4893dfdd6346c628398eeaad9496f6cb | 637,015 |
def add_if_not_none(a, b):
"""Returns a/b is one of them is None, or their sum if both are not None."""
if a is None:
return b
if b is None:
return a
return a + b | 87b71dce3aefddf1affa716547b836855405d3a4 | 637,016 |
def _database_delete_all_data_function_name(dataset):
"""Returns the name of the function to delete all data from the dataset's database"""
return '{}_database_delete_all_data'.format(dataset.name) | ff06ec21a81ef46070e6cd7be592a465baf95e27 | 637,017 |
def removeLocations(lmA, prefix):
"""Removes locations with a given prefix
Keyword arguments:
lmA -- Location map to delete location from
prefix -- Key or part of key in location map dictionary
Creates a copy of provided location map lmA
Copy contains all key-value pairs from l... | ed83a14db23264cf49df81b44b6ce48a9f300c04 | 637,018 |
def create_list_tuples_span_tag(list_span, tag):
""" takes a list of span and returns a list of tuples of the form
[((start_index, end_index), tag), ..., (start_index, end_index), tag)]"""
list_tuples = [(x, tag) for x in list_span]
return list_tuples | f226ce2fca77b8140b58ce9ac64578b21f0e5c64 | 637,021 |
def outliers_z_score(serie, window, treshold):
"""
Find outliers on a serie based on z-scores.
Parameters
----------
:serie: array_like
Input array or object that can be converted to an array.
:windows: int
:treshold: number of standard deviations to filter
Retu... | 4cd730e3912651916a331a22f2f3366bbb327f33 | 637,022 |
def check_bw_unit(bw_unit: str) -> str:
"""Check if the bandwidth unit is one of "gbit" and "mbit".
Parameters
----------
bw_unit : str
The bandwidth unit.
Returns
-------
str
The bandwidth unit changing to lowercase letters and removing extra spaces.
Raises
------... | df7fd27887bd2efb3c9ea5c44c55292fe11d91ae | 637,025 |
import re
def to_snake_case(name):
"""Convert the name from camel-style to snake-style."""
intermediate = re.sub('(.)([A-Z][a-z0-9]+)', r'\1_\2', name)
insecure = re.sub('([a-z])([A-Z])', r'\1_\2', intermediate).lower()
if insecure[0] != '_':
return insecure
return insecure[2:] | a99bb1267465fe392bd5699f3ee28b0bc18afee3 | 637,026 |
def field(name, transform=None):
""" Convenience function to explicitly return a "field" specification for
a Bokeh :class:`~bokeh.core.properties.DataSpec` property.
Args:
name (str) : name of a data source field to reference for a
``DataSpec`` property.
transform (Transform, o... | bc391f991fcebad956464c1f0cc741505d3d4028 | 637,027 |
def regulate_column_names(df, test_type):
"""
Regulate column names for flu_ag test data since Quidel changed their column names multiple times.
We want to finalize the column name list to be:
['SofiaSerNum', 'TestDate', 'Facility',
'Zip', 'FluA', 'FluB', 'StorageDate']
"""
# No reg... | 2439bf64e1efcfefa5bcb93c0f68bfed539cb175 | 637,028 |
def chunk(lines):
"""Return groups of lines separated by whitespace or comments
[(int, str)] -> [[(int, str)]]
"""
chunks = []
chunk = []
for lineno, line in lines:
stripped = line.strip()
if not stripped or stripped[0] == '#':
if chunk:
chunks.append... | c2b372248983e723e7c06d3fa652c9863442df77 | 637,033 |
def _user_lookup(key, users):
"""Given a user id and a list of users, search list for user with
matching id. If found, return user name, else return string 'Not Found'
Args:
key (str): User id to match on
users (list of obj): List of users objects (students)
Return:
(str): U... | 2b02d9b4b3898497f163abefafb23f4afaa17f44 | 637,035 |
def post_process_response(token_ids, reader, merge=True):
"""Post-process the decoded sequence.
Truncate from the first <eos> and remove the <bos> and <eos> tokens.
Convert token_ids to words(merge=True) or tokens(merge=False)
Args:
token_ids: Token id sequence.
merge: If true, merge s... | 669ca779442a66a23fb10c053fd1c8c62bd519a6 | 637,038 |
def retreive_details(input_dict,keys_to_extract):
"""
Retreive specific keys from a dictionary object
This function searches through a dictionary, and
retreives keys that match keys from a list. This function
will find matching keys in every level of the dictionary heirarchy.
Inputs:
... | f80c4bac321227a09a9cdf8bac3b1b4e0b16ff5d | 637,039 |
def _get_bbox_feature(image_size, feature_map, x_min, x_max, y_min, y_max):
"""Get bounding box features.
The feature is the center pixel of a bounding box.
Args:
image_size (tuple): Size of an image in [x, y].
feature_map (numpy.ndarray(numpy.float)): Feature map of size [x, y, n_features... | a5e61183686661015ee6c401b7661ee6c39d7d5e | 637,042 |
def _sane_version_list(version):
"""Ensure the major and minor are int.
Parameters
----------
version : list
Version components
Returns
-------
version : list
List of components where first two components has been sanitised
"""
v0 = str(version[0])
if v0:
... | 5532b9feffa42026abe02cd5087f79de5975e9b6 | 637,043 |
def transpose_table(table):
"""
Transpose any table of values stored as list of lists.
Table must be rectangular.
Returns: Transposed list of lists.
"""
n_table = []
while len(n_table) != len(table[0]):
n_table += [[]]
for col_ind in range(0, len(table[0])):
for row_in... | f6edb065df5b609c482ff85c0126dbd0301ef27f | 637,044 |
def _matches2str(matches):
"""
Get matches into a multi-line string
:param matches: matches to convert
:return: multi-line string containing matches
"""
output_text = ''
for match in matches:
output_text += f"{match[0]} - {match[1]}\n"
return output_text | 61eef45b59a9143cc6fbdf0701c38cf4135df558 | 637,046 |
def parse_list(value):
"""
Parse a string to extract a simple list of string values.
"""
if value.startswith('[') and value.endswith(']'):
value = value[1:len(value)-1].strip()
elif not value.strip():
return []
return list(value.split(',')) | 933dbb5af1f662bc3d4782d547c70d75ea02d6c1 | 637,047 |
def mk_int(s):
"""Convert to a int, if it can't, return 0"""
s = s.strip().replace(",", "")
return int(s) if s else 0 | 6f7ee17125fa9add84d624f9e3cad610cfc3be0f | 637,048 |
def load_metaparameters(param_dict=None):
"""
Parameters for bayesian optimizer. Default dictionary listed and updated by param_dict.
The default contains some redundancy dependent on the architecture.
If the generic architecture is used, the 'dense_X' values are ignored.
If not, the values of 'den... | 684d2cf181e5f51a1bbc476ff684a75859b8542f | 637,054 |
def _apply_filters(filters, fn):
"""
Parameters
----------
filters: a filter bank
fn: a function to apply on the parameters
Returns
-------
filters: the filters modified
"""
for k in range(len(filters)):
filters[k] = fn(filters[k])
return ... | e29e9f767914b7b915d49d99e429981f1ada2748 | 637,055 |
def bytes_to_int(d):
"""Convert a list of bytes to an int
Bytes are in LSB first.
>>> hex(bytes_to_int([0, 1]))
'0x100'
>>> hex(bytes_to_int([1, 2]))
'0x201'
"""
v = 0
for i,d in enumerate(d):
v |= d << (i*8)
return v | feeb6a4bfaf248f68ca5aacaafc73134dcf57dd3 | 637,056 |
import pkg_resources
def _check_presence(dependencies):
"""Check if all dependencies are present. Return missing dependencies."""
missing = []
for dependency in dependencies:
requirement = dependency.name + dependency.constraint
try:
pkg_resources.require(requirement)
e... | 75d98b914829fd6acd44a84db9b27b88a0b07c83 | 637,058 |
import secrets
def spoiler(help_text: str, button_text="🕵️ Show Hint") -> str:
"""
HTML boilerplate for spoiler element in challenge descriptions.
"""
div_id = secrets.token_hex(5)
return f"""
<div>
<div id="{div_id}-help" class="d-none">
<hr/>
... | d93a93c7c19b33007b999430eff603b9033275b4 | 637,059 |
def arrays_as_dataset(states, actions, rewards, next_states, absorbings, lasts):
"""
Creates a dataset of transitions from the provided arrays.
Args:
states (np.ndarray): array of states;
actions (np.ndarray): array of actions;
rewards (np.ndarray): array of rewards;
next_st... | ac6a5cc1d63c6508e8e181f86aae6d7d46d6d513 | 637,061 |
def is_utf8_encoded(bstring):
"""
Return ``True`` if the given byte string can be decoded
into a Unicode string using the UTF-8 decoder.
:param bytes bstring: the string to test
:rtype: bool
"""
try:
bstring.decode("utf-8")
return True
except UnicodeDecodeError:
... | 845f79d725b95adc8ba75feabda2c9e68214aa98 | 637,062 |
def find_val_or_next_smaller_iter(bst, x, d=None):
"""Get the greatest value <= x in a binary search tree.
Returns None if no such value can be found.
"""
while True:
if bst is None:
return d
elif bst.val == x:
return x
elif bst.val > x:
(bst, ... | 16b018345f4be498c644868a4661eee7e7a8b499 | 637,063 |
def _validate_name(name):
"""
Validates the given name.
Parameters
----------
name : `None` or `str`
A command's respective name.
Returns
-------
name : `None` or `str`
The validated name.
Raises
------
TypeError
If `name` is not given a... | e629f0bbc82d421441344a958554df1082b7fdae | 637,065 |
def get_accuracy(Y, Y_pred):
"""
Calcualtes accuracy.
:param Y: int(N, )
Correct labels.
:param Y_pred: int(N, ) | double(N, C)
Predicted labels of shape(N, ) or (N, C) in case of one-hot vector.
:return: double
Accuracy.
"""
return (Y == Y_pred).mean()
# return ... | c3c16a8e4a96dd8eb80f249377d2cfa3f0b01e98 | 637,068 |
def fib(n):
"""
Compute the n'th Fibonacci number.
:param n: target Fibonacci number
:return: the appropriate number
"""
if n <=2:
return 1
else:
return fib(n-1) + fib(n-2) | 02c86ec003868c61f6198edf7647973d936654c2 | 637,070 |
def python_link_doc(m, o=None, format="rst"):
"""
Returns a url about :epkg:`Python` documentation.
.. runpython::
:showcode:
from pyquickhelper.sphinxext import python_link_doc
print(python_link_doc("io"))
@param m Python module
@param o func... | 2c9444b7a307f03a0dc192d4842c0f414b59f0bc | 637,072 |
def parse_results(results):
""" parses the results file into a dictionary of names and tuples """
# hold the results in a dictionary
results_dict = {}
# loop over each line (result)
for result in results:
# split the string based on spaces
parts = result.split()
# there shoul... | 6ed1868697c043a603470d41bb3e62a6946ea342 | 637,074 |
from typing import Type
from typing import Any
def typed_property(name: str, expected_type: Type[Any]) -> property:
"""Avoids definition of repetitive property class methods.
Simplifies type assertions on class attributes values.
Illustrates an important feature of inner functions or closures.
Args:... | 2f704ae0fe0e6fae60bbc05917ee73b790d77a68 | 637,076 |
def _src_lines(start_line, end_line):
"""
Test lines to write to the source file
(Line 1, Line 2, ...).
"""
return "\n".join(
[f"Line {line_num}" for line_num in range(start_line, end_line + 1)]
) | e4b602774279af8599b98413513835a72731960c | 637,080 |
def _grad_nll(p, gp, y):
"""
Given parameters and data, compute the gradient of the negative log
likelihood of the data under the george Gaussian process.
Parameters
----------
p : array
GP hyperparameters
gp : george.GP
y : array
data to condition GP on
Returns
... | 600f22945036454621860d2289fcfdd9a29fdd1e | 637,081 |
def mutation_type(alleles):
"""
Is this mutation a transition (A <-> G and C <-> T) or a transversion (everything else).
"""
alleles = set([a.upper() for a in alleles])
assert len(alleles) == 2 and alleles.issubset({"A", "C", "G", "T", "N"})
return "ts" if alleles in [{"A", "G"}, {"C", "T"}] els... | 5cd4dd0d7364516a1368860f03355cd918b1fb0e | 637,082 |
import torch
def gaussian_noise(x, std=1, **kwargs):
"""Add Gaussian noise and clips the output."""
return torch.clamp(x + torch.randn_like(x) * std, **kwargs) | 6122fc2ee8dfc52adbd8e8f76e2c01ba4e425ab2 | 637,083 |
from typing import Union
def human_number(number: Union[int, float]) -> str:
"""human-readable number format.
It is a general-purpose number formatter, which separates every three
digits to make it human-readable.
Args:
number (int or float): Accepts only one element (i.e., scalar).
Ret... | 9ba5c22763cc67d057eb59720c0a67b68f720b07 | 637,086 |
def contains(func, iterable):
"""
Return true if one element of iterable for which function returns true.
"""
if func is None:
func = bool
for x in iterable:
if func(x):
return True
return False | 17eed61acc4bbd74ae800fe33298e0548ef7f96b | 637,090 |
def isiterable(variable):
"""
Check whether the given variable is iterable.
Lists, tuples, NumPy arrays, but strings as well are iterable. Integers,
however, are not.
Parameters
----------
variable :
variable to check for being iterable
Returns
-------
answer : :class:... | d01204c0380470cdbe69da5a9c10de1ca0365f68 | 637,091 |
from typing import Callable
def star(f: Callable) -> Callable:
""" Converts a function of multiple arguments, to a function taking a tuple.
Useful for e.g. min(list_of_tuples, key=star(lambda a,b: ....)). """
return lambda args: f(*args) | 59a6f4bcca310e4468a038cc72eb2200367a9708 | 637,094 |
def get_row_column(play, board):
"""
prompt for user input until its correct
catch any letters or incomplete values in user input
:param play - string, user command:
:param board - object, board:
:return row, column - int, locations on board in 2-D:
"""
# loop until there is valid user i... | b6905eb5ad89ef83f3841378d309f49b72e48b7e | 637,098 |
import math
def continued_fraction_expansion(target, terms):
"""
Return continued fraction expansion of a real number.
>>> continued_fraction_expansion(1.4142, 2)
[1, 2, 2]
The first component is the integer part, and rest is fractional
part, whose number of terms is specified by the second ... | 020ce08ecbdbced0e6ee907d2eaf774e5c5aabd1 | 637,104 |
def compute_prob(eng: float, beta: float, num_spin: int) -> float:
"""Boltzmann probability distribution
Args:
eng (float): Energy of the sample.
beta (float): Inverse temperature
num_spin (int): Number of spins in the sample.
Returns:
float: Log-Boltzmann probability.
... | e6e043bd5ad5c4269c1c22b5a17e9f114bf37619 | 637,106 |
import opcode
def _opcode(name):
"""Return the opcode by name from the opcode module."""
return opcode.opmap[name] | bdd5491ad6626317e64c58d40afb249b380ceeb4 | 637,107 |
def augment_lab_config(lab_config):
"""augment the configuration by
- adding a "connected_to" attribute to each port which has a cable plugged in
Args:
lab_config (dict): [description]
Returns:
dict: lab_config
"""
for cable in lab_config["cables"]:
lab_config["devices"][cable["sour... | 10afe404f8e08e2d617add5dcb1602bd50c12259 | 637,108 |
def format_link(link):
"""
Append site url
"""
return "https://old.reddit.com" + link if link[:3] == "/r/" else link | 53bec63d072239f63e81be7ff56a690416f798dd | 637,112 |
def purity(label_pred, label_true, Ia_flag=0):
"""Calculate purity.
input: label_pred, predicted labels
label_true, true labels
Ia_flag, Ia flag (optional, default is 0)
output: purity
"""
cc_Ia = sum([label_pred[i] == label_true[i] and label_true[i] == Ia_flag f... | 72487a0b1afa768deb23d50057a38b0a9e1c3309 | 637,113 |
import json
import time
def serialize_spool_file_contents(reason, expiration=None, creation=None):
"""Serialize the contents of the spool file (as JSON).
:param reason: a string representing the reason why the downtime exists.
:param expiration: The unix time when this downtime should be considered valid... | 07e91580321ed5de67dee44c841c5487d1a6a30d | 637,114 |
from pathlib import Path
import click
def validate_json_yaml_filename(ctx, param, value):
"""Validate the name of the file has the proper extension and add the extension to the file object"""
if value is None:
return value
if not hasattr(value, "name") or value.name == "<stdout>":
# stdin... | 2adf1053cd1c4326f8ba2de137ca4f3c81a1c4a6 | 637,115 |
def get_middle_point(xx, yy):
"""
Roughly get the middle point of line of x, y coordinates
:param xx: np.array , x array coordinates
:param yy: np.array , y array coordinates
:return: (x_center, y_center)
"""
half = int(len(xx) / 2)
return xx[half], yy[half] | 3bfc0684755e5a3b5976b61ff8da9d6cd819dd9b | 637,116 |
def GetRegionFromZone(zone):
"""Returns the GCP region that the input zone is in."""
return '-'.join(zone.split('-')[:-1]).lower() | c00acab2899d33efcc33672848a91e8845a09fba | 637,117 |
def take_keys(keys, data_dict):
"""Take keys from dict
Arguments:
keys {List[str]} -- Keys it include in output dict
data_dict {Dict}
Returns:
[Dict]
"""
return {k: v for k, v in data_dict.items() if k in keys} | 223f3bb59662abbe875c6d1cd06883f47a0d8f65 | 637,118 |
def locationGenerator(r,t,c,data='data', contextMgr=False):
"""
Given R, T, C, this funtion will generate a path to data in an imaris file
default data == 'data' the path will reference with array of data
if data == 'attrib' the bath will reference the channel location where attributes are stored
""... | 1c5b88c0e03d2f50e0891c7a77800752a631409d | 637,120 |
def drop_substring_from_str(item: str, substring: str) -> str:
"""Drops 'substring' from 'item'.
Args:
item (str): item to be modified.
substring (str): substring to be added to 'item'.
Returns:
str: modified str.
"""
if substring in item:
return item.replace(s... | 0f1bc24d21809afc2e5416efd396153efb75c76c | 637,121 |
import re
def format_species(name, mhchem=False, mathrm=False):
""" Format the name of a chemical species.
Usage: formatted_name = format_species(name, mhchem=False)
Takes a string which represents an atomic or molecular species
and returns a string with LaTeX-style sub- and superscripts... | 1c91e52beba0ecdc8dd60f0f0d435166d6753f5e | 637,123 |
def is_decorated(func):
"""Return True if |func| is decorated by @public or @require decorators."""
return hasattr(func, '__auth_public') or hasattr(func, '__auth_require') | bdb6a3a1dfa9a9da7d045fa57966318190454f7a | 637,124 |
def decode_bytes(s, encoding='utf-8', errors='replace'):
"""Decodes bytes to str, str to unicode."""
return s.decode(encoding, errors=errors) if isinstance(s, bytes) else s | 2ff943128e83585b9c3241e8bed4db80d9090c38 | 637,125 |
def metaslice(alen, nmeta, trim=0, thickness=False):
"""
Return *[imin,imax,istp]* so that `range(imin,imax+1,istp)` are the
boundary indices for *nmeta* (centered) metaslices.
Note: *imax* is the end boundary index of last metaslice,
therefore element *imax* is *not* included in last
... | 2a3a47958fd11bb92b8c049e57f087ed4039e553 | 637,126 |
import json
def import_json(path):
"""Decodes and returns the JSON object in the file at the specified path.
Args:
path (str): The path of the file to read.
"""
with open(path) as data_file:
return json.load(data_file) | b61b56851995a3e000d631187a3501c12066a081 | 637,132 |
import torch
def get_distorted_x(x, prob, corrupt=True):
"""
Distorts the node feature matrix (X) either through corruption or through blanking out
- Corruption: Add uniform random noise in [0,1] to the node feature matrix
- Blanking out: Replace entries in the node feature matrix with zer... | 6ba6d5ef38cf5bedd332c6176d2ccf7aa1042019 | 637,133 |
def _select_entries_param(list, param):
"""Takes a list of logfile_entry objects and returns a sub set of it.
The sub set includes a entries that have a source attribute that occurs in the param argument.
Positional arguments:
list -- a list of logfile_entry objects
param -- a list of strings, representing source... | e92c7a68543f790095e1ea65a0b72c4c68447a96 | 637,141 |
def choose_robots(exclude_bimanual=False):
"""
Prints out robot options, and returns the requested robot. Restricts options to single-armed robots if
@exclude_bimanual is set to True (False by default)
Args:
exclude_bimanual (bool): If set, excludes bimanual robots from the robot options
R... | c090639380ca301a51973e235ff6bbbbe848c1b6 | 637,144 |
def simd_loop_filter(loops, tuning):
""" Filter out the SIMD candidate loops based on the tuning information.
We select the legal simd loop with the highest score.
If there is no such loop, we will set "loops" to all "1"s.
AutoSA will not tile loops with the tiling factor as one for latency hiding or
... | bf9c261aa6a3af7fd4cb30205f3745c7ed29a551 | 637,149 |
from bs4 import BeautifulSoup
def scrape_target_elements(html, target, target_type, specific_tag=''):
"""Scrape target from the html document
Positional Arguments:
html (str): standard html document
target (str): name of tag, id or class
target_type (str): tag (html element such as <l... | 9494138b275a09b2cec20aa42eee8d06bdc89e40 | 637,150 |
import itertools
def _MakeBytes(bits, toks):
"""Creates a multi-byte string from ASCII strings and/or ASCII codes.
Args:
bits: Number of bits per character, must be in {8, 16, 32}.
toks: A list of tokens, each of which is a ASCII strings or an integer
representing a character's ASCII value (e.g., 0... | 858541b8ab9a872c4f92ff1cc720bc26219d823f | 637,153 |
def limit(string, print_length=58):
"""Limit the length of a string to print_length characters
Replaces the middle with ...
"""
if len(string) > print_length:
trim = int((print_length-3)/2)
return string[:trim] + '...' + string[-trim:]
else:
return string | 1c92d104a5732c0d7f4ebe35f048b6e492824f93 | 637,154 |
def reduce_subjects(doc):
"""Iterates and sort all topic and subject related fields and
returns a set of unique subjects.
:param doc: Dictionary of subject values from the Solr document
query
:rtype: Set of subject terms
"""
subjects = []
if doc.has_key('subject'):
f... | 61c0797c858d91852d1c9f27b59dc4402612eada | 637,156 |
import random
def get_otp_code() -> str:
"""Get random 6-digit OTP code"""
return "".join([random.choice("0123456789") for i in range(6)]) | e652c6bafb9066b944ecd4b7e944b2eef564d549 | 637,158 |
import requests
def download_json(url, args={}):
"""
Downloads a JSON
:param url: The URL of the JSON
:type url: string
:param args: Optional keyword arguments for requests
:type args: dict
:return: The downloaded JSON
:rtype: dict
"""
r = requests.get(url, **args)
return r.json() | d73878e5a17f3d7665f5533dde739a23c5f25206 | 637,176 |
def load_all_vectors(embd, wikiWordsPath):
"""Loads all word vectors for all words in the list of words as a matrix
Arguments
embd : Dictonary of word-to-embedding for all words
wikiWordsPath : URL to the path where all embeddings are stored
Returns
all_words_index : Dictonary of w... | 29e3a7f1cf9a46917623ed909ecdaaac1f98cbb3 | 637,177 |
import uuid
def get_guid() -> str:
""" Returns a new guid """
return uuid.uuid4().hex | 5f7bc873a3e786bae10465ab4328d04d4c328df4 | 637,178 |
def gen_team(name):
"""Generate a dict to represent a soccer team
"""
return {'name': name, 'avg_height': 0, 'players': []} | e4e064158e5791e2fde66dcd22ac2206f7ed421f | 637,180 |
from typing import Callable
from typing import Tuple
from typing import Mapping
import inspect
def get_function_parameters(
f: Callable,
) -> Tuple[Mapping[str, inspect.Parameter], type]:
"""
Returns function's signature as parameters and the output type.
:param f: the function
:return: the param... | e087c220a5b788b8081d224e1c8f2d7771a32df6 | 637,188 |
import time
def timefunc(func):
"""
decorator to measure the execution time of the decorated function.
"""
def profiled_func(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, 'took', end - start, 'time')
... | afe66ad28afa7a4eb5640f4da9e707c38776a48f | 637,189 |
def remove_whitespace(word):
"""Removes whitespace from word"""
return word.strip() | 6d70751cee467ad0455be7604521700803173c37 | 637,192 |
def key_for_path(p):
"""
Representation of the path, ID for a path
:param p: a JSON path dictionary
:return: a unique string for the path
"""
# key for a path is made of starting user id and ending business id in the path
return '%s_%s' % (p[0]['props']['id'], p[-1]['props']['id']) | 6755a46735d975656a17c091cd7f709c2f942d67 | 637,193 |
def fix_ts(timestamp):
""" Remove milliseconds from timestamps """
s, ms = divmod(int(timestamp), 1000)
# import time
# s = int(time.time()) # Uncomment for testing
return s | 8fc7e4e332cdb6cdc76d10569126607f96bcc093 | 637,198 |
import math
def get_point_from_angle(point, angle, lenght):
"""
Return a point given a starting point, the angle that it has to form with respect to X-axis and how far from that
point it has to be.
:param point: Initial point
:param angle: angle with respect to X-axis
:param lenght: How far fr... | 8dc330eed65c3ed5404ac7511a8396d1a453af83 | 637,201 |
def class_identifier(typ):
"""Return a string that identifies this type."""
return "{}.{}".format(typ.__module__, typ.__name__) | f2491824c32aeada8400595fec2cbc8c3658d587 | 637,203 |
def save_df_as_csv(d, output_file, fields_order=None, csv_order_by=None, keep_index=False, encoding='utf-8-sig', blankna=False, excel=False, verbose=False, **kwargs):
"""Save a dataframe in a csv
fields_order allows to precise what columns to put first (you don't need to specify all columns, only the ones you w... | 2f5027f9d130297111016db3c2f5947ec616dc18 | 637,206 |
import inspect
def get_instance_user_attributes(cls):
"""
Returns user attributes defined in a class or instance of a class
:param cls:
:return: list
"""
_def_attrs = dir(type('dummy', (object,), {}))
_def_attrs.extend(['staticMetaObject'])
attributes = inspect.getmembers(cls, lambda... | 39806dbcd62a0a4984b997f778ed0508fb50738f | 637,211 |
def get_class_name(o, lower=False):
"""
Returns the class name of an object o.
"""
if not isinstance(o, type):
o = o.__class__
if lower:
return o.__name__.lower()
else:
return o.__name__ | 15ef10f6612e34e4c81bae707044daca15b5f81f | 637,216 |
def _namespace_data(data: dict, namespace: str) -> dict:
"""Prefix configuration key with a namespace.
Namespace is ConfigSource wide, and is resolved at source build time.
It should be one of:
- "target"
- "app"
- library name (where "mbed_lib.json" comes from)
If given key is already na... | caf52e230465cb4f3d02b21187507d5fe7c123f2 | 637,217 |
import time
def format_time(ts):
"""Converts UNIX timestamp to local timestring with human-readable format"""
return time.strftime("%d %B %Y, %I:%M %p", time.localtime(int(ts))) | 4f6230c245e9b1c11a74378f7458b11326c00633 | 637,222 |
def _sanitize(hex_str, comment_strings=None, ignore_strings=None):
"""
Sanitize string input before attempting to write to file.
:param hex_str: the string input to sanitize
:param comment_strings: a tuple of strings identifying comment characters
:param ignore_strings: a tuple of strings to igno... | d89c1fea29480bd072de7c5b37967f4719f75557 | 637,225 |
from typing import List
import pathlib
def find_all_coreref_files(directory: str) -> List[pathlib.Path]:
"""Searches for all the COREREF files in a directory and all its subdirectories.
Parameters
----------
directory: str
A string containing the path to directory where we want to search the ... | 6fabc4adc435d96ce4123ae7ac8cd122d8d975d3 | 637,228 |
def find_max_recursively(S, n):
"""Find the maximum element in a sequence S, of n elements."""
if n == 1: # reached the left most item
return S[n-1]
else:
previous = find_max_recursively(S, n-1)
current = S[n-1]
if previous > current:
return previous
else... | 26b430dbc31db2e7f34f94725f0c24188d1e2b58 | 637,230 |
def is_child_node(node):
"""
Return `True` if the given node is a "child" node, `False` otherwise.
"""
if not node:
return False
return node.is_child is True and node.is_root is False | 3e42dabc1b539f3990e7e53417066ae2b37d926d | 637,232 |
def xor_string(string: str, xor_int_value=42):
"""Takes a given string and does an XOR operation on the converted ord() value of each character with the "xor_int_value", which by default is 42
Examples:
>>> string2encode = 'Now is better than never.'\n
>>> xor_string(string2encode)\n
'd... | 4e3dd51cd49a6f3df9491dd86d76e6fcecf6fc38 | 637,233 |
def voxel_to_world_coordinates(voxel_index, bbox, grid_shape):
"""Given a voxel, the bbox that encloses the scene and the shape of the
grid, it computes the center of the voxel in world coordinates.
Arguments:
----------
voxel_index: array(shape=(3, ), dtype=int32)
The voxel indice... | 5e97499068ed9fd898b0559a84406350a9f103d4 | 637,236 |
def compute_veer(wind_a, height_a, wind_b, height_b):
"""
Compute veer between wind direction measurements
Args:
wind_a, wind_b(:obj:`array`): arrays containing the wind direction mean data; units of deg
height_a, height_b(:obj:`array`): sensor heights (m)
Returns:
veer(:obj:`a... | f47d943bc267ac21174cb35e7560b72961dcdbbe | 637,240 |
import re
def _ReplaceIndices(language, expression):
"""Replaces array access with underscored variable.
For matrices: `variable[3,7]` becomes `variable_3_7`
For vectors: `variable[3]` becomes `variable_3`
The accessor for matrices is chosen according to the language (`[]` vs. `()`)
"""
#Ma... | 6d8d546bcc4207ff18a1916bf56e0047cfcf6d36 | 637,242 |
def bdf_width(width: int) -> int:
"""Calculates the width in bits of each row in the BDF from the actual witdth of a character in pixels."""
# NOTE: Lines in BDF BITMAPs are always stored in multiples of 8 bits
# (https://stackoverflow.com/a/37944252)
return -((-width) // 8) * 8 | c9d478d41ab94358524e384cf0c384994052626c | 637,243 |
def EVI(red, nir, blue):
""" Return the Enhanced Vegetation Index for a set of np.ndarrays
EVI is calculated as:
.. math::
2.5 * \\frac{(NIR - RED)}{(NIR + C_1 * RED - C_2 * BLUE + L)}
where:
- :math:`RED` is the red band
- :math:`NIR` is the near infrared band
- :math... | 96a4e64da0e6c97ee10d9ba0378c5605ccf1b1af | 637,244 |
import re
def is_valid_hash(value, algo):
"""Returns if the value is a valid hash for the corresponding algorithm."""
size = 2 * algo().digest_size
return bool(re.match(r'^[a-fA-F0-9]{%d}$' % size, value)) | 7879928b67504321da225346748801b9c6a56b30 | 637,245 |
def zbar_bch15_5_encode(x):
"""ZBar's implementation of bch15_5_encode"""
return (
(-(x & 1) & 0x0537) ^
(-(x >> 1 & 1) & 0x0A6E) ^
(-(x >> 2 & 1) & 0x11EB) ^
(-(x >> 3 & 1) & 0x23D6) ^
(-(x >> 4 & 1) & 0x429B)
) | 7dcb250dae1bca7921b13cd824a3571b222fc183 | 637,248 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.