content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def replace_decorator(node, capture, filename):
"""
Replaces usage of ``@slowTest`` with ``@pytest.mark.slow_test``
"""
return utils.rewrite_decorator(node, DECORATOR, MARKER) | 79,000 |
def update_bullets(settings, screen, stats, sb, ship, aliens, bullets):
"""Update position of bullets and get rid of old bullets"""
# Update the bullet position.
bullets.update()
# get rid of the bullets that have dissapeared.
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
... | 79,001 |
def GetPercentage(number, total):
"""Returns the float percentage that a number is of a total."""
if not number:
return 0
return float(number) / total * 100 | 79,002 |
def _store_path(path, ctx, imports):
"""Given a path, prepend the workspace name as the zappent directory"""
# It feels like there should be an easier, less fragile way.
if path.startswith("../"):
# External workspace, for example
# '../protobuf/python/google/protobuf/any_pb2.py'
st... | 79,003 |
def generate_grammar_rule(ops, inner_rule_name, rule_name, alias_prefix):
"""
Generates one grammar rule for ops with same priority.
"""
# every op produce a match for non-terminal
# op key used as alias
matches = []
plain_ops = {}
if inner_rule_name is not None:
matches.ap... | 79,004 |
def create_custom_program_attribute(driver):
"""Creates a custom text attribute for a program object
Args:
driver (lib.base.CustomDriver)
"""
modal = dashboard.AdminDashboard(driver) \
.select_custom_attributes() \
.select_programs() \
.add_new_custom_attribute()
test_utils.ModalNewPr... | 79,005 |
def print_to_log(to_print_list, log_file, log_identifier=""):
"""
Writes to the log file, registering the time and identifier.
Adds the content of `to_print_list` to the `log_file`,
using the `log_identifier` to indicate where a given
log entry originated.
:param to_print_list: string you want... | 79,006 |
def parse_billing_code_col(s:str):
"""Split billing code into separate fields for code_type and code. E.g., 'MSDRG .... 001'."""
l:list = s.split()
if 'MS-DRG' in s:
code_type, code = l[0], l[4]
elif re.search('CPT|HCPCS', s):
code_type, code = l[0], l[1]
else:
code_t... | 79,007 |
def munsell_colour_to_munsell_specification(munsell_colour: str) -> NDArray:
"""
Retrieve a normalised *Munsell* *Colorlab* specification from given
*Munsell* colour.
Parameters
----------
munsell_colour
*Munsell* colour.
Returns
-------
:class:`numpy.ndarray`
Norma... | 79,008 |
def predict(market,profit,hold,cur_profit_present,stop):
"""
一个极其简单的示例策略,如果空仓则买入,如果有仓位就卖出
"""
if hold==0:
return {'if_buy':1}
else:
return {'if_buy':0} | 79,009 |
def inject_params(lines: str, params: dict) -> List[str]:
"""Replace placeholders with parameters.
Args:
lines: A file content including placeholders (`{{ ... }}`).
params: A mapping a name of placeholders to a value.
Returns:
A file content replaced placeholders with parameters.
... | 79,010 |
def enrich():
"""Enrich the ontology."""
enrich_pubchem_synonyms()
enrich_chebi_xrefs() | 79,011 |
def load_depth(file):
"""
Load a depth map from file
Parameters
----------
file : str
Depth map filename (.npz or .png)
Returns
-------
depth : np.array [H,W]
Depth map (invalid pixels are 0)
"""
if file.endswith('npz'):
return np.load(file)['depth']
... | 79,012 |
def close_story(request):
"""Close an open story.
---
story_id:
in: path
type: string
required: true
"""
auth_context = auth_context_from_request(request)
# Only available to Owners for now.
if not auth_context.is_owner():
raise PolicyUnauthorizedError("Only Own... | 79,013 |
def parthandler(parttype, params=()):
"""decorator that register a function as a bundle2 part handler
eg::
@parthandler('myparttype', ('mandatory', 'param', 'handled'))
def myparttypehandler(...):
'''process a part of type "my part".'''
...
"""
def _decorator(fu... | 79,014 |
def create_opaque_secret(namespace: str,
name: str,
key: str,
value: str):
"""
Create new k8 Opaque Secret.
:param namespace: Namespace of the secret.
:param name: Name of the secret
:param key: Key of the secret
:param ... | 79,015 |
def get_field_instance(field_name: str) -> FieldInstance:
"""
Return a FieldInstance object for the given field name.
Args:
field_name: The name of the field to get a FieldInstance for.
Returns:
A FieldInstance object for the given field name.
"""
info = _FIELD_INFO_MAP[field_n... | 79,016 |
def DetermineLocaleType(locale_str):
"""Determines the locale 'type' for a given locale name.
Returns:
(string) Always one of the following strings,
'world' If the locale name refers to the world.
'country' If the locale name looks like a country ID.
'region' If the locale name ... | 79,017 |
def test_no_specified_input_file_error(datafiles, runner):
"""
The input template file as named, does not exist
"""
inpath = str(datafiles)
assert len(os.listdir(inpath)) == 1
os.chdir(inpath)
assert inpath == os.getcwd()
result = runner.invoke(cctconvert.main, ['whatever.json'])
... | 79,018 |
def main():
"""メイン関数."""
parser = ArgumentParser(description='エスポワールシチー産駒の出走予定をLINE Notifyに送る')
parser.add_argument('-d', '--debug', action='store_true', help='デバッグ用')
parser.add_argument('--loggingdebug', action='store_true', help='デバッグ用')
args = parser.parse_args()
log_level = logging.DEBUG i... | 79,019 |
def m_to_recruitment(seq, args=None):
"""
返回bool值0/1
:param seq: 任意值
:param args: 可不传 传时seq==args为1
:return: 0/1
example:
:seq '11'
:args '00'
:return 0
"""
if seq:
seq = "统招"
else:
seq = "非统招"... | 79,020 |
def test_201120_unknown_vtec(dbcursor):
"""Test that we emit a warning when finding an unknown VTEC action."""
data = get_test_file("TOR.txt").replace(".NEW.KJAN", ".QQQ.KJAN")
prod = vtecparser(data)
prod.sql(dbcursor)
assert any(x.find("QQQ") > -1 for x in prod.warnings) | 79,021 |
def install_cipd_packages(dest, *packages):
"""Bootstraps CIPD in |dest| and installs requested |packages|.
Args:
dest (str): The CIPD installation root.
packages (list of CipdPackage): The set of CIPD packages to install.
"""
# Build our CIPD manifest. We'll pass it via STDIN.
manifest = '\n'.join('... | 79,022 |
def spread_segment_wise(starts, input_data):
"""
Generalized version of :func:`spread_residue_wise()`
for residues and chains.
Parameters
----------
starts : ndarray, dtype=int
The sorted start indices of segments.
Includes exclusive stop, i.e. the length of the corresponding
... | 79,023 |
def get_model(instance):
"""Get model by instance."""
return instance._meta.model | 79,024 |
def do_architecture_delete(cs, args):
"""Remove a specific architecture."""
architecture = _find_architecture(cs, args.architecture)
cs.architectures.delete(architecture) | 79,025 |
def encode(bananaFactory, obj):
"""
Banana encode an object using L{banana.Banana.sendEncoded}.
@param bananaFactory: A no-argument callable which will return a new,
unconnected protocol instance to use to do the encoding (this should
most likely be a L{banana.Banana} instance).
@param... | 79,026 |
def crossSpecgram(x, y, NFFT=256, Fs=2, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None) :
"""
Use matplotlib.mlab function, _spectral_helper, to calculate cross power between x and y in short time bins.
USAGE:
Pxy,freqs,t=crossSpe... | 79,027 |
def force_slashend(path):
"""
Return ``path`` suffixed with ``/`` (path is unchanged if it is already
suffixed with ``/``).
"""
if not path.endswith('/'):
path = path + '/'
return path | 79,028 |
def test_error_brackets(messenger):
"""
Test that the brackets on an error message have been correctly applied
"""
text = setup_level_text('error')
level = {"text": "error", "color": messenger._error}
msg = messenger._Messenger__brackets(level)
assert(msg == text) | 79,029 |
def masked_dense(inputs,
units,
num_blocks=None,
exclusive=False,
kernel_initializer=None,
reuse=None,
name=None,
*args, # pylint: disable=keyword-arg-before-vararg
**kwargs):
"""A ... | 79,030 |
def _add_point_element(element: Dict[str, Any], label_id: LabelID, *_: Any) -> None:
"""Add new Point Label Element for given Label.
:param element: JSON describing single element
:param label_id: ID of a given Label that the element should be added to
"""
position = LabelPosition(x=element['x'], y... | 79,031 |
def cell_to_num(x: str) -> Tuple[int, int]:
"""Converts a cell to a row, column index
:param x: Name of the cell (e.g. A2)
:type x: str
:return: Row, column index
:rtype: tuple
"""
regex = re.compile("([A-Z]*)([0-9]*)")
output = regex.search(x)
if output:
column = output.gr... | 79,032 |
def release_logging_handlers(product_name):
"""Closes any currently used logging port handlers.
Resulting in the stream, file and serial port handler being closed
and removed from the logging object.
"""
log_root = log.getLogger(product_name).logger
for handler in log_root.handlers:
log... | 79,033 |
def line_path_error_function(x, y, xerr, yerr, xa=-inf, xb=inf, samplefac=10):
"""Compute the probability that the data points actually lie along a
line given the x and y value of the data point, the errors
on the data, and the line parameters. If desired, compute only for the
segment extending from xa ... | 79,034 |
def scoreboard(self: Client) -> ScoreboardProxy:
"""Delegates to a
:py:class:`mcipc.rcon.be.commands.scoreboard.ScoreboardProxy`
"""
return ScoreboardProxy(self, 'scoreboard') | 79,035 |
def find_hooks(file_prefix):
"""
Find all files in subdirectories whose names start with <file_prefix>
"""
file_pattern = os.path.dirname(__file__) + '/*/' + file_prefix + "*.py"
module_paths = [f for f in glob.glob(file_pattern) if os.path.isfile(f)]
module_paths.sort()
# Gather all hooks... | 79,036 |
def tsne(adata,
color=None,
feature_symbols=None,
use_raw=None,
layer=None,
sort_order=True,
groups=None,
components=None,
projection='2d',
legend_loc='right margin',
legend_fontsize=None,
legend_fontweight=None,
legend_fontoutline=None,
size=None,
color_map=None,
palette=None,
frameon=None,
ncols=None... | 79,037 |
def apply_key_map(new_record: dict, old_record: dict, key_ref: dict):
"""
Apply key mapping between two records based on a key reference.
Example:
Given `key_ref`: `{'column1':'column2'}`.
Extracts values from `old_record['column1']` to `new_record['column2']`.
Parameters
----------
... | 79,038 |
def initialize_globals(verbose):
# type: (bool) -> None
"""Initialize any runtime globals
:param bool verbose: verbose
"""
global _RESOURCES_PATH
if _RESOURCES_PATH is None:
_RESOURCES_PATH = _ROOT_PATH / 'resources'
if not _RESOURCES_PATH.exists():
_RESOURCES_PATH = ... | 79,039 |
def spe_to_fst(A, B, C, D):
"""
Takes in a rule of form A->B/C_D and creates an FST from that rule.
Following are the types of rules covered by this generator:
* a / b -> c_d (ex. qwertcaduiop -> qwertcbduiop)
* TODO: a / b -> #_c (ex. aceuio -> bceuio)
* TODO: a / b -> c_#... | 79,040 |
def test_building_torrent_piece_queue_multifile():
"""Test building piece queue from multi-file torrent."""
torrent_md = TorrentMD(TORRENT_PATH_MULTI)
assert hasattr(torrent_md, "torrent_dict")
assert hasattr(torrent_md, "torrent_bytes")
assert torrent_md.piece_count == len(torrent_md.piece_has... | 79,041 |
def add_goods(chipscoco):
"""
:param chipscoco:
chipscoco = {"goods": {
1: {"name": "洗发水", "price": 22, "amount": 0},
2: {"name": "牙膏 ", "price": 15, "amount": 0},
3: {"name": "宠物绳 ", "price": 29, "amount": 0},
4: {"name": "面包", "price": 16, "amount": 0},
5: {"name": ... | 79,042 |
def semantic_segmentation_labelling(img, label_config):
"""One-hot encoder for semantic segmentation problem
Parameters
----------
img : ndarray
Batched input image data of size (batch_size, image_size, image_size, 1)
label_config : dict
Label contained into the dataset
Returns... | 79,043 |
def keltner_channel_d_index_kernel_n(ohlcv, window_size, out, res_index):
"""
Calculate Keltner Channel Down for given data.
:param ohlcv: link to GPU memory with array of timestamp, Open, High, Low, Close, Volume
:param window: array of window sizes
:param out: link to GPU memory for result
:p... | 79,044 |
def attack(y, k, s, m, a, c):
"""
Recovers the states associated with the outputs from a truncated linear congruential generator.
More information: Frieze, A. et al., "Reconstructing Truncated Integer Variables Satisfying Linear Congruences"
:param y: the sequential output values obtained from the trunc... | 79,045 |
def plot_kline(kline):
"""
回测结束时绘制k线图
:param kline: 回测时传入指定的k线数据
:return:
"""
kline = kline
# kline.reverse()
# format it in pandas
try: # dataframe有7列的情况
df = pd.DataFrame(kline,
columns=['time', 'open', 'high', 'low', 'close', 'volume', 'c... | 79,046 |
def inverse_odds(x, epsilon=EPSILON):
"""
Calculate probability from odds, and regularize returned probability to range [epsilon, 1-epsilon]
:param x: odds value
:return: probability value
"""
p = x/(1+x)
p = np.minimum(np.maximum(p, epsilon), 1 - epsilon)
return p | 79,047 |
def below_threshold(mat, threshold):
"""
:param mat: input image
:param threshold: threshold value
:return: values above the threshold are set to zero, and values less than or equal to the threshold are unchanged
"""
return cv2.threshold(mat, threshold, 0, cv2.THRESH_TOZERO_INV)[1] | 79,048 |
def read_pip():
""" Read and Return the pip dependencies """
datei = open('requirements.txt','r')
output_stream = []
for zeile in datei:
zeile = zeile.replace("\n", "")
output_stream.append(zeile)
datei.close()
return output_stream | 79,049 |
def handle_range(visitor, node):
"""
Rust renders Python's range with special syntax.
Python ranges come in three flavours, depending on the number
of arguments, and they map to Rust as follows:
1. range(a) -> 0..a
2. range(a, b) -> a..b
3. range(a, b, c) -> (... | 79,050 |
def add_to_segment_data(sfrdata, data, flowline_routing=None,
variable='flow',
line_id_column=None,
segment_column=None,
period_column='per',
data_column='Q_avg'):
"""Like add_to_perioddata, but f... | 79,051 |
def write_out_datasets_shuffled_with_different_random_seed():
"""
Write out a couple additional shuffled datasets. Robustness check to make sure our main results are consistent across train sets.
"""
raise Exception("This is deprecated; we now can just reshuffle the train/test/val sets using the origin... | 79,052 |
def interpret_quantity(value, expect_sequence):
"""Interpret a value as a pint Quantity via pisa.ureg
Parameters
----------
value : scalar, Quantity, or sequence interpretable as Quantity
expect_sequence : bool
Specify `True` if you expect a sequence of quantities (or a
pint-Quantit... | 79,053 |
def either_sqrt(num):
"""What if we want to send some custom error message back instead of just
giving back an inscrutable Nothing? We can use the Either Monad!"""
if num < 0:
return either.Either.Left(
"You can't take the square root of a negative number!")
else:
return eith... | 79,054 |
def create_table(outfile, info_tuples):
"""Create tsv output for all info_tuples.
"""
out_str = "{}\t{}\t{}\t{}\t{}\n"
with open(outfile, 'w') as out:
out.write(out_str.format("accession",
"trusted_global",
"trusted_domain",
... | 79,055 |
def init_arguments(cmd: Command) -> None:
"""Feed the arguments to the argument parser."""
group = cmd.parser.add_mutually_exclusive_group(required=True)
group.add_argument('-f', '--file', help='Path of file in trestle directory to validate.')
group.add_argument('-t', '--type', choices=const.MODEL_TYPE_... | 79,056 |
def zclude(bed, other, exclude=True):
"""
Include or exclude intervals from bed that overlap other.
If exclude is True:
new = bedtools intersect -v -a bed -o other
"""
if other is None: return bed
n_orig = sum(1 for _ in nopen(bed))
tmp = mktemp()
if exclude:
run("bedtool... | 79,057 |
def psy_ta_rh(tdb, rh, patm=101325):
""" Calculates psychrometric values of air based on dry bulb air temperature and
relative humidity.
For more accurate results we recommend the use of the the Python package
`psychrolib`_.
.. _psychrolib: https://pypi.org/project/PsychroLib/
Parameters
-... | 79,058 |
def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):
"""
internal. pprinter for iterables. you should probably use pprint_thing()
rather then calling this directly.
"""
fmt = u("{%s}")
pairs = []
pfmt = u("%s: %s")
if max_seq_items is False:
nitems = len(seq)
els... | 79,059 |
def get_sync_result_for_virtual_account(obj, pretty_print, beep,
domain,
name,
headers):
"""Returns the summary of devices synced from the given smart account & virtual account with PnP.
"""
... | 79,060 |
def userTagOrDiscrim(userID : str, guild : Guild = None) -> str:
"""If a passed user mention or ID is valid and shares a common server with the bot,
return the user's name and discriminator. TODO: Should probably change this to display name
Otherwise, return the passed userID.
:param str userID: A user... | 79,061 |
def generate_flist(split):
"""Generates file lists."""
flist = os.listdir(os.path.join(DATA_DIR, split))
g = open(os.path.join(DATA_DIR, f'{split}.txt'), 'w')
for f in sorted(flist):
if f.startswith('dog'):
label = 1
elif f.startswith('cat'):
label = 0
if f.endswith('.jpg'):
g.writ... | 79,062 |
def acquire_lock(conn, lockname, identifier, acq_timeout=ACQ_TIMEOUT,
timeout=DEFAULT_TIMEOUT):
"""
Wait for and acquire a lock. Returns identifier on success and False
on failure.
Args:
conn: redis connection object
lockname: name of the lock
identifier: an ide... | 79,063 |
def make_entries(screen, settings):
"""This function makes entries with keys, default values and labels from
settings. It returns a dictionary with entry widgets as values."""
entries = dict()
# For each setting, create a text field and put it next to the
# corresponding label.
for i, (key, def... | 79,064 |
def mail_admins(subject, message, fail_silently=False, priority=None):
"""
Add one or more new messages to the mail queue addressed to the site
administrators (defined in ``settings.ADMINS``).
This is a replacement for Django's ``mail_admins`` core email method.
The ``fail_silently`` argument is o... | 79,065 |
def macos_command_line_application(name, **kwargs):
"""Builds a macOS command line application.
A command line application is a standalone binary file, rather than a `.app`
bundle like those produced by `macos_application`. Unlike a plain
`apple_binary` target, however, this rule supports versioning and embedd... | 79,066 |
def template_view_factory(template_name, context={}):
"""Returns a generic view which renders a template using the optional
context and request. """
return lambda request: render_to_response(template_name, context, request) | 79,067 |
def calculate_resource_utilization_for_kube_nodes(
nodes: Sequence[V1Node], pods_by_node: Mapping[str, Sequence[V1Pod]],
) -> ResourceUtilizationDict:
""" Given a list of Kubernetes nodes, calculate the total available
resource available and the resources consumed in that list of nodes.
:param nodes: a... | 79,068 |
def unfuse_right(A, shp):
"""
Reverses fuse_right.
"""
d, chiL, chiR = shp
A = A.reshape((chiL, d, chiR)).transpose((1, 0, 2))
return A | 79,069 |
def delete_password(key):
"""Deletes the given password from the database. Returns True if the password was deleted."""
from saq.database import get_db_connection
with get_db_connection(name=saq.CONFIG['global']['encrypted_passwords_db']) as db:
c = db.cursor()
c.execute("DELETE FROM `encryp... | 79,070 |
def add_subgroup_columns_from_text(df, text_column, subgroups):
"""Adds a boolean column for each subgroup to the data frame.
New column contains True if the text contains that subgroup term.
"""
for term in subgroups:
# pylint: disable=cell-var-from-loop
df[term] = df[text_column].apply(lambda x: ... | 79,071 |
def sliding_windows(size, step_size, width, height):
"""Slide a window of +size+ by moving it +step_size+ pixels"""
for i in range(0, height - size + 1, step_size):
for j in range(0, width - size + 1, step_size):
yield Window(j, i, size, size) | 79,072 |
def gaussion_f(mu, sigma2, x):
"""
Gaussian function
:param mu:
:param sigma2:
:param x:
:return:
"""
return 1 / sqrt(2 * pi * sigma2) * exp(-0.5 * (x - mu) / sigma2) | 79,073 |
def validate_owner_repo(ctx, param, value):
"""Ensure that owner/repo is formatted correctly."""
# pylint: disable=unused-argument
form = 'OWNER/REPO'
return validate_slashes(param, value, minimum=2, maximum=2, form=form) | 79,074 |
def squiggleFig(x1,y1,d1,a1,w1, x2,y2,d2,a2,w2):
"""Return a rounded bezier curve -- something like ~.
This is the naive implementation, using 2 identical slightly-offset
bezier curves to outline the figure. It looks uneven or calligraphic.
xn,yn = endpoints
dn = distance of control point from end... | 79,075 |
def check_free_space(min_free_space: int) -> bool:
"""
Check available free space in filesystem and return True/False if there is enough free space
or not.
min_free_space is measured in kB
"""
if not any([isinstance(min_free_space, int), isinstance(min_free_space, float)]):
log.warning(... | 79,076 |
def spechum2mixr(q):
"""
Calculate mixing ratio from specific humidity.
**Inputs/Outputs**
Variable I/O Description Units
-------- --- ----------- -----
q I Specific humidity kg/kg
r O Mixing ratio kg/kg
"""
return q/(1-q) | 79,077 |
def test_mro():
"""Test the inheritance order is correct."""
expected_mro = tuple(
[
pitci.xgboost.XGBoosterSplitLeafNodeScaledConformalPredictor,
pitci.base.SplitConformalPredictorMixin,
pitci.xgboost.XGBoosterLeafNodeScaledConformalPredictor,
pitci.base... | 79,078 |
def get_formato_series(series, entidades):
"""
Convierte groupby a formato tidy (columnas son estados e indice es la fecha).
Input:
- series:
DataFrame en formato groupby agrupada for una columna que corresponde a
entidades federativas y otra columna que corresponde a una fecha.
- e... | 79,079 |
def numpy_image_to_float(img, out_range=(0, 1)):
"""
Convert a numpy image (3d tensor, h x w x channels) into float format where
the output range is as given in out_range.
Return a numpy array.
"""
# http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.img_as_float
new_img = s... | 79,080 |
def close_if_open_survey(web):
"""
Checks if a specific survey window is visible. If it is, will execuite Javascript to close it.
:param web: A web driver object.
"""
try:
if web.find_element_by_id('IPEinvL'):
web.execute_script('clWin();')
return
except NoSuchEl... | 79,081 |
def dataset_get_table_table_name_post(tableName): # noqa: E501
"""Returns the specified table
Returns the HTML Representation of the table. # noqa: E501
:param tableName: Should be equal to either bitcoin, bitconnect, dash, ethereum, iota, litecoin, monero, nem, neo, numeraire, omisego, qtum, ripple, str... | 79,082 |
def test():
"""Perform some modicum of internal tests."""
try:
raise Exception('yo!')
except Exception as e:
print(f'{e!r}: oops!')
pass
f = ZwiFollowers()
f.traverse(ZwiBase.from_dict, __wees)
f.traverse(ZwiBase.from_dict, __wers)
db0 = DataBase.db_connect()
d... | 79,083 |
def from_roms(roms_file, ini_file, record=0, time=None, grid=None,
clobber=False, cdl=None):
"""
Given a ROMS history, average, or climatology file, generate
initial conditions on the same grid.
Parameters
----------
roms_file: string or list
Input ROMS source (history, av... | 79,084 |
def main(
context_settings={ # noqa: B006
"help_option_names": (
"-h",
"--help",
)
}
):
"""CLI to profile a process's memory/CPU usage and plot it.""" | 79,085 |
def timeEvolutionMatrix(n, E, G, Q, Q_decay, tau, laser_wavelength, laser_intensity,
tau_f = None, detuning = None, symbolic_print = None, numeric_print = None,
rabi_scaling = None, rabi_factors = None, atomic_velocity = None):
"""Function to create and populate the co... | 79,086 |
def load_focalplanes(args, comm, schedules, verbose=False):
""" Attach a focalplane to each of the schedules.
Args:
schedules (list) : List of Schedule instances.
Each schedule has two members, telescope
and ceslist, a list of CES objects.
Returns:
detweights (dict)... | 79,087 |
async def test_outbound_return_route_set_by_msg(
alice_gen, bob, send, message, response, dispatcher
):
"""Test no return route or endpoint or reply raises error."""
alice = alice_gen(partial(send.return_response, bob.pack(response)), dispatcher)
new_msg = copy.deepcopy(message)
new_msg = new_msg.w... | 79,088 |
def dannce_train(params):
"""Entrypoint for dannce training."""
# Depth disabled until next release.
params["depth"] = False
# Make the training directory if it does not exist.
make_folder("dannce_train_dir", params)
params["loss"] = getattr(losses, params["loss"])
params["net"] = getattr(... | 79,089 |
def in_cluster_scvelo_coh(adata, k_cluster, k_confidence, return_raw=False):
"""In-Cluster Confidence Score.
Args:
adata (Anndata): Anndata object.
k_cluster (str): key to the cluster column in adata.obs DataFrame.
k_confidence (str): key to the column of cell velocity confide... | 79,090 |
async def discover():
"""Discover and return devices on local network."""
discover = TuyaDiscovery()
try:
await discover.start()
await asyncio.sleep(DEFAULT_DISCOVER_TIMEOUT)
except Exception:
_LOGGER.exception("failed to discover devices")
finally:
discover.close()
... | 79,091 |
def serve_responses(responses, passwords, pubkeys, port):
"""
Return a threading TCP based SocketServer listening on ``port``.
Used as a fake SSH server which will respond to commands given in
``responses`` and allow connections for users listed in ``passwords``.
``pubkeys`` is a Boolean value det... | 79,092 |
def test_service():
"""Tests that the get_cost function for ServiceAgreement returns the correct value."""
ddo = get_sample_ddo()
sa = ddo.get_service(ServiceTypes.ASSET_ACCESS)
assert sa.get_cost() == 1.0
assert sa.get_c2d_address()
assert sa.main["name"] == "dataAssetAccessServiceAgreement"
... | 79,093 |
def svn_client_mkdir2(*args):
"""svn_client_mkdir2(apr_array_header_t paths, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t"""
return _client.svn_client_mkdir2(*args) | 79,094 |
def factory_share_class(business_identifier: str):
"""Create a share class."""
business = factory_business(business_identifier)
share_class = ShareClass(
name='Share Class 1',
priority=1,
max_share_flag=True,
max_shares=1000,
par_value_flag=True,
par_value=0.8... | 79,095 |
def test_create_button_from_dict_tuple_list(button_data):
"""
:param button_data:
:return:
"""
button = Button(
button_data=button_data,
front_marker="front_",
back_marker="_back",
).generate()
assert isinstance(button, InlineKeyboardButton)
assert button.text ==... | 79,096 |
def update_output(list_of_contents, list_of_names, list_of_dates):
"""
check for upload of the files
"""
if list_of_names:
if len(list_of_names) == 1:
if list_of_contents is not None:
children = [
parse_contents(c, n, d) for c, n, d in
... | 79,097 |
def upload(csv_file, bucket_name, blob_name):
"""Uploads csv_file to bucket_name.
Args:
csv_file: CSV file to upload.
bucket_name: Bucket to upload the files to.
blob_name: Path of the file in the bucket.
Returns:
The path of the uploaded file in GCS.
"""
client = st... | 79,098 |
def set_interface(dhcp, mac, ip_addr, name, prefix, gateway, dns, domain):
""" Create udev rules to define NICs """
if dhcp:
if ip_addr is not None or prefix is not None or gateway is not None:
error("ERROR: --ip-addr, --prefix, and --gateway require --static", exit=True)
else:
i... | 79,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.