content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def cubic_ease_in_out(p):
"""Modeled after the piecewise cubic
y = (1/2)((2x)^3) ; [0, 0.5)
y = (1/2)((2x-2)^3 + 2) ; [0.5, 1]
"""
if p < 0.5:
return 4 * p * p * p
else:
f = (2 * p) - 2
return (0.5 * f * f * f) + 1 | 6bff96da6d52ff7e7a65ac04a893755ca957e25c | 568,853 |
def accuracy(reference, test):
"""
Calculate the fraction of test items that equal the corresponding reference items.
Given a list of reference values and a corresponding list of test values,
return the fraction of corresponding values that are equal.
In particular, return the fraction of indexes
... | f605c4cc5bbb7ced4cf311f0224becae3d3bc69f | 568,854 |
def binary_to_decimal(binary):
"""Convert a binary string into an integer. E.g. '101' -> 5."""
return int(binary, 2) | d002a66821d5598e29b66a26b0ca310a44a25084 | 568,855 |
def first(s):
"""Return the first element in a sequence."""
return s[0] | 37c1bc8931008b4c74e85d1f958e671c9ce6d083 | 568,858 |
import json
def load_data(filename):
"""Load examples from preprocessed file.
One example per line, JSON encoded.
"""
# Load JSON lines
with open(filename, encoding='utf-8') as f:
examples = [json.loads(line) for line in f]
return examples | 76e6639d05e1e823e8f0ccc71250ed562eac7f8f | 568,862 |
import math
def dist_calc(x, y):
"""Returns a distance calcultion fuction from a static (x, y)"""
def func(x1, y1):
return math.sqrt(math.pow(x1-x, 2) + math.pow(y1-y, 2))
return func | 7a55c4b00c2a72eb64f1468b650d6195a791b32a | 568,867 |
def convert_scores_to_percentiles(
query_df, score_column, percentile_column_name, invert_percentiles=False
):
"""
convert_scores_to_percentiles
=============================
Method used to convert a range of scores to a range of percentiles from 0.0 to 1.0. Most often, the higher
the percentil... | 30c1857cfcb7ed7e9c4eea141eb6e7220944dacc | 568,872 |
def parse_chrom_names(filename):
"""Parse file with chromosome names."""
chrom_names = set()
with open(filename) as handle:
for line in handle:
line = line.strip().split('\t')
chrom_names.add(line[0])
return chrom_names | 9108bffeb412ebcb4ce303fba72f2b904b9dc7d9 | 568,876 |
import requests
import io
def get_rules_from_uri(uri):
"""Retrieves a rules file from a URL."""
download = requests.get(uri)
if not download.content:
raise Exception('No content retrieved from {}'.format(uri))
file = io.BytesIO(download.content)
return file | cb464e6762f80eb6cd133a4cd95ab04aa4d2d861 | 568,878 |
def get_conv_def(conv_defs, layer_name):
"""Get the custom config for some layer of the model structure.
Args:
conv_defs: A named tuple to specify the custom config of the model
network. See `ConvDefs` for details.
layer_name: A string, the name of the layer to be customized.
Returns:
The numb... | d3f74dcadb7c9861404d4b1d7a81e531b689ad7a | 568,880 |
def get_position_features(sg_df, id_cols):
"""Get features ['Target Cut %', 'sense']
:param sg_df: DataFrame
:param id_cols: list
:return: DataFrame
"""
position_df = sg_df[id_cols + ['Target Cut %']].copy()
position_df['sense'] = sg_df['Orientation'] == 'sense'
return position_df | 824e72368277c6f84ffb6205fb84e93ae174aa0f | 568,881 |
import torch
from typing import List
def get_batchnorm_modules(module: torch.nn.Module) -> List[torch.nn.Module]:
"""Return all submodules which are batch normalization layers."""
return [submodule for submodule in module.modules() if isinstance(submodule, torch.nn.modules.batchnorm._BatchNorm)] | 9828e53a1f6d92dd93db4614bb975ea3e8be84df | 568,884 |
def fillNaToCustom(data):
"""Iterates through NA values and changes them to Typ
Parameters:
dataset (pd.Dataset): Both datasets
Returns:
pd.Dataset: Dataset with any NA values in the columns listed changed to Typ
"""
data["Functional"] = data["Functional"].fillna("Typ")
return data | a7cc65503297a5b9bf740ed0ec41d643b59ea1f8 | 568,889 |
def progress_hook(out):
"""
Return a progress hook function, suitable for passing to
urllib.retrieve, that writes to the file object *out*.
"""
def it(n, bs, ts):
got = n * bs
if ts < 0:
outof = ''
else:
# On the last block n*bs can exceed ts, so we c... | 671a0dea5b77d002ff106faa5e436abe86b5e5d5 | 568,892 |
def center_anchor(center_id):
"""Given a center id, returns a string suitable for use as an HTML id attribute value"""
return 'c{}'.format(center_id) | 11d4956db72f85b8770b41f2a336842617d204ba | 568,893 |
import json
def RunScriptsAndParseOutput(launch_command, vm):
"""A function to launch the command and return the performance.
Args:
launch_command: Arguments to the script driver.
vm: Client vm on which the script will be run.
Returns:
json representation of the performance results.
"""
stdout... | 83fe2ace2fcaa73a012897d65ac86cc037c7ee15 | 568,894 |
import six
def has_value(value):
"""Check a given value is not empty."""
if value is None:
return False
if isinstance(value, six.string_types):
if not len(value.strip()):
return False
return True | 8d488aa0cfc109998f2ab01e1586bbc757db61b3 | 568,896 |
def strip_and_split(s, sep):
""" Split s on sep and strip the resulting elements """
return (c.strip() for c in s.split(sep)) | 4c8f85035aeade43dbbdd46c8b2a4ab2baa9f2c5 | 568,903 |
def _connect_local(spec):
"""
Return ContextService arguments for a local connection.
"""
return {
'method': 'local',
'kwargs': {
'python_path': spec.python_path(),
}
} | 70f2c17e94ab52e5984198a1c183d6bb5f3c3979 | 568,904 |
def dataclass_param(request):
"""Parametrize over both implementations of the @dataclass decorator."""
return request.param | 4954d0fe17b620f592d1899af885d1a221f8ad24 | 568,908 |
def metalicity_jk_v_band(period, phi31_v):
"""
Returns the JK96 caclulated metalicity of the given RRab RR Lyrae.
(Jurcsik and Kovacs, 1996) (3)
(Szczygiel et al., 2009) (6)
(Skowron et al., 2016) (1)
Parameters
----------
period : float64
The period of the star.
phi31_v : ... | fddd8e895372a68f1aaf96b4879155adb2cf0a8e | 568,909 |
def valid(records):
"""Returns True if all records in the set are valid."""
return all(record.valid() for record in records) | 0e7c630e660eaa951c1cfa18fe0736bc93d7a677 | 568,913 |
def draw_relative(canvas, color, current_x, current_y, dx, dy):
""" Draw starting at the indicated point and return the new point."""
new_x = current_x + dx
new_y = current_y + dy
canvas.create_line(current_x, current_y, new_x, new_y, fill=color)
return new_x, new_y | 90da21cb418b81ad96724b26977501b874a1a6ae | 568,915 |
import torch
def corner_to_standup_box_torch(box_corner):
"""
Find the minmax x and y for each bounding box.
Parameters
----------
box_corner : torch.Tensor
Shape: (N, 8, 3) or (N, 4)
Returns
-------
standup_box2d : torch.Tensor
(n, 4)
"""
N = box_corner.shape... | 3b5703eca4359467862df4753a64f28f907d9508 | 568,918 |
def od2list(od):
"""Convert OrderedDict to list"""
return [key for key in od], [od(key) for key in od] | d1ffaa3fa8f89d7bed34b15bcdb5d2f1fc284f74 | 568,919 |
from typing import Optional
def env_chk(
val: str,
fw_spec: dict,
strict: Optional[bool] = True,
default: Optional[str] = None,
):
"""
Code borrowed from the atomate package.
env_chk() is a way to set different values for a property depending
on the worker machine. For example, you mi... | 9f74d795376821e0cfb8e125a6653e59fb8354fd | 568,921 |
def find_start_end_dates(dates1, dates2):
"""
Find start and end dates between two different sized arrays of datetime
objects.
Parameters
----------
dates1 : list
List of datetime objects.
dates2 : list
List of datetime objects.
Returns
-------
... | 4fdefb2a0dd23962cf8e0f1dcdce832a81d39eb9 | 568,923 |
import torch
def create_optimizer(optim_cfg: dict, model: torch.nn.Module) -> torch.optim.Optimizer:
""" Take in optimizer config and create the optimizer for training. """
name = optim_cfg.get("type", None)
if name.lower() == "sgd":
lr = float(optim_cfg["lr"])
momentum = float(optim_cfg["... | 1f55b4c07cb6911aeda8aba4bcffcdb5626dcb13 | 568,924 |
import inspect
def get_members_from_module(module):
"""Returns the members from a module.
:param module: A module
:return: A list of types that are members of the module
"""
def filter_members(member):
return (
inspect.isclass(member)
or inspect.isfunction(member)... | d02621b6f7feb1dafb460492513119b09802f143 | 568,928 |
def strA(arr, start="[", sep=",", end="]"):
""" returns a string representation of an array/list for printing """
res=start
for i in range(len(arr)):
res+=str(arr[i])+sep
return res + end | 4160755875c8d1c41bfb9f5afcaf6201ada86c82 | 568,930 |
def add_gcvi(image):
"""
Calculates the Green Chlorophyll Vegetation Index (GCVI)
"""
gcvi = image.expression(
'(NIR/G) - 1', {
'NIR': image.select('NIR'),
'G': image.select('G'),
}
).rename('GCVI')
return image.addBands(gcvi) | fcbf4fa4d77da13f63377cd3e324cda948323162 | 568,934 |
def _create_k8s_software_string(software_name: str, software_version: str) -> str: # noqa: E501
"""Generate string containing the software name and version.
Example: if software_name is "upstream" and version is "1.17.3",
"upstream 1.17.3" is returned
:param str software_name:
:param str soft... | 39197d2daeef6401cdb41b7e611f3b11d81c9ef5 | 568,937 |
def zeemanSplitting(S, I, N, J, F):
"""
Return the Zeeman splitting factor in Hz/microG
"""
alphaJ = (F*(F+1) + J*(J+1) - I*(I+1)) / (2*F*(F+1))
alphaI = (F*(F+1) + I*(I+1) - J*(J+1)) / (2*F*(F+1))
gJ = (J*(J+1)+S*(S+1)-N*(N+1)) / (J*(J+1))
gI = 0.4036#*0.0
return -2*(gJ * alphaJ + gI * alphaI) * 1.3996 | 02a19ff69b0d5e1f4d9dac2944154de750152c9b | 568,940 |
def point_double(a):
# http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
"""
compute A = X1^2
compute B = Y1^2
compute C = B^2
compute D = 2 ((X1 + B)^2 - A - C)
compute E = 3 A
compute F = E^2
compute X3 = F - 2 D
co... | d2d31ddce55b6cd23420351e3e2b75cf431390b3 | 568,942 |
def feature_dict(entry):
"""Template dictionary for JSON feature from TED entry"""
corners = [*entry["corners"], entry["corners"][0]] # create Linear Ring
feature = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [corners]
},
"pro... | 0638da4ec93da344a72e00cc61795301fe10ffd8 | 568,944 |
def convert_none(x: float) -> int:
"""
Helper to use 0 for None values.
"""
if isinstance(x, str):
x = float(x)
if x is None:
return 0
else:
return int(x) | 03977a5d28d492bad0661fd4e6173260707aed12 | 568,947 |
def _get_noise_id(tr):
"""
Get trace id for noise type data. e.g., 'starttime-endtime'
:param tr: an obspy trace
:return str event_id: noise id
"""
starttime = tr.stats.starttime
endtime = tr.stats.endtime
event_id = "-".join([starttime.strftime("%Y%m%d%H%M%S"), endtime.strftime("%Y%m%d... | 16960810091e2ae6daa512eb8ccfe8f79c15e960 | 568,949 |
def get_hms(t_sec):
"""
Convert a time given in seconds to hours, minutes, and seconds
Parameters
----------
t_sec : int
Time in seconds.
Returns
-------
h : int
The hours portion of the time.
m : int
The minutes portion of the time.
s : int
The ... | 7c1ecddd67ee50d37c3731e8f69e11270b1580b4 | 568,950 |
def do_each(*actions):
"""Perform a series of actions."""
def _inner(state, *args):
for action in actions:
action(state, *args)
return _inner | 5b9aa006d13432661e008f035f745bb584967af2 | 568,952 |
from pathlib import Path
from typing import Optional
import json
def get_n_articles(data_dir: Path) -> Optional[int]:
"""get `n_articles` reported in a processing step's output dir."""
try:
return int(
json.loads(data_dir.joinpath("info.json").read_text("utf-8"))[
"n_articl... | 1c339c59c8a37f7bf3e936c36dc60cb0c5d65e15 | 568,958 |
def name_without_zeroes(name):
"""
Return a human-readable name without LSDJ's trailing zeroes.
:param name: the name from which to strip zeroes
:rtype: the name, without trailing zeroes
"""
first_zero = name.find(b'\0')
if first_zero == -1:
return name
else:
return str... | 02ce5faf37594de8d439657a86e1c0bd233f5e3e | 568,963 |
import functools
def delay_denial(func):
"""
Decorator to declare which methods should have any swift.authorize call
delayed. This is so the method can load the Request object up with
additional information that may be needed by the authorization system.
:param func: function to delay authorizati... | b90b8b98d1c702ccd8ae2a4e998aefc29e50e8be | 568,964 |
def get_table(table):
"""
Updates table styling
:param table: an html table
:return: the newly styled table
"""
table['class'] = "usa-table"
return table | bc25990a83fae2c9a6da106f7af25e1ef87a39d5 | 568,965 |
import math
def element_length(structure, index):
"""
Returns the length of the index-th element in a Structure
:param structure: Structure object
:param index: the index of the target element
:return: the length of the index-th element
"""
return math.sqrt(sum([(j - k) ** 2 for j, k
... | 30ad84005d5307d450d190d946a0a54c2e50afeb | 568,973 |
def key_exists(dic, key):
"""Check if key exists in dictionary and return Boolean.
Args:
d (dict): Dictionary which might contain key.
key (Any): Identifier.
Returns:
Boolean : Whether dictionary contains key.
"""
if key in dic:
retur... | 0c59fdd3d904b7570b03d21c9f551666f4b2c203 | 568,976 |
from typing import Union
from typing import Counter
def find_mode(column: Union[list, str]) -> Union[str, int]:
"""
Gets the mode of an iterable. If there are multiple modes, returns the first encounter.
"""
counts = Counter(column)
top = counts.most_common(1)
return top[0][0] | e562cd5b82adc12da01705da53f9ea3831b17e37 | 568,977 |
def check_overlapping_bounds(polydata_0, polydata_1):
"""
Checks whether two polydata have overlapping bounds
:param polydata_0: vtkPolyData representing a 3D mesh
:param polydata_1: vtkPolyData representing a 3D mesh
:return : True if bounding boxes overlap, False otherwise
"""
bounds_0 ... | e5f71418266cbd61936b3cb5614bde7951c4e5a1 | 568,980 |
def print_totals(hist_dict, filename):
"""
Parameters
----------
hist_dict : Dictionary
Histogram dictionary containing number of repeats with certain length.
filename : String
Output file name.
Returns
-------
total : Int
Total number of repeats found.
""... | a45bf032f36122b83ca7e16835a5267472a2c8d6 | 568,984 |
def add_threshold_grouping_features(df, original_feature, threshold):
"""
Add a new feature to tell whether the original feature value is > or <= the threshold.
:param df: Input feature dataframe
:param original_feature: The existing feature used to generate the new feature
:param threshold: The th... | 43881291203026ca68a79a291588f9d77a1b4f0a | 568,988 |
def linear_fct(x, a, b):
"""Return f(x) of the linear function f(x) = ax + b.
:param x: (float) X-coord
:param a: (float) slope
:param b: (float) intercept
"""
x = float(x)
a = float(a)
b = float(b)
return (a * x) + b | 89b17297d7457f93f96c1bfd447323a74451eb17 | 568,991 |
def split_rules_and_strings(arr):
"""
Given a list of strings,
representing the rules
and the query strings,
split the rules and strings
into a dictionary and a list
for further use.
:param arr: A list of strings.
:return: A tuple of dict and list
representing the ruleset and th... | e928020d0c7bdbc02732fa5283244a9860052c40 | 568,999 |
def sign(x):
"""Returns 1 if the argument is positive, -1 else"""
return (x>=0)*2-1 | 35ec79f00d15cfa54de85b187f9c3d157f77cfb4 | 569,001 |
import re
def remove_hashtags(tweet):
"""Takes a string and removes any hash tags"""
tweet = re.sub('(#[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove hash tags
return tweet | 03fad91a4cc1d5f94b0df509ea474b3965564e9e | 569,004 |
import math
def get_max_dyadic_subsampling(xi, sigma, alpha=5.):
"""
Computes the maximal dyadic subsampling which is possible for a Gabor
filter of frequency xi and width sigma
Finds the maximal integer j such that:
omega_0 < 2^{-(j + 1)}
where omega_0 is the boundary of the filter, defined ... | eb2eeed2919da3732f854a5e565dad5b6ab30530 | 569,006 |
def infer_drug_days_supply(
days_supply=None,
refills=None,
quantity=None,
default_rx_days=30,
):
"""
Return the number of days this medication is "active".
The number of days this medication is active is determined by the
value of `days_supply` if it exists, and otherwi... | d9b6d81dcc5e787e0c5933abad25592f064f8755 | 569,010 |
def decrypt(private_key, encrypted):
"""
:param private_key: (d, n)
:param encrypted: list of encrypted bytes
:return: decrypted string
"""
d, n = private_key
plain = [chr(int(pow(x, d, n))) for x in encrypted]
return ''.join(plain) | 94e903a4ad99f2837ccb3b57117eabb67ccbff8f | 569,011 |
def base_scope(view):
"""Returns the view's base scope.
"""
return view.scope_name(0).split(' ', 1)[0] | 99d5ed0b64c067bec33fd6cd7da382cc368508a3 | 569,013 |
def _get_all_no_id(cursor, table_name, table_id, print_string, verbose, **kwargs):
"""Gets all elements from a table as a dictionary, excluding id"""
cursor.execute("""SELECT * FROM """ + table_name)
values = []
for row in cursor:
val = dict(zip(row.keys(), row))
val.pop(table_id)
... | 4b2160b945128d30bc4ad15ab2b3ca9543e43645 | 569,014 |
def listify(x):
"""
If given a non-list, encapsulate in a single-element list.
@rtype: list
"""
return x if isinstance(x, list) else [x] | 4bea144985edd7ec7231f93b069b459a9a627b00 | 569,015 |
import torch
def total_variation_loss(img):
"""
This method calculates total variation loss from given image.
Pixel difference between current and right pixel, and between current and below pixel is used in calculation.
Sum of squares is calculated and divided by count.
Division is not specified i... | d84037bd949bb8f6237f4d90f42a49e9a9abb2a1 | 569,017 |
import re
def simplify_strings(to_simplify, lower_case=True, simplifier=True):
"""
Simplify a `string`, `set(strings)`, `list(strings)`, `keys in dict`
Options for simplifying include: lower capitals, separators, both (standard), own set of simplifier
Parameters
----------
to_simplify : list,... | 7e8d23ec673fed8389e085bd8fb9f6a2836cc7b9 | 569,018 |
import collections
def flatten_dict(d: dict, sep: str = "_") -> dict:
"""
convert the AST structure
'AST': {'equals': [ {'nabla': ['2911']},{'function': ['1452']}]}}
to
{'equals_0_nabla_0': '2911', 'equals_1_function_0': '1452'}
from https://medium.com/better-programming/how-to-flatten-a-dict... | d383d03aec55e7979e619592ed1db2aed1d5e11c | 569,023 |
def repl_preadd(name: str, old: str, new: str):
"""
if the string old is in the string name, it is removed, and the string new
is addded at the beginning of the string name
the updated string is returned
"""
if old in name:
name = name.replace(old, '')
name = new + name
retur... | b272ef96d2f2ec3530a67f35f440fdd75d25b5d1 | 569,026 |
def sliding_box(start, stop, size, step=1):
"""
Find sliding boxes of region
Parameters:
-----------
start: int
0 based start coordinate of the region.
stop : int
0 based stop coordinate of the region, i.e. stop is not part of the
region anymore;
size : int
T... | 7bb0ce44fe0d97e36b38abdc7342df0f5c47fd91 | 569,028 |
import sympy
def numeric(num_str):
"""
Returns rational numbers compatible with symbols.
Input is a string representing a fraction or integer
or a simple integer.
"""
if type(num_str) == int:
a = num_str
b = 1
else:
tmp = num_str.split('/')
if len(tmp) == 1:... | 22be209e5ea22bef5c97ad7f541a950aa8080e60 | 569,038 |
from typing import Tuple
def decode_multi_byte_int(byte_str: bytes) -> 'Tuple[int, int]':
"""Decode a byte string into a multi-byte length
A multi-byte length may contain up to 5 bytes, of which the lower
7 bits of each are used to construct the final 31-bit value.
For each byte, the topmost bit is ... | c8efccf4f428c1357273802a1e3336af8f60db3b | 569,041 |
def pad_string(string: str, length: int) -> str:
"""Pads a string to specified length.
Args:
string: the text string to be padded with spaces
length: the length of the returned string
Returns:
A string exactly length characters long.
This is a helper function to hide the messy... | d6ae3c560866b891b078958a4f118c7e4870e373 | 569,043 |
def get_max_tweets(api, user_id):
"""Get as many tweets as possible for a user
Args:
api (twitter.API): twitter api
user_id (int): twitter user id as an int (not screen name!)
Returns:
list(twitter.models.Status): list of tweets from that user
"""
tweets = api.GetUserTimeli... | 20cc1c02f629e436b7ce81787c9a9069ae396776 | 569,046 |
def _evaluate_term_fwd(term, eta0, eps0, deps, eta_derivs,
eval_directional_derivative, validate=False):
"""Evaluate the DerivativeTerm in forward mode.
Parameters
----------------------
term: `DerivativeTerm`
A `DerivativeTerm` object to evaluate.
eta0, eps0 : `numpy... | 5e04024c9489170f32c6ab911164a018e7fd2c7d | 569,047 |
def prepare_experiment(study_name: str, season: str, timestamp: str) -> dict:
"""Returns a dictionary with the correct experiment configuration
Args:
studyName(string): the name of the study
season(string): the season of the study
timestamp(string): ISO 8601 timestamp formatted as YYYY-M... | 3862fb956c71e42caea154f7d646d76e31440cce | 569,050 |
def separa_palavras(frase: str) -> list:
"""
The function receives a sentence and returns a list
of words within the sentence.
"""
return frase.split() | 52c50c99af0ba9b42365cbd420ea183320f1646a | 569,051 |
def convert_booleans(kwargs):
"""Converts standard true/false/none values to bools and None"""
for key, value in kwargs.items():
if not isinstance(value, str):
continue
if value.upper() == 'TRUE':
value = True
elif value.upper() == 'FALSE':
value = Fal... | 17b26eb9f9c4b4eff13e7cc2136f24225eebd925 | 569,054 |
def get_class_name(obj):
""" A form of python reflection, returns the human readable, string
formatted, version of a class's name.
Parameters:
:param obj: Any object.
Returns:
A human readable str of the supplied object's class name.
"""
return obj.__class__.__name__ | 17a0f39134c4667d24215d69fd5c75698a12cc88 | 569,055 |
def get_time(dte):
""" Renvoie d'une date au format time
:param datetime dte:
:rtype: time
"""
return dte.time() | 5852f4852fa8ce6f0e368f98ba3c9409acaa2def | 569,056 |
def read_phantom_head(fname):
"""
Given filename, read and parse phantom header file
return voxels and dimensions
"""
lines = None
with open(fname) as f:
lines = f.readlines()
vx = 0.0
vy = 0.0
vz = 0.0
nx = 0
ny = 0
nz = 0
for line in lines:
s = ... | 3d7ba61a28b1342dedf506229c8a4c632686cb99 | 569,059 |
import grp
def gidFromString(gidString):
"""
Convert a group identifier, as a string, into an integer GID.
@type uid: C{str}
@param uid: A string giving the base-ten representation of a GID or the
name of a group which can be converted to a GID via L{grp.getgrnam}.
@rtype: C{int}
@re... | dda83779e79f66d197cec07e94e1742ffb74c74a | 569,062 |
def memo_fibonacci(n, memo=[]):
"""
A fibonacci function that uses memoization.
Subproblems that we've done are stored in a memo.
Top down approach. The complexity is O(n).
"""
# Set up a memo list of n + 1 size
n = int(n)
memo = [None] * (n + 1)
def recursion(n, memo):
if n ... | 15dfd20cf875857dbc24bfa78f478a0d155bd8bc | 569,071 |
def mk_id(identifier):
"""Make an id from a string such as 'C0326'."""
return identifier | de196c51e566a6c7eb2277952d513a50075a5997 | 569,078 |
def get_transactions() -> list:
"""Gets each transaction to combine to look for a matching combo."""
print("Enter each transaction amount and press enter."
"\nEnter when done.")
transactions = []
while True:
each = input("Transaction: ").strip("$ ")
if each:
transac... | 93bdf042b6a5b8a9c85203ded8f6af5f4e847a12 | 569,081 |
import math
def distance(t1,t2):
"""Find vector distance between two tuples"""
if len(t1) != len(t2):
raise ValueError("distance: tuples must be the same length")
r = [0,] * len(t1)
for i in range(0,len(t1)):
r[i] = (t1[i] - t2[i]) ** 2
r = tuple(r)
return math.sqrt( sum(r) ... | 3d1279f390267a1c172c7699976d9f37b7a2d58a | 569,084 |
def collect_siblings_until(element, stop_set):
"""returns a list of all siblings of element until something in
stop_set is encountered (or the document ends).
stop_set must be a set of element type names (like h1, h2...).
"""
collection = []
while True:
element = element.nextSibling
if element is N... | 585d3aace39e1ad7403511de6316fa17bd0d5824 | 569,088 |
def id_query(doc_id):
"""Create a query for a document with the given id.
Parameters
----------
doc_id : |ObjectId|
The document id to match.
Returns
-------
dict
A query for a document with the given `doc_id`.
"""
return {'_id': doc_id} | 1906fe9b6d97dcf6b698bf7463c8b144c57d4021 | 569,090 |
def aix_path_join(path_one, path_two):
"""Ensures file path is built correctly for remote UNIX system
:param path_one: string of the first file path
:param path_two: string of the second file path
:returns: a uniform path constructed from both strings
"""
if path_one.endswith('/'):
path... | 073115ad92683dd6d22da6dc2d5dea6562e51e74 | 569,095 |
import ctypes
import pickle
def _load_model(ptr, length):
"""
Internal function used by the module,
unpickle a model from a buffer specified by ptr, length
Arguments:
ptr: ctypes.POINTER(ctypes._char)
pointer to the memory region of buffer
length: int
the length... | 9c5bf4f6d7d0d3748bd1a8f789b0b104932c5a9c | 569,097 |
def kW2W(x):
"""kW -> W"""
return 1000.*x | 4f164243d0b12fb488edf9213d3bc13326e2e047 | 569,098 |
import re
def parse_full_section(section_name, docs):
"""
Find warning defined in the documentation.
Parameters
----------
docs : str
Returns
-------
str or None
Returns warnings from documentation or ``None`` if
function didn't find it.
"""
parser = re.compil... | 5cf967b132ac1fb1412b658799a80b3f9659e60d | 569,099 |
def tensor_to_numpy(pytensor):
"""Converts pytorch tensor to numpy"""
if pytensor.is_cuda:
return pytensor.cpu().detach().numpy()
else:
return pytensor.detach().numpy() | f78ba9ff5f92a57b63380061d11e9ce113855b59 | 569,101 |
def mirror(image, label):
"""Horizontally flipp image and label.
Args:
image: A 2-D/3-D tensor of shape `[height, width, channels]`.
label: A 2-D/3-D tensor of shape `[height, width, channels]`.
Return:
Two tensors of shape `[new_height, new_width, channels]`.
"""
image = image[:, ::-1, ...]
... | f73b5672144e61a56aeeb353daddf11f230b27bc | 569,108 |
def isvalidtriplet(codon,dictentry):
"""
Function which checks if a given triplet has max hamming distance of 1
to a other triplet. Used for generation of possible substitutions triplets
@type codon: string
@param codon: nucleotide triplet
@type dictentry: string
@param dictentry: nucleo... | f2b41ecb8d250820ddcde7b1a9430e9d2a549ad8 | 569,109 |
def get_json_cache_key(keyword):
"""
Returns a cache key for the given word and dictionary.
"""
version = "1.0"
return ":".join(["entry:utils", version, "meaning", keyword]) | 1abe7db751f2be4848c00e9d5f53bf16fcb1f3c9 | 569,116 |
def get_type(id, name):
"""
returns the type of route based on its id and full name
reverse-engineered from observed patterns since we could not
find a data source for them
Possible types:
Bus, Rail, Streetcar, Express, Cable Car, Shuttle, Overnight, Rapid
"""
if id[-1] == 'X': # i... | f98fb5db261f831ced9ddd694cf9fe6b4dbf1e2c | 569,117 |
def compute_mean(serie):
"""
Compute mean of a serie
"""
clean_serie = serie.dropna()
length = len(clean_serie)
acc = 0.0
try:
for _, value in clean_serie.iteritems():
acc += value
except TypeError:
return (float('NaN'))
finally:
return (acc / leng... | b412cfbeb434222b21e3f00c93cd4ef56a42d9f0 | 569,120 |
import base64
def decode_b64(data):
"""Wrapper for b64decode, without having to struggle with bytestrings."""
byte_string = data.encode('utf-8')
decoded = base64.b64decode(byte_string)
return decoded.decode('utf-8') | f14c8b18c7f590ae25301fe414a7bba08046226d | 569,122 |
def find_experiment_in(experiment, all_experiments):
"""Search the phil experiment list and find where an experiment came from.
:param Experiment experiment: The experiment to search for
:param all_experiments: The list of all experiments from phil
:type all_experiments: list[dials.util.ph... | 7780f49aa1d55c95a1aee2af75de9becdf67097d | 569,126 |
def chrange(start, stop):
"""
Construct an iterable of length-1 strings beginning with `start` and ending
with `stop`.
Parameters
----------
start : str
The first character.
stop : str
The last character.
Returns
-------
chars: iterable[str]
Iterable of ... | 7d31406bd0920e2abe031f19f95dc728d7c64aba | 569,127 |
def IncludeCompareKey(line):
"""Sorting comparator key used for comparing two #include lines.
Returns the filename without the #include/#import prefix.
"""
for prefix in ('#include ', '#import '):
if line.startswith(prefix):
return line[len(prefix):]
return line | 85f3cf7f4cdd3910e78a0239d9c3c566447869d5 | 569,128 |
def is_tag(xml_obj, tag):
"""Return true if the XML object is the Tag"""
return xml_obj.tag == tag | 8fa96fcdfa100852d45779baf9e811beb7dea3fb | 569,134 |
def _get_repositories_to_use(context, rhsm_info, target_repositories):
"""
Filters the available repositories based on the target_repositories passed.
:param context: An instance of a mounting.IsolatedActions class
:type context: mounting.IsolatedActions class
:param rhsm_info: An instance of a RHS... | a95c25e639ddcc178d55017158f537ee3a4c465b | 569,136 |
def get_size(r1, c1, r2, c2):
"""Get the size of this slice."""
return (r2 + 1 - r1) * (c2 + 1 - c1) | c8b41366df84500c913461051ebb6cce891e56b1 | 569,137 |
def find_min_iterative(array, left, right):
""" Find the minimum in rotated array in O(log n) time.
>>> find_min_iterative([1,2,3,4,5,6], 0, 5)
1
>>> find_min_iterative([6, 5, 4, 3, 2, 1], 0, 5)
1
>>> find_min_iterative([6, 5, 1, 4, 3, 2], 0, 5)
1
"""
while array[left] > array[right]... | 2f694295465aa8bba86bb63ecd6ee1e69d19ba5e | 569,139 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.