content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _get_db_subnet_group_arn(region, current_aws_account_id, db_subnet_group_name):
"""
Return an ARN for the DB subnet group name by concatenating the account name and region.
This is done to avoid another AWS API call since the describe_db_instances boto call does not return the DB subnet
group ARN.
... | db6736d9e5d56eb2940875f7564c6293db2c080e | 652,821 |
def count_words(text):
"""Count the words of text passed as argument."""
total_words = 0
for word in text.split("\n"):
if word.strip():
total_words += 1
return total_words | dfdb91870907c02844690c0a198bf993265bfa2d | 652,823 |
import pickle
def load_from_pickle(load_path):
"""Deserialize data from pickle file.
:param load_path: (str) Path of file to load
:return: (Python obj) Deserialised data
"""
with open(load_path, "rb") as file:
data = pickle.load(file)
return data | 89ac2dfaab0b855fee77111d1d1f1f1a16d22fa6 | 652,826 |
def _get_monthly_values(df):
"""Accepts a Panda's DataFrame with columns ['month', 'average', and 'count'].
Returns a list of dicts ensuring all possible months have values. Months
not listed in DataFrame assigned average and count of 0."""
months = ['April', 'May', 'June', 'July', 'August', 'September',
'Octo... | a75e197ef36d71325f9c66e6a11e1f7ab9b76178 | 652,830 |
import torch
def get_xG_and_goals(preds, labels):
"""
Calculate expected goals and goals.
Args:
preds (tensor or lists of tensors): predictions. Each tensor is in
in the shape of (n_batch, num_classes). Tensor(s) must be on CPU.
labels (tensor or lists of tensors): correspondin... | fdf4bcdd3bbe880362d11c970fd63377d6875269 | 652,831 |
def _list_comprehensions(obj, item=None, return_tuple=False, make_none=False):
"""
Generates a new list/tuple by list comprehension.
Args:
obj (Union[int, list, tuple]):
If integer, it will be the length of the returned tuple/list.
item: The value to be filled. Default: None.
... | fa23fa13175e7fb3dccd097a05be0080c7a48d4a | 652,834 |
def is_basetype(value):
"""
Returns:
(bool): True if value is a base type
"""
return isinstance(value, (int, float, str)) | d7969ba34f87aa954c9127a0cc89ba3438f3fcbc | 652,835 |
import math
def interleave(left_size, right_size):
""" Finds the number of possible ways to interleave the left and right sub tree
We are interested only in the combinations with fixed ordering, giving the formula:
(left_size + Right_size)! / (left_size! * right_size)
"""
return math.factorial(l... | f23388ba7b9b0c03141e3612328ba9b6740e3502 | 652,836 |
def poly_to_integer(coeffs, order):
"""
Converts polynomial to decimal representation.
Parameters
----------
coeffs : array_like
List of polynomial coefficients in descending order.
order : int
The coefficient's field order.
Returns
-------
int
The decimal r... | 5ab18d47c047ea857eea84226b35b90dc317d557 | 652,837 |
import ntpath
def get_file_name(file_key):
"""
Returns the name of an email file based on the full s3 file path
:param file_key: the file path
:return: string
"""
return ntpath.basename(file_key) | 898f97c90f6edf862d7b30e2cbd2918bc37c3af2 | 652,844 |
def GenZeroStr(n):
"""Generate a bunch of zeroes.
Arguments:
n -- Number of zeroes
Returns: string
"""
return "".join(["0"] * n) | 744b77789e96cc287b43f1d7080a63722479ce96 | 652,845 |
def patch_response(response):
"""
returns Http response in the format of
{
'status code': 200,
'body': body,
'headers': {}
}
"""
return {
'statusCode': response.status_code,
'headers': dict(response.headers),
'body': response.content.decode(),
'isBa... | 4a4f073e8fa242803b83508c4e581e0be2020fff | 652,846 |
def formatPrayers(prayers):
"""
Convenience function that re-formats prayer times to a format that is
easier to use with other functions.
For example,
INP: ["2019-01-27", "05:05", "11:53", "14:58", "17:19", "18:49"]
OUT: ["2019-01-27 05:05",
"2019-01-27 11:53",
"2019-01-27 ... | 51fe5bea4831dab2c5be901da0df789b00e053b2 | 652,849 |
def format_seconds(ticks):
"""
Given ticks (int) returns a string of format hour:minutes:seconds
"""
seconds = ticks / 20
hours = int(seconds / 3600)
seconds = seconds - hours * 3600
minutes = int(seconds / 60)
seconds = seconds - minutes * 60
seconds = round(seconds, 3)
return s... | 62fa0788ed4db20d5669f99e6423856cf3d46b15 | 652,853 |
def f(r: int, t: int, Cf: float) -> float:
"""Calcula el monto de depósito anual teniendo en cuenta la tasa de
interés, el tiempo y el monto a retirar.
:param r: tasa de interes anual
:r type: int
:param t: tiempo
:r type: int
:param Cf: monto a retirar
:r type: float
:return: monto... | 631d65b2376427412483241e52964e70317f7898 | 652,856 |
def rescale_layout(Y, scale=1):
"""Return scaled position array to (-scale, scale) in all axes.
The function acts on NumPy arrays which hold position information.
Each position is one row of the array. The dimension of the space
equals the number of columns. Each coordinate in one column.
To resca... | 97d297663a2848e469e021aa1e371535eda6636e | 652,860 |
import json
def gen_send_data(data:str):
"""This function converts the given data to a JSON
string that can be passed to WhatsApp to send a message.
Args:
data (string): The message to be sent.
"""
message_data = {
"data": [
{
"message": data,
... | abdd867f5c27a60fbe65f1327975c09cc2a56d81 | 652,861 |
import torch
def _get_seg_ids(ids, sep_id):
""" Dynamically build the segment IDs for a concatenated pair of sentences
Searches for index SEP_ID in the tensor
args:
ids (torch.LongTensor): batch of token IDs
returns:
seg_ids (torch.LongTensor): batch of segment IDs
example:
... | 22936d9c5d37ab2bb643ae75402710fc097f271e | 652,875 |
def heun_step(f, x0, t0, t1):
"""
One time step of Heun's method
f : function dx_dt(t0, x0)
x0 : initial condition
t0 : this step time
t1 : next step time
"""
# time step
delta_t = t1 - t0
# slope
s1 = f(t0, x0)
# next step by Euler
x1_euler = x0 + s1 * delta_t
... | c36de034d0ec049c3a65a71f217a0e5e1fef2111 | 652,876 |
import requests
def download_insee_excel(url, output_file, verbose=False, check=True):
"""Downloads data from url to an Excel file.
Args:
url (str): An url to request for the excel data.
output_file (str): The output excel filepath.
verbose (boolean): A verbose indicat... | 4c28bbac01e1f8816d9ad02eb71df1333e3f48d2 | 652,877 |
def J2kWh(x):
"""J -> kWh"""
return x/1000./3600. | 63992882b4f8a5bb0c6682f5f0a458e565d4ec4b | 652,878 |
def product_sum(record: list) -> list:
"""Return a list that contains the sum of each prodcut sales."""
return [sum(i) for i in record] | 00db2d32b1b1fc80cb29f6b859edde64d25be78c | 652,879 |
def calc_check_digit(number):
"""Calculate the check digit. The number passed should not have the
check digit included."""
digits = [int(c) for c in number]
checksum = (
7 * (digits[0] + digits[3] + digits[6]) +
3 * (digits[1] + digits[4] + digits[7]) +
9 * (digits[2] + digits[5]... | 05ff30b39c286939d174a01f3f29144a72e3a1df | 652,883 |
def sensor_error(raw_sensor_value):
"""Actual sensor error derived from field tests."""
return (raw_sensor_value + 2.5) / 1.32 | bc9cf40071198d38d638326c647c482a49f75a0d | 652,885 |
def is_color(s):
"""Test if parameter is one of Black or Red"""
return s in "BR" | 9fdb97989bfed9596188f1e0b659345afdac4c1d | 652,886 |
from datetime import datetime
import pytz
def utc_offset(time_zone: str) -> int:
"""Convert time zone string to utc offset integer for hour diff."""
now = datetime.now(pytz.timezone(time_zone))
offset = now.utcoffset()
if offset:
return int(offset.total_seconds() / 3600)
return 0 | 0d6e8d69de1f4b374fcff553aa4d105def294f8d | 652,888 |
def not_rpython(func):
""" mark a function as not rpython. the translation process will raise an
error if it encounters the function. """
# test is in annotator/test/test_annrpython.py
func._not_rpython_ = True
return func | 7d5f36a71844d84093e50485e0598f8e0e257bfd | 652,892 |
import re
def collapse_spaces(value):
"""
First replace multiple newlines with a single newline,
then collapse multiple non-newline whitespace characters
"""
return re.sub(r'(?![\r\n])\s+', ' ', re.sub(r'[\r\n]+', '\n', value)) | 60e50e0efe7ca18b8228be8de48a154d159444a6 | 652,896 |
def calc_life(trajs, ub=5, lb=-5):
"""
Identifies transition paths and returns lifetimes of states.
Parameters
----------
trajs : list of lists
Set of trajectories.
ub, lb : float
Cutoff value for upper and lower states.
"""
try:
assert ub > lb
e... | 4feeeb9d8dd0e9457db4e8852c38f4de770289b7 | 652,898 |
def nx(request):
"""Number of model states."""
return request.param | 6afb7924e442f30c9d4d5e581b9e51e1a54d0287 | 652,902 |
def get_ns_from_rel(full_ns:str, rel_from:str, comp:str, sep: str = '.') -> str:
"""
Converts a relative import into a full namespace
Args:
full_ns (str): The namespace that import is relative to
rel_from (str): from part of import such as ``..uno.x_interface``
comp (str): Component... | b21ffb2ca3389e9d61a47c793c3cead0e7418621 | 652,903 |
def _empty_filter(arg):
"""Place holder for a filter which always returns True.
This is the default ``image_filter`` and ``collection_filter``
argument for ``fetch_neurovault``.
"""
return True | e131be7b0ee00f5f63c6a2c223aaa274588da74c | 652,905 |
def prepare_embedding_config(args):
"""Specify configuration of embeddings.
"""
# Device
args.ent_emb_on_cpu = args.mix_cpu_gpu
# As the number of relations in KGs is relatively small, we put relation
# emebddings on GPUs by default to speed up training.
args.rel_emb_on_cpu = False
prin... | 790613c3e87e48aae3a50aa14aaec50c12934c2a | 652,906 |
def estimatePiSquared(n):
"""
Estimates that value of Pi^2 through a formula involving partial sums.
n is the number of terms to be summed; the larger the more accurate the
estimation of Pi^2 tends to be (but not always).
"""
partialSum = 0 # Initializing
# Implementation of the mathema... | 800506347555f5b6bd693ee5b0e31d66ce696f5d | 652,908 |
def get_volume_fn_from_mask_fn(mask_filename):
"""Extract volume path from mask path"""
return mask_filename.replace("S-label", "") | a85bca3624b317fa9c85d15cc4141cbb4e9ab6ef | 652,913 |
def get_colour(series_options, series_name):
"""Return the graph colour for the series specified."""
if series_options is None:
return None
if series_name in series_options:
if "colour" in series_options[series_name]:
return series_options[series_name]["colour"]
return None | baacaf514f9ec27df96f90c23b5f18283c7da38c | 652,914 |
def text_to_paras(text, aux=""):
"""
:in: str text
list of str: paras = text_to_paras(text, aux='')
aux = '.' for use in baidutr batch translate
seg text to paras
newline delimiters a para
empty lines ignored
"""
# lines = text.split('\n')
lines = text.splitlines()
lines = ... | ea4b3cf7ecf906ace038fba1f6596c6a8611e066 | 652,918 |
def pay_excess(principal, minimum, remainder):
"""Pay any excess remaining after making minimum payments."""
excess = remainder
if principal - excess <= 0:
excess = principal
remainder = remainder - principal
else:
remainder = 0
return principal - excess, minimum + excess, ... | 5ed7133f23430aa7373d172516e29b6e29d9db1d | 652,919 |
def sanitize_column_list(input_column_list):
"""Remove empty elements (Nones, '') from input columns list"""
sanitized_column_list = [input for input in input_column_list if input]
return sanitized_column_list | 77b635cd5589f46b9381803893b2c8d36cdcdcae | 652,921 |
from functools import reduce
def compose(*args):
"""Composes all the given function in one."""
return reduce(lambda fun, tion: lambda arg: fun(tion(arg)),
args,
lambda arg: arg) | e67ff42d3e006fc43e2d5e4a801cdb68f1f2e61e | 652,922 |
def amp_img(html_code):
"""Convert <img> to <amp-img>"""
return html_code.replace("<img", "<amp-img") | e1759f093d37244ef9ff797b78243edda4f94a58 | 652,925 |
def _multiplicative_inverse(num, modulo):
"""
Return the multiplicative inverse of the given number in given modulo or raises a ValueError if no inverse exists.
:param num: Number to be inverted
:type num: int
:param modulo:
:type modulo: int
:raises ValueError if num has no inverse
:ret... | e8d367c5feb51a93fc26b07af2a0c8cf8872a365 | 652,926 |
def _split_var_path(path):
"""
Split the given OpenMDAO variable path into a system path and a variable name.
Parameters
----------
path : str
The variable path to be split
Returns
-------
sys_path : str
The path to the system containing the given variable.
var_name... | 654f3be82cb73b4eb56c72981ab89f12832eaf9c | 652,931 |
import logging
def logger_has_filter(logger, filter_class):
"""
Will `logger` execute a filter of `filter_class`?
:param logging.Logger logger: the logger to examine
:param class filter_class: the filter class to search for
:return: :data:`True` if the `logger` contains a `filter_class`
f... | d00fec09b59e6186995af88371d7e0e5e50d049d | 652,935 |
def rescale(X, x_min, x_max):
"""
Rescaled the array of input to the range [x_min, x_max] linearly.
This method is often used in the context of making maps with matplotlib.pyplot.inshow.
The matrix to be accepted must contain arrays in the [0,1] range.
:param X: numpy.ndarray
This is the in... | 6f002651a48519e1f2a82365ba1c03f2e6a7c828 | 652,937 |
def kelvin2celcius(K):
"""
Convert Kelvin to Celcius
:param K: Temperature in Kelvin
:return: Temperature in Celcius
"""
return K - 273.15 | 9e05374cdd986020678695a8aea83e155d4dcaac | 652,939 |
from typing import Collection
from typing import Any
def has_duplicates(itera: Collection[Any]) -> bool:
"""Determine if ``itera`` contains duplicates.
Args:
itera (Collection): a sized iterable
Returns:
bool
"""
seen = set()
for i in itera:
if i in seen:
... | 44325db654023577c4fa38ad4693b1e5f79021d9 | 652,943 |
def parse_docs(hunter, docs):
"""returns tuple of (name, docs)"""
if not docs:
return hunter.__name__, "<no documentation>"
docs = docs.strip().split('\n')
for i, line in enumerate(docs):
docs[i] = line.strip()
return docs[0], ' '.join(docs[1:]) if len(docs[1:]) else "<no documentat... | b7836a4371d3fc97bc4ab25598a6b3c4c576e95b | 652,944 |
def gmas(ipe, gmpe, sx, rx, dx, oqimt, stddev_types):
"""
This is a helper function to call get_mean_and_stddevs for the
appropriate object given the IMT.
Args:
ipe: An IPE instance.
gmpe: A GMPE instance.
sx: Sites context.
rx: Rupture context.
dx: Distance cont... | 662e1466a0aedc8d7030c4a84f0b34fecac4d2fc | 652,948 |
def get_default_dims(dims):
"""Get default dims on which to perfom an operation.
Whenever a function from :mod:`xarray_einstats.stats` is called with
``dims=None`` (the default) this function is called to choose the
default dims on which to operate out of the list with all the dims present.
This f... | 752aca06ced4bd1edb421bc03b2c26c06bc4a450 | 652,951 |
def _invert_indices(arr, range_max):
"""return all indices from range(range_max) that are not in arr as a list"""
inv = []
for j in range(range_max):
if j not in arr:
inv.append(j)
return inv | 610cc79ae4bde74d64425e9e6c41fa252bcf2cdc | 652,955 |
import torch
def lincomb(rp: torch.Tensor, coeff: torch.Tensor) -> torch.Tensor:
"""Returns the normal distributions for w linear combinations of p
portfolios
Args:
rp (torch.Tensor): p-by-n matrix where the (i, j) entry corresponds to
the j-th return of the i-th portfolio
coeff... | b1328f9004ee18ad1a8f0ea9e84ed10d31681ff3 | 652,961 |
def rindex_str(text, sub, start=None, end=None):
"""
Finds the highest index of the substring ``sub`` within ``text`` in the range [``start``, ``end``].
Optional arguments ``start`` and ``end`` are interpreted as in slice notation. However,
the index returned is relative to the original string ``te... | 1d575404632e4618e3193e29ac22daf3e82aebc7 | 652,962 |
def int_to_sequence(integer):
"""Return a list of each digit in integer
For example:
1111 -> [1, 1, 1, 1]
451 -> [4, 5, 1]
"""
return [int(n) for n in str(integer)] | 3982564f921dc795cce67acd74592c8041273c98 | 652,971 |
def moeda(valor=0.0, moeda='R$'):
"""
Funçao que formata um valor ao formato de moeda
:param valor: Valor a ser formatado
:param moeda: Moeda ao qual deve ser formatado
:return: Valor formatado na moeda desejada
"""
return f'{moeda} {valor:.2f}'.replace('.', ',') | 01f023e374de72adff4ae72f7f8de310d183cd72 | 652,972 |
from typing import Any
def is_fixture(obj: Any) -> bool:
"""
Returns True if and only if the object is a fixture function
(it would be False for a Fixture instance,
but True for the underlying function inside it).
"""
return hasattr(obj, "ward_meta") and obj.ward_meta.is_fixture | b319c0b0da526142c541164694143411443dd1a1 | 652,977 |
def normal_round(num: float, ndigits: int = 0) -> float:
"""Rounds a float to the specified number of decimal places.
Args:
num: the value to round
ndigits: the number of digits to round to
"""
if ndigits == 0:
return int(num + 0.5)
else:
digit_value = 10 ** ndigits
... | bd24e33da0f1b2a51788b0ebcd1b669a5eb56cb0 | 652,983 |
def make_pairs_for_model(model_num=0):
""" Create a list of pairs of model nums; play every model nearby, then
every other model after that, then every fifth, etc.
Returns a list like [[N, N-1], [N, N-2], ... , [N, N-12], ... , [N, N-50]]
"""
if model_num == 0:
return
pairs = []
pai... | c9465a50a02486475420376db73fad4fa98a9b28 | 652,986 |
from functools import reduce
def compose(*functions):
"""
Returns a function which acts as a composition of several `functions`. If
one function is given it is returned if no function is given a
:exc:`TypeError` is raised.
>>> from brownie.functional import compose
>>> compose(lambda x: x + 1... | e3f5a58b9a36f463ed4869592de723df31abc6bd | 652,988 |
def _formatwarning(message, category, filename, lineno, line=None):
# pylint: disable=unused-argument
"""
Replacement for warnings.formatwarning() that is monkey patched in.
"""
return "{}: {}\n".format(category.__name__, message) | e7fc82637cf37738fa9d230b818bc40ca8e08a3c | 652,989 |
import re
def is_text(email_message):
"""Whether a message is text"""
return re.match(r"^text/.*", email_message.get_content_type(), re.IGNORECASE) | 47d94159ef028e9e5940766a922556eacf1a2c81 | 652,996 |
import json
def parse_sthv2_splits(level):
"""Parse Something-Something dataset V2 into "train", "val" splits.
Args:
level (int): Directory level of data. 1 for the single-level directory,
2 for the two-level directory.
Returns:
list: "train", "val", "test" splits of Somethin... | ee38c715a562c1185c2da1aec4be46ee9e3e1dca | 652,998 |
def dfs_topological_sort(arr, n):
""" Topological sort with DFS. Return an empty list if
there is a cycle.
"""
graph = [[] for _ in range(n)]
for u, v in arr:
graph[u].append(v)
visited, stack = [0] * n, []
def dfs(u):
if visited[u] == -1:
return False
i... | 8c917f372029a7a4e7f132a5141d05a69d8fb227 | 652,999 |
from typing import OrderedDict
def get_profile(line, listOfFeatures):
"""
Returns a tuple of feature values for the profile in question.
line is a string that contains key:value pairs separated by whitespace.
Each key is a feature and each value is its value.
profile is a list of f... | a8325a2b15e341f1cf07d522b8d39dc29d613477 | 653,001 |
def convert_to_html(model):
"""
Takes a model instance and produces an HTML table that represents the
results in a nice way for us to look at.
Parameters
----------
model : dict
Dictionary of layers and their properties as a list in the form of
[Vp, Vs, rho, thickness, top]
Returns... | f5ecc9677f7bfc0692e7f58b3dc6ce4f1955ee44 | 653,002 |
import pkg_resources
def matched_by_list(package, version, requirements):
"""
Verify whether the given version of the package is matched by the given requirements file.
:param package: Name of the package to look for
:param version: Version of the package to look for
:param requirements: A list o... | 054994cfb2bc2e953ff11be59071f5a74ebfdb68 | 653,006 |
import math
def downsampled_image_dims_from_desired_num_pixels(image_dims, num_pixels, maximum=False):
"""
Compute the best downsampled image dimensions, given original image dimensions and the ideal total number of
pixels for the downsampled image. The final number of pixels in the downsampled image dime... | e5197efba1141c4af38b4a8659f02cd9fb8bf246 | 653,007 |
def ParseSortByArg(sort_by=None):
"""Parses and creates the sort by object from parsed arguments.
Args:
sort_by: list of strings, passed in from the --sort-by flag.
Returns:
A parsed sort by string ending in asc or desc, conforming to
https://aip.dev/132#ordering
"""
if not sort_by:
return N... | 901d3fa9c23f715c85c395409db4499c8e542cd5 | 653,011 |
import re
def find_exported_class_path(spark_config_env_sh):
"""
find any current class path
:param spark_config_env_sh: all the text from the cloudera manager spark_env.sh
:return: the entire line containing the exported class path
"""
return re.search('SPARK_CLASSPATH=.*', spark_config_env_s... | 0724db979a8af3aaa5aac58edc8eb3ffbd61a19b | 653,015 |
def dictify(x):
"""Ensure `x` is a dict.
"""
if isinstance(x, dict):
return x
elif x:
return dict(x)
else:
return dict() | d25f79b6d521cd3650b8e0f314230246d3208657 | 653,018 |
from typing import Union
def _check_criteria(last_nouns: list, looking_for_singular: Union[bool, None],
looking_for_female: Union[bool, None], looking_for_person: bool, is_exact: bool) -> list:
"""
Checks the values of the nouns in last_nouns for matches of the specified gender/number
... | 114cc1fedfb0ac533551fae45176176fdc6c9c87 | 653,020 |
def string2fields(string, lengths):
"""Slice string into fixed-length fields."""
return (string[pos:pos + length].strip()
for idx, length in enumerate(lengths)
for pos in [sum(map(int, lengths[:idx]))]) | 92a08198f496bf0b2a2981824d6b3fd13255494d | 653,022 |
import requests
from bs4 import BeautifulSoup
def extract_url(url, values=None):
"""Given an url, extracts the contents as a BeautifulSoup object.
Args:
url: URL to parse.
Returns:
The site contents as a BeautifulSoup object
"""
if values:
r = requests.post(url, data=value... | 56ea95796cb718634390ac595d74f637bc8385d6 | 653,023 |
def l1_bit_rate(l2br, pps, ifg, preamble):
"""
Return the l1 bit rate
:param l2br: l2 bit rate int bits per second
:param pps: packets per second
:param ifg: the inter frame gap
:param preamble: preamble size of the packet header in bytes
:return: l1 bit rate as float
"""
return l2br... | bb060b30a283d6b0c9ae761bd23c7bda4a1d838a | 653,024 |
def imap_helper(args):
"""
Helper function for imap.
This is needed since built-in multiprocessing library does not have `istarmap` function.
If packed arguments are passed, it unpacks the arguments and pass through the function.
Otherwise, it just pass the argument through the given function.
... | 96facdd07c0af4c85bcfb7b9998d6e3eedbeec15 | 653,025 |
def check_subset(list_one:list, list_two:list):
"""
You are given two lists of integers list_one and list_two. If list_two is a subset of list_one, return
true, otherwise return list of items that are in list_two but NOT in list_one.
Note: subset can be empty, if so return False
Example 1:
Input: list_one = ... | 98866ba0166f8aaf7d5283bb832868e6ce4db158 | 653,027 |
def appear_only_at_sentence_beginning(word, title, sents):
"""
if the token appears in the text only at the beginning of the sentences
>>> title = [u"Feng", u"Chao", u"Liang", u"Blah"]
>>> doc = [[u"Feng", u"Chao", u"Liang", u"is", u"in", u"Wuhan", u"."], [u"Chao", u"Liang", u"is", u"not", u"."], [u"Li... | f268c486fbe526d962f6c901429f2601fd58047b | 653,029 |
def bubble_sort(L):
"""
Implementation of the bubble sort algorithm
Complexity: O(n^2)
:param L: List-object
:return: Sorted list-object
"""
swap = False
while not swap:
swap = True
for j in range(1, len(L)):
if L[j-1] > L[j]:
swap = False
... | 069b72a662b626f8dcc27823e1e3ab6d5d7113db | 653,032 |
def ensure_list(i):
"""If i is a singleton, convert it to a list of length 1"""
# Not using isinstance here because an object that inherits from a list
# is not considered a list here. That is, I only want to compare on the final-type.
if type(i) is list:
return i
return [i] | d932e98a5a8cadc07246ac428addd407c59e04e5 | 653,035 |
import operator
def crop_nd_arr(img, bounding):
"""Crop the central portion of an array so that it matches shape 'bounding'.
Parameters
----------
img : array
An nd array that needs to be cropped.
bounding : tuple
Shape tupple smaller than shape of img to crop img to.
Returns... | 32dd5f6d89145a2961d39ceeb8ef23d8647598a0 | 653,036 |
def listify(value):
"""
Convert an option specified as a string to a list. Allow both
comma and space as delimiters. Passes lists transparently.
"""
if isinstance(value, (list, tuple)):
# Already a sequence. Return as a list
return list(value)
else:
# assume `value` is a... | 8b8636884ecaddf9f558ca8cb4d80583c01b59bf | 653,041 |
def _extend(M, sym):
"""Extend window by 1 sample if needed for DFT-even symmetry"""
if not sym:
return M + 1, True
else:
return M, False | f07638db5f6b4870ccfcd26b3acc286c2d64d269 | 653,043 |
def parse_by_line(input_string, prefix_string, offset):
"""breaks input string by lines and finds the index of the prefix_line.
Returns the line that is offset past the prefix_line"""
split_by_line = input_string.splitlines()
prefix_line = split_by_line.index(prefix_string)
return split_by_line[p... | bc3cd05c1ad1088c3d653c81131217a01ac2f8ab | 653,044 |
import re
def add_css_class(component, className):
"""
Update the className property of a Dash component to include a CSS class name.
If one or more classes already exist, the provided className will be appended
to the list. If the provided className is already present, no change will be made
to ... | 2ca66ab2a69aa9d5b40fedb94aedc60b0a7e50d5 | 653,047 |
def log_get_flags(client):
"""Get log flags
Returns:
List of log flags
"""
return client.call('log_get_flags') | fd47c683715832f788e6f6f21097894cb24db301 | 653,049 |
def error_500(error):
"""Return a custom 500 error."""
return 'Sorry, internal server error.' | f45c15482d3c768ed9672a39ad14adac24d2ebfd | 653,050 |
def get_ta_status_flag(funding_status):
"""Generate TA status flag for student entry.
This flag is from a "teaching preference request" perspective, not a funding
perspective.
Arguments:
funding_status (str): funding entry for current term
Returns:
(str) : flag ("" for non-TA, "*"... | 691c19b6f9b3660715e984998817b29aaff697df | 653,057 |
import torch
def safe_divide(input_tensor: torch.Tensor, other_tensor: torch.Tensor) -> torch.Tensor:
"""
Divide input_tensor and other_tensor safely, set the output to zero where the divisor b is zero.
Parameters
----------
input_tensor : torch.Tensor
other_tensor : torch.Tensor
Returns... | 5abc49218d5df4624215eb8802a8db52291dbbf7 | 653,059 |
def decodeBytesToUnicode(value, errors="strict"):
"""
Accepts an input "value" of generic type.
If "value" is a string of type sequence of bytes (i.e. in py2 `str` or
`future.types.newbytes.newbytes`, in py3 `bytes`), then it is converted to
a sequence of unicode codepoints.
This function is u... | 32c16b2f7565e75178a58bc99e9a6452f3550466 | 653,061 |
def calc_result_myteam_first(score):
""" Determines whether the team won, drew or lost based on the score
Returns a 'W', 'L', 'D'
"""
result = ('W' if score[0] > score[1] else ('L' if score[0] < score[1] else 'D'))
return result | 29717c1f6b143a09bcc220e8ceca6eed04c879c2 | 653,064 |
from pathlib import Path
def find_case_sensitive_path(path: Path, platform: str) -> Path:
"""Find the case-sensitive path.
On case-insensitive file systems (mostly Windows and Mac), a path like ``text.txt``
and ``TeXt.TxT`` would point to the same file but not on case-sensitive file
systems.
On ... | 1a75c19313062186807c4fb974bd4ae8e78bfd6b | 653,066 |
def findOwner(cursor, tableName):
"""
Finds the owner of a table.
"""
cursor.execute("""SELECT OWNER
FROM ALL_OBJECTS
WHERE object_name = '"""+tableName.upper()+"'")
return cursor.fetchone()[0] | 6376f4fe459200326581f587ad381762a028dfe3 | 653,069 |
def best_days(dragon, me):
"""
>>> d = {'Monday': (1, 6), 'Friday': (3, 5)}
>>> m = {'Monday': (2, 4), 'Friday': (3, 6)}
>>> best_days(d, m)
['Monday']
>>> d = {'Monday': (1, 6), 'Friday': (3, 5)}
>>> m = {'Monday': (0, 4), 'Friday': (3, 6)}
>>> best_days(d, m)
[]
>>> d = {'Mon... | 492b4756784a7b9aebe9ca6e89028ef747e9df12 | 653,073 |
import requests
import json
def post(url, params, proxies, headers):
"""Send a request with the POST method."""
response = requests.post(url, data=json.dumps(params),proxies=proxies, headers=headers)
return response | a6d57ee82021154540ea7b8c68329d2f85eaa157 | 653,074 |
def resource_filename(lang_code: str, resource_type: str, resource_code: str) -> str:
"""
Return the formatted resource_filename given lang_code,
resource_type, and resource_code.
"""
return "{}_{}_{}".format(lang_code, resource_type, resource_code) | 84b83e1c0a3bd04a2170c9e222ced10c410f6f7b | 653,076 |
def get_epsilon_array(gamma_array):
"""Flip 0 and 1 for epsilon from gamma"""
return list(map(lambda d: '1' if d == '0' else '0', gamma_array)) | 38cb467764b021f853ccdf4614007f1578e47ae1 | 653,077 |
def extract_build_cmds(commands, exe_name):
"""Extracts build command information from `ninja -t commands` output.
Args:
commands: String containing the output of `ninja -t commands` for the
libcxx_test_template.
exe_name: The basename of the built executable.
Returns:
... | 02a31267bca83cf1d2a6430db1b949141be21025 | 653,081 |
def check_request_params(data, params):
"""
Checks that a JSON request contains the proper parameters.
Parameters
----------
data : json
The JSON request
params: list
The parameters that should appear in the JSON request
Returns
-------
str
A message det... | bfbc4aa1bea8f7925b54598ab0f31acbef1c1e87 | 653,084 |
def calculate_total_bags(graph):
"""
Given a graph, return the total bags required
"""
value = 0
for node in graph:
value += int(node["count"]) + int(node["count"]) * calculate_total_bags(
node["inside"]
)
return value | 03cbca239b6867ad5abc3c8312bf9e2163a9b939 | 653,086 |
def min_ge(seq, val):
"""
Same as min_gt() except items equal to val are accepted as well.
>>> min_ge([1, 3, 6, 7], 6)
6
>>> min_ge([2, 3, 4, 8], 8)
8
"""
for v in seq:
if v >= val:
return v
return None | f881596755eb730b4d0b4f6fa264ef7d83fdacef | 653,090 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.