content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_experience_for_next_level(level: int) -> int:
"""Gets the amount of experience needed to advance from the specified level to the next one.
:param level: The current level.
:return: The experience needed to advance to the next level.
"""
return 50 * level * level - 150 * level + 200 | d21b6e4bacccd9f9d79c5f7e71997027c306d545 | 587,020 |
def is_between(low, x, high):
"""Determine whether x is between X1 and X2"""
return (low <= x) and (x <= high) | 54334474c948210c149d793b181d323067e104a1 | 587,021 |
def coordDiff(xf, xi, tf, ti):
"""
Calculate changes in distance (dx) and time (dt)
final(x, t) - initial(x, t)
"""
dx = xf - xi
dt = tf - ti
return dx, dt | c81e6d9582d42a21d403f953f14011ab16f0baba | 587,022 |
import json
def json_dumps(content):
"""Dump a python object using a nicely formated json format"""
return json.dumps(content, indent=4, sort_keys=True).replace(' \n', '\n') + '\n' | a57e470be937b8a34bfdc33a3187cbda1ab9fc08 | 587,025 |
def get_hosts(pdcs: list) -> list:
"""
Get list of PDataContainers and get only hostnames into a list.
:param pdcs: list of PDataContainers
:return: list of strings of hostnames
"""
return [pdc.host for pdc in pdcs] | 60e23741be519fa42fa2897e0bb94e654ddb5eb3 | 587,028 |
import unicodedata
def convert_single_latins(input_string: str) -> str:
"""Convert other characters that are based on single Latin characters.
Ø LATIN SMALL LETTER O WITH STROKE
ł LATIN SMALL LETTER L WITH STROKE
https://stackoverflow.com/questions/8935111/translating-letters-not-in-7bit-ascii-to-as... | 961857f71423c059b0cdc11c155c9ca10f77b54e | 587,029 |
def get_next_offset(offset, limit, size):
"""
Calculates the next offset value provided the current one as well as the page limit and the
total size of the items
:param offset:
:param limit:
:param size:
:return:
"""
next_offset = offset + limit
if next_offset >= size or size <= ... | 6b2f3ffb5f3b1471b7629e71a963f0f36b20c692 | 587,031 |
import requests
def register_app(client_name, host, redirect_uris='urn:ietf:wg:oauth:2.0:oob',
scopes='read write follow'):
"""Register application
Usage:
>>> d = register_app('myapp', host='pawoo.net')
>>> d
{'id': 1234, 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob', ... | 3009dd7edb7a8bfdac2bff50223ec1bf4645b990 | 587,032 |
def hex2rgb(hexstring, digits=2):
"""Converts a hexstring color to a rgb tuple.
Example: #ff0000 -> (1.0, 0.0, 0.0)
digits is an integer number telling how many characters should be
interpreted for each component in the hexstring.
"""
if isinstance(hexstring, (tuple, list)):
return hex... | 78ff771461ea8483579736f8c0fac4c127cb9fd9 | 587,041 |
def extend_segment(segment, max_l, padding):
"""
segment: segment start and end indices [x0,x1]
max_l: maximum indice possible
padding: percentage to extend
"""
x0 = segment[0]
x1 = segment[1]
length = x1-x0
ext = int(padding*length)
return [max([0,x0-ext]), min([max_l,x1+ext])] | 772240ee15ed54958f2d62c6d973c0a30e333706 | 587,043 |
def permutation_from_disjoint_cycles(cycles, offset=0):
"""Reconstruct a permutation image tuple from a list of disjoint cycles
:param cycles: sequence of disjoint cycles
:type cycles: list or tuple
:param offset: Offset to subtract from the resulting permutation image points
:type offset: int
:... | 3c992f3612340e94e569b81be9195f79de8f864e | 587,045 |
from typing import List
import requests
def _get_adcm_tags() -> List[str]:
"""Return unsorted list of ADCM tags from hub.arenadata.io (newest tag is last)"""
return requests.get("https://hub.arenadata.io/v2/adcm/adcm/tags/list").json()["tags"] | 09b9a4113c784d96ca7a5f90484094f2d896dacc | 587,046 |
def n_grams(text, n, as_list=True):
"""Splits text into consecutive n-grams, e.g. pairwise, triples, etc."""
w = text.split()
if len(w) >= n:
n_grams = [w[i : i + n] for i in range(len(w) - n + 1)]
if as_list:
return n_grams
joined = []
for n_gram in n_grams:
... | 5180e37b135e222454a94127dae5ce5396e3fad6 | 587,055 |
def _scale_wh_by_target_width(w: int, h: int, target_width: int):
"""Helper functions for scaling width and height based on target width.
Parameters
----------
w : int
Width in pixels.
h : int
Heights in pixels.
target_width : int
Target width (in pixels) for rescaling.
... | 57020348ed4a82ff2c201672cc76c6c56bfa21a5 | 587,056 |
def rate(hit, num):
"""Return the fraction of `hit`/`num`, as a string."""
if num == 0:
return "1"
else:
return "%.4g" % (float(hit) / num) | d3a502fe286257971fbc1d00605b6c65659c5745 | 587,057 |
import torch
def model(X: torch.Tensor) -> torch.nn.Module:
"""Simple fake linear model."""
return torch.nn.Linear(X.shape[1], 1) | 43d3dcf2f4cb351ab4ead47d8462c9647f5b6f56 | 587,063 |
def listToString(inputList):
"""Converts a list of integers into an ASCII string."""
return ''.join([chr(i) for i in inputList]) | f6b1ea22fb1ed18fbea9607ba3bf79cd074fb795 | 587,068 |
import random
def _augment_gain(audio, low=0.75, high=1.25):
"""Applies a random gain between `low` and `high`"""
g = random.uniform(low, high)
return audio * g | 93d05e9c9190f3e20639bf99a4d23d216a2ca6f3 | 587,069 |
def check_ascii_compliance(plaintext):
"""Returns true if all the characters of plaintext are ASCII compliant (ie are in the ASCII table)."""
return all(c < 128 for c in plaintext) | b8c3328793387baf78b8ce5b9a00499d51a37c1e | 587,075 |
import string
def make_search_string(val):
"""
Reduces a string to a simplified representation
containing only a well defined set of characters
for a simplified search
"""
cset = string.ascii_letters + string.digits + ' _-#'
search = ''.join([c for c in val if c in cset])
return search... | 21550b7c6bfbff4f16a472a7fa0db93b4597b586 | 587,076 |
def coerceValuesForColumn(column, values):
"""
Coerces the values to the type appropriate for the column
:param Column column:
:return: type appropriate for column
:raises: ValueError
"""
data_class = column.getDataClass()
values = data_class.cons(values)
values.name = column.getName(is_global_name=Fa... | 18559208a13fd77383798a38aac5fbbd2dd9d51c | 587,077 |
import re
def split_for_natural_sort(s):
"""
split a string *s* for natural sort.
"""
return tuple((int(y) if y.isdigit() else y for y in re.split(r'(\d+)', s))) | 15a88440f45533a47d84b86919b3514b7f91a874 | 587,080 |
def _fixed_width_format(x: float, figs: int = 3) -> str:
"""Format x as a number targeting `figs+1` characters.
This is intended for cramming as much information as possible in a fixed-width
format. If `x >= 10 ** figs`, then we format it as an integer. Note this will
use more than `figs` characters if... | b1a27af54916ac98256c86859093eddefd5b7ae8 | 587,081 |
import time
def _WaitUntil(predicate, max_attempts=5):
"""Blocks until the provided predicate (function) is true.
Returns:
Whether the provided predicate was satisfied once (before the timeout).
"""
sleep_time_sec = 0.025
for _ in range(1, max_attempts):
if predicate():
return True
time.s... | ec4acc6351ab9985e7770fbf71e21e68dda48759 | 587,087 |
def SubStringExistsIn(substring_list, string):
"""Return true if one of the substring in the list is found in |string|."""
return any([substring in string for substring in substring_list]) | 8a0373f17f799e9895225e6c0eaa49bf07aaf5e9 | 587,088 |
def evaluate(labels, predictions):
"""
Given a list of actual labels and a list of predicted labels,
return a tuple (sensitivity, specificty).
Assume each label is either a 1 (positive) or 0 (negative).
`sensitivity` should be a floating-point value from 0 to 1
representing the "true positive ... | 77e042cb71b6785005aa74210a73b1465db80492 | 587,089 |
import hashlib
import base64
def hash_string(string):
"""Hash a given string."""
m = hashlib.sha256(str(string).encode('utf-8'))
return base64.urlsafe_b64encode(m.digest()).decode('utf-8') | ef5da1c071a232fa86f58f46a032eaa9ef88274d | 587,091 |
def get_paragraph_list(text):
"""Returns a list of paragraphs from a given text blob."""
return [p.strip() for p in text.splitlines() if p.strip()] | 378143b0fc093b7c1b0c82eb74a787f3ba51eb80 | 587,092 |
def logical_left_shift(number: int, shift_amount: int) -> str:
"""
Take in 2 positive integers.
'number' is the integer to be logically left shifted 'shift_amount' times.
i.e. (number << shift_amount)
Return the shifted binary representation.
>>> logical_left_shift(0, 1)
'0b00'
>>> logi... | 124d48f9c73ab89556e56580d725f625084e3408 | 587,095 |
def format_size(num: int, align=False) -> str:
"""
Given a number of bytes, produce a human-readable expression for this
size using common units such as kB and MB.
"""
step = 1000.0
unit = None
result = num
for unit in [None, 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']:
if un... | 182d9ba1ab871bd2a49e2c06ce5184d2faee2464 | 587,096 |
def create_clue_string(clue):
""" Given a clue, which is a tuple
(position, direction, length, question),
create a string in the form 'position direction: question (length)'.
For example, given the clue
((2, 3), 'across', 4, 'Black bird'),
this function will return
'(2,3) across: Bla... | 39c76c88e195d522aec9782d5b10f1bceb5c47a5 | 587,100 |
def trailing_ones_str(bin_str: str):
"""
This method returns the trailing ones of a binary number formatted as string.
:param bin_str: The binary number as str.
:return: The trailing ones as int.
"""
# Only strings are allowed
if not isinstance(bin_str, str):
raise TypeError("String... | eb7b3e3154af8a2964678651456f98fa72cbd879 | 587,103 |
def factor_octets(octet_array, is_ipv6):
"""Convert each decimal octet into a factor of the
divisor (16 or 256) and a remainder"""
if is_ipv6:
divisor = 256
else:
divisor = 16
factord_octet_array = []
for i in range(len(octet_array)):
factord_octet_array.extend([octet_arr... | c5111c6a56eb051e4a1582039734dd0338dfc073 | 587,105 |
import re
def norm_part(s):
"""
>>> norm_part('BrIck 1x4')
'Brick 1 x 4'
>>> norm_part('Brick 1 x 4')
'Brick 1 x 4'
>>> norm_part(' Brick 1 x 4')
'Brick 1 x 4'
>>> norm_part('Brick 1x2x2')
'Brick 1 x 2 x 2'
>>> norm_part('b 1x2x2')
'Brick 1 x 2 x 2'
>>> norm_part('t 1x1... | c58f83875cbdbbfef1918747bee41edb7996f6ca | 587,106 |
def _tpu_zone(index):
"""Chooses a GCP TPU zone based on the index."""
if index < 70:
return 'europe-west4-a'
elif index < 80: # 10
return 'us-central1-b'
elif index < 90: # 10
return 'us-central1-c'
elif index < 100: # 30 (seems like 10...)
return 'asia-east1-c'
elif index < 110:
ret... | 8b1d5c0ca749ddbe58cd50ad378b4460b40c8563 | 587,111 |
import functools
import warnings
def deprecated(_func=None, *, print_msg=None):
"""
This is a decorator which can be used to mark functions as deprecated.
It will result in a warning being emitted when the function is used.
Args:
print_msg: Information to point user to newest version.
"""... | 1d2849a95702f470fb8933b695712839fc71a90f | 587,112 |
def splitArgs( argstr ):
"""Split argument string into usable python arguments
argstr: argument string with format fn,arg2,kw1=arg3...
returns: fn, args, kwargs
This function is adapted from Mininet (https://github.com/mininet/mininet/blob/8af3f28b67ca27077d8082ae25c4800870df6109/mininet/util.p... | 7625c82f624aa247b8bee0a57639a06be8777608 | 587,113 |
from typing import get_origin
from typing import get_args
import typing
def is_closed_python_set_type(ttype):
"""
A "closed" generic type has all of its type parameters parameterized
by other closed or concrete types.
e.g.
Returns true for Set[string] but false for Set or set
"""
origin ... | b6084d5bff1d314cfb03ec52d449418595b1af02 | 587,115 |
def get_vm(module, proxmox, vmid):
"""
Look up a vm by id, and fail if not found.
"""
vm_list = [vm for vm in proxmox.cluster.resources.get(type='vm') if vm['vmid'] == int(vmid)]
if len(vm_list) == 0:
module.fail_json(vmid=vmid, msg='VM with vmid = %s not found' % vmid)
if len(vm_list) >... | e094f0bc884faa997bf49a64bb022a37287331fe | 587,117 |
def m_to_mile(value):
"""Converts distance in meters to miles
Args:
value: floating point representing the distance in meters
Returns: distance in miles
"""
if value is None:
return None
return value / 1609 | 85846c8a6b43be86af0d13c3833f283cd399ee31 | 587,118 |
def _fix_coords(coords, offset):
"""Adjust the entity coordinates to the beginning of the sentence."""
if coords is None:
return None
return tuple([n - offset for n in coords]) | 59eb86a89d9a68f357fb02e6abb91380332d8299 | 587,122 |
def load_polymer(filename):
""" Return the polymer string from FILENAME. """
polymer = None
with open(filename) as f:
for line in f:
polymer = line.rstrip()
break
return polymer | f961a095137390e0a50f83121da4acb34c3e1a4d | 587,125 |
def filter_on_average(rec, q = 20):
""" Returns True if the supplied sequence record passes the quality threshold.
Default threshold is 20.
"""
qScores = rec.letter_annotations["phred_quality"]
if (sum(qScores)/len(qScores)) < q:
return False
return True | e3d1d1adaa411a7861216778b05105e8c1165179 | 587,126 |
def parse_dhm_response(msg: str) -> int:
"""Parse server's DHM key exchange request
:param msg: server's DHMKE message
:return: number in the server's message
"""
return int(msg.split(':')[1]) | 065d16e8ae317d49ee2e29743b3004f8d79aadd2 | 587,132 |
def opposite_player(player):
"""Finds the opposite player based on the input. Assumes only two players
Args:
player (string): Input player to invert
Returns:
(string): Opposite player from the input
"""
if player == "X":
return "O"
else:
return "X" | 09a7306e15d0d05fbe6d89134b3186c29163bce0 | 587,133 |
import math
def reduce_base_60(f):
"""extract the base 60 fractional portion of a floating point number.
i.e. minutes from degrees, seconds from minutes.
"""
fract, whole = math.modf(f)
# Add a tiny bit before rounding to avoid binary rounding errors.
fract = abs(fract)
fract = (fract + 1... | 4c0e292603f6f0a69e1833b8a8f62bff6f40da3c | 587,134 |
def number(lines):
"""
Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering.
Write a function which takes a list of strings and returns each line prepended by the correct number.
The numbering starts at 1. The format is n: string. Notice the colon and ... | 9383609279265db689d42ae34440803dcc309d22 | 587,138 |
def torange(arg):
"""Convert a string representing a range to an actual range.
>>> torange("1-4")
[1, 2, 3, 4]
>>> torange("1,2,3")
[1, 2, 3]
>>> torange("1-5,8,9")
[1, 2, 3, 4, 5, 8, 9]
>>> torange("5-1,9,10")
[5, 4, 3, 2, 1, 9, 10]
"""
result = []
for r in str(arg).sp... | d38d4b8f762075d5e2e5b03f7a49b71cd99e30b8 | 587,141 |
def relEqual(x, y, tol = 2**-26):
"""
Simple test for relative equality of floating point within tolerance
Default tolerance is sqrt double epsilon i.e. about 7.5 significant figures
"""
if y == 0:
return x == 0
return abs(float(x) / float(y) - 1.) < tol | a85d8cbee10361f4e4c6297ce35807e0071542b6 | 587,143 |
import click
def validate_between_zero_and_one(ctx, param, value):
"""Check that param value is between 0 and 1"""
if value < 0 or value > 1:
raise click.BadParameter('must be greater than or equal to 0 and'
f'less than or equal to 1, currently {value}')
return val... | eb7880225bf7252451635d6d9bb7f7413f6405bd | 587,146 |
from datetime import datetime
import json
def _get_timepoints_from_json(json_str):
"""
Get TIMEPOINTS list from JSON string.
Expected JSON looks like:
```json
[
["0:00", "5:59"],
["6:00", "11:59"],
["12:00", "17:59"],
["18:00", "24:00"]
... | f8fd38fda01053488421ce942576dbad26c3c3d2 | 587,147 |
import textwrap
def baseline( minimize=False ): # pragma: no cover
"""RosettaScript to calculate DSSP secondary structure and
phi-psi angles.
:param bool minimize: If :data:`True`, apply minimization before
evaluating the structure.
:return: :class:`str`
.. seealso::
:func:`.ge... | 492938e9b8fb8e3302f6a8d999f1582ad87a2bdb | 587,149 |
def _str_eval_true(eval, act, ctxt) :
"""Returns true."""
return [True] | 9578f55b0dd2a3bcfddff0b79c28a7f6b8fa58c8 | 587,152 |
def transform_noise_level(value, model):
""" Validate a noise level
Args:
value (:obj:`float`): value
model (:obj:`ListVector`): model
Returns:
:obj:`float`: value
Raises:
:obj:`ValueError`: if the value is not a non-negative float
"""
if value < 0:
msg... | bde3f18ed87cbced8825b327f3b15baa423e1b78 | 587,156 |
def flatten(my_list):
"""Flattens nested lists."""
curr_items = []
for x in my_list:
if isinstance(x, list) and not isinstance(x, (str, bytes)):
curr_items += flatten(x)
else:
curr_items.append(x)
return curr_items | 0aa1c5b4c125bc7f1c7c238345d846e1668e5d92 | 587,165 |
def canonical_bounds(intron):
"""
Checks an intron sequence's dinucleotide boundaries
for canonical splice sites. Returns False if boundaries
are non-canonical.
Splice site variants derived from table 1 in
DOI: 10.1093/nar/gku744
"""
canonical = {
"AT": ["AC"], #"AC", "AG", "AA... | 7ae620f29dd18625b78aa6d21d9010f9b78a02f7 | 587,166 |
def _txt_tabular(columns, titles=None, separator=''):
"""Tabularises a list of lists, with the option of including titles.
Used in textfile outputs.
Parameters
----------
columns : list
A list of lists, with each sublist representing the columns of the
table. Each list must be of th... | b9d6bdb5db7ec1e953c391e46aee9cffe5ee70cf | 587,169 |
def parseVersion(strversion):
"""Parse version strings of the form Protocol '/' Major '.' Minor. E.g. 'HTTP/1.1'.
Returns (protocol, major, minor).
Will raise ValueError on bad syntax."""
proto, strversion = strversion.split('/')
major, minor = strversion.split('.')
major, minor = int(major), i... | ec802e4fda179b3b3bf78ed165d647f622c1babd | 587,170 |
import copy
def sort_potentials(potentials, use_copy=True):
"""
Sort a list of ECP potentials into a standard order
The order within a potential is not modified.
The order of the shell list is in increasing angular momentum, with the largest
angular momentum being moved to the front.
If use... | e983d8816dd9839b726cc097f8a2e503f006aadb | 587,173 |
from typing import List
def concat_MSA(msa_files) -> List[str]:
"""
Concatenate MSA files and return lines
"""
lines = []
for msa_file in msa_files:
with open(msa_file, 'r') as f:
lines += [line.strip() for line in f.readlines() if line[0] != '\x00']
return lines | 300e569e1694e1ea19987a714afd33d77aae89aa | 587,174 |
def first_org_id_from_org_roles(org_roles):
""" Return first Jisc ID found in an objectOrganisationRole."""
for role in org_roles:
if not isinstance(role, dict):
continue
org = role.get('organisation')
if not isinstance(org, dict):
continue
org_id = org.ge... | c1debea7c6d7cf48b0fc2c129ba6c23c6c7ba296 | 587,175 |
import torch
def softmax(Z, dim=-1, get_ll=False, W=None):
""" SoftMax (safe).
Parameters
----------
Z : torch.tensor
Tensor with values.
dim : int, default=-1
Dimension to take softmax, defaults to last dimensions.
get_ll : bool, default=False
Compute log-likelihood, ... | 796e7e8b63f032b8c7e644274372cd2097f38528 | 587,177 |
def _create_min_max_boundaries(max_length,
min_boundary=256,
boundary_scale=1.1):
"""Create min and max boundary lists up to max_length.
For example, when max_length=24, min_boundary=4 and boundary_scale=2, the
returned values will be:
buckets_min ... | ecc0e0b170c5031fe409e53f57c5df5f4d4959aa | 587,178 |
def to_codes(df):
"""Return a dataframe with all of the categoricals represented as codes"""
df = df.copy()
cat_cols = df.select_dtypes(['category']).columns
df[cat_cols] = df[cat_cols].apply(lambda x: x.cat.codes)
return df | 1e1390f3ab94da770a96040f84fee426a3a98c6e | 587,181 |
def get_feeds_links(data):
"""Extracts feed urls from the GTFS json description."""
gtfs_feeds_urls = []
for feed in data:
if feed["spec"] != "gtfs":
continue
if "urls" in feed and feed["urls"] is not None and feed["urls"]:
gtfs_feeds_urls.append(feed["urls"]["stati... | d84393b8f07b4158823f7771695bad1b354a793f | 587,186 |
def extract_bouts(
df, valid, range_column="t", valid_column="valid", keep_invalid=True, by=[]
):
"""
Extract from a Pandas DataFrame a list of bouts, where each bout is indicated by a minimum and maximum
timestamp range and determined by valid ranges.
Parameters
----------
df : pandas.Data... | 8d41cfa9b4d81731e3d239e399eda51835bb336a | 587,187 |
import re
def GetFramePlaceholder(frameFormat):
"""
Gets the frame placeholder in a frame format string.
This function expects the input frameFormat string to contain exactly one
frame placeholder. The placeholder must be composed of exactly one or two
groups of one or more hashes ('#'), and if t... | fbf83aeba6708ac6a1f5223d24e76303c13c0865 | 587,189 |
def parallel_anims(anims):
"""Combines animations in anims to a single animation,
where the animations run simultaneously"""
def func(ctx, time):
for anim in anims:
anim(ctx, time)
return func | 1393e60836a6a839fd195fd0b5f3464ae3f4b437 | 587,191 |
def get_definitions_diff(previous_definition_string, new_definition_string):
"""Returns a triple of lists (definitions_removed,
definitions_shared, definitions_added)"""
old_definitions = [i for i in previous_definition_string.split('|') if i]
new_definitions = [i for i in new_definition_string.split('|... | d90ee08f02682c47922d07b0d057bf927e693d7e | 587,192 |
def set_identity_providers_if_unset(facts):
""" Set identity_providers fact if not already present in facts dict
Args:
facts (dict): existing facts
Returns:
dict: the facts dict updated with the generated identity providers
facts if they were not already present
... | cc8d02a5206aff6fa06f43436c5db37a78c42125 | 587,194 |
def optional_column(
dictionary: dict, key: str, column_width: int = 0, alignment: str = "<"
):
"""Adds a value to a column, if the key exists in the dictionary
and adds spaces of the appropriate width if not.
Args:
dictionary (dict): Dictionary with data inside
key (str): Key of the d... | 6cfe690496ae0f35f1b62b39d4e7674f2f73a13f | 587,195 |
def domain_repr(domain):
"""Return repr for a domain."""
return str(domain) | 5d4998e403345f3c95c5523bb6e85f682707e97a | 587,196 |
def header(title):
"""Construct a nice looking header."""
star_count = int((20 - len(title) - 2)/2)
head = '\n' + '*'*20 + '\n'\
+ '*'*star_count \
+ ' ' + title.upper() + ' ' \
+ '*'*star_count + '\n'\
+ '*'*20
return head | d8fefe830276185ebeb8ee628e3c50ba137cbbf7 | 587,197 |
def AverageCluster(C):
"""
AverageCluster calculates the average local clustering coefficient value
of a network.
Input:
C = array of clustering coefficient values
Output:
c = average clustering coefficient value
"""
n = len(C)
c = sum(C)/n
return c | 5dfa24025507c377daacda966671f770999f5584 | 587,200 |
import random
def sample(max_index, size=40000, split=8000):
"""Samples indices."""
indices = random.sample(range(max_index), size)
train = indices[:-split]
test = indices[-split:]
return train, test | aa650781c35d0b73b9edc441f0ebcd4577fa5821 | 587,201 |
import math
def qty_to_size(qty: float, price: float) -> float:
"""
converts quantity to position-size
example: requesting 2 shares at the price of %50 would return $100
:param qty: float
:param price: float
:return: float
"""
if math.isnan(qty) or math.isnan(price):
raise Typ... | 01d770f99ea80574781a6fd59924770c0da3faf7 | 587,202 |
def mean(numlist):
"""
Computes the mean of a list of numbers
"""
# Check to see that input is type numlis
if not isinstance(numlist, list):
raise TypeError('Invalid input must be type list.')
if len(numlist) == 0:
raise ZeroDivisionError('Cannot calculate the mean of an empty ... | 4e0638e5d2ef4872751989c71a7fc1c53c4ff089 | 587,206 |
import struct
def unpack_elements(element_fmt, byte_elements):
"""Unpack each ``bytes`` element in an iterable with a single format."""
return [struct.unpack(element_fmt, element) for element in byte_elements] | 1c1e6af119723484a8932de2314e7b4a7b4a5840 | 587,212 |
def sum_counters_le(sum_cnt, num):
"""
Returns an SMT inequality assertion given a list of counters and a threshold
"""
return "(<= (+ " + sum_cnt + ") " + str(num) + ")\n" | ca5a19b736b95578e4c860871d631012c496bc84 | 587,213 |
def selection_sort(arr: list) -> list:
"""Sort a list using selection sort
Args:
arr (list): the list to be sorted
Returns:
list: the sorted list
"""
size = len(arr)
# Loop over entire array except the last element
for j in range(size - 1):
# Set the current minimu... | db68af84b643864e29f9f96a6a755989e618bda8 | 587,215 |
def calculate_lensing_template(bb_lensed, bb_unlensed):
"""Function to calculate the BB spectrum of lensing from output CLASS
BB spectra.
These spectra are the lened and unlensed outputs for a given
set of cosmological parameters, therefore we simply take the difference
of the lensed and unlensed B... | 0779836e213898dd599a245d8dc477c4c0117470 | 587,218 |
def ms_to_hours(milliseconds):
"""Convert milliseconds into format (h)h:mm:ss"""
seconds = milliseconds / 1000
minutes = seconds // 60
seconds -= minutes * 60
hours = minutes // 60
minutes -= hours * 60
if minutes < 10:
minutes = '0' + str(int(minutes))
else:
minutes = st... | b2939b2d45f487427b9c8673e29a86df7c39bbab | 587,220 |
def read_file(file_name_to_read):
"""
This function reads the file given the file name as an input
Inputs:
file_name_to_read - string, name of file you want to read
outputs:
content_of_file - string, the content of the file
"""
# this way of doing it is disgusting, bu... | c57a21df48c28d3f3e8bdffcb8ed41b304a36d3a | 587,223 |
def apply_financial_params(dataframe, financing_terms, inflation_rate):
"""
apply_financial_params
Add the year's financial parameters including
depreciation schedule (array for years 0,1,2,3,4,5), Solar ITC fraction, Solar ITC min size kw, Solar ITC max size kw,
years of loan term, loan rate, dow... | 26cfbd72c0110924cff7add0f728dad5f036b6da | 587,225 |
def filter_pre_post_table(
combi_table,
focus_countries,
reg_var="coordinator_country",
focus_var="project_lq",
volume_var="project_total",
):
"""Filters an activity table to focus on particular variables and countries"""
combined_table_focus = combi_table.loc[
combi_table[reg_var].... | b8f128e4ed15902fc5ba8794bfc1f86c6d178fc7 | 587,229 |
def dummy_filter(filter_instance):
"""
Ignore filter method of Filter classes.
Can be used for documentation-only params and custom non-field filters.
"""
def noop_filter(qs, value):
return qs
filter_instance.filter = noop_filter
return filter_instance | 32b97d8ec476e94432953898cac509a9396131d5 | 587,231 |
def IsFrontEndNode(base_www_url):#{{{
"""
check if the base_www_url is front-end node
if base_www_url is ip address, then not the front-end
otherwise yes
"""
base_www_url = base_www_url.lstrip("http://").lstrip("https://").split("/")[0]
if base_www_url == "":
return False
elif ba... | 6391667990dbd769e5195424c36b37ee4b7d5153 | 587,232 |
def NcbiNameLookup(names):
"""Returns dict mapping taxon id -> NCBI scientific name."""
result = {}
for name in names:
if name.NameClass == "scientific name":
result[name.TaxonId] = name
return result | a6831021b7f105e4a7e272ff28ff6aba03534d1c | 587,233 |
def group_perf_by_events(filedir):
"""
Given a perf trace generated by: perf script > out.perf,
return a list of all the events (each event is a CPU sample)
Each event is a list of strings (lines) of the trace
Example of 2 events:
line 1 of each event: the program name; thread id (tid)... | 30c0e04b3e2929c54e2a0840bb20b818b5abb710 | 587,238 |
def __row_to_dict(row: list, column_names: list) -> dict:
"""
Converts a row from the database to a dictionary
Parameters
----------
row : list
Data to convert
column_names : list
Ordered list of column headers
Returns
-------
dict
Row data, as dictionary
... | 94e621c69c9b63b8d1f93cb6b6c19ae820873c6e | 587,242 |
def multiply(first_term, second_term):
"""Multiplication"""
return first_term * second_term | 4764654d5bf51e1c7dac7e9fa98a7e8ac7276db1 | 587,245 |
def _hard_neutralize(v, g):
"""Remove the gender component from a word vector.
Args:
v (np.array): Word vector.
g (np.array): Gender Direction.
Return:
np.array: return the neutralized embedding
"""
return v - g * v.dot(g) / g.dot(g) | 21ed59fba2206bec8535c5e9bb60d83f30e5c6f7 | 587,247 |
import random
def get_random_colors(number_of_colors):
"""
Get a number of random colours as hex
"""
colors = [
"#" + "".join([random.choice("0123456789ABCDEF") for j in range(6)])
for i in range(number_of_colors)
]
return colors | 429e48e32aa05aab7d0c700a80f81d009193b2cd | 587,249 |
def parse_float(a):
""" Converts to a float value; raise TypeError. """
try:
res = float(a)
return res
except:
msg = 'Cannot convert value to a float.\nValue: %s' % a.__repr__()
raise TypeError(msg) | 08b8a8010385c8f48d3db239d54b401599245fc4 | 587,250 |
def con_joule_to_kwh(energy_joule):
"""
Converts energy value from Joule to kWh
Parameters
----------
energy_joule : float
Energy demand value in Joule
Returns
-------
energy_kwh : float
Energy demand value in kWh
"""
energy_kwh = energy_joule / (1000 * 3600)
... | 11e267ee63d691502b6eee63f61ed3f847d4dee3 | 587,251 |
import torch
def calculate_gram_matrix(x):
"""Calculates the gram matrix of the input tensor
Parameters
----------
x : torch.Tensor
Input tensor
Returns
-------
torch.Tensor
The calculated gram matrix of the input tensor
"""
batch_size, depth, height, width = x.s... | 51c64e7564e0776d5f8c617be755dbbdf371f773 | 587,253 |
def predictModel(model, x_test):
"""
Implements scikit-learn's predict() for Random Forest Classifiers
Parameters
----------
model: sklearn.RandomForestClassifier object
fitted Random Forest model
x_test: list
list of test values
Examples
--------
>>> pred = predict... | 45568091cdf6759d51a8c42f721f779ad677c3c2 | 587,254 |
def contains_incorrect_symbols(test_expr, target_expr):
"""Test if the entered expression contains exactly the same symbols as the target.
Sometimes expressions can be mathematically identical to one another, but
contain different symbols. From a pure maths standpoint, this is fine; but
in que... | cb6fd60437bd41211d6aa18baeb9ef6d47e5cf7c | 587,257 |
def rbndvi(b2, b4, b8):
"""
Red-Blue NDVI (Wang et al., 2007).
.. math:: RBNDVI = (b8 - (b4 + b2))/(b8 + (b4 + b2))
:param b2: Blue.
:type b2: numpy.ndarray or float
:param b4: Red.
:type b4: numpy.ndarray or float
:param b8: NIR.
:type b8: numpy.ndarray or float
:returns RBND... | af6e18fb0b5a2adb06d648cb4013c03f5164d4b0 | 587,258 |
import tempfile
def is_ipython_kernel_cell(filename):
""" Return True if a filename corresponds to a Jupyter Notebook cell
"""
return (
filename.startswith('<ipython-input-') or
filename.startswith(tempfile.gettempdir() + '/ipykernel_') or
filename.startswith(tempfile.gettempdir() ... | c28c8e57ae79100e4f4849cdc64bd4418e21c495 | 587,259 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.