content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import six
def _prompt(message, result_type=str):
"""
Non-public function that prompts the user for input by logging 'message',
converting the input to 'result_type', and returning the value to the
caller.
"""
return result_type(six.moves.input(message)) | 333da5d331a011d0f2e5505276bc1c415360c510 | 608,149 |
import csv
def read_crubadan_language_model(pairs, config, gram_type):
"""
Read a Crubadan language model for a (language name, ISO code) pair.
Args:
pairs: a list of (name, code) pairs to construct models for
config: model parameters
gram_type: what type of gram to use - 'charact... | 8d3ce5829830f1900b6c54b54bb0584934e43986 | 284,651 |
import random
def _order_alternatives(alts):
""" Pop don't know alts, randomize and append "don't know" alt last """
new_alts = []
no_answer = []
for alt in alts:
if alt['no_answer']:
no_answer.append(alt)
else:
new_alts.append(alt)
random.shuffle(new_alts)... | 757f37194567f6c7432660137e7b9efbd97efe70 | 518,062 |
def _which_asm_has_finer_mesh(asm, neighbor=None):
"""Determine which assembly has finer meshing
Parameters
----------
asm1 : DASSH Assembly object
Active assembly around which we are creating mesh
asm2 (optional) : DASSH Assembly object
Neighboring assembly across active hex side
... | 10465f9272abe37cb3a1d448a4ffacd08eed0dc5 | 614,819 |
import re
def normalize_name(name, dns_1035=False):
"""
Normalize name
:param name: name to normalize
:type name: str
:param dns_1035: (Optional) use DNS-1035 format, by default False
:type dns_1035: bool
:return: str -- normalized name
"""
invalid_delimiters = ' ', '_', '+'
i... | d9f8219d3bb9f73e6e294eab0e1d86f0206a9934 | 492,644 |
def get_folders(values_dict):
"""Returns a dict of all the folders in the given value_dict."""
return dict(
(item, configs) for (item, configs) in values_dict.iteritems()
if item.endswith('/')
) | f383e21fedb4ee3510d1360a442fb0bfd32a9fd7 | 619,965 |
def str2bool(value):
"""Parse a string into a boolean value"""
return value.lower() in ("yes", "y", "true", "t", "1") | 76b078822bac4f706cc6e6b1e730128e0f656185 | 578,335 |
def convert_to_bytes(mem_str):
"""Convert a memory specification, potentially with M or G, into bytes.
"""
if str(mem_str)[-1].upper().endswith("G"):
return int(round(float(mem_str[:-1]) * 1024 * 1024))
elif str(mem_str)[-1].upper().endswith("M"):
return int(round(float(mem_str[:-1]) * 1... | ae0e80565778d7c6308cb07be30cf3a293fd9733 | 194,273 |
def moreThan3Chars(value):
"""String must contain at least 3 characters."""
if len(value) >= 3:
return True
return False | a50a923e70a6ed89a094ac2040ac27f0f0273aa5 | 591,593 |
def get_thresholds(points=100, power=3) -> list:
"""Run a function with a series of thresholds between 0 and 1"""
return [(i / (points + 1)) ** power for i in range(1, points + 1)] | 5238a5d6ecf3f5ef05b4128a047f63e93b20cbfd | 232,048 |
def margin_fee(self, **kwargs):
"""Query Cross Margin Fee Data (USER_DATA)
Get cross margin fee data collection with any vip level or user's current specific data as https://www.binance.com/en/margin-fee
GET /sapi/v1/margin/crossMarginData
https://binance-docs.github.io/apidocs/spot/en/#query-cross-ma... | f2ca69c13b77fffadf6aa319f1847004ed5615da | 23,958 |
def learn_routem_configs(device, output_config=False):
""" Gets the current running config on device
Args:
output_config ('bool'): Specifies whether the config
or path of the config is outputted
Raise:
None
Returns:
Config ('dict'): {pid: conf... | 7cbc98a273025c8b71a85046abd37b1612f7da76 | 156,380 |
def make_param_dict(param_val_dict):
"""Makes dictionary for VI RandomVariable and parameters.
:param param_val_dict: (dict of list) A dictionary with key being
parameter names, and values being a list of
[RandomVariable, mean_vi_param, scale_vi_param]
:return:
model_param: (dict o... | 887d211c47440094450b3fc1b20451281fb7a2b2 | 361,539 |
def _ct_specification_type_to_python_type(specification_type: str) -> str:
"""
Convert a custom specification type into its python equivalent.
:param specification_type: a protocol specification data type
:return: The equivalent data type in Python
"""
python_type = specification_type[3:]
r... | 4a63283b0c888fe31e0d87b18b42d1948633b962 | 596,987 |
def qn(namespace, tag_name):
"""Return the qualified name for a given namespace and tag name
This is the ElementTree representation of a qualified name
"""
return "{%s}%s" % (namespace, tag_name) | 1d2d6a5455980f65e615e4dd3f3a2e8323623ea2 | 375,401 |
import uuid
def CreateShoppingCampaign(client, budget_id, merchant_id):
"""Creates a shopping campaign with the given budget and merchant IDs.
Args:
client: an AdWordsClient instance.
budget_id: the str ID of the budget to be associated with the shopping
campaign.
merchant_id: the str ID of the... | 208b2ad37d2fda5ee5b85827029597ed8bc6801b | 36,057 |
def skip_label(what):
"""Generate a "skip" label name."""
return f"skip {what}" | 60c32ec2636cb3c14216b604dfa1987381f52dd5 | 107,035 |
def vector_orientation (x, y):
"""Assigns an orientation to a 2D vector according to the Spanish CTE compass rose."""
if x <= 0.3826 and x >= -0.3826 and y <= 1 and y >= 0.9238:
return "North"
elif x < 0.8660 and x > 0.3826 and y < 0.9238 and y > 0.5000:
return "Northeast"
elif x <= 1 and x >= 0.8660 and y <= 0... | d23030e759dcb697cd4ed9d1ad8a50ac51204ac7 | 98,907 |
def not_implemented(*args, **kwargs) -> dict:
"""
Default response if pair is good, but no action is taken
:return: OpenC2 response message - dict
"""
return dict(
status=501,
status_text="command good, no action taken"
) | 02d0f6e6e4915dd14bbb65b1a29c3ae61798d64d | 327,140 |
def _calculate_precision(value: str) -> int:
"""Calculate the precision of given value as a string."""
no_decimal_point = value.replace(".", "")
no_leading_or_trailing_zeros = no_decimal_point.strip("0")
return len(no_leading_or_trailing_zeros) | be97a9ab0484e052d80033d0d26cd1259a9f6237 | 86,051 |
def get_cache_key_counter(bound_method, *args, **kwargs):
""" Return the cache, key and stat counter for the given call. """
model = bound_method.__self__
ormcache = bound_method.clear_cache.__self__
cache, key0, counter = ormcache.lru(model)
key = key0 + ormcache.key(model, *args, **kwargs)
ret... | 241b13b29b3dce0888f2eeb40361dfa03d5f8389 | 12,964 |
def _parse_ipv4_number(input_):
"""Parses a single IPv4 number"""
r = 10
try:
if len(input_) >= 2:
if input_[:2].lower() == "0x":
r = 16
input_ = input_[2:]
elif input_.startswith("0"):
r = 8
input_ = input_[1... | bb2ddbe23a17dfb9ff39c5c4a2a2a60092b1f51a | 250,352 |
def degree_of_item(train):
"""Calculates degree of items from user-item pairs."""
item_to_deg = {}
for pair in train:
_, item = pair
if item in item_to_deg:
item_to_deg[item] += 1
else:
item_to_deg[item] = 1
return item_to_deg | 9f44848b446ffded46c0ceb2aff7e2540cf9f346 | 318,592 |
def hashdigit(cpf, position): # type: (str, int) -> int
"""
Will compute the given `position` checksum digit for the `cpf`
input. The input needs to contain all elements previous to
`position` else computation will yield the wrong result.
"""
val = sum(int(digit) * weight for digit, weight in z... | f6984e209b2061c1c7af41da3704ddee77e04d45 | 186,198 |
def get_ip_label(ip):
"""
Format ip address of the node and convert into label
The label will consist of hexadecimal values of the ip. Each octet will be
converted into it's corresponding hex value and the whole label will be
saved as an 8 character string. For example, 10.255.0.192 would have a
... | ee39aa2d5ba20011efe971e2da31a9dd57560e52 | 219,090 |
import itertools
def group_on_delimiter(iterable, delimiter):
"""Group elements separated by delimiter into chunks.
group(['a', 'b', '', 'c', 'd', '', 'e'], '') => [['a', 'b'], ['c', 'd'], ['e']]
"""
return [list(g) for is_delimiter, g in itertools.groupby(iterable, lambda el: el == delimiter) if not... | 1d4c89b33c8e6ff7b682acddbd05218a44323de1 | 605,099 |
import string
def subfig(fig,xloc=0,yloc=1,fontsize=16,**plt_kwargs):
"""
Add subfigure labels to axes in figure using axes coordinates
Parameters:
fig: Figure on which to apply labels
xloc: X location for label, in axes coordinates (0-1)
yloc: Y location for label, in axes co... | fc0d45fab52ebd250bf1590333655c8543ffbb77 | 362,458 |
def point_str(point) -> str:
"""
Convert a point to a string
"""
# some string conversion functions (since looking up strings in a dict is pretty fast performance-wise)
return str(point[0]) + ";" + str(point[1]) | 39ea3fbd51fa179941fd36598b508feae4e5a57a | 234,914 |
import torch
def log1p_safe(x):
"""The same as torch.log1p(x), but clamps the input to prevent NaNs."""
x = torch.as_tensor(x)
return torch.log1p(torch.min(x, torch.tensor(33e37).to(x))) | 5f1f4ce93dd2192bc6722b183ddec276788c8070 | 129,615 |
from typing import Counter
def count_pileups(bam, contig, start, end):
"""Returns the number of piled-up bases between the given
start and end positions in the given contig."""
raw_counts = Counter({x.pos: x.n
for x in bam.pileup(contig, start, end)
if s... | 7fe2335f6fbd37d0eb31ddff0ef1f6a0dc17b622 | 458,177 |
def actions(self):
"""
Returns all the action objects whether enabled or disabled.
"""
return self.__actions | 9eec5e6df3788259230cceb63f9baa0faa868cc8 | 108,208 |
def list_output_tensors(node):
"""
Since Tensorflow 1.14, sometimes the node.output_tensors may not be a list, though the output_tensors is plural.
"""
return [node.output_tensors] if hasattr(node.output_tensors, 'dtype') else node.output_tensors | f1e0a5fe304c25eec25936b9a200c8797ace389f | 183,467 |
def get_gradient_values(gradient_img, multiplier=1):
""" Given the image gradient returns gradient_alpha_rgb_mul and one_minus_gradient_alpha.
These pre-calculated numbers are used to apply the gradient on the camera image
Arguments:
gradient_img (Image): Gradient image that has to applied on the c... | 507ea8e1f6b03bc42f77453835ea55ee9a525bca | 273,672 |
def get_search_url(search, page):
"""
Create the search URL according to search params and page number.
"""
url = (f"https://hub.docker.com/api/content/v1/products/" +
f"search?architecture=arm,arm64,386,amd64&operating_system=linux" +
f"&page={page}&page_size=100&q={search}&type=i... | f482170f3cbfaa9d9738411394702c45ed587350 | 154,436 |
def json_encode_datetime(d):
"""Encoder for datetimes (from module datetime)."""
return {"datetime" : d.strftime("%Y-%m-%d %H:%M:%S.%f"),
"tzinfo" : d.tzinfo} | c800ab344601a26f69bcebc7a7bd8ca40acadaa8 | 561,750 |
def get_page_image_url(page_ann, vol_meta):
"""Return image url of the page
Args:
page_ann (dict): page annotation
vol_meta (dict): volume meta data
Returns:
str: image url of page
"""
cur_image_grp_id = ""
cur_image_grp_id = vol_meta["image_group_id"]
image_ref = p... | becabcbdf613e0cc0bffe6c340e6dfa71d204927 | 189,806 |
def _common_length_of(l1, l2=None, l3=None):
"""
The arguments are containers or ``None``. The function applies
``len()`` to each element, and returns the common length. If the
length differs, ``ValueError`` is raised. Used to check arguments.
OUTPUT:
A tuple (number of entries, common length ... | 3a3f2ecfb541691d2ca833b14f9c8761f92584af | 640,761 |
import json
def jsonDecode(jsonString):
"""Takes a json String and converts it into a Python object such as
a list or a dict.
If the input is not valid json, a string is returned.
Args:
jsonString (str): The JSON string to decode into a Python
object.
Returns:
dict: ... | ab5fbd22089a80dc13e413986df0ec6de4c85b82 | 478,818 |
def getBlockNumbersForRegionFromBinPosition(regionIndices, blockBinCount, blockColumnCount, intra):
""" Gets the block numbers we will need for a specific region; used when
the range to extract is sent in as a parameter
Args:
regionIndices (array): Array of ints giving range
blockBinCount (in... | 065630ade7cf5b5ffc86b05fd80bcd890a0eed76 | 621,802 |
import json
def output_fn(predictions, content_type):
"""Post-process and serialize model output to API response"""
print('result:', predictions)
res = predictions.cpu().numpy().tolist()
return json.dumps(res) | f0c22dcd7e5a447b38afd141d6de7d16028fc670 | 623,646 |
from typing import List
from typing import Optional
def determine_root_gpu_device(gpus: List[int]) -> Optional[int]:
"""
Args:
gpus: non-empty list of ints representing which gpus to use
Returns:
designated root GPU device id
"""
if gpus is None:
return None
assert is... | c988e01573b242ab106ef4ef406f0ba88f7533c1 | 601,277 |
def posteriors(likelihoods, priors):
"""Calculate posterior probabilities given priors and likelihoods.
Usage: probabilities = posteriors(likelihoods, priors)
likelihoods is a list of numbers. priors is a list of probabilities.
Returns a list of probabilities (0-1).
"""
# Check that there is a... | fc47c102d27f9d45dc1b38d58704255251961b6d | 214,622 |
def filter_unmodified_overrides(pkg_info, overrides):
"""
Given a list of overrides from a particular package, return a copy of the
list that's filtered so that any overrides that have not been changed from
the underlying file are removed.
"""
for override in overrides:
result = pkg_info... | bbb4076af863ed2594696714c4ad5ad9a5c1233b | 508,071 |
def toContigScafMap(scaffToContigListDict):
"""
Transforms the input dictionary (key -> list of items) into the inverse dictionary (item -> key).
To each item (contig) only one key (scaffold) exists.
@param scaffToContigListDict: map: scaffold -> list of contigs
@return: map: conti... | 257baef5bd783cd693465c6a9ee11161667ac0ee | 280,423 |
def get_mask(source, source_lengths):
"""
Args:
source: [B, C, T]
source_lengths: [B]
Returns:
mask: [B, 1, T]
"""
B, _, T = source.size()
mask = source.new_ones((B, 1, T))
for i in range(B):
mask[i, :, source_lengths[i]:] = 0
return mask | 8466ff5113ca22488b4218f86c43bfea248197d1 | 24,855 |
def datt3(b3, b5, b8a):
"""
Vegetation Index proposed by Datt 3 (Datt, 1998).
.. math:: DATT3 = b8a / (b3 * b5)
:param b3: Green.
:type b3: numpy.ndarray or float
:param b5: Red-edge 1.
:type b5: numpy.ndarray or float
:param b8a: NIR narrow.
:type b8a: numpy.ndarray or float
... | 41bdcf06b049a36e5673f884762b488f42213f5b | 462,215 |
def isInside(point, leftTop, rightBottom):
"""
return True if point is in the rectangle define by leftTop and rightBottom
"""
if not (leftTop[0] < point[0] < rightBottom[0]):
return False
if not (leftTop[1] < point[1] < rightBottom[1]):
return False
return True | f9727e5ac11011ea45d05d5db1a439848c882481 | 650,229 |
def dicts_equal(dictionary_one, dictionary_two):
"""
Return True if all keys and values are the same between two dictionaries.
"""
return all(
k in dictionary_two and dictionary_one[k] == dictionary_two[k]
for k in dictionary_one
) and all(
k in dictionary_one and dictionary_... | abd7d1d89c034c8f57b34b3994f2f8a32b63987e | 123,080 |
def defaultargs(options):
"""Produce a dictionary of default arguments from a list of options
tuples
Parameter
tuple[] - (flag, default, docstring) tuples describing each flag
Return
dict - {flag: default} for each option in input
"""
config = {}
for longname, default, d... | fe6a6c11aad99a95491507910a8dccb63139a785 | 283,666 |
import collections
def picard_idxstats(picard, align_bam):
"""Retrieve alignment stats from picard using BamIndexStats.
"""
opts = [("INPUT", align_bam)]
stdout = picard.run("BamIndexStats", opts, get_stdout=True)
out = []
AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "a... | 6ee5d38b272e4ae05a3df5d02230509bb427133b | 64,923 |
import json
def lerArquivoJSON(caminho_arquivo):
"""
Retorna conteúdo de um arquivo JSON de comandos SQL, delegando tratamento para bloco de função reservado
:param caminho_arquivo:
:return: data (JSON)
"""
with open(caminho_arquivo, "r") as read_file:
data = json.load(read_file)
... | 2cfdd872295a244fb2a83f6b287a954e806da829 | 651,251 |
def _slugify(doi):
"""Generate a name from DOI using the same approach as SciHub."""
return doi.replace('/', '@') | f41552f5810ef13995db4edff90120400c7ed052 | 473,169 |
def _ceildiv(x, y):
"""Rounds `x/y` to next largest integer."""
return -int(-x // y) | 7430a8148424c170cee225571eeb3574c9a9c237 | 293,409 |
from pathlib import Path
import json
def template_json(keyboard):
"""Returns a `keymap.json` template for a keyboard.
If a template exists in `keyboards/<keyboard>/templates/keymap.json` that text will be used instead of an empty dictionary.
Args:
keyboard
The keyboard to return a te... | 7949c78a164abfb04ef1b46caaf0897acac88bfc | 61,846 |
def b_to_s(b: bytes) -> str:
"""convert bytes to string
:param b: input bytes
:type b: bytes
:return: output string
:rtype: str
"""
s = b.decode('utf8')
return s | 98c4abf3d78e86f5e1b00459135e65d4ec94e030 | 336,825 |
def filter_data(data: dict, keys: list) -> dict:
"""Returns a dictionary with only key/value pairs where the key is in the keys list"""
return {k: data[k] for k in keys if k in data} | 78dc222b3f6af7d252a01f6d9b5457f14656a477 | 428,932 |
def my_kinetic_energy(vel, mass):
""" Calculate total kinetic energy.
Args:
vel (np.array): particle velocities, shape (natom, ndim)
mass (float): particle mass
Return:
float: total kinetic energy
"""
k = 0.0
for i in vel:
k += sum(0.5 * mass * i ** 2)
return k | 75917ef0fa698539db6207c2b297ad02acea1026 | 222,565 |
def get_metric_scores(ground_truth, simulation, measurement, metric, measurement_kwargs={}, metric_kwargs={}):
"""
Function to combine measurement and metric computations
:param ground_truth: pandas dataframe of ground truth
:param simulation: pandas dataframe of simulation
:param measurement: meas... | 4087e60ce0578d11756f449e776e01ee81b6e4ac | 696,025 |
def duration(first, last):
"""Evaluate duration
Parameters
----------
first : int
First timestamp
last : int
Last timestamp
Returns
-------
str
Formatted string
"""
ret = ''
diff = last - first
if diff <= 0:
return ''
mm = divmod(di... | d368f18cb574dadab3794e3816410c9d8dcb07ee | 636,643 |
def _legendre(a, p):
"""
Returns the legendre symbol of a and p
assuming that p is a prime
i.e. 1 if a is a quadratic residue mod p
-1 if a is not a quadratic residue mod p
0 if a is divisible by p
Parameters
==========
a : int
The number to test.
p : prime
... | 3349f3154fdb6618a4366acf1fffd4179bced25a | 136,488 |
def parse_dir(save_dir):
"""Parses the save directory to get only the directory (without the file name) to save the pictures to
:param save_dir: save directory string
:return: save directory string without the file name
"""
dir_list = save_dir.split('/')
dir = ''
if len(dir_list) == 1:
... | d40ff6ff03859654210bce5ed67d33f25e07a467 | 660,502 |
def difference(actual, expected):
"""
Returns strings describing the differences between actual and expected sets.
Example::
>>> difference({1, 2, 3}, {3, 4, 5})
('; added {1, 2}', '; removed {4, 5}')
>>> difference({1}, {1})
('', '')
:param set actual: the actual set... | cd0d20645effe52df995c6bb6d04eecd6be06e12 | 404,202 |
def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
Choice output
{
"JobName": "your_job_name",
"JobRunId": "jr_uuid",
"JobRunState": "SUCCEEDED",
"StartedOn": "2021-09-20T20:30:5... | 50b61531dc1d28965148429128d4f1b840d2cc00 | 379,632 |
def _times_to_steps(ts, num_trotter_slices):
"""
Based on the requested times `ts`, calculate Trotter step numbers at which
(subsystems of) evolved states need to be saved.
.. doctest::
>>> _times_to_steps([10, 25, 30], 100)
([33, 83, 100], 0.3)
>>> _times_to_steps([8, 26, 19],... | f18e0ef0ecbcbbfa28a1f8ea663f8161c05a0f6c | 233,328 |
import codecs
def _int_to_bytes(i):
"""
Converts the given int to the big-endian bytes
"""
h = hex(i)
if len(h) > 1 and h[0:2] == "0x":
h = h[2:]
# need to strip L in python 2.x
h = h.strip("L")
if len(h) % 2:
h = "0" + h
return codecs.decode(h, "hex") | 5fdfdeac50d13e26385277c9cef12b4ed393a08b | 56,506 |
def bonus_letter(puzzle: str, view: str, letter: str) -> bool:
"""Return True iff the letter is a consonant that appears in the puzzle but not view.
>>> bonus_letter('apple', 'a^^le', 'p')
True
>>> bonus_letter('banana', 'ba^a^a', 'b')
False
>>> bonus_letter('apple', '^pp^e', 'a')
False
... | 6255fc1d39055f7d28b4027ca697bb0ca6a4e174 | 458,203 |
def arithmetic_mean(samples):
"""Computes the arithmetic mean of a set of samples.
"""
return float(sum(samples)) / float(len(samples)) | d71cd1782a1c30e0bd6579079a3a56e5c47da764 | 345,100 |
def level_list(root):
"""Get full level order traversal of binary tree nodes.
Example:
>>> from leetcode_trees import binarytree
>>> tree = binarytree.tree_from_list([5,1,4,None,None,3,6])
>>> binarytree.print_tree(tree)
___5___
1 _4_
3 6
>>> print(binarytree.level_representation(tree))
[[... | f53c14c5b195a6d0b5364c5258bd2576f1fabe66 | 640,564 |
def fibonacci(n):
"""Fibonacci series
0, 1, 1, 2, 3, 5, 8, 13, ...
"""
if n <= 1:
return n
a = 0
b = 1
c = 1
for i in range(2, n):
a = b
b = c
c = a + b
return c | 275e6594e8662df9d1a5661344ffa3c1e28a7889 | 261,778 |
def load_model(plugin, model, weights, device):
"""
Load OpenVino IR Models
Input:
Plugin = Hardware Accelerator IE Core
Model = model_xml file
Weights = model_bin file
Output:
execution network (exec_net)
"""
# Read in Graph file (IR) to create network
net = plugin.read_... | f9fa99f2e111d5aa4a1b9f24774f049e55138d73 | 209,081 |
def energy_overlap(sp1, sp2):
"""
Calculate the overlap energy range of two spectra, i.e. lower bound is the
maximum of two spectra's minimum energy.
Upper bound is the minimum of two spectra's maximum energy
Args:
sp1: Spectrum object 1
sp2: Spectrum object 2
Returns:
... | 4e0f08f3be1e7c8fc39805bc9d16319c1f61f3a4 | 113,435 |
def GetFC(FCFCS):
""" Return the FC of the FCFCS """
return FCFCS[0] | 8329ada301193b9acc69d52acfcd7801df439b5b | 433,899 |
def strip_suffix(s: str, suffix: str) -> str:
"""Strip the given suffix, if present, and return the resulting string."""
return s[: -len(suffix)] if s.endswith(suffix) else s | ea9f31e5fd15b222f01be767db8a64d008d00812 | 327,535 |
def make_list_template_element(title, subtitle=None, image=None,
resource_id=None, action=None, i18n_titles=None,
i18n_subtitles=None, i18n_images=None,
i18n_resource_ids=None):
"""
create carousel list template a Row.
... | 46665f7c91a9fc4525899279da3318494e0991a9 | 459,253 |
def get_brand_tweets(dataframe, brand):
"""
Filters out all tweets that dont belong to a specific brand
:param dataframe: dataframe from kaggle with all the tweets.
:param brand: brand that we want to keep.
"""
return dataframe[dataframe["author_id"] == brand] | 2d28351ce61b574582c812f8dbad29511ba34897 | 537,787 |
def z_function(text):
"""
Z Algorithm in O(n)
:param text: text string to process
:return: the z_array, where z_array[i] = length of the longest common prefix of text[i:] and text
"""
n = len(text)
z_array = [0] * n
l = r = 0
for i in range(1, n):
z = z_array[i - l]
... | ed0552ca771865644b2df59c80bc3b785578fab5 | 604,940 |
async def pause_(self, ctx):
"""Pause the currently playing song."""
vc = ctx.voice_client
if not vc or not vc.is_playing():
return await ctx.send('I am not currently playing anything!', delete_after=20)
elif vc.is_paused():
return
vc.pause()
await ctx.send(f'**`{ctx.author}`**... | 47271577c1aec1176f33ec56b8285787e1609b0b | 602,849 |
def element_name(element_path):
"""
Gives the last element in an xpath
:param element_path: An xpath with at least one '/'
"""
return element_path[element_path.rfind('/') + 1:] | 975b99d9fc30141e630c31a2ec310f827685b383 | 286,726 |
def cli_method(func):
"""Decorator to register method as available to the CLI."""
func.is_cli_method = True
#setattr(func, 'is_cli_method', True)
return func | 0eb80215e37b7b9290732dc1a8a2a33bbfb647ed | 59,565 |
def findAllInfectedRelationships(tx):
"""
Method that finds all INFECTED relationships in the data base
:param tx: is the transaction
:return: a list of relationships
"""
query = (
"MATCH (n1:Person)-[r:COVID_EXPOSURE]->(n2:Person) "
"RETURN ID(n1) , r , r.date , r.name , ID(n2);... | 0b5e35d98ae8a91973e60c68b772e159294db751 | 690,897 |
def combine_two_lists_no_duplicate(list_1, list_2):
"""
Method to combine two lists, drop one copy of the elements present in both and return a list comprised of the
elements present in either list - but with only one copy of each.
Args:
list_1: First list
list_2: Second list
Return... | 4caa2d3494eeef61d502bc898433d04362e81f39 | 690,327 |
def _make_credentials_property(name):
"""Helper method which generates properties.
Used to access and set values on credentials property as if they were native
attributes on the current object.
Args:
name: A string corresponding to the attribute being accessed on the
credentials attrib... | 17692cb4cf0ea072d4345d60106bb04c0ad030bd | 651,517 |
def extract_text(element):
"""
Return *text* attribute of an implied element if available.
"""
if element is not None:
return element.text
else:
return None | b17c43e1d816a56f43ba27af5bc4a626f8b66181 | 557,293 |
import re
def valid_url(url):
"""Return `True` if URL is valid."""
return re.match(r'https?://\S+', url) is not None | 05afb03fc96679dd361e799f86d85d8a343cdf18 | 196,251 |
def _gcd(a, b):
"""Computes the greatest common divisor of two numbers using Euclid's Algorithm.
Example:
>>> _gcd(30, 18)
6
Args:
a (int): The first parameter.
b (int): The second parameter.
Returns:
int: The greatest common divisor of a and b.... | 0e3ea9b27e22651875c48ae3660ab681117d9dc5 | 477,896 |
def _getControllerWalkNodes(tag):
"""Get the node conneted to a controllers tag as a controller object
Arguments:
tag (controller list): Maya's controller tag
Returns:
dagNode: The list of controller objects
"""
nodes = []
if not isinstance(tag, list):
tag = [tag]
... | c1e79c8d323931959de3ea7f1882d856ed41eb81 | 314,267 |
def group_by_key(param_list, key):
"""
Return a dictionary of the form {key_value: [param_list]}
where the list of param sets is broken up according to common key values
>>> param_list = [{'a':0, 'b':1, 'c':2, 'd':3, 'name':'counter'}, {'a':0, 'b':1, 'c':3, 'name':'jumper'}, {'a':0, 'b':'beta', 'name':'greek'}]
... | 90fb9857385b19d72bd723eb5207f0a577b99434 | 397,274 |
import math
def trunc_gaussmf(x, parameters):
"""
Gaussian Truncated fuzzy membership function
:param x: data point
:param parameters: a list with 2 real values (mean and variance) and 2 limits
:return: the membership value of x given the parameters
"""
mean = parameters[0]
var = para... | a8160968379f626378774137d59662af5527110c | 344,199 |
import json
def LoadJSON(json_string):
"""Loads json object from string, or None.
Args:
json_string: A string to get object from.
Returns:
JSON object if the string represents a JSON object, None otherwise.
"""
try:
data = json.loads(json_string)
except ValueError:
data = None
return ... | 598c9b4d5e358a7a4672b25541c9db7743fcd587 | 709,634 |
def get_domain_id_field(domain_table):
"""
A helper function to create the id field
:param domain_table: the cdm domain table
:return: the id field
"""
return domain_table + '_id' | 5805da82b4e57d14d4105d92a62cf4b5cc4bc3f2 | 5,711 |
def get_form_field_chart_url(url, field):
"""Append 'field_name' to a given url"""
return u'%s?field_name=%s' % (url, field) | 239147fdac8d2f953aba3152b1e709b0057207d5 | 216,978 |
import time
def timef(fun):
"""
decorator to record execution time of a function
"""
def wrapper(*args,**kwargs):
start = time.time()
res = fun(*args,**kwargs)
end = time.time()
print(f'Function {fun.__name__} took {end-start}s\n')
return res
return wrapper | 17e2ce5caf7e32b74306c57a8f8d03afb4a92272 | 281,106 |
import string
def hex_escape(bin_str):
"""
Hex encode a binary string
"""
printable = string.ascii_letters + string.digits + string.punctuation + ' '
return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str) | f934aa66f3821272f89aafdf12e1343b297b3370 | 191,584 |
from typing import List
def attributes_to_list(attributes: str) -> List[str]:
"""Transform a string with potentially multiple attributes to a list of the attributes.
Args:
attributes: Attributes as a single string.
Returns:
List of attributes.
"""
attributes_list = attributes.spl... | 011a9cdeaba4830ea931e5cc67040111d4abb557 | 196,032 |
def filter_images_by_tags(annotations_df, include=None, exclude=None):
"""Filter images on tags
:param annotations_df: pandas DataFrame of project annotations
:type annotations_df: pandas.DataFrame
:param include: include images with given tags
:type include: list of strs
:param exclude: exclud... | 9164b1452dd66145ecd3b1ef4089123330ef04d5 | 590,218 |
def truncate(text, max_len, fill="..."):
"""
Truncate given text to a given maximum length.
Parameters
----------
text : str
The text to truncate.
max_len : int
The maximum allowed length for `text`. If `text` is longer than
`max_len` it will be shortened, otherwise it w... | 8bc0a033b720bba3391fd14eb043c67efc4d7afa | 432,641 |
def is_subsequence(short_seq, long_seq):
"""Is short_seq a subsequence of long_seq."""
if not short_seq:
return True
pos = 0
for x in long_seq:
if pos == len(short_seq):
return True
if short_seq[pos] == x:
pos += 1
if pos == len(short_seq):
return True
return False | cd72675cd423b5ae60f6286575ee3e319bf9c72e | 170,023 |
def add_vec(pos, vec, dt):
"""add a vector to a position"""
px, py, pz = pos
dx, dy, dz = vec
px += dx * dt
py += dy * dt
pz += dz * dt
p = (px, py, pz)
return p | 891bd5a1535fdad58957083369661eff68ab6c25 | 378,729 |
import requests
import json
def get_stock(symbol):
"""
Fetches stock information from the IEX API.
:param symbol: The trading symbol or ticker, e.g. "AAPL" for Apple Inc.
"""
url = 'https://api.iextrading.com/1.0/stock/' + symbol + '/batch'
print(url)
params = { 'types': 'quote' }
... | 2c7a8a858851dab42c2dac318777a4125aa0be4d | 194,108 |
def format_seconds(total_seconds: int) -> str:
"""Format a count of seconds to get a [H:]M:SS string."""
prefix = '-' if total_seconds < 0 else ''
hours, rem = divmod(abs(round(total_seconds)), 3600)
minutes, seconds = divmod(rem, 60)
chunks = []
if hours:
chunks.append(str(hours))
... | c0f79b7f45c32589537b5dbf51a95b4811c50417 | 12,570 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.