content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def extract_pos(positions, cash):
"""Extract position values from backtest object as returned by
get_backtest() on the Quantopian research platform.
Parameters
----------
positions : pd.DataFrame
timeseries containing one row per symbol (and potentially
duplicate datetime indices) a... | 248ecd5054df0eed7126137f2b9145c11eeff2c4 | 74,366 |
def left_of_line(point, p1, p2):
""" True if the point self is left of the line p1 -> p2
"""
# check if a and b are on the same vertical line
if p1[0] == p2[0]:
# compute # on which site of the line self should be
should_be_left = p1[1] < p2[1]
if should_be_left:
retu... | 5cb130fecd46fe7eb74cee5179f4705b8ee4760f | 690,180 |
def resolve(impmod, nameparts):
"""
Resolve the given (potentially nested) object
from within a module.
"""
if not nameparts:
return None
m = impmod
for nname in nameparts:
m = getattr(m, nname, None)
if m == None:
break
return m | 4a6a0af926b7dbf226075e986a6d3fd65225fa4f | 518,275 |
from unittest.mock import Mock
def make_coroutine_returning(return_value):
"""
A utility function used to create coroutines that return a specific value.
:param return_value: The value that the coroutine should return when awaited.
:return: A mock coroutine
"""
async def mock_coroutine(*args, ... | 818331f569466c34c21b2760a12d1bd804d945bd | 443,344 |
def getattrrec(object, name, *default):
"""Extract the underlying data from an onion of wrapper objects.
``r = object.name``, and then get ``r.name`` recursively, as long as
it exists. Return the final result.
The ``default`` parameter acts as in ``getattr``.
See also ``setattrrec``.
"""
... | a847b7f54d2a737ac31226807c2f28ca58d1ef72 | 70,536 |
def redirect(target):
"""
Returns a redirect map to the target provided
"""
return {
'status': '302',
'statusDescription': 'Found',
'headers': {
'location': [{
'key': 'Location',
'value': target
}]
}
} | 787c485c63a05f761b7b89198c311f6f522e5d3b | 313,976 |
def maxed_rect(max_width,max_height,aspect_ratio):
"""
Calculates maximized width and height for a rectangular area not exceding a maximum width and height.
:param max_width: Maximum width for the rectangle
:type max_width: float
:param max_height: Maximum height for the rectangle
:type max... | 886cda77c833c3614b05cb41c9eeb209ea90c149 | 84,247 |
def extract_subgraph(adj_matrix, groundtruth, nodes):
"""
Return the subgraph and the ground-truth communities induced by a list of nodes.
The ids of the nodes of the subgraph are mapped to 0,...,N' - 1 where N' is the length of the list of nodes.
:param adj_matrix: compressed sparse row matrix or num... | 4272b7acb2c632d3200f6b105cbb7a582a8bf10d | 409,581 |
import hashlib
def _hashdigest(message, salt):
""" Compute the hexadecimal digest of a message using the SHA256 algorithm."""
processor = hashlib.sha256()
processor.update(salt.encode("utf8"))
processor.update(message.encode("utf8"))
return processor.hexdigest() | 2c9c5886d72700826da11a62f4cc9c82c2078090 | 27,757 |
def validate(raw):
""" Checks the content of the data provided by the user.
Users provide tickers to the application by writing them into a file
that is loaded through the console interface with the <load filename>
command.
We expect the file to be filled with coma separated tickers :class:`string... | c69b5b4177e11fabc3f70c0388e3b50f56a201b7 | 18,620 |
def _tasklines_from_tasks(tasks):
"""
Parse a set of tasks (e.g. taskdict.tasks.values()) into tasklines
suitable to be written to a file.
"""
tasklines = []
for task in tasks:
metapairs = [metapair for metapair in task.items()
if metapair[0] != 'text']
meta_... | a4d4677f9005e3e4f82bd67eee9a4faba168f79c | 561,711 |
def frame_rti(detectorrows, ampcolumns, colstart, colstop, rowstart, rowstop,
sampleskip, refpixsampleskip, samplesum, resetwidth,
resetoverhead, burst_mode):
"""
Helper function which calculates the number of clock cycles, or RTI,
needed to read out the detector with a give... | 07388d58bc1a8ddc2bc7df79266df264e36d3bd2 | 93,700 |
def normalize_on_minute(dtstamp, minute):
"""
Change a datetime stamp to be rounded down to the nearest interval of `minute`.
This also truncates off the seconds and microseconds parameters by setting them to 0.
>>> normalize_on_minute(datetime(2012, 3, 19, 15, 9, 12, 41), 15)
datetime.datetime(2012, 3, 19, 15, 0... | c11c611edf6e01bae941ef368b2b647532b9c7a8 | 258,246 |
from typing import List
from typing import Tuple
def run(code: List[Tuple[str, int]]) -> Tuple[str, int]:
"""
Runs a program, returning status and accumulator.
The status can be either "loop" or "halt".
"""
pc = 0
acc = 0
instructions_run = set()
while True:
if pc == len(code)... | 7984bf1d9a57e129770b1d7701212ffcaa4278b4 | 457,302 |
import re
def _api_version(release: str, significant: int = 3) -> str:
"""Return API version removing any additional identifiers from the release version.
This is a simple lexicographical parsing, no semantics are applied, e.g. semver checking.
"""
items = re.split(r"\.|-|\+", release)
parts = it... | 07fe3bfdc1693ea8d6028a79149acc4fb0dd2b9e | 136,340 |
import re
def extract_id(url):
"""Extract the tournament id of the tournament from its name or URL."""
match = re.search(r'(\w+)?\.?challonge.com/([^/]+)', url)
if match is None or match.group(2) is None:
raise ValueError(f'Invalid Challonge URL: {url}')
subdomain, tourney = match.groups()
... | c16f28fc114b5439800713e02a06243cbd3b67d8 | 93,340 |
def _incs_list_to_string(incs):
"""Convert incs list to string.
Example:
['thirdparty', 'include'] -> "-I thirdparty -I include"
"""
return ' '.join(['-I ' + path for path in incs]) | 6b6dbfd687fdf87e2203381a512f65460438e1ae | 202,575 |
def turn(fen):
"""
Return side to move of the given fen.
"""
side = fen.split()[1].strip()
if side == 'w':
return True
return False | 1adbe7b325ee957348ad1ba591335f38c5835573 | 428,369 |
def get_composer_names(artist_database, composer_id):
"""
Return the list of names corresponding to an composer
"""
if str(composer_id) not in artist_database:
return []
alt_names = [artist_database[str(composer_id)]["name"]]
if artist_database[str(composer_id)]["alt_names"]:
... | 5ad465de92cbd0e08c668e887b3fe65fdd9edb7a | 269,609 |
def centres_from_shape_pixel_scales_and_origin(shape, pixel_scales, origin):
"""Determine the (y,x) arc-second central coordinates of an array from its shape, pixel-scales and origin.
The coordinate system is defined such that the positive y axis is up and positive x axis is right.
Parameters
------... | 66c08c63fa3cf5c0907590660075bb49719589e8 | 227,481 |
def hlstr(string, color="white"):
"""
Return HTML highlighting text with given color.
Args:
string (string): The string to render
color (string): HTML color for background of the string
"""
return f"<mark style=background-color:{color}>{string} </mark>" | 52e9d069d559feec2237d0847e667a1cb53326d8 | 27,343 |
from bs4 import BeautifulSoup
def get_job_title_indeed(card: BeautifulSoup) -> str:
"""
Extracts the jobs title from the portion of HTML containing an individual job card.
Args:
card (BeautifulSoup object): The individual job posting card being processed.
Returns:
str: The job title... | 882f91df7bb193823ca6c12a76f65eff91d865e9 | 619,812 |
def join(sep, s):
"""Return 's' joined with 'sep'. Coerces to str."""
return sep.join(str(x) for x in list(s)) | e4e11b06629db19ed955ea0e7d5b956b6ea961b5 | 214,068 |
import string
import random
def get_random_str(size=13):
"""
generates the random string of given size
Args:
size (int): number of random characters to generate
Returns:
str : string of random characters of given size
"""
chars = string.ascii_lowercase + string.digits
r... | 04688d425787f96de2d4a559191266db39b1c1c1 | 312,126 |
import fnmatch
def is_ignored(path, ignore_patterns):
"""
Helper function to check if the given path should be ignored or not.
"""
for pattern in ignore_patterns:
if fnmatch.fnmatchcase(path, pattern):
return True
return False | fbe6c7cf9daac52e7d57553ad10ed74a6e2fffba | 444,412 |
def stats(index_and_true_and_retrieved):
""" Returns comma-separated list of accuracy stats
Included are (relevant instances, retrieved instances, overlap,
precision, recall, f-score)
index_and_true_and_retrieved is composed of:
index: used to track which sa... | e3edcc8e1a75f91eee869ceb275611365c22c23a | 349,684 |
def bytes_from_str(s: str):
"""
Convert string to bytes
"""
return s.encode() | b888bdd8276d36197a1c27892b74e897d17dc6d0 | 470,420 |
def convert_to_base_unit(value, unit):
"""
Convert value from current unit to base unit
:param (int) value: Numerical value
:param (str) unit: unit, where empty string denotes base unit
:return: (int) the value in base unit
"""
POWERS_BY_UNIT = {'n': -3,
'u': -2,
... | bd76d50b8dceab5e28c1c582a061dd5a01bce3a0 | 236,483 |
import torch
def c2d(x):
"""
Transform Cartesian coordinates to polar degree (r=1).
Parameters
----------
x, y : floats or arrays
Cartesian coordinates
Returns
-------
theta : floats or arrays
Polar degree
"""
x0, x1 = x.select(-1,0), x.select(-1,1)
return t... | 9596858aa0720faf7798ac1f6b1745a8b4123d78 | 496,671 |
import re
def modify_vars(vars_orig, var_modifiers):
"""Return a copy of `vars_orig` modified according to `var_modifiers`.
Parameters
----------
vars_orig : list of str
A list of variable names.
var_modifiers : list of str or None, optional
A list of variable modifiers. Each vari... | 58f27e60b650a219abad70501e4573ab818b8450 | 625,903 |
def land(*fns):
"""
Functionally logical ands the given functions.
>>> lor(starts_with('123'), ends_with('asd'))('123asd')
True
>>> land(starts_with('123'), ends_with('asd'))('asd')
False
>>> land(starts_with('123'), ends_with('asd'))('123')
False
:param fns: Functions to and
:... | 8b48e5862704548515593d8183aa88b82392da51 | 637,624 |
import re
def camel_case_split(str):
"""
e.g. str = "mayaMatchmoveTools" >> ['maya', 'Matchmove', 'Tools']
e.g. str = "MayaMatchmoveTools" >> ['Maya', 'Matchmove', 'Tools']
"""
return re.findall(r'[a-zA-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))', str) | cfa85307755e586f4b03aa9dd90b830ceb85b10e | 506,225 |
import re
def check_convert_input(user_inputs: list):
"""
Check input for erroneous formatting.
If input is clean, convert it to more useful format.
Args:
guesses (dict): {
'word1':'XXXXX',
'word2':'XXXXX',
etc.
}
Returns:
guesses (dict... | cb378bbbf994d32a79fd385e17e568f380bc189c | 376,498 |
def build_dict(arg):
"""
Helper function to the Evaluator.to_property_di_graph() method that
packages the dictionaries returned by the "associate" family of
functions and then supplies the master dict (one_dict) to the Vertex
obj as kwargs.
"""
# helper function to the Evaluator.to_property_... | 9f379b6f612e86dcc5e73cbcc479c186e95653b7 | 271,287 |
import base64
def toProtobufString(protoObject):
"""
Serialises a protobuf object as a base64-encoded protobuf string
"""
# the base64-encoding shouldn't be necessary, but otherwise
# currently the "string" with high-bit-set bytes gets helpfully
# re-coded into corresponding unicode string in ... | 2a3270432f9cd4070fd5d2167ee5db118fd4660e | 382,672 |
import torch
def prepare_sequence(seq, to_ix):
"""return indexes sequence of input word sequence
Args:
seq (list): word sequence
to_ix (dict): word to index map
Returns:
Tensor: indexes in Tensor format
"""
idxs = [to_ix[w] for w in seq]
return torch.tensor(idxs, dtyp... | da8276a4d54e15fa2f5cd9964abfa5483b9b5fd8 | 416,348 |
def html_obfuscate_string(string):
"""Obfuscates a string by converting it to HTML entities
Useful for obfuscating an email address to prevent being crawled by spambots
"""
obfuscated = ''.join(['&#%s;' % str(ord(char)) for char in string])
return obfuscated | 21ef043a000f013ca7c19dba993b451b31de6398 | 486,094 |
def get_job_kwargs(job):
"""Returns keyword arguments of a job.
:param Job job: An apscheduler.job.Job instance.
:return: keyword arguments
:rtype: dict
"""
return job.kwargs | 407e20c48886b9ecac9ecaf9bfeef634fdbd5da4 | 288,284 |
def get_unique_rows(df, columns, sort_by):
"""De-dupe a Pandas DataFrame and return unique rows.
:param df: Pandas DataFrame.
:param columns: List of columns to return.
:param sort_by: Column to sort by.
:return: Pandas DataFrame de-duped to remove duplicate rows.
"""
df = df[columns]
... | 1d1950cf07b54b03ecd86fdd5d5a038e51323ef7 | 255,730 |
def _text_indent(text, indent):
# type: (str, str) -> str
"""
indent a block of text
:param str text: text to indent
:param str indent: string to indent with
:return: the rendered result (with no trailing indent)
"""
lines = [line.strip() for line in text.strip().split('\n')]
return ... | 00101ea91edf3207983b57aa0d9022c08a4956ba | 77,626 |
def levenshtein_distance(w1, w2):
"""
Calculates the Levenshtein (minimum edit) distance between two words. This implementation is based on the one
provided by Stavros Korokithakis ( https://www.stavros.io/posts/finding-the-levenshtein-distance-in-python/ ),
licensed under BSD with Attribution. For questions concer... | ffdd256eafffc2294b2750dc84b8ed53e272900d | 148,755 |
def _is_variable_argument(argument_name):
"""Return True if the argument is a runtime variable, and False otherwise."""
return argument_name.startswith('$') | cf74d6dfd1c0ea1b560bf3766e2fac8af1dbafda | 17,537 |
import requests
def SendJSON(address, parameters):
""" Send a JSON request given a URL address and JSON parameters
"""
r = requests.get(url = address, params = parameters)
return r.json() | a1a0260923aeb5ad00a7a63c22c5639fb6a544cd | 245,827 |
def get_polygon_area(verts):
"""
Calculate the area of a closed polygon
Parameters
----------
verts : numpy.ndarray
polygon vertices
Returns
-------
area : float
area of polygon centroid
"""
nverts = verts.shape[0]
a = 0.
for iv in range(nverts - 1):
... | 86165171c8f75b079ae554759db47bce9841b1fa | 606,735 |
def default_if_none(value, arg):
"""If value is None, use given default."""
if value is None:
return arg
return value | bceed44594652d17ba9c4aab6eec6697e72032ab | 534,884 |
def compact(iterable, generator=False):
""" Returns a list where all None values have been discarded. """
if generator:
return (val for val in iterable if val is not None)
else:
return [val for val in iterable if val is not None] | 229b7a37bfa85ea4373fe54aabdb32dbae87e9ca | 397,352 |
def depth_first_search(grid, start, target):
"""
Search a 2d grid for a given target starting at start.
Args:
grid: the input grid as a List[List]
start: the start grid in format (x,y) zero index
target: the target value to find in the grid
Returns:
Coordinate of the tar... | 1bd8c5c5c5a3b44df97e9ff899576bfab44ad4e4 | 618,917 |
def _ends_in_by(word):
"""
Returns True if word ends in .by, else False
Args:
word (str): Filename to check
Returns:
boolean: Whether 'word' ends with 'by' or not
"""
return word[-3:] == ".by" | d6a080f8d3dcd5cab6ad6134df3dd27b3c2ceeea | 46,321 |
def split_role(r):
"""
Given a string R that may be suffixed with a number, returns a
tuple (ROLE, NUM) where ROLE+NUM == R and NUM is the maximal
suffix of R consisting only of digits.
"""
i = len(r)
while i > 1 and r[i - 1].isdigit():
i -= 1
return r[:i], r[i:] | fe79df1421eb7903ea7f898b4940ec8feb48cdb7 | 363,590 |
def read_chunk(stream):
"""Read at most a chunk from a stream"""
chunk_size = 16 * 1024
return stream.read(chunk_size) | 7ae1bf00edb285f34137048d836d81575ddb7834 | 446,587 |
def __prompt_overwrite(filename: str) -> bool:
"""Prompt if the given file should be overwritten.
:param str filename: the filename
:return: `True` if answered `y`, `False` if answered `n` or nothing
:rtype: bool
"""
prompt = input(f"Should '{filename}' be overwritten? [y/N] ")
if prompt.lo... | 7694c8babfe51a62f73497bb7235d00dcddfe8e8 | 430,237 |
def flatten(seq):
"""Flatten a list of lists (NOT recursive, only works for 2d lists)."""
return [x for subseq in seq for x in subseq] | 9cf1df0818d1852006f45b6b2a20000458f69b9a | 141,823 |
def get_std_opt_group(parser):
""" Returns the 'Standard Options (optional)' argument group from the
standard parser. """
for group in parser._action_groups:
if group.title=="Standard Options (optional)":
return(group)
return(None) | acb4fd58c59750a2f9836013dcc65849263c9593 | 258,222 |
def dictionary_filter(dictionary, cols) -> dict:
"""Can be used to filter certain keys from a dict
:param dictionary: The original dictionary
:param cols: The searched columns
:return: A filtered dictionary
"""
return {key:value for (key,value) in dictionary.items() if key in cols} | d7a67bad623dce18e29e643d4cd2c1a9f3151a2d | 538,130 |
def optional_arguments(d):
"""
Decorate the input decorator d to accept optional arguments.
"""
def wrapped_decorator(*args):
if len(args) == 1 and callable(args[0]):
return d(args[0])
else:
def real_decorator(decoratee):
return d(decoratee, *args)... | 433dbb2653fcec612cfeb5817fd3a37155741c78 | 124,425 |
from typing import Dict
from typing import List
def span_subwords(
word: str,
unk_token: str,
vocab: Dict[str, int],
max_input_chars_per_word: int,
) -> List[str]:
"""
Tokenize a word into several subwords.
This code is copied from Bert tokenization.py.
Requiremen... | c0ea928e7c37f6f901a6c0424fd30e257b29f1f2 | 303,157 |
def has_train(args):
"""Returns if some kind of train data is given in args.
"""
return (args.training_set or args.source or args.dataset or
args.datasets or args.source_file or args.dataset_file or
args.train_stdin or args.source_file) | 6412f38f364e3332f606227b5404836b4940424e | 463,459 |
def GetCbsdRegistrationRequest(cbsd):
"""Returns a CBSD registration request from the |Cbsd| object.
"""
return {
'cbsdCategory': cbsd.category,
'installationParam': {
'latitude': cbsd.latitude,
'longitude': cbsd.longitude,
'height': cbsd.height_agl,
'heightType... | 2720960f20e9eb792f0cc4dc5564c85a5dd69743 | 635,041 |
import re
def match_email(text):
"""Given a string, tries to find a regex match for an email."""
email_regex = r'(.+\s+)*(<)*\s*(?P<email>\w+(?:.+\w+)*@\w+(?:.+\w+)' + \
r'(?:\.\w+)+)(>)*'
match = re.match(email_regex, text)
if match:
return match.group('email') | 0e888af8366062f1af789b12b5e3792ba492fd92 | 596,096 |
def strip_prefix(string, prefix):
"""Strip the given prefix from the string if it's present
"""
return string[len(prefix):] if string.startswith(prefix) else string | f7deb89958f2eeee2f2cf904172a65f6e00a68b2 | 174,322 |
def modulus(x, y):
""" Modulus """
return x % y | ea2694f98133ddaf43da3f3eb702f5ba22dec597 | 73,576 |
def remove_suffix(s: str, suffix: str) -> str:
"""Remove the suffix from the string. I.e., str.removesuffix in Python 3.9."""
# suffix="" should not call s[:-0]
return s[: -len(suffix)] if suffix and s.endswith(suffix) else s | 17474d37726249dc84aa89f0861fe43db43bf1e9 | 46,177 |
from typing import Collection
from typing import Callable
from typing import Tuple
def key_func_for_attribute_multi(
attributes: Collection[str],
) -> Callable[
...,
Tuple[Tuple[str, str], ...],
]:
""" Return a closure that given a slave, will return the value of a list of
attributes, compiled int... | b6695436124187927b9ac36362271f6aaf102e0a | 537,727 |
def versiontuple(v: str) -> tuple:
"""
Function to converts a version string into a tuple that can be compared, copied from
https://stackoverflow.com/questions/11887762/how-do-i-compare-version-numbers-in-python/21065570
"""
return tuple(map(int, (v.split(".")))) | 53a506e7c5eb6c7b1d601968487bbce88f8905d4 | 450,711 |
def _combine_prg_roles(user_prg_roles, startup_prg_roles):
"""
Collapse two dictionaries with list values into one by merging
lists having the same key
"""
for key, value in startup_prg_roles.items():
if user_prg_roles.get(key):
user_prg_roles[key] = user_prg_roles[key] + value
... | d7864f6b087593eed7fe5872100a0cb261db54fc | 388,560 |
import re
def extract_code(text):
""" Extracts the python code from the message
Return value: (success, code)
success: True if the code was found, False otherwise
code: the code if success is True, None otherwise
"""
regex = r"(?s)```(python)?(\n)?(.*?)```"
match = re.search(rege... | a912c90973f1d5ebbc356f4a9310a45757928d63 | 674,485 |
def _get_percent(text):
"""If text is formatted like '33.2%', remove the percent and convert
to a float. Otherwise, just convert to a float.
"""
if not text:
return None
if text.endswith('%'):
text = text[:-1]
return float(text.strip()) | 2975f0a603a113bf7991753250a83be4da363070 | 697,388 |
def init_global_params(run_settings):
"""
initialize global parameters
:run_settings: run settings dict, must contain
- dims
- max_iterations
- num_centroids
- threshold
:returns: GlobalParams list
"""
global_params = []
global_params.append(run_settings['num_... | fda866c9870bad2eae4522a3aec86d8d490164e2 | 279,485 |
import socket
def get_ipv4(hostname):
"""Get list of ipv4 addresses for hostname
"""
addrinfo = socket.getaddrinfo(hostname, None, socket.AF_INET,
socket.SOCK_STREAM)
return [addrinfo[x][4][0] for x in range(len(addrinfo))] | 134adec72e28809f364725904f78996755725e6f | 308,263 |
import struct
def unpack(fmt, data):
"""
a more ergonnomic struct.unpack,If data is longer than the fmt spec it copes
remaining data returned as last data element
@param fmt: format string as per L{struct.unpack}
@type fmt: L{str}
@param data: data to be unpacked, optionally more
@type da... | 14f6d3fc413c9c6145af975cb2ad5445c78acce7 | 349,507 |
def format_bytes(nbytes):
"""Format ``nbytes`` as a human-readable string with units"""
if nbytes > 2 ** 50:
return "%0.2f PiB" % (nbytes / 2 ** 50)
if nbytes > 2 ** 40:
return "%0.2f TiB" % (nbytes / 2 ** 40)
if nbytes > 2 ** 30:
return "%0.2f GiB" % (nbytes / 2 ** 30)
if nb... | 6996b7632dcd638edb9ae9ef1d3168e583bc87ff | 594,818 |
def read_data_asc(f):
"""
Read the elevation data from
the file 'f'. This data will be returned as a
two-dimensional list to be interpreted as:
[
Y1:[X1, X2, ...Xn],
Y2:[X1, X2, ...Xn],
...
Yn:[X1, X2, ...Xn]
]
"""
data = list()
header = ... | 4b495a0300ea9ea3a664706fce650d5c51bce643 | 166,710 |
def default_if_none(value, default):
"""Return given default if value is None"""
if value is None:
return default
return value | 86c036ac86d8b6b6c3ae2f2800d4711b38d7c523 | 430,668 |
def _GetObjcName(attr):
"""Returns the Objective-C name for the given attribute."""
if attr.name.startswith('init'):
return 'getI' + attr.name[1:]
return attr.name | db8819567c5636ddd783330d84a92be8ba23fb77 | 598,929 |
def recommender_function(model, X, treatment_column):
"""
Calculate the recommender function for a set of patients based on a
previously fitted model. Implementation corresponds to the one
proposed in [1] (Eq. 6).
Parameters
----------
model:
Model that will be used to comput... | f1bb817b3e2297ac0c66ae008d765db9a749544f | 453,558 |
def resolve_underlying_function(thing):
"""Gets the underlying (real) function for functions, wrapped functions, methods, etc.
Returns the same object for things that are not functions
"""
while True:
wrapped = getattr(thing, "__func__", None) or getattr(thing, "__wrapped__", None) or getattr(th... | 08e9d0909acb803d4877cb8610aace8465266bb9 | 463,233 |
def clo32(val):
""" Count Leading Ones starting from bit 32. """
# pylint: disable=line-too-long
first_bit = val[31] ^ 0x0
ctr = (1 & val[31]) + \
(1 & val[30]) + \
(1 & val[29] & val[30]) + \
(1 & val[28] & val[30] & val[29]) + \
(1 & val[27] & val[30] & val[29] ... | 8a94901a9ca30533c2124ef0f5331d6e405b427f | 576,194 |
def fileNumber(filePath):
"""
Get the number of the file. foo.0080 would return 0080
"""
num = filePath.split('.')[-1]
return int(num) | 731918660f0c145c15ba99c2f5eb8be9745e8576 | 10,404 |
def sequence_input_funcs(input_funcs):
""" Returns a function that
- is like (the first element of input_funcs) the first time that it's called
- is like (the second element of input_funcs) the second time that it's called, etc.
- just returns None (ignoring its arguments) when ther... | 26cffdfaaceff694c9df6afa8b39f98a26d79474 | 539,706 |
def Format_Phone(Phone):
"""Function to Format a Phone Number into (999)-999 9999)"""
Phone = str(Phone)
return f"({Phone[0:3]}) {Phone[3:6]}-{Phone[6:10]}" | 8e46c35bca9d302d86909457c84785ad5d366c15 | 708,876 |
def invert_image(image):
"""
Inverts a binary image
Args:
image: a binary image (black and white only)
Returns:
An inverted version of the image passed as argument
"""
return 255 - image | eb466971c77fae2a57ad86a3b555884865ed404a | 18,574 |
import hashlib
def digest(binary_data: bytes) -> str:
""" Return a SHA256 message digest for the given bytes string
:param binary_data: The binary data to digest
:return: A length-64 hex digest of the binary data
"""
m = hashlib.sha256()
m.update(binary_data)
return m.hexdigest() | c37403e2e47cd49fbfddbc33c09444186e8b8a9e | 385,960 |
def create_all_possible_moves(m, n):
"""Create all moves on a (m,n) board."""
moves = []
for i in range(m):
for j in range(n):
moves.append((i, j))
return list(set(moves)) | 355670f2d0ffb5e462ca2ed02f8b6c766122807b | 245,140 |
from typing import List
from typing import Tuple
def replace_one(title: str, abstract: str,
concepts: List[Tuple[int, int, str]]) -> str:
"""
Replace concepts in one PubMed article's title and abstract.
:param title: title string
:param abstract: abstract string
:param concept... | 9d3c3bae5e0118506ee9cc5d8cdcd8665de14f9e | 154,585 |
from functools import reduce
def extend(*dicts):
"""
Returns a dictionary that combines all dictionaries passed as arguments
without mutating any of them.
"""
def fold(acc, curr):
acc.update(curr)
return acc
return reduce(fold, dicts, {}) | 5f99cba8446f0a8bbd4385c8c91e5e3261fc0367 | 528,056 |
def mblg_to_mw_johnston_96(mag):
"""
Convert magnitude value from Mblg to Mw using Johnston 1996 conversion
equation.
Implements equation as in line 1654 in hazgridXnga2.f
"""
return 1.14 + 0.24 * mag + 0.0933 * mag * mag | f23acde1063c9c0f4c13a5d3679bf7e894fd6a00 | 624,816 |
import time
def exec_remote_cmd(client, cmd, t_sleep=5, verbose=False):
"""A wrapper function around paramiko.client.exec_command that helps with
error handling and returns only once the command has been completed.
Parameters
----------
client : paramiko ssh client
the client to use
c... | e6a79b58925252284c5427895d41ce3eed77f58f | 56,271 |
def find_in_map(map_name, key, value):
"""The intrinsic function Fn::FindInMap returns the value of a key from a \
mapping declared in the Mappings section.
Args:
map_name: The logical name of the mapping declared in the Mappings
section that contains the key-value pair.
key: Th... | 491168fb619334f8dac8857b96481d90d9f8675f | 70,113 |
def get_displayname(id, context):
"""
This function gets the printable username of a user
"""
user = context.message.guild.get_member(id)
if user is None:
return f"User {id}"
else:
return user.display_name | 0f284e67a56ed460eecabe02b10d9f9669f2246a | 224,651 |
import struct
def get_flag(alignment: bytes) -> int:
"""
Extract the alignment flag from a BAM alignment
Parameters
----------
alignment : bytes
A byte string of a bam alignment entry in raw binary format
Returns
-------
int
The alignment flag
Notes
-----
... | 8cd0e2678467de22bb7cf4a027be33529c21ca94 | 269,243 |
def is_in_graph(G, v):
""" Check whether a node is in the graph. """
assert isinstance(v, str) # v should be a label
return v in G.nodes() | 7dce9b4042b0a780734e31a6703aa427853bbc50 | 290,021 |
from typing import Callable
from typing import Iterable
from typing import Any
def ifilter(
function: Callable, iterable: Iterable, false: bool = False
) -> Iterable[Any]:
"""
Filter out the elements from iterable in accordance to function.
Notes
-----
The Python builtin filter class implemen... | f0c2ac169b5ddf1863f0f6e364076e7e5795e19f | 130,828 |
def from_base_alphabet(value: str, alphabet: str) -> int:
"""Returns value in base 10 using base len(alphabet)
[bijective base]"""
ret = 0
for digit in value:
ret = len(alphabet) * ret + alphabet.find(digit)
return ret | 386a286b2ad0f894adef69d40b8522f47ccdf287 | 335,585 |
from pathlib import Path
def file_exists(file_path):
"""
Check if file exists
:param file_path: (str) path to file
:return: (bool) True if file exists, False otherwise
"""
return Path(file_path).is_file() | 69a973f1c399477dff8b04381d5c7defa6f435c7 | 283,638 |
def get_es_worker(es_algorithm, logger, **kwargs):
"""Instantiate an evolution strategic algorithm worker.
Return an ES algorithm worker from the algorithms package.
Args:
es_algorithm: algorithms.*. ES algorithm.
logger: logging.Logger. Logger.
Returns:
algorithms.*Worker.
... | 6a12d0f44c0edfe34235d145fdb38e5b64ac836f | 579,350 |
def convertir_tiempo(segundos: int) -> str:
"""Convierte un tiempo en segundos a horas, minutos y segundos
:param segundos: tiempo en segundos
:type segundos: int
:return: tiempo en formato hh:mm:ss
:rtype: str
"""
horas = segundos // 3600
minutos = (segundos % 3600) // 60
segun... | be37add8e4acfa4af3dd1273468bc8ae1a38c52a | 177,984 |
def get_best_k(trials,
k=1,
status_whitelist=None,
optimization_goal='minimize'):
"""Returns the top k trials sorted by objective_value.
Args:
trials: The trials (Trail objects) to sort and return the top_k of.
k: The top k trials to return. If k=1 we don't retu... | 626c9664f013ed37c435a466603372d6f615d4c8 | 69,921 |
def update_driver_standings(standings, race_result):
"""
This function updates the driver's standings to reflect the points earned from a race.
Parameters:
standings (list): A list of dictionaries that contains the current driver's championship standings.
race_result (list): A list of dicti... | 60138ad12ab1b9738ccb52f44123d7c242726165 | 276,945 |
def clean_reg_name(reg, list):
"""
Clean the name of the registers by removing any characters contained in
the inputted list.
"""
for char in list:
reg = reg.replace(char, '')
return reg | 70bcd35e498c61c4ab1d53896d85fcd4fb74b5ff | 32,286 |
def isAlphanum(c):
"""return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character.
"""
return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or
(c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126)); | c955f5f7417ebcb0ce391bbbe244c2938035de81 | 618,998 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.