content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def return_countries():
"""
Get the countries available
:return: country JSON
"""
with open("country.json", "r") as country:
return country.read() | 61,600 |
def outer_product(a: Vector, b: Vector) -> Matrix2d:
"""
Given vectors a = (a1, a2, ..., an),
b = (b1, b2, ..., bm)
Returns a matrix of shape NxM
A = [ a1b1, a1b2, ..., a1bm,
.
.
.
anb1,... | 61,601 |
def epsilon_greedy_policy(Qs, nA, i_episode, epsilon=None):
"""epsilon greedy policy
env: Gym environment
s: state
i_episode: index of current episode -> epsilon should reduce when i increase
eps: customized epsilon
"""
epsilon = 1 / i_episode if epsilon is None else epsilon
... | 61,602 |
def BJtime(mergeTime):
"""
utc时间转换北京时间
"""
mergeTime = mergeTime.replace('T', ' ').replace('Z', '')
mergeTime = datetime.datetime.strptime(mergeTime, '%Y-%m-%d %H:%M:%S')
mergeTime = mergeTime + datetime.timedelta(hours=8)
mergeTime = datetime.datetime.strftime(mergeTime, '%Y-%m')
return... | 61,603 |
def make_simple_templating_function(template):
"""Factory for making a templating function that applies the context object to the given template to create a
string.
Arguments:
template -- Templated string, whose values will be filled at run-time from the passed context.
For example, the... | 61,604 |
def _plot_summary_stats(bin_data: pd.DataFrame) -> None:
"""Creates plots with key evaluation metrics for LTV model.
This function creates visualization with bar charts of bin (default decile)
level average predicted and actual LTV as well as provides overall
Spearman Rank Correlation, Normalized Gini coeffici... | 61,605 |
def shutdown(*args, **kwargs):
"""
App shutdown and cleanup
:return: None
"""
if hasattr(settings, 'MESSAGE_QUEUE') and isinstance(settings.MESSAGE_QUEUE, MessageQueue):
settings.MESSAGE_QUEUE.shutdown() | 61,606 |
def main(company_list, concurrency = False):
"""
Main function call.
--------
:param <company_list>: List ; list of publicly traded companies' tickers
"""
#Concurrent running
if concurrency:
try:
process_1 = Process(target = extract_info_intraday, args=(company_list,))
process_1.start()
process_2 = P... | 61,607 |
def flatten_to_single_ndarray(input_):
"""Returns a single np.ndarray given a list/tuple of np.ndarrays.
Args:
input_ (Union[List[np.ndarray],np.ndarray]): The list of ndarrays or
a single ndarray.
Returns:
np.ndarray: The result after concatenating all single arrays in input_.... | 61,608 |
def show_oss(ctx):
"""
Show supported os
"""
manager = ctx.obj["manager"]
for anos in manager.oss:
click.echo(anos) | 61,609 |
def get_pbs_node_requirements(sys_settings,node_count):
"""Get the cpu and memory requirements for a given number of nodes
Args:
sys_settings (dict): System settings dict, as supplied from config_manager
node_count (int): Number of whole nodes on target system
Returns:
dict... | 61,610 |
def api_fixture():
"""Define a fixture for simplisafe-python API object."""
api = Mock()
api.refresh_token = "token123"
api.user_id = "12345"
return api | 61,611 |
def copy_sample(ctx: click.Context, src: Path, dest: Path) -> None:
"""Copy a sample directory.
Args:
ctx: Click context object.
src: Source path.
dest: Destination path.
"""
if dest.exists():
LOGGER.error("Directory %s already exists!", dest)
ctx.exit(1)
LO... | 61,612 |
def checkArray(comment,check,expected,tol=1e-7):
"""
This method is aimed to compare two arrays of floats given a certain tolerance
@ In, comment, string, a comment printed out if it fails
@ In, check, list, the value to compare
@ In, expected, list, the expected value
@ In, tol, float, optional, ... | 61,613 |
def task_interactive():
"""Run the Docker container in interactive mode"""
def run():
cmd = [
'docker',
'run',
'-it',
'--rm',
'-w',
'/app',
'--volume',
'%s/:/app' % CONFIG['volume_path'],
IMAGE,
... | 61,614 |
def classificationModel(model,dataFrame,predictors,outcome,nFolds:int):
"""
Method for computing accuray and cross-validation based upon given model
"""
if dataFrame is None:
return None
model.fit(dataFrame[predictors],dataFrame[outcome])
predictions=model.predict(dataFrame[predictors])
... | 61,615 |
def simu_abstract_div_stutter(ts):
"""Compute the coarsest divergent stutter bisimulation abstraction for a Finite Transition System.
@param ts: input finite transition system, the one you want to get
its abstraction.
@type ts: L{FTS}
@return: the abstraction, and the corresponding... | 61,616 |
def runtime_error(exception):
"""Handle a runtime error, e.g., an unresponsive server.
:param exception: Exception caught.
:return: constants.EXIT_CODE_ERR
"""
parser.print_error(msg=exception)
return constants.EXIT_CODE_ERR | 61,617 |
def donchian(candles: np.ndarray, period=20, sequential=False) -> DonchianChannel:
"""
Donchian Channels
:param candles: np.ndarray
:param period: int - default: 20
:param sequential: bool - default=False
:return: float | np.ndarray
"""
if not sequential and len(candles) > 240:
... | 61,618 |
def genball(npt, ndim, rstate=None):
""" Simulate points in ndim ball """
# use Barthe2005
x = rstate.standard_normal(size=(npt, ndim))
y = rstate.exponential(0.5, size=npt)
x1 = x / np.sqrt((y + (x**2).sum(axis=1)))[:, None]
return x1 | 61,619 |
def autoenc_quantize(x, nbits, nmaps, do_training, layers=1):
"""Autoencoder into nbits vectors of bits, using noise and sigmoids."""
enc_x = tf.reshape(x, [-1, nmaps])
for i in xrange(layers - 1):
enc_x = tf.layers.dense(enc_x, nmaps, name="autoenc_%d" % i)
enc_x = tf.layers.dense(enc_x, nbits,... | 61,620 |
def grab_liberty_siam_dataset(pairs=250000):
"""
References:
http://www.cs.ubc.ca/~mbrown/patchdata/patchdata.html
https://github.com/osdf/datasets/blob/master/patchdata/dataset.py
Notes:
"info.txt" contains the match information Each row of info.txt
corresponds corresponds ... | 61,621 |
def ndcg_at_k(
rating_true,
rating_pred,
col_user=DEFAULT_USER_COL,
col_item=DEFAULT_ITEM_COL,
col_rating=DEFAULT_RATING_COL,
col_prediction=PREDICTION_COL,
relevancy_method="top_k",
k=DEFAULT_K,
threshold=DEFAULT_THRESHOLD,
):
"""Normalized Discounted Cumulative Gain (nDCG).
... | 61,622 |
def select_table_value_from_page(**params):
"""从画面上选择出一个列表的数据"""
return """\
with open('../script_lib/parse_table_value.js', encoding='utf-8') as file:
script = file.read()
header = driver.execute_script(script, '{header_selector}')[0]
result = driver.execute_script(script, '{data_selector}')
... | 61,623 |
def create_canvas(height, width):
"""Creates blank canvas given height and width. Returns Canvas object."""
new_canvas = Canvas(height, width)
return new_canvas | 61,624 |
def test_renorm_exception():
"""Can arise with zero, negative, or NaN spectra."""
sp = FlatSpectrum(1) * -10
bp = ObsBandpass('johnson,v')
with pytest.raises(ValueError):
sp.renorm(15, 'vegamag', bp) | 61,625 |
def test_healthz_readiness_ok(client):
"""Test the /healthz/ready check endpoint"""
response = client.get("/healthz/ready")
print(response.data)
assert response.status_code == 200
assert response.data == b"OK\n" | 61,626 |
def families_lens():
"""."""
return ['Lens', 'LensRev'] | 61,627 |
async def jobs_list(
db=Depends(get_db),
):
"""
Get all jobs
"""
try:
return get_jobs(db)
except Exception as e:
return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, content=f'{str(e)}') | 61,628 |
def load_training_data(direc: str = 'data/training/training_articles.csv', size: int = 50):
"""
opens text file with sample articles to train and tokenizes
"""
with open(direc) as f:
return [prepare_text_for_lda(line) for line in f] | 61,629 |
def reduce2scalar_seasonal_zonal( mv, seasons=seasonsyr, region=None, latmin=None, latmax=None, vid=None, gw=None ):
"""returns the mean of the variable over the supplied latitude range (in degrees).
The computed quantity is a scalar but is returned as a cdms2 variable, i.e. a MV.
The input mv is a cdms2 va... | 61,630 |
def upsert_org(datadict, ckanapi, debug=False):
"""Create or update organisations through a ckanapi as per given datadict.
Arguments:
datadict A dict with information on organizations, such as:
{
'logo_url': 'http://www.dfes.wa.gov.au/_layouts/images/FESA.Mobile/dfes_print.png',
... | 61,631 |
def parallel(iterable, count, callable, *a, **kw):
"""
Concurrently fire C{callable} for each element in C{iterable}.
Any additional arguments or keyword-arguments are passed to C{callable}.
@type iterable: C{iterable}
@param iterable: Values to pass to C{callable}.
@type count: C{int}
... | 61,632 |
def create_user_object(uname, psswd,sub_u):
"""Return a User object with given information."""
return User(
username=uname,
password=pwd_context.hash(psswd),
sub_user=sub_u
) | 61,633 |
def myreplace(old, new, s):
"""Replace all occurrences of old with new in s."""
result = " ".join(s.split()) # firsly remove any multiple spaces " ".
return new.join(result.split(old)) | 61,634 |
def need_analyzer(args):
""" Check the intent of the build command.
When static analyzer run against project configure step, it should be
silent and no need to run the analyzer or generate report.
To run `scan-build` against the configure step might be neccessary,
when compiler wrappers are used. ... | 61,635 |
def angular_terms(Rca: float, ShfZ: Tensor, EtaA: Tensor, Zeta: Tensor,
ShfA: Tensor, vectors12: Tensor) -> Tensor:
"""Compute the angular subAEV terms of the center atom given neighbor pairs.
This correspond to equation (4) in the `ANI paper`_. This function just
compute the terms. The s... | 61,636 |
def cookie_session_name() -> str:
"""
Retorna o nome do cookie para a sessão.
"""
return "ticket_session" | 61,637 |
def test_plot_pandas_twinx(data):
"""
Tests that we can generate a plot with multiple axes when we pass in different y-valued data.
"""
second_data = data['data'].copy()
second_data['Frequency (Hz)'] *= 2
second_data.rename(columns={'Frequency (Hz)': 'Frequency (kHz)'},
inplace=True)... | 61,638 |
def test_incomplete_fields_syncs_when_business_activities_changes(es_with_signals):
"""
When business activities are updated the incomplete fields should be updated accordingly.
Specifically, when 'other' is added as a business activity, 'other_business_activity'
should show as an incomplete field.
... | 61,639 |
def query():
"""Display search requests and pagination via GET"""
if not request.args.get("search"):
return redirect(url_for("index"))
if request.args.get("start") is None or int(request.args.get("start")) < 0:
start = 0
else:
start = int(request.args.get("start"))
query = ... | 61,640 |
def select_a_genome():
"""
This function randomly selects a genetic operation from following options to produce a genome:
1. Crossover two randomly selected genomes
2. Random selection from available genomes
3. Latest genome
4. Best fitness ever
5. Mutate genome with highest fitness
6. T... | 61,641 |
def prep_qubits(qubits: list, n: int):
"""
Generate a quil program which prepares given qubits in a state representing number n.
:param n: the number to write
:param qubits: qubit indexes to write the number n
:return: circuit to write number n on given qubits.
"""
p = Program()
for q... | 61,642 |
def plot_seq_label(ax, X, Fs=1, color_label=[], direction='horizontal',
fontsize=10, time_axis=False, print_labels=True):
"""Plot label sequence in the style of annotations
Notebook: C4/C4S5_Evaluation.ipynb
Args:
ax: Axis used for plotting
X: Label sequence
... | 61,643 |
def test(pytest_args):
"""Run the tests."""
import pytest
rv = pytest.main([TEST_PATH] + list(pytest_args))
exit(rv) | 61,644 |
def _sqrt_symbolic_denest(a, b, r):
"""Given an expression, sqrt(a + b*sqrt(b)), return the denested
expression or None.
Algorithm:
If r = ra + rb*sqrt(rr), try replacing sqrt(rr) in ``a`` with
(y**2 - ra)/rb, and if the result is a quadratic, ca*y**2 + cb*y + cc, and
(cb + b)**2 - 4*ca*cc is 0... | 61,645 |
def blackNormalizeImage(a):
"""
Normalizes numarray to fit into an image format
that is values between 0 and 255.
"""
#Minimum image value, i.e. how black the image can get
minlevel = 0.0
#Maximum image value, i.e. how white the image can get
maxlevel = 200.0
#Maximum standard deviations to include, i.e. pixe... | 61,646 |
def CASCADE(instance_to_delete, manager):
"""On suppression of the related instance, delete the associated cache object"""
if not instance_to_delete:
return
try:
manager.get(pk=instance_to_delete.pk).delete()
except manager.model.DoesNotExist:
pass | 61,647 |
def test_sample_shape_array_arguments_no_sample_shape(rng_key, case):
"""Test the correctness of broadcasting when arguments can be arrays."""
samples = MvNormal(case["mu"], case["covariance_matrix"]).sample(
rng_key, case["sample_shape"]
)
assert samples.shape == case["expected_shape"] | 61,648 |
def create_mfcc(path, sr=None, offset=0, duration=None):
"""Create an mfcc from the passed path"""
wave = AudioSegment.from_wav(path)
mono = wave.channels != 1
if duration:
y, sr = librosa.load(path, sr=sr, mono=mono, offset=offset, res_type='kaiser_fast')
else:
y, sr = librosa.load(... | 61,649 |
def maybe_pad(draw, regex, strategy, left_pad_strategy, right_pad_strategy):
"""Attempt to insert padding around the result of a regex draw while
preserving the match."""
result = draw(strategy)
left_pad = draw(left_pad_strategy)
if left_pad and regex.search(left_pad + result):
result = left... | 61,650 |
def parseSections (fd):
"""
Quick&Dirty parsing for GNU ld’s linker map output, needs LANG=C, because
some messages are localized.
"""
sections = []
# skip until memory map is found
found = False
while True:
l = fd.readline()
if not l:
break
if l.str... | 61,651 |
def test_edit_group(app, db, check_ui):
"""Validation of correct edit group (all field updated)"""
app.group.validation_of_group_exist()
old_groups = db.get_group_list()
group = random.choice(old_groups)
group_id = group.id
group = Group(group_name=Profinity.long_word_20, group_header=Profin... | 61,652 |
def from_year_fraction(date: float):
"""
this function takes a date in float as input and return datetime as output
Parameter:
--------
date: float such as 2000.02
Return:
--------
the corresponding datetime object
"""
if type(date).__name__ != 'float':
raise Ty... | 61,653 |
def add_dependency(filename, new_dependency, compatibility_version, current_version):
"""Add the given dependency to all headers in a MachO file.
Parameters
----------
filename: str
The path to the macho-o binary file to add dependency to
new_dependency: str
Name of the new dependen... | 61,654 |
def run_workflow(ctx, fullname, payload):
"""Execute a workflow"""
try:
cel_workflows.get_by_name(fullname)
payload = json.loads(payload)
except WorkflowNotFound as e:
click.echo(f"Error: {e}")
return
except JSONDecodeError as e:
click.echo(f"Error parsing the JSO... | 61,655 |
def test_normalized_string001_2095_normalized_string001_2095_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : value=
"""
assert_bindings(
schema="msData/datatypes/normalizedString.xsd",
instance="msData/datatypes/normalizedString001.xml",
class_name="Root... | 61,656 |
def test_exam_init():
"""test Exam with one and two arguments
"""
q1, q2 = exam.Question("q1 text", "q1 image"), exam.Question("q2 text", "q2 image")
ex1 = exam.Exam(q1)
ex2 = exam.Exam(q1, q2)
assert ex1.questions == (q1,)
assert ex2.questions == (q1, q2) | 61,657 |
def even(value):
"""Simple validator defined for test purpose"""
return not (int(value) % 2) | 61,658 |
def diff(a, b, sline=0):
"""
Return a list of deletions and insertions that will turn 'a' into 'b'. This
is done by traversing an implicit edit graph and searching for the shortest
route. The basic idea is as follows:
- Matching a character is free as long as there was no
deletion/ins... | 61,659 |
def new_webui_log_file():
"""Create new logging files for web ui."""
ui_stdout_file, ui_stderr_file = new_log_files(
"webui", redirect_output=True)
return ui_stdout_file, ui_stderr_file | 61,660 |
def xyz_sector_plot(
plt, results_df, error_model, x_limits=None, save_folder=None,
yscale=None, eta_key='eta_x', min_y_axis=1e-3,
thresholds_df=None,
):
"""Plot the different sectors (pure X, pure Y, pure Z) crossover plots
Parameters
----------
plt : matplotlib.pyplot
The matplotl... | 61,661 |
def get_quarter_start(x: Optional[Date] = None) -> Date:
"""
Returns the quarter start as of the given date.
>>> get_quarter_start(Date(2017, 1, 1))
datetime.date(2017, 1, 1)
>>> get_quarter_start(Date(2017, 5, 31))
datetime.date(2017, 4, 1)
>>> get_quarter_start(Date(2017, 6, 30))
date... | 61,662 |
def _compute_J(x, window_starts, L):
"""Compute the cost, which is proportional to the
difference between pairs of windows"""
# Get all windows and zscore them
N_windows = len(window_starts)
windows = np.zeros((N_windows, L))
for w in range(N_windows):
temp = x[window_starts[w]:window_s... | 61,663 |
def getAppLink(dic):
"""Returns the Link for Chapter Application Form.
dic -- Dictionary from the JSON with all values.
"""
return str(dic["content"]["$t"]).split(',')[3].split(' ')[2].strip() | 61,664 |
def create_single_env(env_name, seed, dmlab_homepath, use_monitor,
split='train', vizdoom_maze=False, action_set='',
respawn=True, fixed_maze=False, maze_size=None,
room_count=None, episode_length_seconds=None,
min_goal_distance=Non... | 61,665 |
def test_parameter_3():
"""
Feature: Check the names of parameters.
Description: Check the name of parameter in init.
Expectation: No exception.
"""
class ParamNet(Cell):
def __init__(self):
super(ParamNet, self).__init__()
self.param_a = Parameter(Tensor([1], ms.... | 61,666 |
def download():
"""CLI group."""
pass | 61,667 |
def veh_search_for_immediate_request(sim_time, prq, fleetctrl, list_excluded_vids=[]):
"""This function can be used to find pooling vehicles for an immediate service of a request.
:param sim_time: current simulation time
:param prq: PlanRequest to be considered
:param fleetctrl: FleeControl instance
... | 61,668 |
def rebase(df_: pd.DataFrame, base_year: int) -> pd.Series:
"""Rebase values to a given base year"""
base_values = (
df_.loc[df_.year.dt.year == base_year].set_index("iso_code")["value"].to_dict()
)
return round(100 * df_.value / df_.iso_code.map(base_values), 3) | 61,669 |
def big_sliding_window(raster):
"""Creates 3D array organizing local neighbors at every index
Returns a raster of shape (L,W,9) which organizes (along the third
dimension) all of the neighbors in the original raster at a given
index, in the order [NW, N, NE, W, 0, E, SW, S, SE]. Outputs are
ordered... | 61,670 |
async def updateLeaderboardChannel(lbChannel: Channel) -> None:
"""
Deletes the old leaderboard and posts the updated one.
Parameters:
lbChannel: discord.Channel
Returns:
None
"""
if (lbChannel is None):
print("Leaderboard channel not set in config."... | 61,671 |
def module_hrun(name, base_url, module, receiver):
"""
异步运行模块
:param env_name: str: 环境地址
:param project: str:项目所属模块
:param module: str:模块名称
:return:
"""
logger.setup_logger('INFO')
kwargs = {
"failfast": False,
}
runner = HttpRunner(**kwargs)
module = list(module)... | 61,672 |
def met_gfssdJ1_3sopt_tr50(P, Q, data_source, n, r, J=1, tr_proportion=0.5):
"""
FSSD-based model comparison test
* Use J=1 test location by default (in the set V=W).
* 3sopt = optimize the test locations by maximizing the 3-model test's
power criterion. There is only one set of test lo... | 61,673 |
def dropuser(username, connection='%'):
"""Drop a user from the database. Requires administration access.
"""
# establish connection
conn = config['connection']
# flush privileges
conn.query("FLUSH PRIVILEGES;")
# drop user
conn.query("DROP USER %s@%s;", (username, connection))
#
... | 61,674 |
def find_permutation(s, pattern):
"""Find presence of any permutation of pattern in the text as a substring.
>>> find_permutation("oidbcaf", "abc")
True
>>> find_permutation("odicf", "dc")
False
>>> find_permutation("bcdxabcdy", "bcdxabcdy")
True
>>> find_permutation("aaacb", "abc")... | 61,675 |
def crownibp_bound_propagation(
function: Callable[..., Nest[Tensor]],
*bounds: Nest[GraphInput]) -> Nest[LayerInput]:
"""Performs Crown-IBP as described in https://arxiv.org/abs/1906.06316.
We first perform IBP to obtain intermediate bounds and then propagate linear
bounds backwards.
Args:
functi... | 61,676 |
def radioButtons(
widget,
master,
value,
btnLabels=(),
tooltips=None,
box=None,
label=None,
orientation=Qt.Vertical,
callback=None,
**misc
):
"""
Construct a button group and add radio buttons, if they are given.
The value with which the buttons synchronize is the ind... | 61,677 |
def gridLog(**kw):
"""Send GLRecord, Distributed Logging Utilities
If the scheme is passed as a keyword parameter
the value is expected to be a callable function
that takes 2 parameters: url, outputStr
GRIDLOG_ON -- turn grid logging on
GRIDLOG_DEST -- provide URL destination
"""
impo... | 61,678 |
def remove_plane(z, x, y):
"""Remove linear plane from z values. All need to have same shape!
Parameters
----------
z : [type]
[description]
x : [type]
[description]
y : [type]
[description]
"""
X_reg = np.vstack([x.flatten(), y.flatten(), x.flatten()*y.flatten()... | 61,679 |
def preprocess_df(df: pd.DataFrame, userdict: str = None, jumanpp: bool = False) -> pd.DataFrame:
"""Perform preprocessing for given dataframe,
including, binarizing p/n labels to 1/0, normalization (JP), adding column of tokenized sentence.
"""
df = _binarize_pn(df)
if _check_lang(df) == 'ja':
... | 61,680 |
def go() -> None:
"""Quickly explore ZenML with this walkthrough."""
from zenml.cli.text_utils import (
zenml_go_notebook_tutorial_message,
zenml_go_privacy_message,
zenml_go_welcome_message,
)
from zenml.config.global_config import GlobalConfiguration
gc = GlobalConfigurati... | 61,681 |
def changer_regles(espace):
"""fonction pour changer les règles de l'espace courant
----------------------------
Entrées : objet Espace initialisé
Sortie : changement des règles de l'espace courant pour les prochaines itérations
"""
print("les règles actuelles sont : ")
print("nombr... | 61,682 |
def local_help_filename(pkg_info, help_file):
"""
Determine what the full file name of a help file from a given package would
be if it was stored locally
"""
return os.path.join(sublime.packages_path(), pkg_info.doc_root, help_file) | 61,683 |
def get_model_predictions(data, model):
"""
Function to get prediction for a data point (datapoint being a tokenized text segment)
Input: data to predict, model to predict with
Output: prediction for input data
"""
output = model(torch.tensor([data['input_ids']]), attention_mask=torch.tens... | 61,684 |
def p2p_gnuetella08():
"""
Returns the graph from: https://snap.stanford.edu/data/p2p-Gnutella08.html,
where we preprocess it to only keep the largest connected component
:return: undirected NetworkX graph
"""
graph = nx.read_edgelist(graph_dir + "p2p-Gnutella08.txt")
return graph.subgraph... | 61,685 |
def buildserver(images=None, tags=None):
"""build Docker image"""
images = images or ("rg-server", f"gcr.io/{GC_PROJECT}/rg-server")
version = _server_version()
tags = tags or ("latest", version)
all_tags = [f"{i}:{t}" for i in images if i for t in tags if t]
LOGGER.info("Building Docker image... | 61,686 |
def object_lookup_command():
""" Sample query: querystring = {'filter':'subnet','count':'50','exact_subnet':'1.1.1.1'} """
querystring = {
'filter': 'subnet',
'count': '50',
'exact_subnet': demisto.args()['ip']
}
if not valid_ip(querystring['exact_subnet']):
return_error(... | 61,687 |
def isObsMosaic(data, indx, mtype=MOSAIC_TYPES):
"""
Returns True or False if an observation is a mosaic of a
type listed in MOSAIC_TYPES.
data : Contains data from readObservations() in the DATA key
indx : Row number within data
mtype : A list of mosaic types
The typ... | 61,688 |
def most_probable_alleles(allele_list):
"""
Identify the most probable haplotype in a list
:param list allele_list: List of tuples of (allele, p_value)
:return: List of 2 most probable alleles in the group
:rtype: list[str]
"""
all_alleles = defaultdict()
# First collect all the keys. ... | 61,689 |
def bootstrap_freq_sweep_ci(df, quantity, replicate_identifier,
n_bootstrap, ci, estimator=np.mean):
""" Gets bootstrap confidence interval for an estimator of
frequency sweep (or time sweep) data. Boot strap can be either a
percentile bootstrap of an estimator of a studentized bootstra... | 61,690 |
def atcab_sha_hmac(data, data_size, key_slot, digest, target):
"""
Use the SHA command to compute an HMAC/SHA-256 operation.
Args:
data Message data to be hashed. (bytearray or bytes)
data_size Size of data in bytes. (int)
key_slot Slot key id to ... | 61,691 |
def get_embedded_json(port, flag):
""" Reads out uart from port and looks for the flag. The flag is valid json
with the values wanted by the programmer.
"""
with Serial(port, 115200, timeout=1) as ser:
wd_parse_retries = 0
while wd_parse_retries < 7:
# 1. Use read debug to ... | 61,692 |
def ra_parser(lines):
"""return a list from RA lines.
The RA (Reference Author) lines list the authors of the paper (or other
work) cited. RA might be missing in references that cite a reference group
(see RG line). At least one RG or RA line is mandatory per reference block.
All of the authors ar... | 61,693 |
def write_json_atomic(filename, obj, indent=None, sort_keys=None):
"""Write JSON to `filename` such that `filename` never exists in a partially written state."""
filename = _expand(filename)
if filename.startswith('s3://'):
write_json(
filename, obj, indent, sort_keys
) # s3 ope... | 61,694 |
def load_markercolors():
"""
Returns a dictionary mapping sources of the E. coli data with standard colors
and glyphs. This ensures constant marking of data across plots.
"""
colors, _ = get_colors()
mapper = {
'Bremer & Dennis, 2008': {'m':'X', 'm_bokeh':'circle_dot'},
'Brunsch... | 61,695 |
def test_spectral_embedding_symmetrzation(seed=36):
"""Test spectral embedding with amg solver vs arpack using non symmetric laplacian"""
radius = 4.0
geom_params = {'affinity_kwds':{'radius':radius}, 'adjacency_kwds':{'radius':radius}, 'adjacency_method':'brute',
'laplacian_method':'geom... | 61,696 |
def get_Dna_Token(dnac):
"""
Intent-based Authentication API call
The token obtained using this API is required to be set as value to the X-Auth-Token HTTP Header
for all API calls to Cisco DNA Center.
:param: dnac
:return: Token STRING
"""
url = 'https://{}/dna/system/api/v1/auth/token'... | 61,697 |
def un_map_pack_response_edition_modifier(response_modifier):
"""
Returns an un-map-packer to the given response modifier for message edition endpoints.
Parameters
----------
response_modifier : `None`, ``ResponseModifier``
The response modifier to un-map-pack if any.
Returns
... | 61,698 |
def _extract_non_mrjob_tags(cluster):
"""get tags from a cluster as a dict, excluding tags starting with
``__mrjob_``"""
return {k: v for k, v in _extract_tags(cluster).items()
if not k.startswith('__mrjob_')} | 61,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.