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
""" % {
'label': label, # ENH: make optional
'name': name,
'resn': ("and resn %s" % resn) if resn else '',
'chain': ("and chain %s" % chain) if chain else '',
'color': color,
'style': style,
'transparency': ("set %s_transparency=%s, %s\n" %
(style.rstrip('s'), transparency, label)
if transparency is not None else ''),
}
|
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 the
next character's index becomes a multiple of `tab_width` (8 by default).
Parameters:
- `astring`: a multi-line string.
- `tab_width`: the number of columns between tab stops.
- `convert_whitespace`: convert form feeds and vertical tabs to spaces?
- `whitespace`: pattern object with the to-be-converted
whitespace characters (default [\\v\\f]).
"""
if convert_whitespace:
astring = whitespace.sub(' ', astring)
lines = [s.expandtabs(tab_width).rstrip() for s in astring.splitlines()]
return lines
|
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):
if not hasattr(plugin, "DEFAULT_META"):
plugin.DEFAULT_META = {}
plugin.DEFAULT_META.setdefault("validators", [])
plugin.DEFAULT_META["validators"].append((name, (), kwargs,))
return plugin
return wrapper
|
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:
locations.append('rectum')
if 15 <= depth <= 57:
locations.append('sigmoid')
if 57 <= depth <= 82:
locations.append('descending')
if 80 <= depth <= 84: # I made this up
locations.append('hepatic')
if 82 <= depth <= 132:
locations.append('transverse')
if 130 <= depth <= 134:
locations.append('splenic')
if 132 <= depth <= 147:
locations.append('ascending')
if 147 <= depth:
locations.append('cecum')
return locations
|
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
"""
lens = len(gradsTime)
if lens==15 or lens==14:
time = datetime.strptime(gradsTime, "%H:%Mz%d%b%Y")
elif lens==12 or lens==11:
time = datetime.strptime(gradsTime, "%Hz%d%b%Y" )
elif lens== 9 or lens== 8:
time = datetime.strptime(gradsTime, "%d%b%Y" )
elif lens== 7:
time = datetime.strptime(gradsTime, "%b%Y" )
else:
raise Exception('invalid length of GrADS date/time string')
return time
|
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).
"""
ielt = array.searchsorted(value)
if ielt == array.size:
ielt -= 1
if not after and array[ielt] != value and ielt > 0:
ielt -= 1
return ielt
|
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 = 2*10**(-7) according to Sultan '92
alpha ~ 10**(-7) according to Risbeth & Garriott '69
"""
n_mol = 0
if alt < 200:
return 0
for i, n_i in enumerate(denis):
if i == 2 | i == 3 | i == 5:
n_mol += n_i
return n_mol*2*10**(-7)
|
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 volume (unitless).
Sw : float
Water saturation (unitless)
R : float
Regression coefficients matrix
estimated with regress.m
Returns
-------
Vp : float or array_like
P-wave velocity (km/s).
Vs : float or array_like
S-wave velocity (km/s).
Rho : float or array_like
Density (g/cc).
References: Grana, Mukerji, Doyen, 2021, Seismic Reservoir Modeling: Wiley - Chapter 2.1
"""
# multilinear regression
Vp = R[0, 0] * Phi + R[0, 1] * Clay + R[0, 2] * Sw + R[0, 3]
Vs = R[1, 0] * Phi + R[1, 1] * Clay + R[1, 2] * Sw + R[1, 3]
Rho = R[2, 0] * Phi + R[2, 1] * Clay + R[2, 2] * Sw + R[2, 3]
return Vp, Vs, Rho
|
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 copy of the input object,
which also contains the modelling results, warnings, etc.
You can access the results and warnings like so:
fread_objects = map(_get_loop_decoys, argslist)
for obj in fread_objects:
for decoy in obj.results:
# do something
for warning in obj.warnings:
# do something
"""
frd, seqargs, kwargs = args
frd.set_silent()
frd.automodel_loop(*seqargs, write_models=False, **kwargs)
return frd
|
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, minuend
|
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'
>>> assert dryness_formula(30, 31) == 375, '31 storys per month'
>>> assert dryness_formula(30, 15) == 500, '15 storys per month'
>>> assert dryness_formula(30, 7) == 625, '7 storys per month'
>>> assert dryness_formula(30, 3) == 750, '3 storys per month'
>>> assert dryness_formula(30, 1) == 875, '1 storys per month'
>>> assert dryness_formula(30, 0) == 1000, '0 storys per month'
>>> assert dryness_formula(1, 0) == 1000, '0 storys per day'
>>> assert dryness_formula(0, 0) == 1000, '0 storys'
"""
v = math.log2(256 / (num_storys / (days + 1) * 31 + 1))
return max(0, min(1000, round(v / 8 * 1000)))
|
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, 'total': 100, 'status': 'Task completed!', 'result': 42}
|
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 which represent the fasta file inputs used for index construction
output_index_fp(str): base name of file path to be used as output directory for index files
Returns:
call_args_list(list): the sequence of commands to be passed to the bowtie2 build call
"""
if bowtie_build_fp is '':
raise ValueError('bowtie2_build_path name is empty')
if output_index_fp is '':
raise ValueError('output file name invalid. index_output_fp is None')
if input_contigs_fasta is '' or input_contigs_fasta is None:
raise ValueError('no fasta file found')
# required arguments
calls_args_list = [bowtie_build_fp, input_contigs_fasta, output_index_fp]
return calls_args_list
|
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.
Returns: class_names, original_shape
Raises: Exception if datasets are not compatible
"""
# check class names
class_names1 = dataset1['class_names']
class_names2 = dataset2['class_names']
msg = f'Class names are not equal: {class_names1}, {class_names2}'
e = Exception(f'Datasets are not compatible!\n{msg}')
if len(class_names1) != len(class_names2):
raise e
for i in range(len(class_names1)):
if class_names1[i] != class_names2[i]:
raise e
# check if both have a shape or not
has_shape1 = has_shape2 = False
if 'specs' in dataset1 and 'original_shape' in dataset1['specs']:
has_shape1 = True
if 'specs' in dataset2 and 'original_shape' in dataset2['specs']:
has_shape2 = True
if has_shape1 and not has_shape2:
raise Exception(
'Dataset 1 has a original_shape but dataset 2 does not!')
if has_shape2 and not has_shape1:
raise Exception(
'Dataset 2 has a original_shape but dataset 1 does not!')
# check shapes
original_shape = None
if has_shape1 and has_shape2:
shape1 = dataset1['specs']['original_shape']
shape2 = dataset2['specs']['original_shape']
msg = f'Shapes are not equal: {shape1}, {shape2}'
e = Exception(f'Datasets are not compatible!\n{msg}')
if len(shape1) != len(shape2):
raise e
for i in range(1, len(shape1)):
if shape1[i] != shape2[i]:
raise e
original_shape = shape1
return class_names1, original_shape
|
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, {}).get('framework-name', None)
|
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 node in the graph.
If the node is a leaf node, this is the reference index,
otherwise this is a tuple, containing the identifier of the
child nodes.
distance : float
The distance of the given node to its parent node.
"""
if tree_node.is_leaf():
return tree_node.index, tree_node.distance
else:
child_ids = []
child_distances = []
for child_node in tree_node.children:
id, dist = convert_node(graph, child_node)
child_ids.append(id)
child_distances.append(dist)
this_id = tuple(child_ids)
for id, dist in zip(child_ids, child_distances):
# Add connection to children as edge in the graph
# Distance is added as attribute
graph.add_edge(this_id, id, distance=dist)
return this_id, tree_node.distance
|
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 read {byte_count} bytes of data, but only got {len(data)} bytes")
return data
|
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 Intervals): list of ExpansionHunter genotype confidence intervals.
Return:
int: the smallest distance (in base-pairs) between one of the Interval in the parent_CIs Interval list, and
the given proband_CI.
"""
return min([abs(proband_CI.distance_to(parent_CI)) for parent_CI in parent_CIs])
|
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+(chunk_size//2)
return middle_x, middle_y
|
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'
:returns: legends, markers
- legends : transformed list of legends
- markers : transformed list of markers
Usage
>>> n_labels = 3
>>> legends, markers = None, None
>>> legends, markers = prepare_plot_data(n_labels, legends, markers)
>>> print(legends)
[None, None, None]
>>> print(markers) # default markers
['circle', 'circle', 'circle']
"""
if legends is None:
legends = [None] * n_labels
if markers is None:
markers = ['circle'] * n_labels
def length_checker(list):
if len(list) < n_labels:
list_instance = locals()['list']
raise ValueError(
f'Number of labels is {n_labels}, however too short list: {list_instance}')
for list in [legends, markers]:
length_checker(list)
return legends, markers
|
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("SELECT id FROM data_vendor WHERE name = %s", (vendor_name,))
# will return a list of tuples
vendor_id = cur.fetchall()
# index to our first tuple and our first value
vendor_id = vendor_id[0][0]
return vendor_id
|
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 если число псевдопростое, False если составное
:rtype: bool
"""
if number == 2:
return True
for _ in range(1, k + 1):
random_number = (random.randint(1, number) % (number - 2)) + 2
# проверка на взаимную простоту чисел random_number и number
if math.gcd(random_number, number) != 1:
return False
# проверка условия теоремы Ферма, с использованием возведения
# числа в степень по модулю
if pow(random_number, number - 1, number) != 1:
return False
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://arxiv.org/abs/1312.6114)
Args:
mu (torch.Tensor): batch of means from the encoder distribution
logvar (torch.Tensor): batch of log variances from the encoder distribution
Returns:
z (torch.Tensor): batch of sampled latents from the encoder distribution that
support backpropagation
"""
# logvar = \log(\sigma^2) = 2 * \log(\sigma)
# \sigma = \exp(0.5 * logvar)
# clamped for numerical stability
logstd = (0.5 * logvar).clamp(-4, 15)
std = torch.exp(logstd)
# Sample \epsilon from normal distribution
# use std to create a new tensor, so we don't have to care
# about running on GPU or not
eps = std.new(std.size()).normal_()
# Then multiply with the standard deviation and add the mean
z = eps.mul(std).add_(mu)
return z
|
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[identifiers[0]], identifiers[1:])
|
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.open(tar_path, 'r') as tar_fh:
for i in tar_fh.getmembers():
if i.name.endswith(file_name):
return i.name
|
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
--------
>>> scale_factor(1)
0.5
>>> scale_factor(np.array([0, 1, 2, 3]))
array([1, 0.5, 0.3333333, 0.25])
"""
a = (1 + redshift)**-1.0
return a
|
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', 'fuzzer3'],
}
return {}
|
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 = [s.vg for s in sample_list]
lam_list = [s.lam for s in sample_list]
bet_list = [s.bet for s in sample_list]
return jd_list, la_sun_list, rag_list, decg_list, vg_list, lam_list, bet_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 'straight';
use actual_pillar_shape() method to determine the shape from the actual xyz points data
"""
if grid.pillar_shape is not None:
return grid.pillar_shape
ps_node = grid.resolve_geometry_child('PillarShape')
if ps_node is None:
return None
grid.pillar_shape = ps_node.text
return grid.pillar_shape
|
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.split()])
return _archives
|
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 for the filtering flags. The order in which they are returned
matches the order they were defined in the parsing list.
"""
parsed = []
for flag in parse:
val = parameters.get (flag, "false")
if (val == "true"):
parsed.append (True)
else:
parsed.append (False)
if (not any (parsed)):
parsed = [True] * len (parse)
return parsed
|
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 dimensions.
k : int
The subsampling factor.
Returns
-------
res : numpy array
The input numpy array periodized along the last axis to yield a
numpy array of size x.shape[-2] // k along that dimension.
"""
N = x.shape[-1]
res = x.reshape(x.shape[:-2] + (k, N // k)).mean(axis=-2, keepdims=True)
return res
|
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:
return values
|
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 will be.
Returns:
str: timestamp in the new format, empty string in case of a failure
"""
try:
return datetime.utcfromtimestamp(epochs).strftime(date_format)
except TypeError:
return ""
|
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 with variable arities.
:return bool: True if the types of the nodes match.
"""
# out types match?
if node.out_type != node_template.out_type:
return False
# in types (and arities) match?
in_types = node.in_type
template_types = node_template.type_arity_template
if len(in_types) != len(template_types):
return False
for in_type_1, in_type_2 in zip(in_types, template_types):
# check type compatibility
if in_type_1.name != in_type_2.prim_type:
return False
# check arity compatibility
if not in_type_2.is_valid_arity(in_type_1.arity):
return False
return True
|
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 account name string.
Raises:
KeyError: If "DEFAULT" keyword is not in account_map.
"""
if "DEFAULT" not in account_map:
raise KeyError("DEFAULT is not in " + account_map.__str__)
account_name = account_map["DEFAULT"]
for account_keywords in account_map.keys():
if account_keywords == "DEFAULT":
continue
if re.search(account_keywords, keyword):
account_name = account_map[account_keywords]
break
return account_name
|
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)
#tweet = re.sub("cant", 'can\'t', tweet, flags=re.I)
tweet = re.sub("won't", 'will not', tweet, flags=re.I)
#tweet = re.sub("wont", 'won\'t', tweet, flags=re.I)
tweet = re.sub("n't", ' not', tweet, flags=re.I)
tweet = re.sub("i'm", 'i am', tweet, flags=re.I)
#tweet = re.sub("im", 'i am', tweet, flags=re.I)
tweet = re.sub("'re", ' are', tweet, flags=re.I)
tweet = re.sub("it's", 'it is', tweet, flags=re.I)
tweet = re.sub("that's", 'that is', tweet, flags=re.I)
tweet = re.sub("'ll", ' will', tweet, flags=re.I)
tweet = re.sub("'l", ' will', tweet, flags=re.I)
tweet = re.sub("'ve", ' have', tweet, flags=re.I)
tweet = re.sub("'d", ' would', tweet, flags=re.I)
tweet = re.sub("he's", 'he is', tweet, flags=re.I)
tweet = re.sub("she's", 'she is', tweet, flags=re.I)
tweet = re.sub("what's", 'what is', tweet, flags=re.I)
tweet = re.sub("who's", 'who is', tweet, flags=re.I)
tweet = re.sub("'s", '', tweet, flags=re.I)
tweet = re.sub("\'em", ' \'em', tweet, flags=re.I)
return tweet
|
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: int
Length of the reference that is closest to the translation.
"""
ref_lengths = (len(reference) for reference in references)
closest_ref_len = min(ref_lengths,
key=lambda ref_length: (abs(ref_length - trans_length), ref_length))
return 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],
help='Maximum order of sensitivity indices \
to calculate')
parser.add_argument('--skip-values', type=int, required=False, default=1024,
help='Number of sample points to skip (default: 1024)')
# hacky way to remove an argument (seed option is not relevant for Saltelli)
remove_opts = [x for x in parser._actions if x.dest == 'seed']
[parser._handle_conflict_resolve(None, [('--seed', x), ('-s', x)]) for x in remove_opts]
return parser
|
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
file name, and any file extensions you wish, but ideal use the
.json extension for transparency.
Returns
-------
bool,
Returns true if the save opperation terminated without error.
"""
with open(path, 'w') as fp:
json.dump(data, fp, indent=4, sort_keys=True)
return True
|
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:
right = mid - 1
return False
|
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.replace("knight", "k_id")
while " am " in claim:
claim = claim.replace(" am ", " is ")
return claim.lower()
|
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 the user presses return without entering
any text. if `None` (default), re-prompt the user until input is
provided.
interrupt : {'y', 'yes', 'n', 'no'}, optional
The default response if a `KeyboardInterrupt` is raised
(`CTRL + c` from the command line, "interrupt kernel/runtime"
from a Jupyter/Colab notebook). If `None` (default), the
exception is raised. Use with caution to avoid unexpected
behavior and improperly silencing errors.
Returns
-------
bool
The boolean value corresponding to the user input (`True` for
`'y'`/`'yes'`, `False` for `'n'`/`'no'`).
Notes
-----
The `default` value is reflected in the casing of options displayed
after the `prompt` text (e.g., "`[Y/n]`" if `default="yes"`)
"""
response_values = {
'yes': True,
'y': True,
'no': False,
'n': False
}
if interrupt is not None:
interrupt = interrupt.lower()
if interrupt not in response_values.keys():
raise ValueError(
f"'interrupt' must be one of {tuple(response_values.keys())}"
)
if default is not None:
default = default.lower()
try:
default_value = response_values[default]
except KeyError as e:
raise ValueError(
f"'default' must be one of: {tuple(response_values.keys())}"
) from e
response_values[''] = default_value
opts = '[Y/n]' if default_value else '[y/N]'
else:
opts = '[y/n]'
while True:
try:
response = input(f"{prompt}\n{opts} ").lower()
return response_values[response]
except KeyboardInterrupt:
if interrupt is not None:
return response_values[interrupt]
raise
except KeyError:
pass
|
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'
'/{year}/{month}/{day}/nytfrontpage/scan.jpg')
return _frontpage_url_template.format(
year=date.year,
month=str(date.month).zfill(2),
day=str(date.day).zfill(2),
)
|
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.unique().tolist()
classes.sort()
test_idxs = []
for cls in classes:
ser_cls = ser[ser == cls]
if len(ser_cls) <= holdouts:
raise ValueError(
"Class %s has fewer than %d holdouts" %
(cls, holdouts))
idxs = random.sample(ser_cls.index.tolist(),
holdouts)
test_idxs.extend(idxs)
#
train_idxs = list(set(ser.index).difference(test_idxs))
return train_idxs, test_idxs
|
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
where only the reduced state of the system in question shall be returned.
ts then basically is a concatenation of ts_full and ts_system,
while subsystems will indicate that at the respective time in ts either
the full state or only a reduced density matrix should be returned.
Args:
ts_full (list[float]):
List of times where the full state including environment chain
should be returned
ts_system (list[float]):
List of times where only the reduced density matrix of the system
should be returned
len_state (int):
The length of the state
sys_position (int):
The position of the system (first site would be 0)
sys_length (int):
Length of the system, i.e. number of sites the system is
comprised of
Returns:
tuple(list[float], list[list[int]]):
Times and subsystems in the form that has to be provided to
:func:`tmps.evolve`
"""
ts = list(ts_full) + list(ts_system)
subsystems = [[0, len_state]] * len(ts_full) + \
[[sys_position, sys_position + sys_length]] * len(ts_system)
return ts, subsystems
|
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 equally spaced'
return None
|
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
-------
parser_obj : object
updated argparse object
"""
if reset_default:
default = None
else:
default = value["default"]
if value["action"] is None:
parser_obj.add_argument(
*value["tag"],
help=value["help"],
default=default,
choices=value["choices"],
)
else:
parser_obj.add_argument(
*value["tag"],
help=value["help"],
default=default,
action=value["action"],
)
return parser_obj
|
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 within the viewport.
:param driver: Selenium WebDriver object
:param element: WebElement for the element to check
:param fully_in_view: (Default = True) If True, check that the element is
fully in view and not cut off. If False, check that it's at least
partially in view
:return: True if the element is scrolled into view, False otherwise
"""
# the JavaScript used to check if the element is in view.
script_string = '''
return function(el, strict) {
var rect = el.getBoundingClientRect();
var elemTop = rect.top;
var elemBottom = rect.bottom;
if (strict)
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
else
isVisible = elemTop < window.innerHeight && elemBottom >= 0;
return isVisible;
}(arguments[0],arguments[1])
'''
return driver.execute_script(script_string, element, fully_in_view)
|
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.append(
"On %s, %s wrote:"
% (message.timestamp.strftime("%d/%m/%Y %H:%M %p"), message.sender_name)
)
reply.extend(["> " + line for line in message.best_body.split("\n")])
return "\n".join(original), "\n".join(reply)
|
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://flask.pocoo.org/docs/0.12/api/#flask.Flask.make_response>.
"""
# The URL to send the request to
url = 'http://example.com'
# Process the request
response = requests.get(url)
response.raise_for_status()
return 'Success!'
|
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
Optional:
extraParams (str): Name of app
sign (bool): if true, server will sign requests
tryConvention (bool): if false, get values without conversion
aggregate (int):
limit (int): default: 168, max: 2000 (new default: 1920 (80 days))
toTs (timestamp):
Valid exchanges (e):
Cryptsy, BTCChina, Bitstamp, BTER, OKCoin, Coinbase, Poloniex, Cexio, BTCE, BitTrex, Kraken,
Bitfinex, Yacuna, LocalBitcoins, Yunbi, itBit, HitBTC, btcXchange, BTC38, Coinfloor, Huobi,
CCCAGG, LakeBTC, ANXBTC, Bit2C, Coinsetter, CCEX, Coinse, MonetaGo, Gatecoin, Gemini, CCEDK,
Cryptopia, Exmo, Yobit, Korbit, BitBay, BTCMarkets, Coincheck, QuadrigaCX, BitSquare,
Vaultoro, MercadoBitcoin, Bitso, Unocoin, BTCXIndia, Paymium, TheRockTrading, bitFlyer,
Quoine, Luno, EtherDelta, bitFlyerFX, TuxExchange, CryptoX, Liqui, MtGox, BitMarket, LiveCoin,
Coinone, Tidex, Bleutrade, EthexIndia, Bithumb, CHBTC, ViaBTC, Jubi, Zaif, Novaexchange,
WavesDEX, Binance, Lykke, Remitano, Coinroom, Abucoins, BXinth, Gateio, HuobiPro, OKEX
Returns:
history (str) hourly price history from fsym to tsym
"""
url = "https://min-api.cryptocompare.com/data/histohour"
params = {'fsym':fsym, 'tsym':tsym, 'e': e, 'limit': limit}
for k,v in optional_params.items():
params[k] = v
r = requests.get(url = url, params = params)
return r.text
|
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(obj, field, val):
setattr(obj, field, val)
return setter
|
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 False
return True
|
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
delta int: delta value
Returns:
datetime: The datetime with the month delta applied
"""
m, y = (date.month + delta) % 12, date.year + (date.month + delta - 1) // 12
if not m:
m = 12
d = min(date.day, [31,
29 if y % 4 == 0 and not y % 400 == 0
else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1])
return date.replace(day=d, month=m, year=y)
|
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(_si) < 256
for _si in seg]):
return False, None
return True, string
except ValueError:
return False, None
|
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 entries. The first is a sorted list of
integers for every valid timestep.
The second and third are for convenience and represent the start and
end time of the run. (First and last timesteps.)
"""
trajectory_times = sorted([int(k) for k in trajectory['id'].keys()])
start_time = trajectory_times[0]
end_time = trajectory_times[len(trajectory_times)-1]
return(trajectory_times, start_time, end_time)
|
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, example: Toronto Raptors) in the dictionary of teams
for team in teams:
if(teams[team].get_tricode() == team_tricode):
#by returning team we are returning the name of the key in the list of teams which ends
#up being the full name of the team
return team
|
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})
return keep_req
|
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
if it contains IPv4 layer (:class:`pcapkit.protocols.internet.ipv4.IPv4`) and
the **DF** (:attr:`IPv4.flags.df <pcapkit.protocols.internet.ipv4.DataType_IPv4_Flags.df>`)
flag is :data:`False`.
* If the ``frame`` can be reassembled, then the :obj:`dict` mapping of data for IPv4
reassembly (c.f. :term:`ipv4.packet`) will be returned; otherwise, returns :data:`None`.
See Also:
:class:`~pcapkit.reassembly.ipv4.IPv4Reassembly`
"""
if 'IPv4' in frame:
ipv4 = frame['IPv4'].info
if ipv4.flags.df: # dismiss not fragmented frame
return False, None
data = dict(
bufid=(
ipv4.src, # source IP address
ipv4.dst, # destination IP address
ipv4.id, # identification
ipv4.proto.name, # payload protocol type
),
num=frame.info.number, # original packet range number
fo=ipv4.frag_offset, # fragment offset
ihl=ipv4.hdr_len, # internet header length
mf=ipv4.flags.mf, # more fragment flag
tl=ipv4.len, # total length, header includes
header=bytearray(ipv4.packet.header), # raw bytearray type header
payload=bytearray(ipv4.packet.payload or b''), # raw bytearray type payload
)
return True, data
return False, None
|
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.update(kwargs)
return record
|
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 number of reads for each gene
"""
# empirical parameters
lognormmu=3.4
lognormsigma=0.95
lornormrange=[0.1,5.1]
logreadstemp1=[random.gauss(lognormmu,lognormsigma) for i in range(2*numgenes)]
logreadstemp2=[x for x in logreadstemp1 if x>lornormrange[0] and x<lornormrange[1]]
logreads=random.sample(logreadstemp2,numgenes)
reads=[pow(10,x) for x in logreads]
genereads=[int(x*numreads/sum(reads)) for x in reads]
return genereads
|
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 sure that all elements are
selected. If RSYS = 0, the force is reported in the global Cartesian
coordinate system. If RSYS ≠ 0, force is reported in the specified
coordinate system. However, for torque, if RSYS ≠ 0, this command will
account for the shift and rotation as specified by RSYS, but will
report only the Cartesian components.
Forces are stored as items _FXSUM, _FYSUM, _FZSUM, and _FSSUM. Torque
is stored as items _TXSUM, _TYSUM, _TZSUM, and _TSSUM.
This command is valid only with PLANE121, SOLID122, SOLID123, PLANE233,
SOLID236 and SOLID237 elements. For any other elements, you must use
FMAGSUM.
"""
command = f"EMFT,"
return self.run(command, **kwargs)
|
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).
The line break characters below were taken from
<https://docs.python.org/3/library/stdtypes.html#str.splitlines>
"""
if isinstance(unicode_text, str):
splitted_lines = unicode_text.splitlines()
else:
raise TypeError('This function requires a unicode argument.')
#
if unicode_text and \
unicode_text[-1] in '\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029':
splitted_lines.append('')
#
return 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.