content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from typing import Callable
import math
def binom_tree(s: float,
k: float,
r: float,
sig: float,
t: float,
n: int,
iv: Callable[[float, float], float],
fv: Callable) -> float:
"""
Price of an option from a... | 93644712d6284db34b38c24ef1e23e347f346096 | 549,739 |
import functools
def rgetattr(obj, attr):
"""
>>> from types import SimpleNamespace
>>> args = SimpleNamespace(a=1, b=SimpleNamespace(c=2, d='e'))
>>> rgetattr(args, "a")
1
>>> rgetattr(args, "b.c")
2
"""
return functools.reduce(getattr, [obj] + attr.split('.')) | a3994923a6027c7c62cbe05e673a76de7988d76a | 401,674 |
def load_plain_file(file_path):
"""
Reads a path and returns the string information
Arguments:
- file_path (str): path to the file
Returns:
- text (str): the information to be retrieved
"""
with open(file_path, "r") as fp:
info = fp.read()
return info | d205b139cc7c2078e91fc133a87b3959aeb422e1 | 434,483 |
def _vpos(da):
"""
vPOS = Value at peak of season
"""
return da.max("time") | b245bbdb0eb8879301dc8c9e4e16a21a1a44d7e0 | 441,874 |
def parsehmmoutput(hmmresult):
"""parses the hmm output for housekeeping gene locations
parameters
----------
hmmresult
filename of parsable hmmsearch output
returns
----------
genelocs = dict, {gene:location}
"""
genelocs = {}
with open(hmmresult, "r") as f:
for ... | 2b87c097db6706cb543cd0dbeecd421750f5da7a | 357,115 |
def get_mapping(series):
"""
Map a series of n elements to 0, ..., n.
Parameters
----------
series : Pandas series (e.g. user-ids)
Returns
-------
mapping : Dict[]
"""
mapping = {}
i = 0
for element in series:
if element not in mapping:
mapping[eleme... | 452542dee5de04f6e50cc36ee6878dcd7c067bc6 | 201,767 |
def layer_size(X, Y):
"""
Get number of input and output size, and set hidden layer size
:param X: input dataset's shape(m, 784)
:param Y: input labels's shape(m,1)
:return:
n_x -- the size of the input layer
n_h -- the size of the hidden layer
n_y -- the size of the output layer
"""... | 81add6bf528cfe872e62f622161bb25fb7dcb1d3 | 48,800 |
def _parse_volumes_kwarg(cli_style_volumes):
"""
The Python API for mounting volumes is tedious.
https://github.com/docker/docker-py/blob/master/docs/volumes.md
This makes it work like the CLI
"""
binds = {}
volumes = []
for volume in cli_style_volumes:
split = volume.split(':')
... | 4c8d083ec2be02616491af42c725e2c5c14d419f | 280,810 |
import base64
def base64_encode(data: bytes) -> bytes:
"""Does a URL-safe base64 encoding without padding."""
return base64.urlsafe_b64encode(data).rstrip(b'=') | 341a6382a655ceb007bdba71e743d6c8656d4f7f | 578,773 |
def dict_to_list(d):
"""Converts an ordered dict into a list."""
# make sure it's a dict, that way dict_to_list can be used as an
# array_hook.
d = dict(d)
return [x[-1] for x in sorted(d.items())] | 6a56f890d3a5e6e9cb8a19fc5af8598bf3411d33 | 690,124 |
import re
def _remove_emoticons(tweet):
"""finds all emoticons, removes them from the
tweet, and then returns the tweet with emoticons
removed as well as a list of emoticons
Parameters:
-----------
tweet: str
contents of a tweet
Returns
-------
tweet_no_emoticons:
... | bbe7e1abed0228ccfd4aef6f191662a9a674a6ce | 64,629 |
def _color_strip(color):
""" 去除字符串中的多余空格
Parameters
----------
color : str
Returns
-------
str
返回去除了空格的颜色字符串
"""
return color.strip().replace(' ', '') | 8b7f815c64d1a9bf57cbd76db260e64f450783de | 71,093 |
import inspect
def form_of(state):
"""Return the form of the given state."""
if hasattr(state, "__form__"):
if callable(state.__form__) and not inspect.isclass(state.__form__):
return state.__form__()
else:
return state.__form__
else:
raise ValueError(f"{st... | e39aa7db7b324ab38b65232b34b987b862812c54 | 709,484 |
def extract_crs(da):
"""
Takes an xarray Dataset pulled from opendatacube and extracts crs metadata
if exists. Returns None if not found.
Parameters
----------
da: xarray Dataset
A single- or multi-dimensional array containing (or not) crs metadata.
Returns
-------
crs:... | d6c7432663d8606f9ff9346a9eeb82ea40b84ab6 | 429,675 |
def _validate_float(value):
"""Validate value is a float."""
try:
value = float(value)
except ValueError as err:
raise ValueError("Could not convert to float") from err
return value | d22281d79c440ba9c28ff79cbd3321dddd77831a | 381,274 |
import math
def sum_log_scores(s1: float, s2: float) -> float:
"""Sum log odds in a numerically stable way."""
# this is slightly faster than using max
if s1 >= s2:
log_sum = s1 + math.log(1 + math.exp(s2 - s1))
else:
log_sum = s2 + math.log(1 + math.exp(s1 - s2))
return log_sum | 7e41d5e0838a3bf78b0dd7a5c2b01ddcd1216247 | 659,869 |
import torch
def reverse_padded_sequence(inputs, lengths, batch_first=False):
"""Reverses sequences according to their lengths.
Inputs should have size ``T x B x *`` if ``batch_first`` is False, or
``B x T x *`` if True. T is the length of the longest sequence (or larger),
B is the batch size, and * i... | 2794e1effb4227e509d97aa942a87f329a61b7b8 | 51,953 |
def get_first_and_last(input_string):
"""Get the first 10, and last 10 characters,
and returns them as a tuple
Args:
input_string (str): string that will be used as source
Returns:
(str, str): tuple of first and last 10 chars in specified string
"""
return input_string[0: 10],... | 895859f64b394b0f778ccb6c33ffdc731ce299ca | 510,207 |
def clean_and_split_input(input):
""" Removes carriage return and line feed characters and splits input on a single whitespace. """
input = input.strip()
input = input.split(' ')
return input | 232f254db9083c23f49eed9305122f1cf9f5b936 | 212,558 |
def is_scalar(obj):
"""
Return True if the input is a scalar
"""
return obj.dims == [] | 6c1fae8c98758ed9f4da6140afbdef60b10d5cd0 | 534,635 |
def flatten(list_of_lists):
"""Flatten a given list of lists
Args:
list_of_lists (list): Given list of lists
Returns:
list: Flattened list
"""
return [x for each_list in list_of_lists for x in each_list] | fa1738d9ac2d9ec763a5461d7373a81fdef18b6a | 214,701 |
import re
from typing import List
def gen_flags_repr(flags: re.RegexFlag) -> str:
"""通过 RegexFlag 生成对应的字符串
Args:
flags (re.RegexFlag): 正则表达式的标记
Returns:
str: 对应的标记字符串
"""
flags_list: List[str] = []
if re.ASCII in flags:
flags_list.append("a")
if re.IGNORECASE in ... | 60f5b6be4c46c04d4ed3a445ddec597505e50f54 | 549,046 |
def field_size(field_label):
"""
Helper function to determine the size of a binary
table field
Parameters
----------
field_label : PVLModule
The field label
Returns
-------
int :
The size of the one entry in bytes
"""
data_sizes = {
'Intege... | afaff70bc18d4d9d023fb7c89d45560f1a691bcf | 699,111 |
def __date_to_iso8601(date):
"""Convert date to ISO-8601 format
"""
return '{year}-{month:02d}-{day:02d}T{hour:02d}:{minute:02d}:{second:02d}'.format(
year=date.year,
month=date.month,
day=date.day,
hour=date.hour,
minute=date.minute,
second=date.second) | c6e3f8bfd630f1d04656015013c32f3cdcf9dc1f | 474,510 |
def compute_gain(data,pol):
""" Compute the gain and apeture efficiency from the data.
Parameters
----------
data : heterogeneous record array containing 'calc_beam_height' and 'flux' records
Return
------
gain : The gains
"""
gain = data['beam_height_' + pol] / data['flux']
... | 740a90593f2d3e46d86ce9b9b4e9b9f92956e152 | 366,436 |
def dict2list(dict_: dict) -> list:
"""
Converts a dict into a list of key-value dictionaries and returns it.
Parameters
----------
dict_
Some dictionary to be converted.
Returns
-------
list_
Each element is a dict with one key-value pair. These key-value pairs
... | 16a066e41fe2dbb6dcc23e8d3e0b88da34aad84e | 331,744 |
import torch
def identity_grid(shape, dtype=None, device=None, jitter=False):
"""Returns an identity deformation field.
Parameters
----------
shape : (dim,) sequence of int
Spatial dimension of the field.
dtype : torch.dtype, default=`get_default_dtype()`
Data type.
device tor... | 6c70d5f04bc15555d9c5369594acb9e1c50c1e56 | 381,320 |
def sdss2decam(g_sdss, r_sdss, i_sdss, z_sdss):
"""
Converts SDSS magnitudes to DECam magnitudes
Args:
[griz]_sdss: SDSS magnitudes (float or arrays of floats)
Returns:
g_decam, r_decam, z_decam
Note: SDSS griz are inputs, but only grz (no i) are output
"""
gr = g_sdss - r... | a0869eeb138c00eb30476dd34883eabe77066129 | 71,954 |
def get_options(num):
"""Convert bitmasked int options into a dict."""
return {
'require_id': bool(num & 1),
'register_id': bool(num & (1 << 1)),
} | 9141db068aa3e9ab909f37a99f851182ce69a1da | 146,953 |
def read_cfg_intrinsics(cfg, section, key, default):
"""
Read intrinsics from a config file
Args:
cfg: config file
section: [section] of the config file
key: key to be read
default: value if couldn't be read
Returns: resulting intrinsic dict
"""
if cfg.has_optio... | 6f419136e7851685308a1d43ce9585596ca7c802 | 405,768 |
def tile_to_quadkey(tile_x, tile_y, level):
"""This is a function that converts tile coordinates at a certain
level of detail of a Bing Map to a unique string identifier (QuadKey).
:param tile_x: The x axis coordinate of the tile at `level` level of detail
:param tile_y: The y axis coordinate of th... | 6416511a03e4bb65eef969fa223aacbb18b8ee32 | 624,657 |
def _is_fedora(distname):
"""detect Fedora-based distro (e.g Fedora, CentOS, RHEL)"""
distname = distname.lower()
for x in ["fedora", "centos", "red hat"]:
if x in distname:
return True
return False | 273407ec9eccd3ee5e5e209e3a9c6fe54187b188 | 260,837 |
def get_all_headers(rows_list):
"""Utility to get all the keys for a list of dicts"""
headers = []
for row_dict in rows_list:
[headers.append(h) for h in list(row_dict.keys()) if h not in headers]
return headers | 36d4f6e2804535c76ce087f69c17a916a467ae8a | 186,290 |
import math
def get_angle(x, y):
"""Get angle based on the unit circle.
Parameters
----------
x : float
x-value
y : float
y-value
Return: float
angle
"""
if x == 0:
if y > 0:
return 90
else:
return 270
elif x < 0:
... | bf902232a1ae0aa5afff1b8ebfc27f744cdd0d3b | 242,774 |
def FindDocks(docks, dock_direction, dock_layer=-1, dock_row=-1, reverse=False):
"""
This is an internal function that returns a list of docks which meet
the specified conditions in the parameters and returns a sorted array
(sorted by layer and then row).
:param `docks`: a list of L{AuiDockInfo};
... | 188d9afacb05914247f4e47e835315a5a38b51df | 317,174 |
import click
def extended_help_option(extended_help=None, *param_decls, **attrs):
"""
Based on the click.help_option code.
Adds a ``--extended-help`` option which immediately ends the program
printing out the extended extended-help page. Defaults to using the
callback's doc string, but can be giv... | b7c4f623c252baf17cdc7daf645a15ec67451cde | 522,298 |
import typing
def is_basic_iterable(obj: typing.Any) -> bool:
"""Checks if an object is a basic iterable.
By basic iterable we want to mean objects that are iterable and from a
basic type.
:param obj: Object to be analysed.
:return: True if obj is a basic iterable (see list below). False otherwi... | 48a87ea430021fe7086ba9c17d973da1ef5f7fdd | 645,138 |
def calc_nchk(n,k):
"""
Calculate n choose k
"""
accum = 1
for i in range(1,k+1):
accum = accum * (n-k+i)/i
return int(accum) | 3b176bd05147b0f9bc549c885fed303faeb97bbe | 307,528 |
def translate(s: str, src: str, dest: str) -> str:
"""
Converts characters from `s` that appear in `src` with the
characters at corresponding positions in `dest`
"""
if len(src) != len(dest):
raise RuntimeError("impossible error")
for a, b in zip(src, dest):
s = s.replace(a, b)
return s | 52695fd7a56f4f2ba0a91f8f64683e6bda3d0b1a | 79,436 |
def contain_disambig_symbol(phones):
"""Return true if the phone sequence contains disambiguation symbol.
Return false otherwise. Disambiguation symbol is at the end of phones
in the form of #1, #2... There is at most one disambiguation
symbol for each phone sequence"""
return True if phones[-1].s... | 807f81b999632164de13fdf2c0d182e2abb73f44 | 196,270 |
import json
def context_from_json_file(file_name):
"""
Load a json file into a dictionary.
Parameters
----------
file_name: str
Path to the json file.
Returns
dict
Content of the file as dictionary.
"""
with open(file_name, encoding='utf-8') as json_file:
... | 47968c0eb0f267421006ddaebf15c8a4ef643c25 | 589,841 |
def is_odd(n):
"""
Determine whether n is odd.
:parameter n: int, n > 0
:return: bool, if it's odd
"""
return n % 2 != 0 | b254da356b3aa6b87e3a546de2448b26d42a8636 | 266,501 |
def convert_epa_unit(df, obscolumn="SO2", unit="UG/M3"):
"""
converts ppb to ug/m3 for SO2 in aqs and airnow datasets
See 40 CFR Part 50.5, Appendix A-1 to part 50, appendix A=2 to Part 50.
to convert from ppb to ug/m3 multiply by 2.6178.
Also will convert from ug/m3 to ppb.
Parameters
---... | 4af9811c3ae465904b3320cc6d5dd0e29f1ff598 | 69,221 |
from pathlib import Path
def get_raw_svg(path: str) -> str:
"""Get and cache SVG XML."""
return Path(path).read_text() | 60f85b0ff8f1d4478b7093acddef5255230197f9 | 349,653 |
def read_counts(counts_filename):
"""Reads counts file into dict of counts"""
with open(counts_filename) as f:
lines = f.read().splitlines()
lines.pop(0)
lines_proc = dict( (line.split()[1] , float(line.split()[8])) for line in lines if '*' not in line.split()[1] )
return lines_proc | f7b0ae671dd129470d3d8bd1ee44543519adde25 | 521,951 |
import re
def _include_exclude(
dictionary: dict,
include_pattern: str,
exclude_pattern: str,
) -> bool:
"""
Filters the items of a dictionary based on a include / exclude regexp pair.
Returns `True` if the size of the dictionary changed.
"""
incl, excl = re.compile(include_pattern), r... | c7b06f84463c7d003a6516d5fc943da12ac4968e | 680,224 |
import random
import math
def get_random_percents(number):
"""
retruns a list of n random percents that will sum to 100
"""
tanks = []
total = 0
for _ in range(number):
num = random.randint(1, 10)
total += num
tanks.append(num)
percents = []
for tank in tan... | 1a8675448a7be1397c3993581feaf415b380604f | 291,092 |
def get_bbox(x_start, y_start, x_end, y_end):
"""
This method returns the bounding box of a face.
Parameters:
-------------
x_start: the x value of top-left corner of bounding box
y_start: the y value of top-left corner of bounding box
width : the x value of bottom-right corner ... | 79e440d4875f1e32d5f678d6715777ab525f4c69 | 46,572 |
def get_action_value(mdp, state_values, state, action, gamma):
""" Computes Q(s,a) as in formula above """
result = 0
for to_state in mdp.get_all_states():
transition_probability = mdp.get_transition_prob(state, action, to_state)
reward = mdp.get_reward(state, action, to_state)
resul... | 226d8e01054552ae1108d3d83e0e438ddc821df9 | 28,702 |
def _get_required_data(description=False):
"""
Provides a list of the required inputs for all possible ensembles.
Parameters
----------
description : bool, default = False.
If True, it prints the descriptions of the input_variables (i.e. dict),
If False, it only prints the input_va... | 0a37e425e1b9efc426c53a19522b2d0e9fc2edc1 | 155,079 |
def dim_col(d: int) -> str:
"""
Name of an dimension columns.
Parameters
----------
d
Dimension number.
Returns
-------
name: str
Dimension name.
Example
-------
>>> from rle_array.testing import dim_col
>>> dim_col(1)
'dim_1'
"""
return f"d... | e4f76bdba041535993aaea1ba613f1596d8e32e9 | 652,019 |
def get_image_batch(generator,batch_size):
"""keras generators may generate an incomplete batch for the last batch"""
img_batch = generator.next()
if len(img_batch) != batch_size:
img_batch = generator.next()
assert len(img_batch) == batch_size
return img_batch | c9c9b61e1775b275157f4d979eb7117d8fbef0d2 | 425,011 |
def split_folds(X, y, fold_series, test_fold):
"""Take a dataset whose observations have been grouped into folds,
then perform a train-test split.
X, y: feature and target DataFrames.
fold_series: Series containing the fold numbers of the observations.
test_fold: Integer, the fold number that w... | 38051e584c427ffe77273fbbcdd764b6fe432b2f | 45,296 |
import torch
def resort_points(points, idx):
"""
Resort Set of points along G dim
:param points: [N, G, 3]
:param idx: [N, G]
:return: [N, G, 3]
"""
device = points.device
N, G, _ = points.shape
n_indices = torch.arange(N, dtype=torch.long).to(device).view([N, 1]).repeat([1, G])
... | a886b1c694a2c8c1ef5a3c2bdccf201aa7a53812 | 654,095 |
def ansiSameText(s1:str,s2:str)->bool:
"""Compare two strings case insensitive"""
return (s1.lower()==s2.lower()) | 2faad19d93fc60377418b9f6f0b56778f07b46be | 579,495 |
import hashlib
def md5sum(file_path):
""" Calculate md5 checksum of single file
Args:
file_path (str): Path to file
Returns:
str: md5 checksum
"""
md5sum = hashlib.md5()
with open(file_path, 'rb') as file_object:
for block in iter(lambda: file_object.read(md5sum.block... | 7bf5542334a752690bd8e7298ae67c9c14020a21 | 406,603 |
def get_readable_file_size(size):
"""
Returns a human-readable file size given a file size in bytes:
>>> get_readable_file_size(100)
'100.0 bytes'
>>> get_readable_file_size(1024)
'1.0 KB'
>>> get_readable_file_size(1024 * 1024 * 3)
'3.0 MB'
>>> get_readable_file_size(1024**3)
'... | aa103e6c41195dbbcf37d83397570ac19410fdcb | 332,180 |
def decode_model_info_proto(model_info_proto):
"""Decodes the model_info_proto created by create_model_info_proto
Arguments:
model_info_proto (ModelInfo proto): model_info_proto created by create_model_info_proto
Returns:
list_of_model_info_dict (list): A list containing model_info_dicts
... | 34ce3043463dc8cf2b3716f208ab9758a6215a74 | 283,718 |
import random
def generate_addends(n_addend, minimum=1, maximum=9):
"""
n_addend : number of addends
minimum : minimum of an addend. 1 by default
maximum : maximum of an addend. 9 by default
"""
# generate addends
addends_list = []
for _ in range(n_addend):
addends_list.appen... | 40af83dcc94092e7e0834fef3d22394385ff8d96 | 439,256 |
def render_warning(s) :
""" Make rst code for a warning. Nothing if empty """
return """
.. warning::
%s"""%(s) if s else '' | 2ba32b16e9f81b85ce51d4b2e7c9e34d2bd5c9e7 | 316,575 |
def compose_redis_key(vim_name, identifier, identifier_type="vdu"):
"""Compose the key for redis given vim name and vdu uuid
Args:
vim_name (str): The VIM name
identifier (str): The VDU or VNF uuid (NFVI based)
identifier_type (str): the identifier type. Default type is vdu. Also vnf is... | e9a03cf9ff704fea8b9cdf75c59695568e366649 | 709,026 |
from typing import List
from typing import Dict
from typing import ChainMap
def concat_stocks(stock_lists: List[Dict]) -> Dict[str, str]:
"""Concats a list of small dictionaries of `stock`:`price` into one dictionary"""
return dict(ChainMap(*stock_lists)) | b7e050f36b1ee42c969afe4c21b22bf43548e80c | 324,800 |
import re
def pick_address_string(src):
"""
Pick address string from input string with regex
Args:
src (str) : Text would you like get address
Return:
str: Address what you picked
"""
match = re.match(r'.*?[로(지하)?|길동리]\s?(\d+-*)+\s?((번*길)\s?(\d+-*)+)?', src)
return match... | 1748ada790610e9904b758cc32c48fd059f9d51b | 529,929 |
def signed_leb128_decode(data) -> int:
"""Read variable length encoded 128 bits signed integer.
.. doctest::
>>> from ppci.utils.leb128 import signed_leb128_decode
>>> signed_leb128_decode(iter(bytes([0x9b, 0xf1, 0x59])))
-624485
"""
result = 0
shift = 0
while True:
... | 43419df92be9a1bc32f51c7b1dde13d6e1599424 | 536,037 |
def group_weight_decay(net, decay_factor, skip_list):
"""Set up weight decay groups.
skip_list is a list of module names to not apply decay to.
"""
decay, no_decay = [], []
for name, param in net.named_parameters():
if not param.requires_grad:
continue
if any([pattern i... | a3a9a0b3aa45963b0d0fb0aafc3be850e05060b4 | 591,696 |
def l_min(s, m):
""" Minimum allowed value of l for a given s, m.
The formula is l_min = max(\|m\|,\|s\|).
Parameters
----------
s: int
Spin-weight of interest
m: int
Magnetic quantum number
Returns
-------
int
l_min
"""
return max(abs(s), abs(m)) | 9eec996df3b8e026c8b58649fddbbbcc05c38372 | 11,672 |
import re
def generate_unique_name(base: str, items: list):
"""
Generates a unique name for a new item using a common base string
:param base: The generated name will be the base string, followed by a number if required
:param items: The named items to avoid generating a matching name with. Each must... | 9c7093c59825862c1e15f8385e7207e277b6088d | 516,644 |
from datetime import datetime
def ymd2date(y, m, d):
"""
Convert (y, m, d) tuple to datetime.datetime object
where y, m, d are year, mont and date integers
Example (2013, 12, 20)
:param tpl: Tuple inf (y, m, d) format
:return: datetime.datetime object
Example:
>>> import dti... | e4a2fa6a9534c10f887b8ae71e0eae0b13599ce4 | 138,372 |
def setup_with_context_manager(testcase, cm):
"""Use a contextmanager to setUp a test case."""
val = cm.__enter__()
testcase.addCleanup(cm.__exit__, None, None, None)
return val | ef60ebfe6ce00ea2a4784a61241dc22dd292b81d | 624,366 |
def make_get_request(client, endpoint):
"""
Makes a get request to the given endpoint from the client.
"""
return client.get(endpoint) | d64376e5e7b0ad42b3b093af48bfa97e3a137744 | 57,790 |
import re
def get_urls(string):
"""Get all url matching strings from string"""
regex = re.compile(r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|
(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))""... | 3b9f085e99f540d65d86e500f73c6c6607297b96 | 218,631 |
import inspect
def bound_args(func, args, kwargs):
"""Return a dictionary mapping parameter name to value.
Parameters
----------
func : Callable
this must be inspectable; mocks will require a spec
args : List
args list
kwargs : Dict
kwargs Dict
Returns
-------... | 32abe2cdd621b52b0bb306830e542c92430962b9 | 454,704 |
def get_X_Y(lockin):
"""
Get X and Y (Measure)
args:
lockin (pyvisa.resources.gpib.GPIBInstrument): SRS830
returns:
(tuple): X, Y
"""
X, Y = lockin.query("SNAP? 1,2").split("\n")[0].split(",")
X, Y = float(X), float(Y)
return X, Y | 3d56151042682f86350a499ab639852fc6387887 | 15,198 |
def _adjmatType(adjMat):
"""(helper function) retruns <class 'int'> if the adjacency matrix is a (0,1)-matrix, and
returns <class 'list'> if the adjacency matrix contains edge weights, and returns None if
neither of the cases occurs.
Args:
adjMat (2D - nested - list): the adjacency matrix.
... | f57e3a97c6d759a564bcf0e546c67ee975caf4c7 | 669,943 |
def get_square_centre_crop(img):
"""
This function calculates a centered square crop bounding box
as big as the image's smaller dimension allows.
:param img: PIL Image object.
:return: Tuple with bounding box of the square crop.
"""
width, height = img.size
if width > height:
x_... | 141691ea388d783bd51a85f55b9a03519231196a | 264,801 |
def fn2Test(pStrings, s, outputFile):
"""
Function concatenates the strings in pStrings and s, in that order, and writes the result to
the output file. Returns s.
"""
with open(outputFile, 'w') as fH:
fH.write(" ".join(pStrings) + " " + s)
return s | 1c1e811edd80c461c5173774f7bb0014b4ad9f92 | 399,280 |
def meta2idx(current_idxs, meta_per_dataset):
"""
Map meta information of a dataset to the indexes of its samples in the full data.
Parameters
----------
current_idxs: list of list of integers
each sublist corresponds to list of index of cells in each dataset
meta_per_datas... | 9c74a6b778f04a8ff4035bf5601f3bc69cb81180 | 366,629 |
import re
def sentence_segmenter(paragr):
"""
Function to break a string 'paragraph' into a list of sentences based on
the following rules:
1. Look for terminal [.,?,!] followed by a space and [A-Z]
2. If ., check against abbreviation list ABBREV_LIST: Get the string
between the . and the pre... | 127467d8128ee9e47d325ca20905c508fbd17d18 | 143,479 |
def _PyComplex_FromCComplex(space, v):
"""Create a new Python complex number object from a C Py_complex value."""
return space.newcomplex(v.c_real, v.c_imag) | fd980468f0df584ea2672edab40b7108798cd535 | 469,804 |
import re
def template_pattern_match(results, template_pattern):
"""
Return templates which match the template pattern. No pattern specified returns all template
:param results - list of all template
:param template_pattern - optional wildcard (*) name of template to match
:return: list of templat... | 2ad1c1d6b8700f9c2ca4bf67afd8c501b53825b7 | 481,982 |
from typing import List
from typing import Tuple
def group(lst: List, n: int) -> List[Tuple]:
"""
Splits a list into tuples of length n
https://stackoverflow.com/a/15480610/36061
eg
a = 'Moscow|city|London|city|Royston Vasey|vilage'
list(group(a.split('|'), 2))
gives
[('Moscow', 'city... | 61de96a908434e63423529a55194f7a7fa027d54 | 591,917 |
def mod_family_accession(family_accession):
"""Reduces family accession to everything prior to '.'."""
return family_accession[:family_accession.index('.')] | ec033cd33fccd8fbd7a0c4407d706ca32fb87fb2 | 658,789 |
def bollinger_band_generator(dataframe_name, closing_price_column_name = 'close', bollinger_band_window = 20, num_standard_deviation = 2):
"""Creates Bollinger Band function
Args:
dataframe_name (dict): Single security dataframe containing at least closing prices
closing_price_column_name (str):... | 43d585c72338fb050f1f595b0659de689b4b8c18 | 470,328 |
def levels_to_graph(levels):
"""
Convert an array of levels into a unicode string graph.
Each level in the levels array is an integer 0-3. Those levels will be
represented in the graph by 1-4 dots each.
The returned string will contain two levels per rune.
"""
if len(levels) % 2 == 1:
... | 8994d6d6eea5c741f706b78e6754bab7850909b2 | 73,365 |
def delete_session_mock(mocker):
"""Mock for patching DELETE request"""
return mocker.patch("hydra_agent.agent.Session.delete") | 26c3073e2d51dec1f3dcd9bfee3db311fdcf6a66 | 76,284 |
import torch
def log_initial_entropy(log_probs: torch.Tensor):
"""
Calculates the log of the initial state posterior entropy from log_probs, with dimensions
-1: s_k, -2: s_1
:param log_probs:
:return:
"""
inits = log_probs.logsumexp(-1)
return ((-inits).log() + inits).logsumexp(-1) | d38a4359aef1f52117a33c806d04a26f4aee572e | 166,291 |
def enable_show_options(options):
"""Sets all show options to True."""
options.show_nagios = True
options.show_rrdfile = True
options.show_rawmetric = True
options.show_metric = True
options.show_skipped = True
return options | 6da8a5d4c1b381d5ab343c2035ff5262fbf69f23 | 127,027 |
def _bytes(packet):
"""
Returns a human-friendly representation of the bytes in a bytestring.
>>> _bytes('\x12\x34\x56')
'123456'
"""
return ''.join('%02x' % ord(c) for c in packet) | c3877c4081e191bcdcb95dd958beb0fd8356699e | 304,651 |
def profit_in_percentage(value, arg):
"""Profit Percentage with % sign
>>> profit_in_percentage(2, 1)
'100.0 %'
"""
val = value - arg
return str(round(val * 100, 2)) + " %" | cf22a48b5d9b2819883b47d1db558a6c1a3f8707 | 212,813 |
def getDestBinFormatByOS(destOS):
"""
Return the binary format based on the platform name.
Returns 'elf' if nothing is found.
"""
if destOS == 'darwin':
return 'mac-o'
if destOS in ('win32', 'cygwin', 'uwin', 'msys', 'windows'):
return 'pe'
return 'elf' | 99665fdbc0b83cde6c04d68591602699997746b8 | 361,870 |
from typing import Union
def wmi_object_2_list_of_dict(wmi_objects, depth: int = 1, root: bool = True) -> Union[dict, list]:
"""
Return a WMI object as a list of dicts, accepts multiple depth
Example for Win32_LoggedOnUser().Antecedent.AccountType return is [{'Antecedent': {'AccountType': 512}}]
Hence... | 6b54a7b75ee41c7bd3cedb7b38a2e2fe5a44cb15 | 310,152 |
from typing import Sequence
def prepend_parts(prefix_parts: Sequence[str], parts: Sequence[str]) -> Sequence[str]:
"""
Prepend `prefix_parts` before given `parts` (unless they are rooted).
Both `parts` & `prefix_parts` must have been produced by :meth:`.json_path()`
so that any root(``""``) must come... | ced228055e64b0ef7877856ce536ed8884ce6819 | 181,817 |
def get_weekdays(first_weekday=0):
"""Get weekdays as numbers [0..6], starting with first_weekday"""
return list(list(range(0, 7)) * 2)[first_weekday: first_weekday + 7] | 8773a6b35f1104ca298074d90e639919353d357d | 133,303 |
def HOUR(expression):
"""
Returns the hour portion of a date as a number between 0 and 23.
See https://docs.mongodb.com/manual/reference/operator/aggregation/hour/
for more details
:param expression: expression or variable of a Date, a Timestamp, or an ObjectID
:return: Aggregation operator
... | f34b9d923ee9416174d3d2871cface57e539363e | 476,289 |
def map_per_image(label, predictions):
"""Computes the precision score of one image.
Parameters
----------
label : string
The true label of the image
predictions : list
A list of predicted elements (order does matter, 5 predictions allowed per image)
Returns
-------... | 5874d669d83143a6e4dd5f32d15fb58da70fe9aa | 564,595 |
def seqcomp(s1, s2):
"""
Compares 2 sequences and returns a value with
how many differents elements they have.
"""
p = len(s1)
for x,y in zip(s1, s2): # Walk through 2 sequences.
if x==y:
p -= 1
return p | 1ef0e7fddc751225ba2030804b360daf8bf10abd | 670,035 |
import six
def to_string(s, encoding='utf-8'):
"""
Accept unicode(py2) or bytes(py3)
Returns:
py2 type: str
py3 type: str
"""
if six.PY2:
return s.encode(encoding)
if isinstance(s, bytes):
return s.decode(encoding)
return s | 3b2c5ea3e1de9724cb705a79c54f3eb700b0f16d | 319,054 |
def min_length(word, thresh):
""" Predicate for the length of a word """
return len(word) >= thresh | 5f6eff3e06726294a64ef7705e3797ab188202f3 | 625,640 |
def distance(rgb1, rgb2):
"""Return quasi-distance in 3D space of RGB colors."""
return (rgb1[0]-rgb2[0])**2 + (rgb1[1]-rgb2[1])**2 + (rgb1[2]-rgb2[2])**2 | d2db02322d355a0c86c279e5fb38af4438d8d754 | 353,469 |
def combination(a: int, b: int) -> int:
"""
Choose b from a. a >= b
"""
b = min(b, a - b)
numerator = 1
dominator = 1
for i in range(b):
numerator *= (a - i)
dominator *= (b - i)
return int(numerator / dominator) | 9e31462423b998b6a3f10b497ebe5a0a8fb0c0fb | 457,124 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.