content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def dbrestore(c, keyname="local"):
"""Restore the database from a named s3 key
ie - fab dbrestore --keyname dev
"""
local(_api_cmd(f"python manage.py dbrestore {keyname}")) | 5,329,000 |
def normalize_not_found(wrapped):
"""View decorator to make 404 error messages more readable"""
def wrapper(context, request):
# Replace incoming 404 with one that has a sensible message
response = wrapped(_standard_not_found(), request)
return response
return wrapper | 5,329,001 |
def run(cfg, cfg2=None):
""" Start preprocessing. """
# Read all log files generated by ebpf_ros2_*
# TODO: convert addr and port to uint32, uint16
read_csv = functools.partial(pd.read_csv, dtype={
'pid':'Int32', 'seqnum':'Int64', 'subscriber':'Int64', 'publisher':'Int64'})
send_log = 'send... | 5,329,002 |
def jacobi_sequence(ns, alpha, beta, x):
"""Jacobi polynomials of orders ns with weight parameters alpha and beta.
Parameters
----------
ns : iterable
sorted polynomial orders to return, e.g. [1, 3, 5, 7, ...]
alpha : float
first weight parameter
beta : float
second weig... | 5,329,003 |
def process_results(unprocessed, P, R, G):
"""Process the results returned by the worker pool, sorting them by
policy and run e.g. results[i][j][k] are the results from policy i
on run j on graph k. Parameters:
- unprocessed: Unprocessed results (as returned by the worker pool)
- P: number of po... | 5,329,004 |
def make_inline_table(data):
"""Create an inline table from the given data."""
table = tomlkit.inline_table()
table.update(data)
return table | 5,329,005 |
def copy(drs_uri: str,
dst: str,
indicator_type: Indicator=Indicator.notebook_bar if is_notebook() else Indicator.bar,
workspace_name: Optional[str]=WORKSPACE_NAME,
workspace_namespace: Optional[str]=WORKSPACE_NAMESPACE):
"""Copy a DRS object to either the local filesystem, or to... | 5,329,006 |
def _mi_dc(x, y, k):
"""
Calculates the mututal information between a continuous vector x and a
disrete class vector y.
This implementation can calculate the MI between the joint distribution of
one or more continuous variables (X[:, 1:3]) with a discrete variable (y).
Thanks to Adam Pocock, t... | 5,329,007 |
def get_new_deals_intent_handler(handler_input):
"""
Purpose:
Handler for getting new deals
Args:
handler_input (Dict): Input data from the Alexa Skill
Return:
alexa_reponse (Dict): Reponse for Alexa Skill to handle
"""
feed = get_slickdeals_feed(SLICKDEALS_URL)
deal... | 5,329,008 |
def test_trigger_pipeline_build(settings, mocker, version):
"""The correct requests should be made to trigger a pipeline build"""
job_name = "build-ocw-site"
mock_get = mocker.patch(
"content_sync.pipelines.concourse.ConcourseApi.get",
return_value={"config": {"jobs": [{"name": job_name}]}},... | 5,329,009 |
def link_nodes(isy, argv) :
"""
node's infomation
"""
if len(argv) == 0 :
do_interactive_link(isy)
cmd = argv.pop(0).upper()
if cmd in [ "START" ] :
isy.node_discover()
elif cmd in [ "STOP" ] :
node_discover_cancel()
exit(0) | 5,329,010 |
def make_parser():
"""Returns the command-line argument parser for sage-spkg-uninstall."""
doc_lines = __doc__.strip().splitlines()
parser = argparse.ArgumentParser(
description=doc_lines[0],
epilog='\n'.join(doc_lines[1:]).strip(),
formatter_class=argparse.RawDescripti... | 5,329,011 |
def analyse_dataset(imgs, lbls, name=None):
"""Analyse labelled dataset
# Arguments:
imgs: ndarray, a set of images
lbls: ndarray, labels for a set of images
"""
if name is not None:
print('Dataset: {}'.format(name))
unique_lbl, counts = np.unique(lbls, return_counts=True)
min_... | 5,329,012 |
def transform(doc, *, sort_keys=False):
"""reorder"""
heavy_defs = ["definitions", "schemas", "responses", "parameters", "paths"]
r = make_dict()
for k, v in doc.items():
if k in heavy_defs:
continue
r[k] = v
for k in heavy_defs:
if k in doc:
r[k] = do... | 5,329,013 |
def plot_card(
box: str,
title: str,
data: PackedRecord,
plot: Plot,
events: Optional[List[str]] = None,
commands: Optional[List[Command]] = None,
) -> PlotCard:
"""Create a card displaying a plot.
Args:
box: A string indicating how to place this componen... | 5,329,014 |
def publish(
click_context: click.Context, local: bool, remote: bool, push_missing: bool
) -> None: # pylint: disable=unused-argument
"""Publish the agent to the registry."""
ctx = cast(Context, click_context.obj)
_validate_pkp(ctx.agent_config.private_key_paths)
_validate_config(ctx)
if remot... | 5,329,015 |
def variance():
"""Running sample variance co-routine.
``variance`` consumes values and returns the variance with N-1 degrees
of freedom of the data points seen so far.
WARNING: The sample variance with N-1 degrees of freedom
is not defined for a single data point. The first result
... | 5,329,016 |
def generateAllResizedImages(newWidth, newHeight, backgroundColor=None, noBackground=False):
"""
generateAllResizedImages reads each annotation file in
/annotation/* and then creates a resized image based on the
bounding box for that annotation and saves it to the folder
/images/breed/boxes_newWid... | 5,329,017 |
def get_cluster_id(url):
"""
Google assign a cluster identifier to a group of web documents
that appear to be the same publication in different places on the web.
How they do this is a bit of a mystery, but this identifier is
important since it uniquely identifies the publication.
"""
vals =... | 5,329,018 |
def vol_allocation_factory(covs:List, pres:List=None)->[float]:
""" Allocate capital between portfolios using either cov or pre matrices
:param covs: List of covariance matrices
:param pres: List of precision matrices
:return: Capital allocation vector
"""
if pres is None:
pres = []
... | 5,329,019 |
def add_contact_to_room(room_id: str, contact: str):
"""Use the webexteamssdk to add the contact to the room."""
# You can also use it as a context handler to catch errors and capture
# checkpoint data.
with mission.checkpoint(2, "Add the Contact to the Room") as checkpoint:
membership = teams.m... | 5,329,020 |
def get_inspection_page(**kwargs):
"""Fetch inspection data."""
url = KING_COUNTY_DOMAIN + DATA_PATH
params = INSPECTION_PARAMS.copy()
for key, val in kwargs.items():
print(key)
if key in INSPECTION_PARAMS:
params[key] = val
resp = requests.get(url, params=params)
res... | 5,329,021 |
def get_table_count(url, table_id):
"""
Count the number of rowns in a ActivityTable
:param url:
:param table_id: The ActivityTable ID to update count from and return
:return: count : count of rows from ActivityTable
"""
token = ActivitySites.objects.get(site_id=1)
if token.activity_tabl... | 5,329,022 |
def get_audio_mfcc_features(txt_files, wav_files, n_input, n_context, word_num_map, txt_labels=None):
"""
提取音频数据的MFCC特征
:param txt_files:
:param wav_files:
:param n_input:
:param n_context:
:param word_num_map:
:param txt_labels:
:return:
"""
audio_features = []
audio_fea... | 5,329,023 |
def getOffsetsFromPixelFractions(col, row):
"""
Determine just the fractional part (the intra-pixel part) of the col,row position.
For example, if (col, row) = (123.4, 987.6), then
(colFrac, rowFrac) = (.4, .6).
Function then returns the offset necessary for addressing the interleaved PRF ar... | 5,329,024 |
def all_index(request):
"""
Inventory Index View
"""
# build changelist
item_changelist = HTSChangeList(request, Item,
list_filter=[],
search_fields=[],
list_per_page=200,
model_admin=ItemAdmin(Item, None)
)
context_dict = {
'item_changelist': item_ch... | 5,329,025 |
def calcSeason(ra, time):
"""Calculate the 'season' in the survey for a series of ra/dec/time values of an observation.
Based only on the RA of the point on the sky, it calculates the 'season' based on when this
point would be overhead. To convert to an integer season label, take np.floor of the returned
... | 5,329,026 |
def set_node_event_info(info: NodeEventInfo) -> Item:
"""Encaches an item.
:param info: Node event information.
:returns: Item to be cached.
"""
if info.event_type in (
EventType.MONIT_CONSENSUS_FINALITY_SIGNATURE,
EventType.MONIT_BLOCK_FINALIZED,
EventType.MONIT_BLOCK... | 5,329,027 |
def add_cleanup():
"""Generic cleaning helper."""
to_cleanup = []
def f(func, *args, **kwargs):
"""Store the cleaning actions for later."""
to_cleanup.append((func, args, kwargs))
yield f
for func, args, kwargs in to_cleanup:
func(*args, **kwargs) | 5,329,028 |
def move_up(n=1):
"""Moves your cursor up 'n' rows."""
# TODO: is math correct here ?
code.CURSOR_UP(n) | 5,329,029 |
def check_hashtarget(bible_hash, target):
""" tests if the biblepay hash is valid for the hashtarget, means that is it lower.
True = is lower and all is fine """
rs = False
try:
rs = int(bible_hash, 16) < int(target, 16)
except:
pass
return rs | 5,329,030 |
def get_client_secret():
"""
Prompt the user for their Client Secret
:return:
"""
config.client_secret = getpass.getpass(prompt='Please enter your Client Secret: ') | 5,329,031 |
def fix_anacondapy_pythonw(fname):
"""fix shebang line for scripts using anaconda python
to use 'pythonw' instead of 'python'
"""
# print(" fix anaconda py (%s) for %s" % (sys.prefix, script))
with open(fname, 'r') as fh:
try:
lines = fh.readlines()
except IOError:
... | 5,329,032 |
def run_pytest(secret_key, db_pwd, db_host, cloud_host, cloud_pwd):
""" run flask pytest param """
pytest.main(['--cov-config=../.coveragerc',
'--cov=./app',
'--cov-report=xml',
'./tests',
f'--secret_key={secret_key}',
f'--db_p... | 5,329,033 |
def assert_and_infer_cfg_fl(cfg_fl, args, make_immutable=True, train_mode=True):
"""
Calls /semantic-segmentation/config.assert_and_infer_cfg and adds additional assertions
"""
if args.manual_client_setup:
cfg_fl.CLIENT.MANUAL = args.manual_client_setup
if cfg_fl.CLIENT.MANUAL:
prin... | 5,329,034 |
def replace_service(name,
metadata,
spec,
source,
template,
old_service,
saltenv,
namespace="default",
**kwargs):
"""
Replaces an existing service with ... | 5,329,035 |
def test_add_contributor(staff_client, user, private_channel, attempts):
"""
Adds a contributor to a channel
"""
url = reverse("contributor-list", kwargs={"channel_name": private_channel.name})
for _ in range(attempts):
resp = staff_client.post(
url, data={"contributor_name": use... | 5,329,036 |
def timesketch_add_manual_event(
data: Text, timestamp: Optional[int] = 0,
date_string: Optional[Text] = '',
timestamp_desc: Optional[Text] = '',
attributes: Optional[Dict[str, Any]] = None,
tags: Optional[List[str]] = None) -> Dict[str, str]:
"""Add a manually generated event to the sketch.
Ar... | 5,329,037 |
def filter_vcf_by_sex(vcf_file, data):
"""Post-filter a single sample VCF, handling sex chromosomes.
Handles sex chromosomes and mitochondrial. Does not try to resolve called
hets into potential homozygotes when converting diploid to haploid.
Skips filtering on pooled samples, we still need to impleme... | 5,329,038 |
def gen_spacer(spacer_char="-", nl=2):
"""
Returns a spacer string with 60 of designated character, "-" is default
It will generate two lines of 60 characters
"""
spacer = ""
for i in range(nl):
spacer += spacer_char * 60
spacer += "\n"
return spacer | 5,329,039 |
def repo_config_factory(repo_type, repo_id, repo_label, **kwargs):
"""
Constructs a repository configuration in form of a
TTL structure utilizing the TTL templates from
./repo_types_template.
"""
# Check if the repo_type is a known template
if repo_type not in REPO_TYPES:
raise Repos... | 5,329,040 |
def oil_isothermal_density(rho: NDArrayOrFloat, p: NDArrayOrFloat) -> NDArrayOrFloat:
"""Calculates the oil density for a given pressure at 15.6 degC
B&W 1992 Equation 18
Args:
rho: The oil reference density (g/cc) at 15.6 degC
can be compensated for disovled gases by running `o... | 5,329,041 |
def get_waveform_dataset(path):
"""Loads the waveform dataset from a given path.
Args:
path: The path to the .npz file containing the waveform data set.
Returns:
An array of waveform chunks loaded from the given path.
"""
dataset = np.load(path)['arr_0']
return dataset | 5,329,042 |
def logger(filename: str, name: str) -> logging.Logger:
"""configure task logger
"""
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(filename)
formatter = logging.Formatter(
'%(asctime)s %(name)s %(levelname)s: %(message)s')
fh.setLevel(loggin... | 5,329,043 |
def verify_signature(pubkey_path, message, signature):
"""
Use Crypto.Signature.PKCS1_v1_5 to verify the signature on a message.
Returns True for valid signature.
"""
log.debug("salt.crypt.verify_signature: Loading public key")
pubkey = get_rsa_pub_key(pubkey_path)
log.debug("salt.crypt.veri... | 5,329,044 |
def untranslate_module_name(module):
"""Rename module names mention in JSON to names that we can import
This reverses the translation applied by translate_module_name() to
a module name available to the current version of Python.
"""
if PY3:
# remap `__builtin__` and `exceptions` to the `b... | 5,329,045 |
def RGBRamp(size=256, upperValue=.6666666666666667):
"""Generate an RGB color ramp, values range from 0.0 to 1.0"""
assert size > 0
hsv = HSVRamp(size, upperValue)
rgb = Numeric.zeros( (hsv.shape[0], 3), viewerConst.FPRECISION )
for i in xrange(hsv.shape[0]):
rgb[i] = ToRGB(hsv[i])
retu... | 5,329,046 |
def find_poly_ras_intersect(shape, raster_dir, extension='.tif'):
""" Finds all the tiles falling within raster object
the get shape geometry should be seperated from the intesect check,
currently causes a exit code 139 on unix box
:param polygon:
:param extension:
:param raster_dir:
"""
... | 5,329,047 |
def delay(seconds) -> None:
"""
Alias to Python time.sleep(seconds)
Args:
seconds (number): see Python time.sleep documentation
Returns:
None
"""
sleep(seconds) | 5,329,048 |
def Session(
retries: int = 10,
backoff_factor: float = 0.3,
allowed_methods: Iterable[str] = ('HEAD', 'TRACE', 'GET', 'POST', 'PUT', 'OPTIONS', 'DELETE'),
status_forcelist: Iterable[int] = (408, 429, 500, 502, 503, 504),
) -> requests.Session:
"""Return a Session object with full retry capabilities... | 5,329,049 |
def default_plot(times, attendances):
"""
A default plotting method.
"""
fig, ax = plt.subplots(figsize=(12, 6))
ax.axhline(y=0, color="k", linestyle="--")
ax.plot(times, attendances, label=r"$A(t)$")
ax.set_xlabel("t")
ax.set_ylabel("A(t)")
plt.show() | 5,329,050 |
def tp53():
"""Create a TP53 gene fixture."""
params = {
'label': 'tumor protein p53',
'concept_id': 'hgnc:11998',
'symbol': 'TP53',
'location_annotations': [],
'strand': None,
'locations': [
{
'_id': 'ga4gh:VCL._Cl_XG2bfBUVG6uwi-jHtCHa... | 5,329,051 |
def factorOrder(factors, varOrder):
"""Return an order of factors for sampling given a variable order for sampling"""
pri = [0 for x in varOrder]
for i,x in enumerate(varOrder): # first, find position of each var in sampling order
pri[x]=i
factorOrder = [ Factor() for x in varOrder ] # fill order ... | 5,329,052 |
def boundary_nodes(graph, nodes):
# TODO: move to utils
#TODO: use networkx boundary nodes directly: does the same thing
""" returns nodes at boundary of G based on edge_boundary from networkx """
graph = unwrap_graph(graph)
nodes = list(nodes)
nbunch = list(unwrap_nodes(nodes))
# find boundary
... | 5,329,053 |
def home(request):
"""
rendering ui by template for homepage
this view never cache for delivering correct translation inside template
"""
template = loader.get_template('weather/home.html')
return HttpResponse(template.render({}, request)) | 5,329,054 |
def plot_histogram(df, path, col_x, ax=None, size=None, save=True, suffix=None,
show=False, **kwargs):
"""Geneate a histogram plot.
Args:
df (:class:`pandas.DataFrame`): Data frame to plot.
path (str): Path to data frame to use if ``df`` is None, also used
as ... | 5,329,055 |
def __check_interface_state(duthost, interface, state='up'):
"""
Check interface status
Args:
duthost: DUT host object
interface: Interface of DUT
state: state of DUT's interface
Returns:
Bool value which confirm port state
"""
ports_down = duthost.interface_fac... | 5,329,056 |
def test_usergroup_delete(conn_args, query_return, mock_login):
"""
query_submitted = {"params": [13], "jsonrpc": "2.0", "id": 0,
"auth": "9bad39de2a5a9211da588dd06dad8773", "method": "usergroup.delete"}
"""
module_return = ["13"]
query_return({"jsonrpc": "2.0", "result": {"usrgrpids": ["13"]},... | 5,329,057 |
def install_nbextension(path, overwrite=False, symlink=False, user=False, prefix=None, nbextensions_dir=None, destination=None, verbose=1):
"""Install a Javascript extension for the notebook
Stages files and/or directories into the nbextensions directory.
By default, this compares modification time, an... | 5,329,058 |
def find_dateTime_in_html(text):
"""
find dateTime in html
"""
r = findall('<time dateTime="(.*?)">', text)
if r:
return r
return [] | 5,329,059 |
def get_number_of_voxels_per_class(labels: torch.Tensor) -> torch.Tensor:
"""
Computes the number of voxels for each class in a one-hot label map.
:param labels: one-hot label map in shape Batches x Classes x Z x Y x X or Classes x Z x Y x X
:return: A tensor of shape [Batches x Classes] containing the ... | 5,329,060 |
def get_columns_width(user_width):
"""define width of the report columns"""
default_width = [30, 7, 60]
if not user_width:
return default_width
try:
return [7 if user_width[i] < 7 else user_width[i] for i in range(3)]
except (TypeError, IndexError):
_LOGGER.error(
... | 5,329,061 |
def tx_failure():
"""
Failed ```tx```.
"""
message = request.args.get('m')
protocol = request.args.get('p')
address = request.args.get('a')
command = request.args.get('c')
repeats = request.args.get('r')
bits = request.args.get('b')
response = make_response(
render_... | 5,329,062 |
def read_docstring(object_):
"""
Returns object docstring without the FILE information.
"""
fmt = "```\n{}\n```\n"
docs = pydoc.plain(pydoc.render_doc(object_)).split("FILE")[0].rstrip()
return fmt.format(docs) | 5,329,063 |
def _bernoulli_spiral(theta, theta_offset=0., *args, **kwargs):
"""Return Equiangular (Bernoulli's) spiral
Args:
theta: array-like, angles from polar coordinates to be converted
theta_offset: float, angle offset in radians (2*pi = 0)
Kwargs:
exp_scale: growth rate of the exponential
"""
exp_scal... | 5,329,064 |
def register_type(item_type, item_creator):
"""Register data type to Pipe class. Check :py:meth:`Pipe.__or__` and
:py:meth:`Pipe.__ror__` for detail.
:param item_type: The type of data object which used in pipe cascading.
:param item_creator: A function to convert data to Pipe object.
"""
Pipe.... | 5,329,065 |
def _redacted_to_curl(request: httpx.Request) -> str:
"""Pass through to curlify2.to_curl that redacts the authorization in the headers
"""
if (auth_header := request.headers.get('authorization')) is None:
return curlify2.to_curl(request)
req_copy = copy.copy(request)
req_copy.headers = cop... | 5,329,066 |
def get_norm(norm):
"""
Args:
norm (str or callable):
Returns:
nn.Module or None: the normalization layer
"""
support_norm_type = ['BN', 'SyncBN', 'FrozenBN', 'GN', 'nnSyncBN']
assert norm in support_norm_type, 'Unknown norm type {}, support norm types are {}'.format(
... | 5,329,067 |
def parse_scales_line(line):
"""
Args:
- line:
Returns:
- scales_dict
"""
def advance_past_token(str, token):
return str[str.find(token) + len(token):]
scales_dict = {}
line = advance_past_token(line, 'Scales:')
pair_str = line.split(',')
for pair_str in pair_str:
dname, scale = pair_str.split(':')... | 5,329,068 |
def test_org_admin_get_own_user_info(org_admin_headers):
""" services api allows org admin to get its own user info """
org = org_admin_headers['CVE-API-ORG']
user = org_admin_headers['CVE-API-USER']
res = requests.get(
f'{env.AWG_BASE_URL}{ORG_URL}/{org}/user/{user}',
headers=org_admin_... | 5,329,069 |
def parse_remove_configuration(configuration):
"""
Turns the configuration line of splitting into a name and a set of params.
"""
if configuration is None:
return "None", None
print('conf', configuration)
conf_dict = collections.OrderedDict(configuration)
name = 'remove'
for ke... | 5,329,070 |
def _calc_cost_grad_first(data_input, w, label, features):
"""Calculate the partial cost and gradient."""
train_data = read_stage_file(data_input, features + [label])
size_train = train_data.shape[0]
labels = train_data[label].values
train_data = train_data[features].values
if size_train > 0:
... | 5,329,071 |
def mean_over_patches(dataframe, temps):
"""Compute the mean of the module temperatures over all patches of a module."""
for patch_area_agg in ["min", "max", "mean", "median"]:
dataframe["{}_temp".format(patch_area_agg)] = pd.Series({track_id: np.mean(t[patch_area_agg]) for track_id, t in temps.items()}... | 5,329,072 |
def subtract_dbm(dbm1: float, dbm2: float):
"""Adds two decibel values"""
watt1 = dbm_to_watt(dbm1)
watt2 = dbm_to_watt(dbm2)
return watt_to_dbm(watt1 - watt2) | 5,329,073 |
def _validateConfigFile(configFilePath):
"""
Test a configuration file path to be sure it is usable in the plugin
Uses a binary included in the project to test a given configuration file, and will raise an exception
if something is not valid.
The idea if to fail fast at startup for any configuration... | 5,329,074 |
def focused_evaluate(board):
"""
Given a board, return a numeric rating of how good
that board is for the current player.
A return value >= 1000 means that the current player has won;
a return value <= -1000 means that the current player has lost
"""
score = board.longest_chain(board.ge... | 5,329,075 |
def tanh(x, name=None):
"""
sparse tanh activation, requiring x to be a sparse coo or sparse csr tensor.
.. math::
out = tanh(x)
Parameters:
x (Tensor): The input Sparse Tensor with data type float32, float64.
name (str, optional): Name for the operation (optional, default is ... | 5,329,076 |
def record(args, filename):
"""Record a snapshot in a json file, as specified by arguments in args.
Return 0 on success, 1 on failure."""
LOGGER.debug('In subcommand record.')
os.chdir(args.project)
projectpath = os.getcwd()
# parse addons.make into a list of addons
addons_list = []
t... | 5,329,077 |
def collector(monkeypatch):
"""
Unit test: base case
"""
col = SunPowerPVSupervisorCollector(use_device_data_timestamp=False)
attrs = [
'connect',
'disconnect',
'info_metrics',
]
mocked = MagicMock()
mocked.connect.return_value = []
mocked.disconnect.return_... | 5,329,078 |
def _setorder(req, stores):
"""Pull the password store ordering out of the req object"""
for store in stores.get_all_stores():
stores[store] = int(req.args.get(store.__class__.__name__, 0))
continue | 5,329,079 |
def GetParents_old(con, cur, term):
"""
Get all the parents of the term in the ontology tree
input:
con,cur
term : str
The term for which to look for parents
output:
err : str
Error message or empty string if ok
parents : list of str
the parents of term
"""
... | 5,329,080 |
def uploadResourceFileUsingSession(url, session, resourceName, fileName, fullPath, scannerId):
"""
upload a file for the resource - e.g. a custom lineage csv file
works with either csv for zip files (.csv|.zip)
returns rc=200 (valid) & other rc's from the post
"""
print(
"uploading fi... | 5,329,081 |
def read_inc_stmt(line: str) -> tuple[Literal["inc"], str] | None:
"""Attempt to read INCLUDE statement"""
inc_match = FRegex.INCLUDE.match(line)
if inc_match is None:
return None
inc_path: str = inc_match.group(1)
return "inc", inc_path | 5,329,082 |
def _clear_screen():
""" http://stackoverflow.com/questions/18937058/python-clear-screen-in-shell """
if platform.system() == "Windows":
tmp = os.system('cls') #for window
else:
tmp = os.system('clear') #for Linux
return True | 5,329,083 |
def prepare_ssh_command(config_name, server, hostname, client_id, tool, param, view_id=0, username='bluecat', timeout=30,
**kwargs):
"""
:param config_name:
:param server:
:param hostname:
:param client_id:
:param tool:
:param param:
:param username:
:param ti... | 5,329,084 |
def sent2vec(s, model):
"""
Transform a sentence to a vector.
Pre: No parameters may be None.
Args:
s: The sentence to transform.
model: A word2vec model.
Returns: A vector, representing the given sentence.
"""
words = word_tokenize(s.lower())
# Stopwords and numbers m... | 5,329,085 |
def validate_json_object(json_obj, obj):
"""Determines if the json template matches expected Batch object
:param json_obj: json dictionary from template.
:param obj: matched Batch object.
"""
# pylint:disable=protected-access
from enum import Enum
if issubclass(type(obj), Enum):
retu... | 5,329,086 |
def subnet_group_present(
name,
subnet_ids=None,
subnet_names=None,
description=None,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Ensure ElastiCache subnet group exists.
.. versionadded:: 2015.8.0
name
The name for the ElastiCache subn... | 5,329,087 |
def GetTensorFlowVersion(vm):
"""Returns the version of tensorflow installed on the vm.
Args:
vm: the target vm on which to check the tensorflow version
Returns:
installed python tensorflow version as a string
"""
stdout, _ = vm.RemoteCommand(
('echo -e "import tensorflow\nprint(tensorflow.__v... | 5,329,088 |
def process_step_collect_parse(project, step, process_result, format_args=None):
"""
Function will parse the file from an output
:type step: structures.project_step.ProjectStep
:type project: structures.project.Project
:type process_result: proc.step.step_shell.ProcessStepResult
... | 5,329,089 |
async def test_hello_world(client):
"""Test Hello World."""
resp = await client.get('/hello-world', headers={'Accept': 'application/json'})
assert resp.status == 200
assert 'application/json' in resp.headers['Content-Type']
text = await resp.text()
body = json.loads(text)
assert len(body.k... | 5,329,090 |
def datetime_column_evrs():
"""hand-crafted EVRS for datetime columns"""
with open(
file_relative_path(__file__, "../fixtures/datetime_column_evrs.json")
) as infile:
return expectationSuiteValidationResultSchema.load(
json.load(infile, object_pairs_hook=OrderedDict)
) | 5,329,091 |
def _write_dihedral_information(xml_file, structure, ref_energy):
"""Write dihedrals in the system.
Parameters
----------
xml_file : file object
The file object of the hoomdxml file being written
structure : parmed.Structure
Parmed structure object
ref_energy : float, default=1.... | 5,329,092 |
def chat_header_args(panel_vars: List[PanelVariable], parsed_args: Dict) -> List:
"""Creates a list of tuples containing the passed in arguments from the chat command.
Args:
panel_vars (list(nautobot_plugin_chatops_grafana.models.PanelVariable)): A list of PanelVariable objects.
parsed_args (di... | 5,329,093 |
def pd_df_timeseries():
"""Create a pandas dataframe for testing, with timeseries in one column"""
return pd.DataFrame(
{
"time": pd.date_range(start="1/1/2018", periods=100),
"A": np.random.randint(0, 100, size=100),
}
) | 5,329,094 |
def n_tokens(doc: Union[Doc, Span]):
"""Return number of words in the document."""
return len(doc._._filtered_tokens) | 5,329,095 |
def getJobs(numJobs=1):
"""
Return a list of dictionary data as provided to the plugin `submit` method
"""
job = {'allowOpportunistic': False,
'bulkid': None,
'cache_dir': TEST_DIR + '/JobCollection_1_0/job_1',
'estimatedDiskUsage': 5000000,
'estimatedJobTime'... | 5,329,096 |
def create_test_user():
"""Creates a new user with random username for testing
If two randomly assigned usernames overlap, it will fail
"""
UserModel = get_user_model()
username = '%s_%s' % ('test', uuid4().get_hex()[:10],)
user = UserModel.objects.create(username=username)
return user | 5,329,097 |
def make_logical_or_tests(options):
"""Make a set of tests to do logical_or."""
return _make_logical_tests(tf.logical_or)(options, expected_tf_failures=1) | 5,329,098 |
def pushd(working_directory: Union[os.PathLike, str]) -> Iterator[None]:
"""Change the current working directory for a block of code."""
cwd = os.getcwd()
try:
os.chdir(working_directory)
yield
finally:
os.chdir(cwd) | 5,329,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.