content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def ros_unadvertise_service_cmd(service):
"""
create a rosbridge unadvertise_service command object
:param service: name of the service
"""
command = {
"op": "unadvertise_service",
"service": service
}
return command | ef78ba4ffbb6fc8b0f13ccaebdfb13651294a330 | 33,625 |
def mk_struct(name, label, resn=None, chain=None,
color='white', style='cartoon',
transparency=None):
"""Generate the PyMol code to display a structure."""
return """
create %(label)s, %(name)s %(chain)s %(resn)s
show %(style)s, %(label)s
color %(color)s, %(label)s
%(transparency)s
... | 329ec5c8cf2a4d1d54436471a2757d257fb53cca | 33,627 |
import re
def string2lines(astring, tab_width=8, convert_whitespace=False,
whitespace=re.compile('[\v\f]')):
"""
Return a list of one-line strings with tabs expanded, no newlines, and
trailing whitespace stripped.
Each tab is expanded with between 1 and `tab_width` spaces, so that th... | add99c9a5844cc8b7a2c9cc63dc18a42ee4e9f10 | 33,636 |
def add_default(name, **kwargs):
"""Add validator to the plugin class default meta.
Validator will be added to all subclasses by default
:param name: str, name of the validator plugin
:param kwargs: dict, arguments used to initialize validator class
instance
"""
def wrapper(plugin):
... | 96f1bd3faadb636e500a16cd867445714ffe4a52 | 33,637 |
def _lookup_elements(adm, idRefs):
"""Lookup multiple ID references"""
return [adm.lookup_element(key) for key in idRefs] | a6bcecd31142009b202386dd9b5d573163722d0d | 33,640 |
def integrand_x(x, alpha, beta, l, i):
"""Integrand in the reparametrized q^l_i expression."""
return (
x ** (alpha - 1)
* (1 - x) ** (l + beta - i / 2 - 1)
* (1 + x) ** (i / 2)
) | 4eea4308976868ab715951b3e1c64750b2c87a2f | 33,649 |
def depth_to_location(depth: float):
"""
Convert depth (of polyp) to location in colon
based on https://training.seer.cancer.gov/colorectal/anatomy/figure/figure1.html
:param depth:
:return:
"""
locations = []
if depth <= 4:
locations.append('anus')
if 4 <= depth <= 17:
... | 1481bdc4e83d55668d98d19218a6b842c64bb21c | 33,650 |
from datetime import datetime
def GrADStime_to_datetime(gradsTime):
"""
Convert GrADS time string e.g., 00:00z01Jan2000 to datetime
Parameters
----------
gradsTime : str
Grads time in str format e.g., 00:00z01Jan2000.
Returns
----------
re : datetime
"""
l... | df21ac4532510e883245be67ba354f4048761800 | 33,651 |
def add_decoy_tag(peptides):
"""
Adds a '_decoy' tag to a list of peptides
"""
return [peptide + "_decoy" for peptide in peptides] | cc9825c4eb7b6b1bb8b7857b2522bc90fb0e4c01 | 33,652 |
def rejection_sample(fn, condition):
"""
Sample from fn until we get a value that satisfies
condition, then return it.
"""
while True:
value = fn()
if condition(value):
return value | 28674cecc21c6ef30bf1777dd3f4e595c2db1007 | 33,653 |
def mock_time(value):
"""Mock out the time value."""
def _mock():
return value
return _mock | fe4bca50a3593557a74c413980160b812baf6e27 | 33,655 |
def subtile(img, w, h, cx, cy):
"""
Gets a tile-indexed w by h subsurface from the tilemap "img".
"""
return img.subsurface((cx*w, cy*h, w, h)) | c5d996922b58e53775b46b88906e7844cda2d11c | 33,657 |
def qrel_entry(quest_id, answ_id, rel_grade):
"""Produces one QREL entry
:param quest_id: question ID
:param answ_id: answer ID
:param rel_grade: relevance grade
:return: QREL entry
"""
return f'{quest_id}\t0\t{answ_id}\t{rel_grade}' | dcd349ea183ed2ee5c508890f08118dae3844802 | 33,658 |
def find_in_sorted_arr(value, array, after=False):
"""Return position of element in a sorted array.
Returns:
int: the maximum position i such as array[i] <= value. If after is
True, it returns the min i such as value <= array[i] (or 0 if such
an indices does not exist).
"""... | 0a724ca72fdb2abe4feaea3a2b0d971f803479c9 | 33,660 |
def dequeue(interp, queuename):
"""
DEQUEUE queuename
outputs the least recently QUEUEd member of the queue that is the
value of the variable whose name is ``queuename`` and removes that
member from the queue.
"""
var = interp.get_variable(queuename)
return var.pop(0) | cb5141b3779eeedb5ac09d8d14da7403bcdb37c3 | 33,664 |
def r_local(denis, alt):
"""Local recombination from Sultan eq 21 alpha*n_mol
Risbeth & Garriott '69: Dissociative recombination is the principal
E and F region loss mechansim.
Huba '96: RTI not damped by recombination in F region
n_mol is the concentration of molecular ions
alpha... | 89fe0f6bfb0558125f1283d5836940c2937f2c68 | 33,666 |
def LinearizedRockPhysicsModel(Phi, Clay, Sw, R):
"""
LINEARIZED ROCK PHYSICS MODEL
Linear rock physics model based on multilinear regression.
Written by Dario Grana (August 2020)
Parameters
----------
Phi : float or array_like
Porosity (unitless).
Clay : float
Clay volu... | 62287e8d312c020c443663c33f0bf558ad66aa7b | 33,667 |
def _get_loop_decoys(args):
"""Wrapper for Fread.automodel_loop(), to be used with map().
args[0] is a the MultiFread object, args[1] are the sequential
arguments for Fread.automodel_loop(), args[2] are the keyword
arguments for Fread.automodel_loop().
Returns a MultiFread object that is a... | 71e9cf5bd1be078cab862c783dd709bae1b69f61 | 33,669 |
def parse_line(line):
"""Returns a list of ints and a minuend integer.
The line needs to be in the form '1,2,3,...;5' as described in the module
docstring
"""
num_list, minuend = line.split(';')
num_list = [int(num) for num in num_list.split(',')]
minuend = int(minuend)
return num_list,... | 905222663ae3c7b7c3ef9df5d6d7ab783fb28807 | 33,679 |
def time2str(t, fmt='%Y-%m-%d %H:%M:%S', microsec=False):
""" Convert a pandas Timestamp to a string
See https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior for conversion
"""
fmt = fmt + '.%f' if microsec is True else fmt
return t.strftime(fmt)
#return t.strftime(fmt... | a0aecef7b052af4b1c291d6d2a4e54467f319af2 | 33,680 |
def _try_list_if_string(input_str):
"""
Attempt to convert string to list if it is a string
"""
if not isinstance(input_str, str):
return input_str
val_split = input_str.split(",")
if len(val_split) > 1:
return [float(sval.strip()) for sval in val_split]
return input_str | c1c66dcad87dd4be041f6705e2b6252b8889dcd2 | 33,683 |
from typing import List
def _out_of_range(matrix: List[List[int]], row: int, col: int) -> bool:
"""Check if the row/col is out of range."""
return row < 0 or col < 0 or row >= len(matrix) or col >= len(matrix[0]) | 5385b19fd349051a4f869f4669ee16a2861e1e50 | 33,698 |
import math
def dryness_formula(days: int, num_storys: int) -> int:
"""
Dryness(0~1000)
>>> assert dryness_formula(30, 255) == 0, '255 storys per month'
>>> assert dryness_formula(30, 127) == 125, '127 storys per month'
>>> assert dryness_formula(30, 63) == 250, '63 storys per month'
>>> asse... | 0cb6721cb3ea52a926ba43d8fbf81d5343e24172 | 33,700 |
def process_video(self, url):
"""Background task that runs a long function with progress reports."""
def progress_cb(done, total):
self.update_state(state='PROGRESS',
meta={'current': done, 'total': total})
#tag.tag_and_upload(url, progress_cb)
return {'current': 100, '... | da41cda5377a9e97dc3c5a4ac8df7663f36cccd1 | 33,704 |
def form_bowtie_build_cmd_list(bowtie_build_fp, input_contigs_fasta, output_index_fp):
""" format arguments received to generate list used for bowtie_build subprocess call
Args:
bowtie_build_fp(str): the string representing the path to the bowtie program
input_contigs_fasta(list): list of files... | 28af32e6a7626d8bd5647fa12194f0afddb31fbc | 33,705 |
import math
def test3(x, sin=math.sin):
"""
>>> %timeit test3(123456)
1000000 loops, best of 3: 306 ns per loop
"""
return sin(x) | 42ab8ee27fef2d964652d61dbd45ddad883dfd8b | 33,708 |
def check_datasets_compatible(dataset1, dataset2):
"""
Used for cross-corpus datasets that are combined
from two datasets.
Checks if two datasets have the same class names
and original shape.
The first entry of the original shape is ignored,
since the number of samples does not matter.
... | 5cecca002ebcba6b6733acf8b0b521e61e9937db | 33,709 |
def _find_framework_name(package_name, options):
"""
:param package_name: the name of the package
:type package_name: str
:param options: the options object
:type options: dict
:returns: the name of framework if found; None otherwise
:rtype: str
"""
return options.get(package_name, ... | 3b345a5ccbed309ad7a706dce621a8fd405dd9e4 | 33,717 |
def make_number_formatter(decimal_places):
"""
Given a number of decimal places creates a formatting string that will
display numbers with that precision.
"""
fraction = '0' * decimal_places
return ''.join(['#,##0.', fraction, ';-#,##0.', fraction]) | 9d8cfbfb56d01a170f6754925f26f1433a9627e1 | 33,719 |
def convert_node(graph, tree_node):
"""
Add a tree node to a graph.
Parameters
----------
graph : Graph
The graph where the node should be added.
tree_node : Node
The node to be added.
Returns
-------
node_id : int or tuple
The identifier of the added no... | 468b0e87a78e1f289f583f657b04e03132aa123d | 33,722 |
import torch
def to_onehot(c):
""" Creates a onehot torch tensor """
onehot = torch.zeros((1, 1000))
onehot[:, c] = 1.0
return onehot | c89356180d41243158dcee838eab7181f00f870a | 33,726 |
import typing
def _read_exact(stream: typing.BinaryIO, byte_count: int) -> bytes:
"""Read ``byte_count`` bytes from ``stream`` and raise an exception if too few bytes are read
(i. e. if EOF was hit prematurely).
"""
data = stream.read(byte_count)
if len(data) != byte_count:
raise ValueError(f"Attempted to re... | 701180cb98985eca620c7e4d200050d92cc889ea | 33,730 |
def compute_min_distance_mendelian_ci(proband_CI, parent_CIs):
"""Commute the smallest distance between the given proband confidence interval, and the confidence intervals of
parental genotypes.
Args:
proband_CI (Interval): ExpansionHunter genotype confidence interval.
parent_CIs (list of I... | 9b8f71c612972410054b18b05c5e86bda3c96321 | 33,731 |
def is_valid_status_code(status_code):
"""
Returns whether the input is a valid status code. A status code is valid if it's an integer value and in the
range [100, 599] :param status_code: :return:
"""
return type(status_code) == int and 100 <= status_code < 600 | 903878d7fabd6e3abd25d83bb0bbd37e0c8d3ce5 | 33,733 |
from typing import Tuple
def coordinates_to_chunk(x: int, y: int, chunk_size: int) -> Tuple[int, int]:
"""
Convert x, y coordinates to chunk coordinates
"""
normal_x = x // chunk_size
normal_y = y // chunk_size
middle_x = normal_x*chunk_size+(chunk_size//2)
middle_y = normal_y*chunk_size+(... | 40ab03f2a6391f2d11e72cc80d510a3f82af536e | 33,737 |
def prepare_plot_data(n_labels, legends, markers):
"""
:param int n_labels: Number of labels
:param list_or_None legends: List of legends
If None, it will be transformed to list of None
:param list_or_None markers: List of markers
If None, it will be transformed to list of 'circle'
... | 84ce953fd03e9dd548f3e2e7a3e5fcce43b4364a | 33,738 |
def premium(q,par):
""" Returns the (minimum) premium that an insurance company would take
Args:
q (float): coverage
par (namespace): parameter values
Returns:
(float): premium
"""
return par.p*q | 2166bc6e16577a26d3adc17afe5929bf8fca073b | 33,739 |
def fetch_vendor_id(vendor_name, conn):
"""
Retrieve our vendor id from our PostgreSQL DB, table data_vendor.
args:
vendor_name: name of our vendor, type string.
conn: a Postgres DB connection object
return:
vendor id as integer
"""
cur = conn.cursor()
cur.execute("SE... | 504cb7e71791ef7385edf5e143ffa0f4c3d09313 | 33,750 |
import random
import math
def ferma(number: int, k: int = 100) -> bool:
"""Тест простоты Ферма
Wiki:
https://en.wikipedia.org/wiki/Fermat_primality_test
:param number: проверяемое число
:type number: int
:param k: количество тестов
:type k: int, default 100
:return: True если чис... | a36d193ab34db4c75b1738ce63998452b7517693 | 33,752 |
def read_file_first_line(filename):
""" Read first line of given filename """
result = None
with open(filename, 'r') as f:
result = f.readline()
result = result.rstrip("\n")
f.close()
return result | 4cc6502ab76e2bdbf2ccdb2367e69bf02bccf572 | 33,753 |
import torch
def reparameterize(mu, logvar):
"""
Reparameterize for the backpropagation of z instead of q.
This makes it so that we can backpropagate through the sampling of z from
our encoder when feeding the sampled variable to the decoder.
(See "The reparameterization trick" section of https:/... | 339204d7471f319eef4179ca5f89fff79f68f70f | 33,754 |
def get_reference(node, identifiers):
"""Recurses through yaml node to find the target key."""
if len(identifiers) == 1:
return {identifiers[0]: node[identifiers[0]]}
if not identifiers[0]: # skip over any empties
return get_reference(node, identifiers[1:])
return get_reference(node[id... | 5297e7cd7d97b7c7e494a814de8077c3a37f9b90 | 33,769 |
import tarfile
def get_file_from_tar(tar_path, file_name):
"""
Using a partial or full file name, get the full path of the file within the tar.
@param tar_path: path to a tar file
@param file_name: full file name or end of the filename to find
@return the path for the file
"""
with tarfile... | 3f9e093a653aa7f6e9fc4f68138250b8038fbaa2 | 33,774 |
def scale_factor(redshift):
"""
Calculates the scale factor, a, at a given redshift.
a = (1 + z)**-1
Parameters
----------
redshift: array-like
The redshift values.
Returns
-------
a: array-like
The scale factor at the given redshift.
Examples
--------
... | d682cb510f2c7fe53d96b76e88cd5f2bfc964cb5 | 33,777 |
def mock_get_benchmark_config(benchmark):
"""Mocked version of common.benchmark_config.get_config."""
if benchmark == 'benchmark1':
return {
'unsupported_fuzzers': ['fuzzer2'],
}
if benchmark == 'benchmark2':
return {
'unsupported_fuzzers': ['fuzzer2', 'fuzzer... | 2496495fae2293e6ea4b5411f3f44cba1a8dee5d | 33,784 |
def extractRadiantSampleParameters(sample_list):
""" Given a list of samples, extract the parameters into a list. """
jd_list = [s.jd for s in sample_list]
la_sun_list = [s.la_sun for s in sample_list]
rag_list = [s.ra_g for s in sample_list]
decg_list = [s.dec_g for s in sample_list]
vg_list =... | 5f39f27dde793609a3754aa7ee0a8f7c12e12d7e | 33,786 |
def get_batch_len(batch):
"""Return the number of data items in a batch."""
if isinstance(batch, (tuple,list)): # non-vectorized modalities
return len(batch[0])
return len(batch) | 9794e5c050edf951dcc96166364e429a3d61df27 | 33,787 |
from typing import Tuple
def tuple_to_string(tup: Tuple) -> str:
"""Standardized assembly of tuple strings for DTS files
:param tup: typing.Tuple
:return: str
"""
string = ' '.join(tup)
return string | d1abafff084bfd05a4fbfc5116f8004c390a97da | 33,788 |
def extract_pillar_shape(grid):
"""Returns string indicating whether whether pillars are curved, straight, or vertical as stored in xml.
returns:
string: either 'curved', 'straight' or 'vertical'
note:
resqml datasets often have 'curved', even when the pillars are actually 'vertical' or 'str... | 12c754543b89cde31f9c3ef0ebc04d4322ce71f0 | 33,789 |
def parse_archive_csv(path):
"""
Parses archives names file. Returns list of filename lists: [[archive1, archive2, archive3], ...]
:param path:
:return:
"""
with open(path) as f:
lines = f.readlines()
_archives = []
for line in lines:
_archives.append([x for x in line.sp... | ecac6efe412b9f38d0335c2bbe82dc77e6d19547 | 33,794 |
def _get_tcp_slave_address(config):
"""
Get the TCP slave address to be used for the tests.
"""
return config.getoption("--tcp-address") | adec5d4a52f36737766fbc3e7d9b35a8bc5f6eb8 | 33,800 |
def parse_filter_parameters (parameters, parse):
"""
Parse command parameters to get information filtering flags for the command.
:param parameters: The list of parameters provided to the command.
:param parse: The list of filtering parameter names to parse.
:return A list with the values ... | 479ce6b11be9137523c842e64629159b3424b090 | 33,802 |
def subsample_fourier(x, k):
"""Subsampling in the Fourier domain.
Subsampling in the temporal domain amounts to periodization in the Fourier
domain, so the input is periodized according to the subsampling factor.
Parameters
----------
x : numpy array
Input numpy array with at least 3 ... | eba3a9d4a0fea71c0d42c3b7da7b762e56766974 | 33,803 |
def parse_multiple(s, f, values=None):
"""Parse one or more comma-separated elements, each of which is parsed
using function f."""
if values is None: values = []
values.append(f(s))
if s.pos < len(s) and s.cur == ',':
s.pos += 1
return parse_multiple(s, f, values)
else:
... | 3ee6dbf85769541bdadcdf4f2de910f54d8dbef5 | 33,808 |
from datetime import datetime
def epochs_to_timestamp(epochs: int, date_format: str = "%B %d, %Y %H:%M:%S %p") -> str:
"""
Converts epochs time representation to a new string date format.
Args:
epochs (int): time in epochs (seconds)
date_format (str): the desired format that the timestamp... | 1535be9f82292a9387abf1123e934af02f743c92 | 33,816 |
from typing import Dict
from typing import Any
def dict2argstr(d: Dict[str, Any]) -> str:
"""Convert a dict to a text of kwd=arg pairs"""
return ",".join("{!s}={!r}".format(key, val) for (key, val) in d.items()) | 88955a2effb166e11f6fec87bb959f536f97d197 | 33,818 |
def _node_types_match(node, node_template):
"""
Verifies whether input and output types of two nodes match. The first has fixed arities of
the input type whereas the second is a template with variable arities.
:param node: Node with fixed input types arities.
:param node_template: A node template w... | 46cb2c6c23aa6965536988c5918f4efa87dc9065 | 33,822 |
import re
def mapping_account(account_map, keyword):
"""Finding which key of account_map contains the keyword, return the corresponding value.
Args:
account_map: A dict of account keywords string (each keyword separated by "|") to account name.
keyword: A keyword string.
Return:
An acco... | 7fa67f75c1b621ca00d87359072c7516b3f097b7 | 33,823 |
import re
def expand_contractions(tweet):
"""
Expands language contractions found in the English vocabulary
in the tweet.
INPUT:
tweet: original tweet as a string
OUTPUT:
tweet with its contractions expanded
"""
tweet = re.sub("can't", 'cannot', tweet, flags=re.I)
#twee... | 5ba8fd9b59488935e3a4f49372b6c5d1959537d8 | 33,826 |
def _closest_ref_length(references, trans_length):
"""Find the reference that has the closest length to the translation.
Parameters
----------
references: list(list(str))
A list of references.
trans_length: int
Length of the translation.
Returns
-------
closest_ref_len:... | aaa5b2f021fc1996d30258af8dbe2ada69bc85aa | 33,829 |
def cli_parse(parser):
"""Add method specific options to CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object
"""
parser.add_argument('--max-order', type=int, required=False, default=2,
choices=[1, 2],
... | c267bb818c8fa317162304c5aa37d02bad63daee | 33,832 |
import pathlib
import json
def save(data: dict, path: pathlib.Path) -> bool:
"""Save a provided dictionary to file in json.
Parameters
----------
data : dict
The dictionary to be saved to file.
path : pathlib.Path
The path to the file to be saved. This path should included the... | e272abbc4e0f4a1193d2bb4ed7b11ed452519daa | 33,835 |
def filter_none(data):
"""Helper function which drop dict items with a None value."""
assert isinstance(data, dict), "Dict only"
out = {key: value for key, value in data.items() if value is not None}
return out | 25c09c878e1e5c25b93d4947937d38f4bf2b965a | 33,836 |
def max_integer(my_list=[]):
"""
finds the largest integer of a list
"""
if len(my_list) == 0:
return (None)
my_list.sort()
return (my_list[-1]) | d6aa168b1d5207d04761542285bb388c1d235c2b | 33,851 |
def unwrap_twist(twist):
"""
Unwraps geometry_msgs/Twist into two tuples of linear and angular velocities
"""
l_x = twist.linear.x
l_y = twist.linear.y
l_z = twist.linear.z
a_x = twist.angular.x
a_y = twist.angular.y
a_z = twist.angular.z
return (l_x, l_y, l_z), (a_x, a_y, a_z) | 66c4eceeea7791790252ea01c7e8aabe28ea9be0 | 33,852 |
def is_x_a_square(x: int) -> bool:
"""Is x a square number?"""
if x == 0:
return False
left = 1
right = x
while left <= right:
mid = left + (right - left) // 2
if mid ** 2 == x:
return True
elif mid ** 2 < x:
left = mid + 1
else:
... | d6587a6e52c5c189e42da06976fb8f2027c9de82 | 33,858 |
def findFirstWorldFilename(worldsFilename):
"""Get the first world file name."""
file = open(worldsFilename)
worldFilename = file.readline().strip()
file.close()
return worldFilename | c590887b31e53b73b14370dd1aaaebe44afaadb9 | 33,859 |
def templatize(names, claim):
"""Transform a claim into a regex-capable template."""
for name in names:
while name in claim:
claim = claim.replace(name, "name")
while "knave" in claim:
claim = claim.replace("knave", "k_id")
while "knight" in claim:
claim = claim.rep... | 816d29786591740a0f928f94880ca08dd1b7f525 | 33,864 |
def prompt_input(prompt, default=None, interrupt=None):
"""
Prompt the user for [y]es/[n]o input, return a boolean accordingly.
Parameters
----------
prompt : str
The prompt text presented on-screen to the user.
default : {'y', 'yes', 'n', 'no'}, optional
The default response if... | e112a9566b5809a1552f01a08e2ab448142b20ed | 33,869 |
def get_image_url(date):
""" Return the URL to the frontpage of the NYT on a certain date.
:param date: a `datetime.date` object.
:returns: a `str`, the URL to the image of the frontpage of the NYT on the
requested date.
"""
_frontpage_url_template = ('http://www.nytimes.com/images'
... | 3f845c695e2db210be032971cfd71dbc6db96c72 | 33,870 |
import random
def partitionByState(ser, holdouts=1):
"""
Creates training and test indexes by randomly selecting
a indices for each state.
:param pd.DataFrame ser: Classes for instances
:param int holdouts: number of holdouts for test
:return list-object, list-object: test, train
"""
classes = ser.uni... | c98d7ee7d7ddeafa97285db9df339db1a01a188f | 33,872 |
def get_times(ts_full, ts_system, len_state, sys_position, sys_length):
"""
This is a function specifically designed for TEDOPA systems. It calculates
the proper 'ts' and 'subsystems' input lists for :func:`tmps.evolve` from a
list of times where the full state shall be returned and a list of times
... | 26495149a867ed9b42da4c0db288d81c4db350dc | 33,877 |
def find_distance(a, b, c):
"""Determine if distance between three ints is equal
assuming unsorted entries"""
int_holder = [a, b, c]
int_holder.sort()
distance_1 = int_holder[1] - int_holder[0]
distance_2 = int_holder[2] - int_holder[1]
if distance_1 == distance_2:
return 'They are... | 3e488b631c248de3069f4167f157022358114852 | 33,879 |
def read_playlist(filename):
"""
Input: filename of CSV file listing (song,artist,genre) triples
Output: List of (song,artist,genre)
"""
playlist = []
for line in open(filename):
bits = [b.strip() for b in line.split(',')]
playlist.append(bits)
return playlist | efb8a03e3539c6b3b63ab8a806453e4bc04469c2 | 33,883 |
def _parser_setup(parser_obj, value, reset_default=False):
"""Add argument to argparse object
Parameters
----------
parser_obj : object
argparse object
value : dict
argparse settings
reset_default : bool
boolean that defines if default values should be used
Returns
... | 58d1ccde88a6ada8b7f4a09d50d083e3e86677bd | 33,887 |
def full_email(service_account):
"""Generate the full email from service account"""
return "{0}@{1}.{2}".format(service_account.name, service_account.project,
service_account.suffix) | 8b5305f794fd59b24adfefca1338db594fb799bc | 33,897 |
def is_sum(n, power):
"""Returns whether n is equal to the sum of its digits to the given power"""
if n == 1:
return False
return n == sum([int(d)**power for d in str(n)]) | 480c3ca2a4afbc3836c40620152aff020d351cde | 33,906 |
def ExtractWordsFromLines(lines):
"""Extract all words from a list of strings."""
words = set()
for line in lines:
for word in line.split():
words.add(word)
return words | 1b5d53466b495a578b8656f606093fedadf56161 | 33,911 |
def jsonpath_to_variable(p):
"""Converts a JSON path starting with $. into a valid expression variable"""
# replace $ with JSON_ and . with _
return p.replace('$', 'JSON_').replace('.', '_') | ee09b0a6d0a24c414f446d7ef18edb3ef118fd1e | 33,912 |
def _is_scrolled_into_view(driver, element, fully_in_view=True):
"""Returns True if the element is scrolled into view, False otherwise
Currently, Selenium doesn't offer a means of getting an element's location
relative to the viewport, so using JavaScript to determine whether the
element is visible wit... | e83a93a18024e185c6cbfce73dc6af6ebc35ca48 | 33,913 |
def quote_message(body: str, message):
"""Construct a body (with a signature) and a quoted reply."""
original = body.split("\n")
original.append("")
original.append(message.conversation.sender_name)
original.append("CEO, %s" % message.conversation.domain.company_name)
reply = []
reply.appen... | bbff4d670f94768aba6c5dff6a309abf9fb0c238 | 33,918 |
import requests
def make_request(request):
"""
HTTP Cloud Function that makes another HTTP request.
Args:
request (flask.Request): The request object.
Returns:
The response text, or any set of values that can be turned into a
Response object using `make_response`
<http:... | 172f4db34f3e3e25ead1e269159c5f0f08cdf9a4 | 33,922 |
import requests
def get_histohour(fsym = 'BTC', tsym = 'USD', e = 'CCCAGG', limit = 1920, optional_params = {}):
"""Gets hourly pricing info for given exchange
Args:
Required:
fsym (str): From symbol
tsym (str): To symbol
e (str): Name of exchange
Optio... | 0a40d62685d438d0f2bd896a2b905e8e66d56a87 | 33,936 |
def TypeSetter(constructor=None):
"""Returns function that takes obj, field, val and sets obj.field = val.
constructor can be any callable that returns an object.
"""
if constructor:
def setter(obj, field, val):
setattr(obj, field, constructor(val))
else:
def setter(o... | d42cc9320478d723db8437f38d34d3a2307d6b14 | 33,942 |
def is_sorted(list_):
"""
Return True iff list_ is in non-decreasing order.
@param list list_: list to inspect
@rtype bool:
>>> is_sorted([1, 3, 5])
True
>>> is_sorted([3, 1, 5])
False
"""
for j in range(1, len(list_)):
if list_[j - 1] > list_[j]:
return Fal... | 744aedacdedff9ff5453049e3b4631eb02e11178 | 33,946 |
def monthdelta(date, delta):
"""
Method to get a delta of Months from a provided datetime
From this StackOverflow response:
http://stackoverflow.com/questions/3424899/whats-the-simplest-way-to-subtract-a-month-from-a-date-in-python
Arguments:
date datetime: Date to be modified
delt... | aeb32e2f278a9a455b06f4e24b2b84f81860d139 | 33,948 |
def is_string_ipv4(string):
"""
判断一个字符串是否符合ipv4地址规则
:param string: 输入的字符串
:return: 一个元祖: (逻辑结果, ipv4 string 或 None)
"""
string = string.strip()
seg = string.split('.')
if len(seg) != 4:
return False, None
else:
try:
if not all([_si.isdigit() and -1 < int... | adfc59b3e87359fb194070d7dcb5b1e7fcde49b1 | 33,949 |
def find_sum_pair(numbers, target):
"""Find a pair of numbers from a list that sum to the target value"""
for ix, x in enumerate(numbers):
for iy, y in enumerate(numbers):
if ix != iy and x + y == target:
return x, y
return None | b0bd08deb88bd95f3b50fd23bb8cfb371a7483a1 | 33,950 |
def get_timesteps(trajectory):
"""
Determine valid timesteps for the associated hdf5 dump
Parameters
----------
trajectory : The decoded hdf5 file containing the dumped run data.
Usually from something like h5py.File(infile, 'r')
Returns
-------
A tuple consisting of three entr... | 01afcb93c9f226872cef342d048550f17820d9db | 33,962 |
def is_range(obj):
"""Helper function to test if object is valid "range"."""
keys = ['start', 'step', 'stop']
return isinstance(obj, dict) and all(k in obj for k in keys) and \
all(isinstance(obj[k], float) for k in keys) | 4bb1d210ebb0a7265671b3d7070912052f71601e | 33,963 |
def __find_team(teams, team_tricode):
"""
Auxilary function to find the team that matches the tricode.
Args:
teams: list of NBA teams.
team_tricode: the tricode of the given team.
Returns:
corresponding team for the given tricode
"""
#team = key(full team names, exampl... | 7bc9973a7925cb2a8d88915b707cfd2aa40e143b | 33,968 |
def filter_req(req, extra):
"""Apply an extra using a requirements markers and return True if this requirement is kept"""
if extra and not req.marker:
return False
keep_req = True
if req.marker:
if not extra:
extra = None
keep_req = req.marker.evaluate({"extra": extra... | 9d095db4a51d8d77d387b94965c1fafdc8d4c304 | 33,969 |
def ipv4_reassembly(frame):
"""Make data for IPv4 reassembly.
Args:
frame (pcapkit.protocols.pcap.frame.Frame): PCAP frame.
Returns:
Tuple[bool, Dict[str, Any]]: A tuple of data for IPv4 reassembly.
* If the ``frame`` can be used for IPv4 reassembly. A frame can be reassembled
... | b55ac3f9caa0007dd8a70a56de704f25a403755c | 33,971 |
def element_count( atoms ):
"""
Counts the number of each element in the atoms object
"""
res = {}
for atom in atoms:
if ( not atom.symbol in res.keys() ):
res[atom.symbol] = 1
else:
res[atom.symbol] += 1
return res | 963ada4238e918a26df1c0b090b0035a6da638ff | 33,980 |
def td(txt):
"""Format text as html table data."""
return "<td>" + txt + "</td>" | 0e27b75dc40b242f2e39da44bd7d8750bfd4c498 | 33,983 |
def get_provenance_record(caption, ancestor_files, **kwargs):
"""Create a provenance record describing the diagnostic data and plot."""
record = {
'caption': caption,
'authors': ['schlund_manuel'],
'references': ['acknow_project'],
'ancestors': ancestor_files,
}
record.up... | 9ecfe152c21b27854fd9082c63f910b5ccbd9df8 | 33,985 |
def get_datetime_string(datetime):
"""
Given a datetime object, return a human readable string (e.g 05/21/2014 11:12 AM)
"""
try:
if datetime is not None:
return datetime.strftime("%m/%d/%Y %I:%M %p")
return None
except:
return None | d55f024c9b5995d1b544f5a58f4f8de7498fef2a | 33,986 |
import random
def getsimulatedgenereadcounts(numgenes,numreads):
"""
Computes number of simulated reads for all genes
input:
numgenes=total number of genes for which reads are generated
numreads==total number of reads generated
output:
a list of size numgenes containing the num... | e54a4cb16ed3f6a00c59f5d6a2372b8776dc189d | 33,990 |
def emft(self, **kwargs):
"""Summarizes electromagnetic forces and torques.
APDL Command: EMFT
Notes
-----
Use this command to summarize electromagnetic force and torque in both
static electric and magnetic problems. To use this command, select the
nodes in the region of interest and make ... | 77e4321d607a991565f4d55fc661ce9777b8bb1c | 33,994 |
def lines_for_reconstruction(unicode_text):
"""Split unicode_text using the splitlines() str method,
but append an empty string at the end if the last line
of the original text ends with a line break, in order
to be able to keep this trailing line end when applying
LINE_BREAK.join(splitted_lines).
... | 228a94218c1dc0babf984f488e38184483530675 | 33,997 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.