content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import logging
def read_tcp_size(conn, size):
"""Read `size` number of bytes from `conn`, retrying as needed."""
chunks = []
bytes_read = 0
while bytes_read < size:
chunk = conn.recv(size - bytes_read)
if not chunk:
if bytes_read > 0:
logging.warning("Incomplete read: %s of %s.", bytes_r... | 0a0df61d7a0dd2417d24977006fa83022c1fa472 | 591,479 |
from functools import reduce
def combine_play_stats(games):
"""
Combines a list of games into one big player sequence containing play
level statistics.
This can be used, for example, to get PlayPlayerStats objects corresponding
to statistics across an entire week, some number of weeks or an entir... | fd9859edeb4f4c7eb9a6db9859ff523a17760f0d | 591,480 |
from typing import Dict
from typing import Union
def get_default_internal_section() -> Dict[str, Union[int, bytes]]:
"""Create an empty internal section with default values."""
return {
'format_version': 1,
'data': b'',
} | 28e61972192c73a2bb095dd7c1ff33e466fb1193 | 591,481 |
def time_formatter(num, size):
"""Adjust a number to a specific size using padding leading zeroes if
needed.
Arguments:
num (int): the number that will be formatted.
size (int): the number of characters need in the string representation
of the num.
Returns:
... | 07a31bf2aaf5532bb6ae0b7b7d7fcc6d1fdb4a28 | 591,482 |
import torch
def euler_matrices(angles):
"""Computes a XYZ Tait-Bryan (improper Euler angle) rotation.
Returns 4x4 matrices for convenient multiplication with other transformations.
Args:
angles: a [batch_size, 3] tensor containing X, Y, and Z angles in radians.
Returns:
a [batch_si... | 2aff1975014003957d41a8bbf99ba82a45e83e5a | 591,483 |
def _frequency_and_multiplier(freq_type):
"""Converts frequency type to MONTH and returns the computes multiplier."""
multiplier = 1
if freq_type == 5:
freq_type = 3
return freq_type, multiplier | ccb02a1c49bfd1d6de8e4a2a4dceb34a2d0a0e7a | 591,484 |
def map_value(val, min1, max1, min2, max2):
""" Performs linear transformation to map value from
range 1 [min1, max1] to a value in range 2 [min2, max2].
:param val: value (int/float) being mapped
:param min1: min of range 1
:param max1: max of range 1
:param min2: min of range 2
:param max... | f6be3c38bcdc3f84d86c0c91039121fc474a5dfc | 591,488 |
def get_codon_nuc_change(codon_change):
"""
For a given codon change E.g. aAt/aGt, return the changed base ([A,G] in the example).
:param str codon_change: The codon change
:return: The modified ref and alt
:rtype: tuple
>>> get_codon_nuc_change('aAt/aGt')
('A', 'G')
>>> get_codon_nuc_... | aa5712983eea2e7fae58690592ef6f7af317a259 | 591,489 |
def findWithPattern(mystr, startPattern, endPattern):
"""
Find the string that starts with <startPattern> and ends with <endPattern> in the orginal string <mystr>.
Args:
+ mystr: orginal string.
+ startPattern:
+ endPattern:
Returns:
+ The found string,
+ and th... | fc2a0d575fdc53b4d4f626cfd6e65ec45523e72a | 591,491 |
import random
def create_segmented_signals(signal, annmap, sample_rate=257, sec=2):
"""
Creates segmented signals containing all possible anomalies from a signal and its annmap
:param signal: the signal to segment
:param annmap: map containing the positions of the annotations
:param sample_rate: ... | 76bdffe6a3c6831b4c39ff75141f8ae7f3309779 | 591,492 |
def getplotvalues(bounds, binvalues):
"""
Matplotlib hist is slow. Use a hist like plot with conventional line plot.
Expects N+1 bounds where len(binvalues) = N
and returns two arrays both of length 2N to plot as line plot.
Make sure arrays are of correct length
len(binvalu... | ec578023f0f0ed8ad75ef6a33687ac47a410f20e | 591,493 |
def csr_read(csr_val, csr_mask):
"""
Performs a CSR read.
Args:
csr_val: A bitarray containing the current CSR value.
csr_mask: A bitarray containing the CSR's mask.
Returns:
A bitarray of the logical AND of csr_val and csr_mask.
"""
return csr_val & csr_mask | 1ebcece205b1a745dcfb05234217c87f5b6c36e0 | 591,500 |
def cube_vertices(x, y, z, n):
""" Return the vertices of the cube at position x, y, z with size 2*n.
"""
return [
x - n, y + n, z - n, x - n, y + n, z + n, x + n, y + n, z + n, x + n, y + n, z - n, # top
x - n, y - n, z - n, x + n, y - n, z - n, x + n, y - n, z + n, x - n, y - n, z + n, ... | 3edc583148eac01767d4a665e2f98be889aad8ad | 591,503 |
def insert_tc(table, content, many=False, ph="%s"):
"""
示例内容::
insert_tc("table", [1, 2, 3, 4, 5])
转换内容 : ('insert into table values(%s,%s,%s,%s,%s)', [1, 2, 3, 4, 5])
insert_tc("table", [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], many=True, ph="?")
转换内容 : ('insert into table values(... | fd95cca7633bb48d123b15b27487398fbe277bb0 | 591,509 |
def clean_quotes(text: str) -> str:
"""Remove quotes from string"""
if text.startswith('"'):
text = text[1:]
if text.endswith('"'):
text = text[:-1]
return text | 21ff30f744056a224b0a7773164732fda0f86fca | 591,510 |
def set_attribute(name, value):
"""
Decorator factory for setting attributes on a function.
Doesn't change the behavior of the wrapped function.
Usage
-----
>>> @set_attribute('__name__', 'foo')
... def bar():
... return 3
...
>>> bar()
3
>>> bar.__name__
'foo'
... | 6e0bb3f6ffd65cb047459d8df0639891547208d1 | 591,512 |
def get_download_url(gem_filename):
"""
Return a public download URL given a Gem archive filename.
"""
return 'https://rubygems.org/downloads/%(gem_filename)s' % locals() | bec8eff7296bf76fc9ea354c7f9097715bf4082f | 591,514 |
def in_valid_range(this_mark, low_mark=0, high_mark=100):
"""Determine if a mark is within a valid range."""
return low_mark <= this_mark <= high_mark | 6c915dc6e1f051c3c9e86803bb10fc7f2819fdb5 | 591,517 |
def roundup(x: int):
"""
Round to the next hundred
:param x: raw value
:return: rounded value
"""
return x if x % 100 == 0 else x + 100 - x % 100 | 811593b7a739da598b3c6166836a4002d55ae5b0 | 591,518 |
def _replace_semicolons(s):
"""Replaces matlab semicolons with nothing in string s."""
s = s.replace(';', '')
return s | 89fe73bdd9e5d34d54539361ce1f7af0aa9214eb | 591,519 |
def _construct_resource_name(project_id, location, dataset_id, fhir_store_id,
resource_id):
"""Constructs a resource name."""
return '/'.join([
'projects', project_id, 'locations', location, 'datasets', dataset_id,
'fhirStores', fhir_store_id, 'fhir', resource_id
]) | e31b4d8d71eaa8ce2873fef3d0dac6f494c71fab | 591,522 |
def get_common_shape(x, y):
""" Get common shape z from two shapes, x and y.
If x and y are of different ranks, error out.
If x and y have the same rank, but x[i] != y[i] for some i, then z[i] = -1, indicating UNKNOWN.
If x and y are equal, z = x
"""
z = None
if len(x) == len(y):
z =... | 627ede25cfc8b891bf822543c9199dfc0f8f6dbc | 591,524 |
from typing import Any
def empty_tuple() -> tuple[Any, ...]:
"""
Returns an empty tuple
Returns:
tuple[Any, ...]: An empty tuple
"""
return tuple() | c85d02932520fe5a65f80501b98378e8d70e9b7b | 591,527 |
import torch
def bbox_iou(box1, box2, x1y1x2y2=True):
"""
Returns the IoU of two bounding boxes
"""
if not x1y1x2y2:
# Transform from center and width to exact coordinates
b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
b1_y1, b1_y2 = box1[:, 1] - box1[:... | 012a19ef056c5017479e4384d57a08bd638b7aac | 591,531 |
def unitcube(dimension):
"""Shortcut to generate a tuple of bounds of the unit hypercube."""
assert dimension > 0
return [0.0] * dimension, [1.0] * dimension | 2f7bf7bd44c140938d80b9b5872fe3f98058d084 | 591,534 |
import torch
def array2tensor(array, dtype, device):
"""This function transforms numpy array to tensor
Arguments:
array {numpy.array} -- numpy array
dtype {torch.dtype} -- torch dtype
device {int} -- device = -1 if cpu, device >= 0 if gpu
Returns:
tensor -- tensor
"""... | 7008999ac2aa7246cee0c0b24e368c29636d8b3c | 591,540 |
import pytz
from datetime import datetime
def datetimeToEpochtime(dt):
"""Convert a datetime object to epoch time"""
if dt.tzinfo is None:
dt_utc = dt
else:
dt_utc = dt.astimezone(pytz.utc).replace(tzinfo=None)
epoch_utc = datetime.utcfromtimestamp(0)
return int((dt_utc - epoch_utc... | c0baf06de714811593ecc8445408ff9498de6750 | 591,541 |
from datetime import datetime
def isIWT(filename):
"""
Checks whether a file is ASCII Tiltmeter format.
"""
try:
temp = open(filename, 'rt').readline()
except:
return False
try:
comp = temp.split()
if not len(comp) == 4:
return False
except:
... | a8443a7082e47dcbf0be3df42a9ad656bd873042 | 591,542 |
import math
def get_lat_dmm(lat):
"""Takes an OLEX float and converts it into DMM latitude notation (eg. 51'6.432 N)
:param lat: An 'Olex float' representing a latitude coordinate.
:type lat: float
:return: A latitude coordinate (eg. 51'6.432 N)
:rtype: str
"""
lat_d = math.trunc(math.fa... | 1f58844d6a071c0a174669e56d5611010e155568 | 591,545 |
def align_structures(reference_traj, target_traj):
"""
Given a reference trajectory, this function performs a structural alignment for a second input trajectory, with respect to the reference.
:param reference_traj: The trajectory to use as a reference for alignment.
:type reference_traj: `... | ba23ee847deb2ac54cbc3c8d973ce02e0c7f7db2 | 591,548 |
def firefox_options(firefox_options):
"""Firefox options.
These options configure firefox to allow for addon installation,
as well as allowing it to run headless.
'extensions.install.requireBuiltInCerts', False: This allows extensions to
be installed with a self-signed certificate.
'xpinst... | 8eb733e51cd8d5b65720b6896556047fd833aca5 | 591,550 |
import re
def validate_hex(hexcode):
"""Validate a hex code."""
return bool(re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', hexcode)) | d2e4319579d85595c0cc14ac9f717ce01cf0885a | 591,552 |
def read_file(filename: str) -> str:
"""
Read a file.
:type filename: str
:param filename: name of file
:rtype: str
:return: str of contents
"""
with open(filename, 'r') as f:
return f.read() | 9f7d0567dcbf6eaffc9ec3c7dad2c02b04425abd | 591,553 |
import torch
def filter_scores_and_topk(scores, score_thr, topk, results=None):
"""Filter results using score threshold and topk candidates.
Args:
scores (Tensor): The scores, shape (num_bboxes, K).
score_thr (float): The score filter threshold.
topk (int): The number of topk candidat... | 473467be00d702e7674bf0dc96874e40a1bb0f5e | 591,554 |
def df_splitter(df, train_split=0.8):
"""
Accepts a DataFrame and returns a train and test set.
Default split is 80% train, 20% test.
"""
df = df.copy() # Make shallow copy to not modify original
df = df.sample(frac=1) # Randomize copy
split = int(len(df) *... | 70fe3ece7008733431b4d2286b5bcafd46d1d661 | 591,555 |
def as_float_default(s, default=0):
"""Cast a string to float or return a default value instead of throwing an
error on invalid argument.
"""
try:
return float(s)
except ValueError:
return default | 30ad6961668887ac7992523761da5a1ac4861c60 | 591,556 |
from typing import Tuple
def layer_size(X, labels, hidden_layer: int = 5) -> Tuple[int, int, int]:
"""
Get the layer sizes
Parameters
----------
X : numpy.ndarray
Features
Y : numpy.ndarray
Labels
hidden_layer : int
Number of Neurons
Returns
-------
in... | ef6b50bb1cbdbc8e12a3f09a731a101ca64241d7 | 591,560 |
def generate_skymap(samples, **kwargs):
"""Generate a skymap from a SamplesDict object
Parameters
----------
samples: pesummary.utils.samples_dict.SamplesDict
samples you wish to generate a skymap for
**kwargs: dict, optional
all additional kwargs are passed to the `.plot()` method
... | c2349bde8db084273c5ebefc23e3cb1aa7a5a4af | 591,561 |
def get_auxhw_info(header_dict, orca_class_name, unique_id=-1):
"""
returns a list with all the info from the AuxHw table of the header
with name orca_class_name. optionally, if unique_id >= 0 only return
the object for that Orca unique id number.
"""
object_info_list = []
try:
objs... | ff34a44db078a74416e79e394a4c7b626b84cdab | 591,562 |
def solution(A, K):
"""
A function that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
For example, given
A = [3, 8, 9, 7, 6]
K = 3
the function should return [9, 7, 6, 3, 8]. Three rotations were made:
[3, 8, 9, 7, 6] -> [6, 3, ... | 479a829687af95c64ac1710a767756e862677247 | 591,564 |
def process_tags(queryset):
"""Prep the set of tags assocaited with a document or page."""
return ", ".join([tag for tag in queryset]) | fb19b33970e9bea5e8548e8c0842dcd2fa7ee097 | 591,566 |
def uniform_cdf(x):
"""returns the probability that
a uniform random variable is <= x"""
if x < 0:
return 0
elif x < 1:
return x
else:
return 1 | dc63df831234fd92f853374e47273ad9f12b0164 | 591,567 |
def chunk_it(seq, num):
"""Make num chunks from elements in seq.
>>> keywords = ['what', 'is', 'going', 'on', 'exactly']
>>> chunk_it(keywords, 6)
[['what'], ['is'], ['going'], ['on'], ['exactly']]
>>> chunk_it(keywords, 2)
[['what', 'is'], ['going', 'on', 'exactly']]
Args:
seq: A ... | 517f88d52b218d0fc26bbe5f63dec0990ca32d27 | 591,569 |
from typing import List
from pathlib import Path
def str_to_list(string: str, need_exist=False, create=False, sep=",", is_dir=False) -> List[Path]:
"""
Creates a list of pathlib.Paths from a comma (or else) separated list.
"""
paths = [Path(path) for path in string.split(sep)]
if create:
f... | 8bceed849ff86e09fdcfa729f1121269ab73c20b | 591,570 |
def tibetan_day(date):
"""Return 'day' element of a Tibetan date, date."""
return date[3] | 7910e3e3029f2df5044f5d92b1396f0895a4e6da | 591,571 |
import functools
def nest(*iterables):
"""Flatten nested for loops it a single tuple yielding generator.
Useful in that it prevents over indentation.
Source: http://code.activestate.com/recipes/473818/#c1
Thus:
for i, j, c in nest(range(10), range(10), "ABCDEF"):
do_something(i, j, c)
... | 046db54a53c12ad68d5057ea35c264afc7008c89 | 591,573 |
def flat_datasets(datasets):
"""
Returns a list of all datasets in this catalog
"""
flat_ds = []
for ds in datasets:
if ds.is_collection():
flat_ds.extend(flat_datasets(ds.datasets))
else:
flat_ds.append(ds)
return flat_ds | 7aa6e21c98c2a22c6548245b4fd78ae22d1c8325 | 591,575 |
def _timex_pairs(timexes):
"""Return a list of timex pairs where the first element occurs before the
second element on the input list."""
pairs = []
for i in range(len(timexes)):
for j in range(len(timexes)):
if i < j:
pairs.append([timexes[i], timexes[j]])
return... | f0d232e138da377b1e07d866e0472752911b99f5 | 591,578 |
def get_jobs_count(context):
"""Return job count read from the JSON response."""
jsondata = context.response.json()
jobs = jsondata['jobs']
assert jobs is not None
return jsondata['jobs_count'] | ed809411e351cb76a6cd4d5541538bc92c12ee2d | 591,579 |
import re
def validate_date(date):
"""Validate date format.
:param date: The date that will be entered into the database.
:type date: str
:return: True if the date format is well formed with valid characters, false if not.
:rtype: bool
"""
result = None
date_format = "([0-9]{4}-[0-9]{... | c9bf560c6e25246e8713f93b4a85ac87a7693337 | 591,580 |
def aggregate(gradients, **kwargs):
""" Averaging rule.
Args:
gradients Non-empty list of gradients to aggregate
... Ignored keyword-arguments
Returns:
Average gradient
"""
return sum(gradients) / len(gradients) | 08f10021f504910424ad95db6969f38f06e52216 | 591,581 |
import random
def nbackseq(n, length, words):
"""Generate n-back balanced sequences
Parameters
----------
n : int
How many characters (including the current one) to look
back to assure no duplicates
length : int
The total length of the sequence to produce
words : list
... | ff5b7dc59e72bc0e18bd7887d6e8b7818fa67207 | 591,583 |
def numstr(value):
"""Converts a number to a string with no trailing zeros"""
return ('%0.2f' % value).rstrip('0').rstrip('.') | 6d87e2ea3f1c24c08ee852adabe39069c7a8ae78 | 591,584 |
def line_search_bisection(f, bound, accuracy):
"""
Maximize c so that constraint fulfilled.
This algorithm assumes continuity of f; that is,
there exists a fixed value c, such that f(x) is
False for x < c and True otherwise. This holds true,
for example, for the level sets that we consider.
... | 123d58b3782d8e70dd3f965ca1b9940f0b32c9a1 | 591,586 |
from functools import reduce
def urljoin(*args: str):
"""Gets arguments to join as url
Args:
*args: args to join
Returns:
Joined url
Examples:
>>> urljoin('https://www.example.com', 'suffix/', '/suffix2', 'suffix', 'file.json')
'https://www.example.com/suffix/suffix2... | 34a579b44882e2a4206ff053316ebecb08df030d | 591,588 |
def int_to_bools(num, digits):
""" Converts an integer to an array of bools of its binary representation.
Parameters
----------
num : number
The number to encode.
digits : number
The number of digits.
Returns
-------
list(bool)
Array of bools representing the n... | d1c1ee0733950fec11afed21d20f1eec8c2ddd43 | 591,590 |
def _build_command_options(options):
"""Build a list of flags from given pairs (option, is_enabled).
Each option is prefixed with a single '-'.
Include only options for which is_enabled=True.
"""
return ['-' + item[0] for item in options if item[1]] | a850e6199b46886952845e98ec9212a26a79d698 | 591,592 |
def moreThan3Chars(value):
"""String must contain at least 3 characters."""
if len(value) >= 3:
return True
return False | a50a923e70a6ed89a094ac2040ac27f0f0273aa5 | 591,593 |
def apim_api_release_delete(client, resource_group_name, service_name, api_id, release_id, if_match=None):
"""Deletes the specified release in the API."""
return client.api_release.delete(
resource_group_name, service_name, api_id, release_id, "*" if if_match is None else if_match) | 5ee04f1993fee129eb3c0e6618e5f04b41166650 | 591,600 |
def jaccard_coefficient(neighbors_target, neighbors_source):
"""Compute the jaddard coefficient between a source and a target node.
The neighbors are represented by a list of strings.
"""
common_neighbors = len(set(neighbors_source).intersection(set(neighbors_target)))
total_neighbors = len(neighbo... | d3b4ee95bf5492936ac8580678a7446c948cf550 | 591,603 |
import collections
def summarise_random_walk_results(dictofwalks, nodelist, iterationnum):
"""
Takes in dictionary of walks, nodelist, and iteration number to
calculate per protein, of all the visited nodes over all walks,
how many times each node was visited.
Returns a dictionary with counts.
... | b23e73518aafae85dbd111da4486399c40619260 | 591,606 |
def trim_length_from_end(string, length):
""" Trims the length of the given string to the given length
:param string:
:param length:
:return: trimmed string to the length provided
"""
if len(string) > length:
return string[:length]
else:
return string | 566db4af5fa5470d6a802fd1e38792574ea7353a | 591,607 |
def get_orders(orders_items):
"""
Search orders that are linked with other objects from parameter
:param orders_items: OrdersLoadingPlaces or OrdersDestinationPlaces or OrdersVehicles objects
:return: found orders
"""
orders = list()
for order_item in orders_items:
orders.append(orde... | b39965133247a200d9e9cbd6673ca2a897d1e3b3 | 591,608 |
import hashlib
def gen_sha256_hash(targer_str):
"""
Generate sha256 hash
:param targer_str: string to hash
:type targer_str: str
:rtype: str
"""
sha = hashlib.new('sha256')
targer_str = targer_str.encode()
sha.update(targer_str)
return sha.hexdigest() | cf3da62cfb5068fec6e9613da17321c5f90a62f6 | 591,609 |
import typing
def filter_options(keys: typing.Iterable[str],
options: typing.Mapping[str, typing.Any]
) -> typing.Dict[str, typing.Any]:
"""
Filter 'options' with given 'keys'.
:param keys: key names of optional keyword arguments
:param options: optional keyword ... | 9bdccb73e39c6d98f243b734ab551fc851d4ce63 | 591,611 |
import sqlite3
def get_coupons(user_id,user_emotion):
"""Returns the coupons
High-spender, Happy or Neutral - no coupon
High-spender, Sad - 10% coupon
High-spender, Angry - 20% coupon
Average-spender, Happy or Neutral - no coupon
Average-spender, Sad - no coupon
Average-spender, Angry... | 7665cda300dcf5363430ae003d327b181bf5765c | 591,618 |
from pathlib import Path
def path_to_datafile(filename):
"""
Get absolute path to datafile
:param filename: pathname of datafile
:type filename: str
:raises FileNotFoundError: File does not exist
:return: Absolute path
:rtype: str
If ``filename`` contains no path specification eg. ``... | 82812d2e686911e4b4dc6ab0d3182121c599767f | 591,628 |
def calc_precip(minutely):
"""
Calculate the percentage of precipitation over the next 15 minutes
"""
return max(datum["precipProbability"] for datum in minutely["data"]) | d28e6576d2c0b6e62fb1d80cf9b876e6a4593b9a | 591,629 |
def delta(r, a, Q=0):
"""
Returns the value of :math:`r^2 - r_s r + a^2 + r_Q^2`
Uses natural units, with :math:`c = G = M = k_e = 1`
Parameters
----------
r : float
r-component of 4-Position
a : float
Spin Parameter
:math:`0 \\le a \\le 1`
Q : float
Char... | 37530802363f6619630a4717c6d180945767c6f8 | 591,630 |
def is_weekend(dtobj):
"""True if dtobj is a Saturday or Sunday"""
return dtobj.weekday() in (5,6) | 0b51140aca0575df67696f4b53b72da45e2f421b | 591,633 |
def node(pymel):
"""Fixture for a node with a single attribute."""
node = pymel.createNode("transform")
pymel.addAttr(node, longName="foo")
return node | f07cf8702ce50c8028b407cc179f42dd357c095c | 591,638 |
def find_next_coefficient_c(k, previous_c, lamb, beta):
"""Return c_k = lamb^(k-1) * (1 - lamb)^(k * beta - k + 1) * \\binom{k * beta}{k - 1} / k.
To avoid large values of \\binom when 'k' is sufficiently big, and to decrease the runtime,
the value is computed as:
с_1 = (1-lamb)^beta,
c_k = c_{k-... | 3d9f68e222c2cf9320e2c9a1fdc5970e80f0a159 | 591,640 |
def df_float_formatter(df, formatter="{:.2f}"):
"""Select float columns and format them with formatter."""
float_col = df.select_dtypes(include='float64').columns
format_dict = {col: formatter for col in float_col}
df = df.style.format(format_dict)
return df | 409fe2ee7591e51afb11adf6ce0ebfe85e585b1f | 591,642 |
def clean_data(row):
"""Clean table row list from Wikipedia into a string for CSV.
ARGS:
row (bs4.ResultSet): The bs4 result set being cleaned for output.
RETURNS:
cleaned_cells (list[str]): List of cleaned text items in this row.
"""
cleaned_cells = []
for cell in row:
... | 296d89de4a92d432b192700485bde91d492b651d | 591,643 |
def _signup_fields_from_invite(invite):
""" Return the signup form fields derived from the given invite object. """
return {
'signup_email': invite.recipient_email,
'first_name': invite.recipient_first_name,
'last_name': invite.recipient_last_name,
# Pass the invite_token as... | ab01c71563a325ac0048217309eb24c8ce4582de | 591,648 |
def keff_line_parse(keff_line):
"""parses through the ana_keff line in .res file
Parameters
----------
keff_line: str
string from .res file listing IMP_KEFF
Returns
-------
tuple
(mean IMP_KEFF, std deviation of IMP_KEFF)
"""
start = keff_line.find('=')
new_keff... | d66ccb0612742b49e59ba8ce05475916bf70ffd2 | 591,649 |
from typing import List
def get_union_args(tp) -> List:
""" Return a list of typing.Union args. """
return list(tp.__args__) | 49614904ca7eef7ad2ccc11bd92b14f2e120b593 | 591,654 |
def _apply_overall_clipping_threshold(power_ac,
clipping_mask,
clipped_power_ac):
"""
Apply an overall clipping threshold to the data. This
additional logic sets an overall threshold in the dataset
where all points above this th... | b3ed5dc944d8ac4865289e845a28654739eb669d | 591,656 |
import requests
def downloadFile(url, name, ext):
""" Download a file from a given url
:param url: full url
:type url: str
:param name: name for the file (can contain a path)
:type name: str
:param ext: extension for the file
:type ext: str
:return: the created file (closed)
:rtyp... | 75138d70430ab585afbbd9111c46c0d8c9d13ed5 | 591,660 |
import decimal
def print_float(num):
"""
Get float with 3 decimals and normalized
"""
return decimal.Decimal(str(round(num, 3))).normalize() | e1293912503cb5b0b09b73e2479d629c0789c275 | 591,670 |
def checkOneOffButtonClicked(game, clickX, clickY):
"""
Returns true if one-off button was clicked, else false
"""
return (game.oneOffButtonObj is not None and
game.oneOffButtonObj.collidepoint(clickX, clickY)) | 1afbc37af45053e006c69971973feb962420b915 | 591,671 |
def get3parts(line, leftDelim, rightDelim):
""" Return (left, middle, right) from line divided by delimeters,
if one or both delimeters doesn't exist return ('', '', '')
>>> print "%s, %s, %s" % get3parts('one"two"three', '"', '"')
one, two, three
>>> print "%s, %s, %s" % get3parts('one"two-three', '"', '-')
one... | b8b3d4dd7cee1a445472afa2008eeb1d97839646 | 591,672 |
def setbit(byte, offset, value):
"""
Set a bit in a byte to 1 if value is truthy, 0 if not.
"""
if value:
return byte | (1 << offset)
else:
return byte & ~(1 << offset) | 2da1047f85d6f507908e6c9d326a6945e1de77cc | 591,674 |
def decodeCaesar(sequence: str, shift: int = 1) -> str:
"""
Decodes the given string to Caesar Cipher
:param sequence: String to decode
:param shift: Shift value
Example:
>>> decodeCaesar("IFMMP XPSME", 1)
>>> "HELLO WORLD"
"""
return ''.join(chr(((ord(c) - 65 - shift) % 26)... | 689ae7f2829da1247903ee9ecd7754b8e2ec4040 | 591,676 |
def fill(lst, mold, subs):
"""For every <mold> element in <lst>, substitute for the according
<subs> value (indexically). """
nlst = list(lst).copy()
j = 0
for i, elem in enumerate(lst):
if elem == mold:
nlst[i] = subs[j]
j += 1
return nlst | 359b278899da936c15c6a8fe63e34649204ff7f7 | 591,678 |
import shutil
def copy_dir(filepath, destination):
"""Copies a directory and it's contents from one place to another.
Args:
filepath (:obj:`str`): The full path to the directory to copy.
destination (:obj:`str`): The full path to the location you want the directory copied to.
Returns:
... | bada1c670ecfb51b1f03d3e0e50ef58ec90e7501 | 591,679 |
def parse_sequence(directions):
"""Parse textual representation of sequence of directions
into a list."""
return [direction.upper() for direction in directions.split(',')] | 5d704d3716b5fdd86489426ccd9cf0d2d51f8a04 | 591,685 |
from typing import Tuple
from typing import Optional
from typing import Any
import requests
import json
from typing import OrderedDict
def json_get(iiif_uri: str) -> Tuple[int, Optional[Any]]:
"""
Return an OrderedDict from a URI which returns JSON.
:param iiif_uri: ID/URI for the JSON
:return: html ... | dd2368a5547f4c6b895246ebcc0ba915ed66e1f1 | 591,686 |
def make_round(x, base=5):
"""
Rounds the time in interval of 5 min.
"""
return int(base * round(float(x)/base)) | 6da5846fdd6a8d0fa8c9d66e89fda359b5271fbd | 591,687 |
def point_in_box(box, test_point):
"""checks if a point is in a box
Args:
box: two points, a top left and a bottom right
test_point: a test point
Returns:
bool
"""
top_left = box[0]
bottom_right = box[1]
if (top_left[0] < test_point[0]) and (top_left[1] < test_point... | 7b2adf19e0e11c7b1a94089d1d47d1bf09ffd24a | 591,689 |
def compute_energy_fractions(momenta,reference,**opts):
"""Compute the energy fractions of a set of momenta with respect to a reference
Given a set of momenta p1...pk and a reference vector n, the energy fractions are defined as zi = pi.n/(p1.n+...+pk.n)
:param momenta: momenta whose energy fraction we com... | 3c1d1ff55b997dcd0318827b568fc6c0fd32b5e9 | 591,690 |
import string
def makeWordList(gFile, stopWords):
"""Create a list of words from the file while excluding stop words."""
speech = [] # list of speech words: initialized to be empty
for lineString in gFile:
lineList = lineString.strip(
string.whitespace).split() # split each line into a lis... | 0216463f458d5cd8a0659ce0c6792bd585499942 | 591,691 |
def is_overlapping(seg1, seg2):
"""
Check whether 2 segments overlap or not
"""
return not (seg1['end'] < seg2['start'] or seg2['end'] < seg1['start']) | c151f9ff307e32037d681103534bf999ec9d19b5 | 591,692 |
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 |
from typing import Any
def prepare_dynamodb_batch_put_request(
table: str,
items: list[dict[str, Any]],
) -> dict[str, list[dict[str, Any]]]:
"""Prepare PutRequest input for a DynamoDB BatchWriteItem request"""
return {
table: [{"PutRequest": {"Item": item}} for item in items if item is not No... | 9dc70f3dc7964cb6b024ab3f95ed84e8886b4c37 | 591,698 |
from typing import List
from typing import Any
def mpop(stack: List[Any], n: int = 1) -> List[Any]:
"""Pops and returns `n` items from a stack. Mutates `stack`"""
return [stack.pop() for _ in range(n)] | 1fa1d9e0e049c8482de027e2195c74ac46f44920 | 591,704 |
def mget(lst, ind):
"""
Returns a list 'lst2' such that lst2[i] = lst[ind[i]]
In otherwords, get the subsequence of 'lst'.
"""
return [lst[i] for i in ind] | d49b4387be66a4c77f78892f7d0cdc5388eaa2e6 | 591,705 |
def pprSACK(sack):
"""Pretty print a selective ACK"""
return "seq={seq:.0f}\nnode={node:.0f}".\
format(seq=sack.seq,
node=sack.node) | 6eda4b76fa2ac414896bcad76da2374b7c97e4af | 591,713 |
import re
def grep_line(path, taxid):
"""Return the first line in the file at path beginning with taxid."""
file = open(path, "r")
for line in file:
if re.match(str(taxid)+r'\s', line):
return line
return False | 4dc393f75acfc206c14571729b914e8c7c140d16 | 591,715 |
def sqDist(x1, y1, x2, y2):
"""
Returns the square of distance between two points
"""
return (x1-x2)**2 + (y2-y1)**2 | 3b0b31f0143b153cbecda56a588454ebd5def988 | 591,716 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.