content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def get_score(word):
"""Score a given word."""
if len(word) == 4:
return 1
else:
score = len(word)
if len(set(word)) == 7:
score += 7
return score | c48ffc666e1219ec7b19aeb3343a04de95e048bb | 558,797 |
def start_first_monday(df):
"""Slices the dataset keeping data dated after the first monday available
Parameters:
-----------
df : Pandas DataFrame
the original dataset
Returns
-----------
df : Pandas DataFrame
the corresponding dataset
"""
first_date_gap =... | 493e2ff6bc2da3a69f9cfca698d9fc0bb5f35f0f | 202,853 |
def squared(value: int) -> int:
"""Returns the squared value"""
return value * value | 73cfb3e7c7fdfb2bf99296861dc243c5c92cb67e | 255,315 |
def text(item):
"""
Get the text from the tweet
"""
if 'text' in item:
return item['text']
return None | 1451d0933c65b5c09eb8a39eb882162af335cb57 | 600,784 |
def append_from(session, data, page):
""" Collect paginated data."""
r = session.api_request(page)
url_next = r["links"]["next"]
if url_next:
append_from(session, data, url_next[len(session.base_url):])
data.extend(r["data"])
return data | 05100d0f6d10d3851a99a30528d75ba5510f9a21 | 430,784 |
def factor_out_twos(n):
"""
Returns the tuple (d,s) such that n = d*(2**s) for the smallest value of d
"""
d = n
s = 0
while d % 2 == 0:
s += 1
d //= 2
return d,s | 76ed2fa981673098afd66239eca960607e96d7e9 | 615,873 |
def write_string(fid, s):
"""
Write *s* as a null terminated string to *fid*.
"""
fid.write(s + '\0')
return fid | 3e7f00279272da79003ed76db5b4028e1b0b5727 | 454,219 |
def hash_djb2(s, seed=5381):
"""
Hash string with djb2 hash function
:type s: ``str``
:param s: The input string to hash
:type seed: ``int``
:param seed: The seed for the hash function (default is 5381)
:return: The hashed value
:rtype: ``int``
"""
hash_name = seed
... | 1f110277c1da36acfa1c336664e78eb867fa6e97 | 562,016 |
def _set_coords(ds, varname):
"""Set all variables except varname to be coords."""
if varname is None:
return ds
if isinstance(varname, str):
varname = [varname]
coord_vars = set(ds.data_vars) - set(varname)
return ds.set_coords(coord_vars) | b6f94e9e8022dccfb6dfab078203c624f6c8bf3a | 558,158 |
def filterArchitecture(results, architecture):
"""
Restrict the list of results based on given architecture
"""
filtered_results = {}
for name, res in results.items():
filtered_values = []
for value in res:
if architecture is "x86":
# drop aarch64 results
... | a909932f1761d0278627c91498e8631f50ada380 | 303,300 |
from typing import List
def _ternary_search(array: List[int], value, low: int, high: int) -> int:
"""
The implementation detail of the recursive implementation of ternary search.
:param array: is the array to search.
:param value: is the value to search for.
:param low: is the lower bound of the p... | f07a81c640ef9bafe31f01c72bf7ce5af6d30604 | 634,063 |
def solution(nums: list) -> list:
""" This function sorts the passed in array of numbers. """
if nums is None:
return []
return sorted(nums) | e8f44a4ce4b8eede0533329bc9c89ba9e2f0006d | 415,864 |
def length(x):
"""
Returns the length of x
:param x: the time series to calculate the feature of
:type x: pandas.Series
:return: the value of this feature
:return type: int
"""
return len(x) | 461d11ba6ca91b7ab6e7029ea7fe09fe4f78da1c | 567,946 |
def create_garage_parking(data):
"""Create garage parking feature."""
data['Posti_garage'] = (data['Posti auto']
.str.extract(r'(\d).*garage\/box')
.astype('float')
.fillna(0))
return data | 82ad85660b78584565adbbd5fe8ab38e435a1bf7 | 495,441 |
def return_timings(data, trial_type):
"""
Finds all trials matching the string 'trial_type',
retrieves onset in seconds, and returns them as a list.
"""
data = filter(lambda d: trial_type in d[0], data)
onsets = []
for trial in data:
onsets.append(trial[5])
return onsets | f1c4ae2013287b85b603dd9b90affb0ab01f7fdd | 283,605 |
from datetime import datetime
def convert_iso_time(isotime):
"""Will convert an isotime (string) to datetime.datetime"""
return datetime.strptime(isotime, '%Y-%m-%dT%H:%M:%S.%fZ') | 49c60216ac664899614a82ac0fdaaa1731fbaafb | 215,171 |
def FixateInputShape(input_params,
batch_size,
target_max_seqlen=None,
source_max_seqlen=None):
"""Adjusts the input_params so that it always produces fixed shaped output.
Sets p.target_max_length to target_max_seqlen and p.source_max_length to
sourc... | 9034b08e73b6fdded41420f36167f099fade58fb | 64,738 |
import logging
def make_log_metric(level=logging.INFO, msg="%d items in %.2f seconds"):
"""Make a new metric function that logs at the given level
:arg int level: logging level, defaults to ``logging.INFO``
:arg string msg: logging message format string, taking ``count`` and ``elapsed``
:rtype: funct... | 8d99e00284b21d192a741d2cc0f7b1a2c40b18e2 | 137,561 |
from datetime import datetime
def is_naive_datetime(dt: datetime):
"""判断 datetime 对象是否带有时区。
如果没有时区,在任何时候该对象都应该被当作本地时区对待。
"""
return dt.tzinfo is None | cb7be80d98f08740978d1aa58cf8255d688cae95 | 267,487 |
import json
def read_config(file_path):
"""Read JSON config."""
json_object = json.load(open(file_path, 'r'))
return json_object | ed2feb5f23afbdee20573db847f4b7d5615fb6ce | 550,184 |
def load_header(file: str):
"""Check if the graph is directed, bipartite, weighted."""
directed, bipartite, weighted = False, False, True
with open(file, 'r', encoding='utf-8') as f:
row = f.readline()
if 'bip' in row:
bipartite = True
if 'unweighted' in row:
... | e91665878d01a9f460b32d542066f6c27add96db | 327,186 |
def u4(bytes):
"""
Convert a little endian Ublox U4 type to a native integer
"""
if len(bytes) != 4:
raise ValueError('Need exactly 4 bytes')
return int(bytes[0]) + \
int(bytes[1]) * 256 + \
int(bytes[2]) * 65536 + \
int(bytes[3]) * 16777216 | ab446bc02500ad9eba94b8b6bc9de689cf334e57 | 234,186 |
def my_tokenizer(s):
"""
Split a string s by spaces.
Parameters
----------
s : The string.
Returns
-------
s.split() : A list with the resulting substrings from the split
"""
return s.split() | db2e0e637d087c1c5ed7813ef1f3903656d3eab2 | 310,278 |
def decode_data(data, table):
""" Decode data with precalculated table """
dec = []
for i in range(0, len(data), 16):
dec.append(table[data[i:i+16]])
return bytes(dec) | 2351ece8066e1335d172c760d271f2a1a5f47922 | 479,595 |
def OnlyIfDescendedFrom(tag_names):
"""Decorator that only executes this visitor if we have the named ancestor.
If one of the specified parent tag names is in the tree above us, run the
decorated function. Otherwise, continue down the tree by using the default
visitor, as if the decorated function didn't exist... | bfc502191beb09863ed70219dd842ad3b927663f | 244,257 |
def node_pos_formatter(node):
"""
Returns a terminal node's original token.
"""
return node.text | 2886fea43ad06d81e60f29be3c90fba7060e385e | 607,559 |
def sort_and_dedup(input_list: list):
"""Sorts a list alphabetically and remove duplicates. Return tuple"""
seen = set()
seen_add = seen.add
input = sorted(input_list) # sort
uniques = [x for x in input if not (x in seen or seen_add(x))]
output = tuple(uniques)
return output | 7eb7314d7cd8039479755aee2fc775ef760a508a | 461,333 |
def yields_from_gronow_2021_tables_3_A10(feh):
"""
Supernova data source: Gronow, S. et al., 2021, A&A, Tables 3/A10 He detonation + Core detonation
Five datasets are provided for FeH values of -2, -1, 0 and 0.4771
We use four intervals delimited by midpoints of those values.
"""
if feh <= -1.5:... | 16704acc8c5b04ab30e36374ee35af5c979125a8 | 549,806 |
def isint(intstr):
""" Checks if a string is an integer.
Args:
intstr (str): A string
Returns: bool
"""
try:
int(intstr)
return True
except ValueError:
return False | 2d989ec51f64c7e622198ba8bdeceeecbddce2f0 | 253,633 |
def fresh_dict(m, ignore_underscore_fields=True):
"""
Returns a dict representation of the current (unsaved)
state of Model M.
Like django's built-in Model.__dict__, except that seems
to use the stored (i.e. old) rather than new/unsaved
values. In other words, if you change some of M's values
... | e7f4c6177d3702e3025e2117e43e09671e2c03da | 378,549 |
def parse_fasta (lines):
"""Returns 2 lists: one is for the descriptions and other one for the sequences"""
descs, seqs, data = [], [], ''
for line in lines:
if line.startswith('>'):
if data: # have collected a sequence, push to seqs
seqs.append(data)
da... | 4dea579720f43f348389e53751c0308f1c493296 | 26,968 |
def getSegsIgnore(oracleSplitSegs, collars):
"""
This function returns a list of the segment times to ignore based on the input collar sizes. Note that
each collar defined as a start collar size and an end collar size, though both can be the same.
Inputs:
- oracleSplitSegs: ground truth segments a... | b5bfbbc25539f58e7e6de1299c4562ea4df5d70b | 199,242 |
def calculate_benefit_cost_ratio(region, country_parameters):
"""
Calculate the benefit cost ratio.
"""
cost = (
region['network_cost'] +
region['spectrum_cost'] +
region['tax'] +
region['profit_margin']
)
revenue = region['total_revenue']
if revenue > 0 an... | 2c820f3cc758bf22355983dac8950df380168dc9 | 242,577 |
def par_insertion(pairs, chars, rules, steps):
"""
Apply steps of par insertion to the polymer template.
:param pairs: template pairs
:param chars: counter of characters
:param steps: number of required steps
:return: pairs, chars
"""
for _ in range(steps):
for (a, b), value in p... | 9058ce6aa1626d22bd9eaca0e613fdfcdd51d264 | 583,363 |
def _rshift_nearest(x, shift):
"""Given an integer x and a nonnegative integer shift, return closest
integer to x / 2**shift; use round-to-even in case of a tie.
"""
b, q = 1 << shift, x >> shift
return q + (2 * (x & b - 1) + (q & 1) > b) | cb6fa2a2d65367766adab37e05534990dfe3b2a6 | 656,373 |
def touchforms_error_is_config_error(touchforms_error):
"""
Returns True if the given TouchformsError is the result of a
form configuration error.
"""
error_type = touchforms_error.response_data.get('error_type', '')
return any([s in error_type for s in (
'XPathTypeMismatchException',
... | 359fc7bfa195c5adadeec3d230408a892827b8a8 | 611,338 |
def get_data_source(name):
"""Guesses data source from file name.
If the name contains 'terr' then we guess terrestrial data,
otherwise we assume satellite.
Arguments
=========
name : str
File name
Returns
=======
int
0 if satellite, 1 if terrestrial
"""
i... | 2ac0915327805320474a94cb6b9189e7c7041440 | 343,638 |
import traceback
def format_traceback(sys_exc_info):
"""Formats traceback."""
return "".join(traceback.format_tb(sys_exc_info[-1])).rstrip() | 1e6f3b3cf90b49d0757216fbc30dc6c94ff5d197 | 340,005 |
import random
import string
def generate_random_string(len: int):
""" Creates a randomly generated string of uppercase letters
Args:
len (int): The desired length
Returns:
random_string (str)
"""
return ''.join(random.choices(string.ascii_uppercase, k=len)) | 5414ecb7a6e212379000e43fef07e4642c0e63a0 | 17,329 |
def _ply_header(num_vertices, num_faces, use_vertex_colors=False):
"""
Return a string representing the PLY format header for the given data properties.
"""
hdr_top = """ply
format ascii 1.0
comment Generated by Brainload
"""
hdr_verts = """element vertex %d
property float x
property float y
proper... | 40d7b12a1006be4cfa634f887c1054ddb30bb145 | 391,603 |
def get_contacts(filename):
"""
Function to get all the name and email IDs of contacts in separate lists
:param filename: File containing contact list
:return: lists containing names and emails
"""
names = []
emails = []
with open(filename, encoding='utf-8') as contacts_file:
for... | 83518c828ee5da909cf7765ac4cc59fc65f97330 | 161,995 |
def index1(b, i, k):
"""Magic index1 function.
Takes a bitstring k and inserts bit b as the ith bit,
shifting bits >= i over to make room.
"""
retval = k
lowbits = k & ((1 << i) - 1) # get the low i bits
retval >>= i
retval <<= 1
retval |= b
retval <<= i
retval |= lowbit... | d5fa14ed1f11d8b1636f6e842b64dd7d2d9ede68 | 538,103 |
def format(self, ndigit="", ftype="", nwidth="", dsignf="", line="",
char="", **kwargs):
"""Specifies format controls for tables.
APDL Command: /FORMAT
Parameters
----------
ndigit
Number of digits (3 to 32) in first table column (usually the node
or element number). In... | 4c01afdccc4066005a4db7d523ef1d13ccf74b36 | 634,616 |
def _is_match_one(sub_string_list, src_string):
"""
Whether the sub-string in the list can match the source string.
Args:
sub_string_list (list): The sub-string list.
src_string (str): The source string.
Returns:
bool, if matched return True, else return False.
"""
for ... | baa41ca9e8ab1d800d87862edece77f41ec649c1 | 219,722 |
import torch
def all_or_none_accuracy(preds, targets, dim=-1):
""" Gets the accuracy of the predicted sequence.
:param preds: model predictions
:param targets: the true targets
:param dim: dimension to operate over
:returns: scalar value for all-or-none accuracy
:rtype: float32
"""
p... | 4e46720996a383b601f7de332945182971f53988 | 681,596 |
import logging
import requests
def news_API_request(covid_terms: str = "Covid COVID-19 coronavirus"):
"""
This function get the news from the news API according to the given keywords.
:arg
covid_terms (str): Keywords of the news that you want to get
:return:
Json file: A json file co... | bc9fa9d117e92ec5a14ce3ecd2f73966fc86b37d | 424,745 |
def collect_default_successors(start_state):
"""
Collect the default successor states.
NOTE: The start state also evaluated as a successor!
NOTE: This function is necessary for expression validation!
:param start_state: the start state of the searching
:return: the set of default successor state... | 740ef64fc848b2a76d1bf82594acaea5db549b02 | 571,344 |
def bigend_2_int(p_bytes):
""" Convert bigending bytestring to int
"""
l_ix = 0
l_int = 0
while l_ix < len(p_bytes):
l_b = int(p_bytes[l_ix])
l_int = l_int * 256 + l_b
l_ix += 1
return l_int | 5c51a3752eec30804ab45185fb51c70be240a5b6 | 19,906 |
def is_eulerian_tour(graph, tour):
"""Eulerian tour on an undirected graph
:param graph: directed graph in listlist format, cannot be listdict
:param tour: vertex list
:returns: test if tour is eulerian
:complexity: `O(|V|*|E|)` under the assumption that
set membership is in cons... | bafb2e64802b613b024f7da740c2489443e8acef | 392,606 |
def get_max_value(li):
"""Return the largest value from a list."""
m = li[0]
for value in li:
if value > m:
m = value
return m | 3f208bd33fb057901b1d89f8161bb22ddd7e88a6 | 362,642 |
def lcg_generator(
state: int,
multiplier: int = 1140671485,
addend: int = 12820163,
pmod: int = 2 ** 24,
) -> int:
"""
Performs one step in a pseudorandom sequence from state (the input argument)
to state the return value.
The return value is an integer, uniformly distributed in [0, pm... | 486438504a3c177b5e9fdc508857dcd349da76a0 | 144,260 |
def _preprocess(statement: str):
"""Preprocess the input statement."""
statement = statement.strip()
# Replace any occourance of " with '.
statement = statement.replace('"', "'")
if statement[-1] != ";":
statement += ";"
return statement | 48faedb198d937c8efbd655820510df147b11be2 | 580,361 |
def remove_padding(X,pad_value):
"""Convience function used to remove padding from inputs which have been
padded during batch generation"""
return X[X!=pad_value] | 968de77558270bad4858db63374eb2c2e7a1148c | 57,965 |
def get_end_of_line_character(view):
"""Return the EOL character from the view's settings."""
line_endings = view.settings().get("default_line_ending")
if line_endings == "windows":
return "\r\n"
elif line_endings == "mac":
return "\r"
else:
return "\n" | f8f4b45b187d9780671f1848ca25c63c93876a22 | 451,619 |
def gerrit_check(patch_url):
""" Check if patch belongs to upstream/rdo/downstream gerrit,
:param patch_url: Gerrit URL in a string format
:returns gerrit: return string i.e 'upstream'/'rdo'/'downstream'
"""
if 'redhat' in patch_url:
return 'downstream'
if 'review.rdoproject.org' in patc... | 93039f8b11e2359d05984d84953f3d7e05663bef | 234,128 |
from typing import Any
def py_is_not_none(x: Any) -> bool:
"""Check if x is not None."""
return x is not None | 064976648b101a2ae2f0593f2e92149a79a73f42 | 495,383 |
def mul(X, varX, Y, varY):
"""Multiplication with error propagation"""
# Direct algorithm:
Z = X * Y
varZ = Y**2 * varX + X**2 * varY
# Indirect algorithm won't ensure floating point results
# varZ = Y**2
# varZ *= varX
# Z = X**2 # Using Z to hold the temporary
# Z *= varY... | 92f4d24a8f370525062b8826fc1ec8cffaec0bbe | 262,908 |
def compute_score_seq(seq,
score_matrix,
pval_mat,
min_score,
scale,
width,
offset):
"""
Score a sequence using a processed motif scoring matrix
----
Parameters... | eda48309e6778e231a0fb22a907680659cf7082d | 460,009 |
import itertools
def _get_common_blocks(dp_block_sizes, dp_ids):
"""Return all pairs of non-empty blocks across dataproviders.
:returns
dict mapping block identifier to a list of all combinations of
data provider pairs containing this block.
block_id -> List(pairs of dp ids)
... | 027ac3625e21ab70de8bd656ed2e625236c12fbb | 90,488 |
import torch
def roi2bbox(rois):
"""Convert rois to bounding box format.
Args:
rois (torch.Tensor): RoIs with the shape (n, 5) where the first
column indicates batch id of each RoI.
Returns:
list[torch.Tensor]: Converted boxes of corresponding rois.
"""
bbox_list = []... | 6ea7850a6d32bee2254599871dfb9d9db14e4136 | 349,000 |
import re
def urlReg(msg):
"""Try to match an url."""
m = re.match('^.*(https?://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)', msg)
if m:
return m.group(1)
return | 4199486959cbc32a241f5b378d9a4ba887c1ebc3 | 477,241 |
def snp_count(vcf, chromosome, start, end):
"""
Count the number of snps in the window.
:param vcf: vcf, a vcf file with SNPs and their genomic positions
:param chromosome: str, Chromosome name
:param start: int, Start position of the sequence
:param end: int, End position of the sequence
:r... | c18f52662f96d3013452c4884f506901e9da146b | 73,153 |
def add_one(number):
"""A function that adds one to the number given and returns it"""
return number + 1 | 84c9f4a5de79c1d7232c922875fcbeab4f9fee43 | 527,409 |
def is_palindrome(phrase):
"""Is phrase a palindrome?
Return True/False if phrase is a palindrome (same read backwards and
forwards).
>>> is_palindrome('tacocat')
True
>>> is_palindrome('noon')
True
>>> is_palindrome('robert')
False
Should ignore capi... | af277bc5aad18ed08cf48b523b0f08b84ad4ff0e | 394,760 |
def add(x, y):
"""The sum of two bits, mod 2."""
return (x + y) % 2 | 9c12cbcfd1f693942232c8f8c20fe4e58e21cb85 | 273,658 |
def synset_to_wnid(synset):
""" Converts synset to wnid. Synset is a wordnet node object"""
return synset.offset() | ba68060b66ab6cd12edd7322ed091b4b5244112e | 604,369 |
def str2bins(string):
"""
Parses string as a list of floats, comma separated
as in: "1.2,3,6,7" -> [1.2, 3.0, 6.0, 7.0]
"""
return [float(s) for s in string.split(",")] | c670cc045155ebaa1b8ca9a3a098e7ae4837a7bb | 258,626 |
def schedule_1_amount(responses, derived):
""" Return the amount as defined in schedule 1 for child support """
try:
if derived['show_fact_sheet_b'] or derived['show_fact_sheet_c']:
return derived['guideline_amounts_difference_total']
else:
return float(responses.get('pa... | 33fefc60fc8cb49941b2edaea518c4a57022a946 | 607,495 |
def get_class_name(obj):
"""
A simple template tag to retrieve the class name of
an object.
:param obj: an input object
"""
return obj.__class__.__name__ | 261de168f63336517838e868294c0b177c9e628b | 265,219 |
def player_attr_by_id(roster, player_id, attribute):
"""Returns the attribute of a player given a roaster and a player_id.
Args:
roster (dict): Team roster (returned from API)
player_id (str): Player unique identifier (IDXXXXXXX)
attribute (str): Attribute from roster dictionary.
R... | caf17c0802b1b32fb32bf8397be80dc3baac7016 | 252,741 |
def space_indentation(s):
"""The number of leading spaces in a string
Args:
s: str. The input string.
Returns:
int. The number of leading spaces.
"""
return len(s) - len(s.lstrip(' ')) | 9bc74fc261f7f53d073dfc95ca76ba1ee9db90a4 | 586,648 |
def normalize_slice(s, total):
"""
Return a "canonical" version of slice ``s``.
:param slice s: the original slice expression
:param total int: total number of elements in the collection sliced by ``s``
:return slice: a slice equivalent to ``s`` but not containing any negative indices or Nones.
... | f4f204a3ec0a3da4c4a5b33d27330a2445454597 | 521,291 |
def _get_first_last(details):
"""
Gets a user's first and last name from details.
"""
if "first_name" in details and "last_name" in details:
return details["first_name"], details["last_name"]
elif "first_name" in details:
lst = details["first_name"].rsplit(" ", 1)
if len(lst)... | 2a2ef17441c4243c5e58b74567709b9acb52e01f | 118,368 |
def tag_key(tagname: str) -> int:
"""
Convert a tagname ("w.YYYY.NN" or "w.YYYY.N") into a key for sorting.
"w_2017_1" -> 201701
"w_2017_01" -> 201701
"w_2017_10" -> 201710
etc.
"""
return int(tagname.split("_")[1]) * 100 + int(tagname.split("_")[2]) | 91f3559519299ced3952a430dfdc166a42997d0b | 54,945 |
from typing import Any
def is_options_list(options_list: Any) -> bool:
"""
Checks whether the given value is an options list.
:param options_list: The value to check.
:return: True if it is an options list.
"""
return (
isinstance(options_list, list) and
all(... | 51908a901a39d82ae85f49455eca51b5d0176bb7 | 492,095 |
def extract_chat_id(body):
"""
Obtains the chat ID from the event body
Parameters
----------
body: dic
Body of webhook event
Returns
-------
int
Chat ID of user
"""
if "edited_message" in body.keys():
chat_id = body["edited_message"]["chat"]["id"]
... | 382435ac01dd502f52ad2a5e300830f13cca533d | 237,442 |
def pretty_print_time(time, message=None):
"""Pretty print the given time"""
days = time.days
hours, remainder = divmod(time.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
if message is not None:
print(message)
print(f'\t {days} days, {hours} hours, {minutes} minutes, {secon... | 366caa41f110b984508376cf957d5050a04955e7 | 670,679 |
def isHexDigit(s):
"""
isHexDigit :: str -> bool
Selects ASCII hexadecimal digits, i.e. '0'..'9', 'a'..'f', 'A'..'F'.
"""
return s in "0123456789abcdefABCDEF" | 527295b72c56000654b40ffd42f4b2480be3cfad | 331,910 |
def get_crashreport_key(group_id):
"""
Returns the ``django.core.cache`` key for groups that have exceeded their
configured crash report limit.
"""
return u"cr:%s" % (group_id,) | 484fcd0140fdadadebd5faea01e420d39ed66992 | 67,229 |
import copy
import itertools
def cartesian_exp_group(exp_config, remove_none=False):
"""Cartesian experiment config.
It converts the exp_config into a list of experiment configuration by doing
the cartesian product of the different configuration. It is equivalent to
do a grid search.
Parameters
... | 2a2d3b9f78ec680ac4c39150195fee154e001aeb | 330,284 |
def addText(text, endIndex, namedStyleType, requests):
"""Adds requests to add text at endIndex with the desired nameStyleType.
Returns new endIndex.
Args:
text (String): text to add
endIndex (int): Current endIndex of document. Location to add text to
namedStyleType (String): desir... | 476e1b40d16fa5cbea81933e9ef72318cd770488 | 481,202 |
from operator import xor
def otp(m, k):
"""
Encrypts m using key k as a one-time pad.
This simple returns the xor of each corresponding message and key bit.
"""
assert len(m) == len(k)
return [xor(mm, kk) for mm, kk in zip(m, k)] | ac3b4aa10487b61a7f127a8999a09d30b26922e5 | 411,122 |
def combine_by_append(vector1, vector2):
"""
Combines two lists by appending them.
:param vector1: list of values
:param vector2: list of values
:return: a list created by appending vector1 to vector2
"""
return vector1 + vector2 | 1376c70613b4e8df7628062f20bc58759ddddb92 | 359,585 |
def calculate_velocities(cartesians, timestep=1):
"""
Calculate velocities at each timestep given Cartesian coordinates. Velocities at the first and last point are
extrapolated.
:param cartesians: Cartesian coordinates along trajectory
:param timestep: time step between frames in units of fs, defaul... | ab38b3745b0cd36887924e491e143e99053a197d | 254,470 |
def longest_common_prefix(seq1, seq2):
"""
taken from https://www.quora.com/What-is-the-easiest-way-to-find-the-longest-common-prefix-or-suffix-of-two-sequences-in-Python
:param seq1: first string
:param seq2: second string
:return: the prefix
"""
start = 0
while start < min(len(seq1), ... | 79dbaf1e0ef4859bb7b0e525c09d0273b4dbf590 | 99,325 |
from typing import OrderedDict
def duplicate_word_removal(data: list) -> list:
"""
Removes duplicate words
:param data: The list of dictionaries of the form
:type: [{"Header":"", "Header_keywords": [], "Paragraph_keywords": [], slides:[int]}]
:return: The list of dictionaries with duplicate keywo... | d07eb32ce09284db33a5d2787195afe20ca34184 | 419,891 |
def Clamp(num, a, b):
"""
Returns ``a`` if ``num`` is smaller than
or equal to ``a``, ``b`` if ``num`` is
greater than or equal to ``b``, or ``num``
if it is between ``a`` and ``b``.
Parameters
----------
num : float
Input number
a : float
Lower bound
b : float
... | 2b66d62f8f795ecb4907436cb5c09b150abe9438 | 123,560 |
def np_shape(matrix):
"""
Function to calculate the shape of a numpy.ndarray
Returns the matrix shape
"""
return matrix.shape | 411fb27eae62839a8fc87c577bc7ec8c86bdf0c0 | 379,225 |
def calculate_evaluation_metrics(confusion_matrix):
"""
Calculates the evaluation metrics of the model.
:param confusion_matrix: The confusion matrix of the model.
:return: dictionary, with the metrics of the model.
"""
metrics = dict()
metrics['precision'] = confusion_matrix.get('TP', 1) /... | d2c3ea5b75529d4ae324f22350bf4d65c89fbf7c | 120,086 |
def select_single_mlvl(mlvl_tensors, batch_id, detach=True):
"""Extract a multi-scale single image tensor from a multi-scale batch
tensor based on batch index.
Note: The default value of detach is True, because the proposal gradient
needs to be detached during the training of the two-stage model. E.g
... | 1a389d8ff836fb08f5e5519ec5dd9336d031ec54 | 621,326 |
def str2bits(str_in):
"""
Convert string input to bits.
:param str_in: input string
:return: bits array
"""
result = []
for c in str_in:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
return result | f006773e74b17445258436d5581058349a1572ec | 386,754 |
def nchannels(I):
"""
Return the number of color channels of the image `I`.
"""
D = len(I.shape)
if D == 2:
return 1
elif D == 3:
return I.shape[-1]
else:
raise ValueError("Unrecognized image array shape {}".format(I.shape)) | acab605144a9378ec2adcf719aeb5a65a18f30ee | 259,382 |
def proxy_request_method(request):
"""Parametrized fixture changing request method
(GET / POST / PATCH / ...).
"""
return request.param | a78fd8002e78332644387066a72cb62ff5ea2a4f | 166,437 |
def depad(data):
"""Removes padding characters from the end of b64u encoded strings"""
return data.rstrip('=') | 5ac4f34c54e5f9fa7f008c14419b3bd3bb5b6cfd | 279,411 |
def num2col(col_int: int) -> str:
"""
Convert an Excel column index to a string
e.g. 1 == "A", 27 == "AA" e.t.c.
"""
if not isinstance(col_int, int):
raise ValueError("Invalid data type supplied. Must supply an integer")
col_str = ""
while col_int > 0:
col_int, remainder = di... | 251f2b0d645a4485233873457c025faae79cfdf3 | 500,375 |
def split_container(path):
"""Split path container & path
>>> split_container('/bigdata/path/to/file')
['bigdata', 'path/to/file']
"""
path = str(path) # Might be pathlib.Path
if not path:
raise ValueError('empty path')
if path == '/':
return '', ''
if path[0] == '/':
... | 53b0d1164ecc245146e811a97017f66bb1f032a7 | 9,941 |
def _getvaluefrombuffer(buf, loc):
"""Returns a requested value from buffer.
Function is called recursively.
Parameters
----------
buf : dict
Buffer object
loc : list
List of strings with the requested location within buf
Returns
-------
ret : object
Reqeste... | 09bddb0713c6cd900d450e7b960a6f06b69f656a | 170,041 |
def hex_to_RGB(hexstr):
"""
Convert hex to rgb.
"""
hexstr = hexstr.strip('#')
r, g, b = int(hexstr[:2], 16), int(hexstr[2:4], 16), int(hexstr[4:], 16)
return (r, g, b) | 7084907ff084229fd2b4656aa301ca72a80d2fab | 15,350 |
from typing import Union
from typing import Mapping
from typing import Any
from functools import reduce
import operator
def map_reduce(key_path: Union[str, list[str]],
mapping: Mapping[str, Any]) -> Any:
"""Reduce a mapping, returning a value from an arbitrarily deep hierarcy.
The result of ca... | 5b4d35b724e99d9360ce48984adc28b3d5a02cde | 248,481 |
def get_latest_docdata_payment(payment):
"""
Get the latest docdata payment (DocDataPayment) for given payment (DocDataPaymentOrder).
"""
if payment.docdata_payments.count() > 0:
return payment.docdata_payments.order_by('-created').all()[0]
return None | a462257fe33130e2e49bba218fbd1e38933ee1ad | 338,808 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.