content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def recipe_is_complete(r):
"""Return True if recipe is complete and False otherwise.
Completeness is defined as the recipe containing a title and instructions.
"""
if ('title' not in r) or ('instructions' not in r):
return False
if (r['title'] is None) or (r['instructions'] is None):
... | 78242642b97dbb8e051f74c64b9ef742eff196a1 | 64,948 |
def geom(xs, p):
"""Geometric probability mass function. x=number of desired
Bernoulli trials, p=Success probability of a single Bernoulli
trial. Returns: Probability that the x's trial is the first
success"""
if any(xs<1) or p<0 or p>1: raise ValueError('function not defined')
return ((1-p)**(x... | a71057337b6e62042ab67d6bcd166a16d51ce0b9 | 64,955 |
from pathlib import Path
import gzip
def untar(source: Path, verbose=False) -> Path:
"""
Desc: creates a file with the same extension as the
file contained within the zipped archive and
then writes the contents from the zipped file
into the new file created
Args:
source - Path object for ... | 221c7119456630222e408407540428c7de2507e7 | 64,959 |
import random
def generate_list(list_size, element_min, element_max):
"""Generates a list contianing list_size elements.
Each element is a random int between or equal element_min
and element_max"""
sequence = [random.randint(element_min, element_max)
for num in range(list_size + 1)]
... | 37cd37625ba102082d0b366a9a661295d518af68 | 64,960 |
def is_gzip_file(filename):
"""Returns ``True`` if :obj:`filename` is a GZIP file."""
return filename.endswith(".gz") | 0a485dc25ebe28d23f8293815940dcddef35c417 | 64,961 |
def get_icd9_descript_path(data_dir):
"""Get path of icd9 description file."""
return '{}/{}'.format(data_dir, 'phewas_codes.txt') | 2a32f66af3c57b7c93a9e281371c0c74a8f75465 | 64,964 |
def createHeader(ordinal):
"""Creates the header text for each seperate subexcercise"""
print("")
print("---", ordinal, " program---")
print("")
return 0 | f1c49d7252c52651824ce590fbdfd09601b132ec | 64,965 |
import requests
def fetch_gutenberg_book(id: str) -> str:
"""Fetch a book from Gutenberg, given its ebook id."""
url = "https://www.gutenberg.org/ebooks/{}.txt.utf-8".format(id)
response = requests.get(url)
response.raise_for_status()
return response.text | f0c6d8d3099e08f05b00940c85c4872894406e41 | 64,969 |
import torch
def smooth(x, span):
"""
Moving average smoothing with a filter of size `span`.
"""
x = torch.nn.functional.pad(x, (span//2, span//2))
x = torch.stack([torch.roll(x, k, -1) for k in range(-span//2, span//2+1)]).sum(dim=0) / span
return x | 494590de72e78fcbeb11bacf9214bee4ba6efcf3 | 64,972 |
import random
from typing import List
def generate_seeds(rng: random.Random, size: int) -> List[int]:
"""Generates list of random seeds
:param random.Random rng: random number generator
:param int size: length of the returned list
:return: list of random seeds
:rtype: List[int]
"""
seeds ... | 2e8a66745086c55c142877de2d3422b9eab9f160 | 64,976 |
from typing import List
from typing import Dict
def finalise_squad_data_list(squad_data_list: List, version: str='') -> Dict:
"""Convert a SQuAD data list to SQuAD final format"""
return {
'data': squad_data_list,
'version': version
} | 72caf6d8f0c3c6d17c88767d4cceea28534bd4a8 | 64,977 |
def true_filter(test): # pylint: disable=unused-argument
"""Simply return True regardless of the input.
Designed to be used with `get_best_filter` where no filtering is desired;
intended to have same effect as `IsParticle` function defined in
dataclasses/private/dataclasses/physics/I3MCTreePhysicsLibr... | a7e3e983f133f946c2232e84e29435bd43d12dca | 64,982 |
from typing import List
from typing import Dict
def _mock_translate_response(
target_language: str, source_language: str, model: str, values: List[str],
) -> List[Dict[str, str]]:
"""
A simulated response for the Google Translate Client get_languages() call
https://github.com/googleapis/python-transla... | 7b47fb6cc7ca5dafce444072bbedc29f641a2a05 | 64,991 |
def get_first_data_row(sheet):
""" Find first row in the excel with data (company numbers)
Args:
sheet: worksheet object
Returns:
first row with data
"""
for row in range(1, sheet.max_row):
if str(sheet['A' + str(row)].value).isnumeric():
return row
return ... | 49135b47b1aadfc6bcfbd302dfe14bdb7d1f2cfd | 64,996 |
def get_elements(filename):
""" get elements from file, each line is an element """
elements = list()
with open(filename, 'r') as f:
lines = f.readlines()
return [e.rstrip() for e in lines] | 9482655c3dba061160fc2cea135e7492d6465dba | 64,998 |
def _get_end_nodes(graph):
"""Return list of nodes with just one neighbor node."""
return [i for i in graph.nodes() if len(list(graph.neighbors(i))) == 1] | 5cfb4abcf9323255aa18183e0fb06d668e8131dd | 64,999 |
def pyname_to_xmlname(name):
"""
Convert a Python identifier name to XML style.
By replacing underscores with hyphens:
>>> pyname_to_xmlname('some_name')
'some-name'
"""
return name.replace('_', '-') | 4b950faea8577bfde818afa561dd22aded2f18f4 | 65,003 |
def armstrongNumber(num):
"""assumes num is an int
returns a boolean, True if num is an armstrong number, else False.
An armstrong number = sum of digits ** number of digits
e.g. 371 = 3**3 + 7**3 + 1**3
"""
digit_sum = 0
for digit in str(num):
digit_sum += int(digit) ** 3
return... | 519812a5dd4612c1127225c66be0790e4576eb45 | 65,009 |
def is_windows(repository_ctx):
"""Returns true if the execution platform is Windows.
Args:
repository_ctx: the repository_ctx
Returns:
If the execution platform is Windows.
"""
os_name = ""
if hasattr(repository_ctx.attr, "exec_properties") and "OSFamily" in repository_ctx.attr.ex... | a5bb926198d3aac3f1a81591785e11327dd3e97f | 65,015 |
def init_enemy_size(data):
"""
Initializes enemy size dictionary
:param data:
:return: Enemy size dictionary
"""
snakes = data['board']['snakes']
size_dict = {snake['id']: len(snake['body']) for snake in snakes}
#print('Initialized size_dict')
return size_dict | caa9df938ed61cbede5bdf0f76c1058fd2a56c6a | 65,030 |
def calculate_predicted_value(independent_variable, coefficient):
"""Returns the predicted value for a given input and coefficient"""
return independent_variable * coefficient | 3012eb88264462df58d5c32d00f5f877207e7c48 | 65,031 |
import string
import random
def gen_random_str(length: int, chars: str='uld', *, prefix: str='', suffix: str='') -> str:
"""生成随机字符串
Args:
length: 字符串总长度
chars: 使用的字符种类:'u' - 大写字母,'l' - 小写字母,'d' - 数字
prefix: 字符串前缀
suffix: 字符串后缀
"""
random_part_len = length - len(prefix ... | a09e4b3df1df4b8e390e0ceafa198a3d11f8be2e | 65,047 |
import math
def get_sd(mean, grade_list):
"""Calculate the standard deviation of the grades"""
stan_dev = 0 # standard deviation
sum_of_sqrs = 0
for grade in grade_list:
sum_of_sqrs += (grade - mean) ** 2
stan_dev = math.sqrt(sum_of_sqrs / len(grade_list))
return stan_dev | 216c7704152c7f0cb79109730805740578d648d0 | 65,050 |
def file_path_to_chars(file_path):
"""Return the characters in a file at the given path."""
with open(file_path, 'rb') as f:
return [chr(b) for b in f.read()] | d0352ec9451d93338214a09a9904ef373135f147 | 65,051 |
import re
def get_mfc_requirements(msg):
""" Get set of revisions required to be merged with commit """
requirements = set()
lines = msg.split('\n')
for line in lines:
if re.match('^\s*(x-)?mfc(-|\s+)with\s*:', line, flags=re.IGNORECASE):
pos = line.find(':')
line = lin... | 1fd9ca26e4bec401908c639d18e2ad61acda2c41 | 65,053 |
import logging
def filter_keys(d, fn, log_warn=False):
"""Return a copy of a dict-like input containing the subset of keys where fn(k) is truthy"""
r = type(d)()
for k, v in d.items():
if fn(k):
r[k] = v
elif log_warn:
logging.warning(f"filtered bad key: {k}")
r... | 9880ee040673f2c7c0ba44875d72ce3e45fc9bfd | 65,061 |
from typing import Optional
from typing import Any
from typing import OrderedDict
def collection_gen(resources: list, topic_uri: str, uri: str, members: bool=False) -> Optional[Any]:
"""
Generate an OrderedDict for a IIIF Presentation API collection from
a list of manifest Ordered Dicts (with @type, @id, ... | 0123fd946efd4b67da13402fdad1a370ade07377 | 65,063 |
def count_linear(model,output_size):
"""count FLOPs of linear layer
:param model: model object
:param output_size: integer output size of the model
:returns: FLOPs of linear layer
"""
input_size=model.rnn.hidden_layer_sizes[-1]
return input_size*output_size*2 | 4f6729df546cb29afbbd5f610fbbe59095794597 | 65,064 |
def ask_correct_or_jump(folder_path_project: str, list_file_path_long: list) -> bool:
"""ask to test again or skip project
Args:
folder_path_project (str): project folder_path
list_file_path_long (list): list of file_path who has path_lenght above max_path
Returns:
bool: True if ch... | 0419cbb536435b811fca520121ef25e73b96b91b | 65,066 |
import torch
def matern12(r):
"""Matern 1/2 function"""
return torch.exp(-r) | 015efb840b4ef249561b359703195677bc4d1390 | 65,070 |
import csv
def read_in_data_from_file (environment, pathname):
"""
Open file and read data into list of lists
Parameters
----------
environment : list of lists
the datastructure into which the content of the input file is read.
pathname : string
represents the file name includ... | 2bbd16c638f3f2100143a653831f09371b6827cf | 65,072 |
import itertools
def padIterable(iterable, padding, count):
"""
Pad C{iterable}, with C{padding}, to C{count} elements.
Iterables containing more than C{count} elements are clipped to C{count}
elements.
@param iterable: The iterable to iterate.
@param padding: Padding object.
@param co... | 793cf523f5f29c4e1ca0b37cb10f314f1cd903fa | 65,073 |
def union_overlapping(intervals):
"""Union any overlapping intervals in the given set."""
disjoint_intervals = []
for interval in intervals:
if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):
disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)
else:
disjoint_inte... | 946e095d219282c4091cf037a78a7d238cc566a8 | 65,077 |
import math
def dist(*args):
"""Calculates the Euclidean distance between two points. Arguments are of the form
dist(x1,y1,x2,y2)
dist(x1,y1,z1,x2,y2,z2)"""
if len(args) == 4:
return math.sqrt(
sum([(a - b) ** 2 for a, b in zip(args[:2], args[2:])]))
else:
assert (len(a... | dfa0e5bf0ae002c682d14804260347f0626af68e | 65,079 |
def assign_subtasks(total_num, num_tasks=2):
"""
Split the task into sub-tasks.
Parameters:
-----------
total_num: int
Total number of the task to be split.
num_tasks: int
The number of sub-tasks.
Returns:
--------
subtask_ids: list of list
List of the list ... | ec6246f3b47e99d55e0502fe1165dcb232d8acef | 65,080 |
def horner( x, *poly_coeffs ):
""" Use Horner's Scheme to evaluate a polynomial
of coefficients *poly_coeffs at location x.
"""
p = 0
for c in poly_coeffs[::-1]:
p = p*x + c
return p | 236352cb4ae6de13cf8fe6ddfad782af4aba1c6b | 65,083 |
def get_submatrix(matrices, index, size, end_index=None):
"""Returns a submatrix of a concatenation of 2 or 3 dimensional
matrices.
:type matrices: Variable
:param matrices: symbolic 2 or 3 dimensional matrix formed by
concatenating matrices of length size
:type index: int
... | 2331456bf2418a02f69edf330207ce9faf3ee2b7 | 65,086 |
def stringtodigit(string: str):
"""
attempts to convert a unicode string to float or integer
:param str string: String to attempt conversion on
:return:
"""
try:
value = float(string) # try converting to float
except ValueError:
try:
value = int(string) # try c... | acf53b4f799eb202e0d4d6f664c842d61b6afc26 | 65,091 |
def pad(region, margins):
"""
Pad region according to a margin
:param region: The region to pad
:type region: list of four floats
:param margins: Margin to add
:type margins: list of four floats
:returns: padded region
:rtype: list of four float
"""
out = region[:]
out[0] -=... | a56085f5e42122307cd4236d051447c66aaa68f9 | 65,093 |
import string
def get_available_letters(letters_guessed):
""" letters_guessed: list (of letters), which letters have been
guessed so far
Returns: string (of letters), comprised of letters that represents
which letters have not yet been guessed.
"""
lo, g = string.ascii_lowercase, lette... | e7eb61eeab6be37286e6ab39ff07bc3bfa3041ea | 65,094 |
def to_seconds(time_obj):
""" Convert a RationalTime into float seconds """
return time_obj.value_rescaled_to(1) | 80c19f24870d5f3b95f263906ec9e106330015a4 | 65,101 |
def selection_sort(some_list):
"""
https://en.wikipedia.org/wiki/Selection_sort
Split the list into a sorted/unsorted portion. Go through the list from left to right, starting with position 0 in
the unsorted portion. When we find the minimum element of the unsorted portion, swap it to the end of the sor... | 47bb82584e87cd3f00d3a276d0d64682b00e46cb | 65,107 |
def pretty_exception(err: Exception, message: str):
"""Return a pretty error message with the full path of the Exception."""
return "{} ({}.{}: {})".format(message, err.__module__, err.__class__.__name__, str(err)) | 0dfabae14bdf1df4073248e25b1e3d74573c1aed | 65,109 |
from pathlib import Path
def home_directory() -> str:
"""
Return home directory path
Returns:
str: home path
"""
return str(Path.home()) | 8c9c1ccccfc547a26794e5494975e27cde4e73ef | 65,110 |
def _get_image_type_from_array(arr):
"""Find image type based on array dimensions.
Raises error on invalid image dimensions.
Args:
arr: numpy array. Input array.
Returns:
str. "RGB" or "L", meant for PIL.Image.fromarray.
"""
if len(arr.shape) == 3 and arr.shape[2] == 3:
# 8-bit x 3 colors
... | cf3b8aa43a8dc35c000c7a6f5d68eae6ae96a418 | 65,118 |
def get_label_instances(response, target):
"""Get the number of instances of a target label."""
for label in response['Labels']:
if label['Name'] == target:
return len(label['Instances']) | ec0b24fac803148ea8e9b0e07d854d0ec953c63f | 65,123 |
def is_remote(path):
"""Determine if a uri is located on a remote server
First figures out if there is a ':' in the path (e.g user@host:/path)
Then looks if there is a single @ in part preceding the first ':'
:param path: uri/path
:type path: str
:return: True if path points to remote server, Fa... | 979acfc548f5d550d249fceadad6f9ece4f40035 | 65,124 |
import logging
def log_data_summary(X, Y):
"""Sanity check that logs the number of each class.
Args:
X (np.ndarray): Data set
Y (np.ndarray): Labels
Returns:
None
"""
N_total = Y.size
N_1 = Y.sum()
N_0 = N_total - N_1
logging.info("{:d} total examples. {:.1f} ... | 3c706b1609791882a1e54a46c38dc1fa7c5678d9 | 65,126 |
def get_xml_attributes(node):
"""Return the xml attributes of a node as a dictionary object"""
attr = {}
for k, v in node._get_attributes().items():
attr[k] = v
return attr | 8bb013818ed9bba5c4b73d662c4ad11c6dae05e6 | 65,132 |
def max_returns(prices):
"""
Calculate maxiumum possible return in O(n) time complexity
Args:
prices(array): array of prices
Returns:
int: The maximum profit possible
"""
if len(prices) < 2:
return 0
min_price_index = 0
max_price_index = 0
current_min_pric... | 08bc3e900818f0f93927c2e70fa8a38d83a91393 | 65,133 |
def RemoveSlash( dirName ):
"""Remove a slash from the end of dir name if present"""
return dirName[:-1] if dirName.endswith('/') else dirName | 0eabb5d82c3419caccde674fbae150d852e94fb0 | 65,134 |
def to_bool(val):
"""
Copied from
https://github.com/python-attrs/attrs/blob/e84b57ea687942e5344badfe41a2728e24037431/src/attr/converters.py#L114
Please remove after updating attrs to 21.3.0.
Convert "boolean" strings (e.g., from env. vars.) to real booleans.
Values mapping to :code:`True`:
... | 24c1ea4fa76b6ac6752d1255c0dc8203b406ca45 | 65,136 |
import requests
def generic_request(method, url, **kwargs):
"""An alias for requests.request with handling of keystone authentication tokens.
:param method: The HTTP method of the request
:param url: The url to request
:param **kwargs: The keyword arguments defined below as well
as any additi... | e7e2493fee6a76430984492880283f1e0dbbcd19 | 65,139 |
def backoff_constant(n):
"""
backoff_constant(n) -> float
Constant backoff implementation. This returns the constant 1.
See ReconnectingWebSocket for details.
"""
return 1 | 345ab3c2c0147a4f102e9518cb4022b55ef9cb7c | 65,140 |
import re
def find_num_inquiries(Aop, parameters_size):
"""
Find the number of parameter inquiries. Parameter inquiries may not be the
same as the length of parameters array. The "parameter size" is the product
of the "number of the parameter inquiries" and the "number of the
parameters of the ope... | 6699cc72fdddcedeb923368db62a31c869d371d5 | 65,142 |
import time
def collect_host_processes(processes, done_functs=()):
"""Returns a summary of return codes for each process after
they are all finished.
done_functs: iter of functs
Each function in done_functs will be executed with the args (processes, p)
where p is the process that has ... | 4e600079750357851a0675e742dfc9ba14efc7b9 | 65,145 |
def format_number(number, num_decimals=2):
"""
Format a number as a string including thousands separators.
:param number: The number to format (a number like an :class:`int`,
:class:`long` or :class:`float`).
:param num_decimals: The number of decimals to render (2 by default). If no... | 9048a53c239072f1b21b2eb4e6446ae631ea4ace | 65,150 |
from typing import Iterable
from typing import List
from typing import Any
def unique(iterable: Iterable) -> List[Any]:
"""Return a list of all unique elements in iterable.
This function preserves order of elements.
Example:
.. code-block:: python3
unique([3, 2, 1, 1, 2]) -> [3, 2, 1]
... | ca982d339e99caf6f04ac8d89ba9ac09313e18b5 | 65,153 |
import collections
def dict_to_class(dobj):
"""Convert keys of a dict into attributes of a class.
"""
Dclass = collections.namedtuple('Dclass', dobj.keys())
return Dclass(**dobj) | ede87edf15a11036679eaf066acbadcc1423f3ef | 65,164 |
def getDistance(x1, y1, x2, y2):
"""
Using the standard distance Formula
**2 is to perform square operation
**5 is to perform square root operation
"""
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 | 783196001758dc8b052547459b56b33cc3773c10 | 65,166 |
from typing import Tuple
def decode_fault(tup: Tuple[int, ...]) -> str:
"""Decode faults."""
faults = {
13: "Working mode change",
18: "AC over current",
20: "DC over current",
23: "F23 AC leak current or transient over current",
24: "F24 DC insulation impedance",
... | 66399148fef9706db7b51a1d1ea8eecebccdbb88 | 65,168 |
def normalize_job_id(job_id):
"""Convert the job id into job_id, array_id."""
return str(int(job_id)), None | 1573a8db5fa0ea84bf6ef8062bcfaf92d6a504ac | 65,169 |
def to_bool(s: str) -> bool:
"""
Converts the given string to a boolean.
"""
return s.lower() in ('1', 'true', 'yes', 'on') | 3d694f37927caf25d5af579d6d78168b21e99ea7 | 65,170 |
def calculateIoU(startX_, startY_, endX_, endY_, x1, y1, x2, y2):
"""
Calculate the intersection over union (IoU) score for two bounding boxes.
:param startX_: Upper left x coordinate of the first object detection.
:param startY_: Upper left y coordinate of the first object detection.
:param endX_: ... | d682b16593daef33d841f5dc84f16cd2bddc35a0 | 65,172 |
import torch
def accuracy_fn(y_true, y_pred):
"""Calculates accuracy between truth labels and predictions.
Args:
y_true (torch.Tensor): Truth labels for predictions.
y_pred (torch.Tensor): Predictions to be compared to predictions.
Returns:
[torch.float]: Accuracy value between y... | 6ca674aac03b153a2608e8a2e5d3abfce1bbc6d2 | 65,177 |
def compute_p_r_f1(gold_tuples, pred_tuples):
"""
Compute Precision/Recall/F1 score for the predicted tuples.
Parameters
----------
gold_tuples : set
Set of gold-standard 4-tuples.
pred_tuples : set
Set of predicted 4-tuples.
Returns
-------
scores : tuple
A... | 6ebfee38ed3532c4657fefe8d4499dd28b595593 | 65,180 |
def twos_complement(val: int, bits: int) -> int:
"""
returns the two's complement
of the integer passed in.
bits arg needed to determine the first bit
"""
if (val & (1 << (bits - 1))) != 0:
val = val - (1 << bits)
return val | 072a453cb25ffa49679ac3895337a1b0dfa773c8 | 65,183 |
def query(db, query_statement):
"""
执行查询语句,并返回结果
:param db: 数据库实例
:param query_statement: 查询语句
:return: 查询结果
"""
cursor = db.cursor() # 获得游标
cursor.execute(query_statement)
result = cursor.fetchall()
return result | 4950ecf3b15c6d1b0a46b2310bd003b3b4bce01d | 65,184 |
def _remove_atom_numbers_from_distance(feat_str):
"""
Remove atom numbers from a distance feature string.
Parameters
----------
feat_str : str
The string describing a single feature.
Returns
-------
new_feat : str
The feature string without atom numbers.
... | 95daddf73364d3fb619c7fbba0ac2d57a3680952 | 65,190 |
def table_delta(first_summary, second_summary):
"""
A listing of changes between two TableSummarySet objects.
:param first_summary: First TableSummarySet object
:param second_summary: Second TableSummarySet object
:return: Change in number of rows
"""
differences = []
for first, second ... | 96c3931e4891c14a3d0f84a87abbec2ab85bf48d | 65,192 |
def cdata_section(content):
"""
Returns a CDATA section for the given ``content``.
CDATA sections are used to escape blocks of text containing characters which would
otherwise be recognized as markup. CDATA sections begin with the string
``<![CDATA[`` and end with (and may not contain) the stri... | f3cd615deb5b558d1318ef7174612d2f5a67e95e | 65,196 |
def combine_options(options=None):
""" Returns the ``copy_options`` or ``format_options`` attribute with spaces in between and as
a string. If options is ``None`` then return an empty string.
Parameters
----------
options : list, optional
list of strings which is to be converted into a sing... | 86f508aa2dba4f0db1b2824ff525f987cff3db24 | 65,197 |
def _dd_id_to_b3_id(dd_id):
# type: (int) -> str
"""Helper to convert Datadog trace/span int ids into B3 compatible hex ids"""
# DEV: `hex(dd_id)` will give us `0xDEADBEEF`
# DEV: this gives us lowercase hex, which is what we want
return "{:x}".format(dd_id) | fffa8b2e46796cf154197c9f311e0aeba62d0d0a | 65,199 |
def noneOrValueFromStr(s):
"""Return `None` if `s` is '' and the string value otherwise
Parameters
----------
s : str
The string value to evaluate
Return
------
`None` or the string value
"""
r = None if not s or not s.strip() or s.upper() == 'NONE' else s
return r | ad50b520249f42c9567e02514c7760af881e1bcc | 65,202 |
def calcular_moles(presion: float, volumen: float, temp_celsius: float) -> float:
""" Ley de los gases ideales
Parámetros:
presion (float): Presión del gas, en Pascales
volumen (float): Volumen del gas, en litros
temp_celsius (float): Temperatura del gas, en grados centígrados o Celsius
Re... | a81edeeed6dc771f852c76fd2c967258bb751afe | 65,205 |
def test_create_dataframe(df, column_names):
"""
Test if the DataFrame contains only the columns that you specified as the second argument.
Test if the values in each column have the same python type
Test if there are at least 10 rows in the DataFrame.
:param df:
:param column_names:
:return... | cacd0b1a6766f0440edec5ac6198337c56e7d365 | 65,206 |
import click
def good(text: str) -> str:
"""Styles text to green."""
return click.style(f"INFO: {text}", fg="green", bold=True) | 08e3da017d944fdb5b86c2e92b79ac9dc798b6a6 | 65,219 |
def get_jaccard_score(a, s):
"""
Function that computes the jaccard score between two sequences
Input: two tuples; (start index of answer, length of answer). Guaranteed to overlap
Output: jaccard score computed for the two sequences
"""
a_start = a[0]
a_end = a[0]+a[1]-1
start = s[0]
... | c395ff7ab685e19ee893bc90ea2b6baf85efa21d | 65,221 |
import re
def _words_matcher(words):
"""Construct a regexp that matches any of `words`"""
reg_exp = "|".join("{}".format(word) for word in words)
return re.compile(reg_exp, re.I) | efdf898e3ab1c648e3c86edaac524d21dfb3d7cf | 65,223 |
import math
def phi(x):
"""Cumulative distribution function for the standard normal distribution
Taken from python math module documentation"""
return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0 | 5c2b65dfa33c1f7c4cacabba98b3abaede26a059 | 65,227 |
from typing import List
def output_lines_to_code_block(output_lines: List[str]) -> List[str]:
"""Translate the output of a help command to a RST code block."""
result = (
[".. code-block::", ""]
+ [" " + output_line for output_line in output_lines]
+ [""]
)
result = [line.r... | b1660049717fc3d52c418f4154bb8e8f3336e239 | 65,228 |
def cal_anomaly_Y(df, df_ref):
"""
Calculates yearly averaged temperature anomaly (departure) from the reference period.
Parameters:
- df: DataFrame from which anomaly is calculated
- df_ref: DataFrame of the reference period
Returns:
- df_Y: yearly averaged anomaly
- df_... | f05b01cc33f7d9bb1fb702bf3cfce56dbe403000 | 65,229 |
def formatted_bytes(bytes_number):
"""
Given a number of bytes, return a string with a nice format
"""
if bytes_number >= 1024 ** 4:
return f"{bytes_number / 1024 ** 4:.1f} TB"
if bytes_number >= 1024 ** 3:
return f"{bytes_number / 1024 ** 3:.1f} GB"
if bytes_number >= 1024 ** 2:... | 2da92ca3ac6c0f91655d4843c9cb532ed78a5ab1 | 65,230 |
def format_dword(i):
"""Format an integer to 32-bit hex."""
return '{0:#010x}'.format(i) | c3cab18aa7dc3ac4b8cbcc6282b06839aab0bb7b | 65,233 |
def is_derived_node(node):
"""
Returns true if this node is derived (i.e. built).
"""
return node.has_builder() or node.side_effect | 619000446328a693eec4bb0f027eb183bccd42c6 | 65,236 |
import itertools
import re
def remove_control_chars(s):
"""Remove control characters
Control characters shouldn't be in some strings, like channel names.
This will remove them
Parameters
----------
s : str
String to check
Returns
-------
control_char_removed : str
... | f4d35822d4dc9e9a32bdcfe797a4133d9695fb3e | 65,237 |
def good_box(sudoku_board, row_num, col_num, num):
"""
Checks to make sure that a given "box" in a sudoku board is possible if an
int num is placed into that "box"
"""
boxes = [sudoku_board[3 * i: 3 * (i + 1), 3 * j: 3 * (j + 1)] for i in range(3) for j in range(3)]
if num not in boxes[(row_num ... | 4a49adeeb60f9581b973d10740b1040d17ad293e | 65,240 |
def get_documents(cls, ids):
"""Returns a list of ES documents with specified ids and doctype
:arg cls: the class with a ``.search()`` to use
:arg ids: the list of ids to retrieve documents for
"""
ret = cls.search().filter(id__in=ids).values_dict()[:len(ids)]
return list(ret) | 85d84315d70c70b029d1de83862b71611b05d4f6 | 65,241 |
import torch
def to_ca_mode(logits: torch.Tensor, ca_mode: str = "1/2/3") -> torch.Tensor:
"""
Converts the logits to the ca_mode.
Args:
logits (torch.Tensor): The logits.
ca_mode (str): The cornu ammoni division mode.
Returns:
torch.Tensor: The corrected logits.
"""
... | 151a420764d37a7b4b50acfeb86979c9d03a6f83 | 65,243 |
def round_half(x):
"""Rounds a floating point number to exclusively the nearest 0.5 mark,
rather than the nearest whole integer."""
x += 0.5
x = round(x)
return x-0.5 | 26fa072decf8b66a8a8ab54821d8cc297e311051 | 65,250 |
from typing import Dict
from typing import Optional
from typing import Iterable
def get_attrib_value(attribs: Dict[str, str],
name: str,
ns: str,
value_prefixes: Optional[Iterable[str]] = None) -> Optional[str]:
"""
Retrieves the value of an attri... | 97aa9d0fabdd66732fe3be033add2009e4be32ab | 65,253 |
def tokens_ready(setcookies, tokens):
"""check if all required tokens are present in set-cookies headers"""
if setcookies == None or tokens == None:
return False
_tokens = tokens[:]
for tk in setcookies:
if tk in _tokens:
_tokens.remove(tk)
if len(_tokens) == 0:
r... | b290bc15223d878891aea14dea1d448d25fe0061 | 65,257 |
def convert_16bit_pcm_to_byte(old_value: int) -> int:
"""Converts PCM value into a byte."""
old_min = -32768 # original 16-bit PCM wave audio minimum.
old_max = 32768 # original 16-bit PCM wave audio max.
new_min = 0 # new 8-bit PCM wave audio min.
new_max = 255 # new 8-bit PCM wave audio max.
byte_val... | 29af84a0e86b23ec66558faeebb091432feef02a | 65,259 |
def _files_header_size_calc(files, farc_type):
"""Sums the size of the files header section for the given files and farc_type data."""
size = 0
for fname, info in files.items():
size += len(fname) + 1
size += farc_type['files_header_fields_size']
return size | 683edc524a2f353cae8c974f5c72616bddafa27a | 65,263 |
def _feet_to_meters(length):
"""Convert length from feet to meters"""
return length * 2.54 * 12.0 / 100.0 | bde2dc9201d8b50b831334fee2f44ea7310057ca | 65,265 |
def flatten(list_a: list):
"""Problem 7: Flatten a Nested List Structure,
Parameters
----------
list_a : list
The input list
Returns
-------
flat : list
The flattened input list
Raises
------
TypeError
If the given argument is not of `list` type
""... | ec229c1dcfd575b7dd0fd50f45bc6faa1f52af08 | 65,269 |
def sigmoid_derivative(x):
"""Derivative to the Sigmoid function"""
return x * (1 - x) | 58d9f70d54d64b72a22834ffae61b8722e3f343b | 65,272 |
def split_df_into_chunks(df, n_chunks):
"""
Split passed DataFrame into `n_chunks` along row axis.
Parameters
----------
df : DataFrame
DataFrame to split into chunks.
n_chunks : int
Number of chunks to split `df` into.
Returns
-------
list of DataFrames
"""
... | 314fc463100e739d3c20a1edb9e9f5699591ae98 | 65,273 |
def replace_at(string,old,new,indices):
"""Replace the substring "old" by "new" in a string at specific locations
only.
indices: starting indices of the occurences of "old" where to perform the
replacement
return value: string with replacements done"""
if len(indices) == 0: return string
ind... | a136b498a627aba3ebdf6ed3c339a272c88dd3e3 | 65,277 |
def get_sort_params(input_params, default_key='created_at',
default_dir='desc'):
"""Retrieves sort keys/directions parameters.
Processes the parameters to create a list of sort keys and sort directions
that correspond to the 'sort_key' and 'sort_dir' parameter values. These
sorting ... | 6e79ea2c03eb3fa12086e6740b4860069be22fe5 | 65,278 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.