content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_windowed_mean_expression(loom,
list_of_gene_windows,
patient_column='Patient_ID',
patient=0,
cell_type_column=None,
cell_type=None,
... | 5,308,400 |
def parse_trajectory_file(fname):
"""
This routine reads a file of particle trajectory data generated by the ptm simulation.
Data from ptm is output in formatted ascii, with the time history of a particle trajectory
given by a 8-column array with an unknown number of rows. The data from each particle is... | 5,308,401 |
def get_learner(config_args, train_loader, val_loader, test_loader, start_epoch, device):
"""
Return a new instance of model
"""
# Available models
learners_factory = {
"default": DefaultLearner,
"selfconfid": SelfConfidLearner,
"oodconfid": OODConfidLearner,
}
... | 5,308,402 |
def localHomologyMultiproc(
k, cplx, numProcs, localSimplices=None, iterate=True, rankOnly=False
):
"""Compute local homology relative to the star over a list of simplices in parallel"""
if localSimplices is None:
localSimplices = []
for ki in range(k + 1):
localSimplices += ksi... | 5,308,403 |
def text_repr(diffs):
"""
Helper function to dump xml elements into plain string form for the sake of comparison.
It also get rid of all attributes in xml elements if any.
"""
return {change_type:[etree.tostring(elem.attrib.clear() or elem).decode('utf-8') for elem in elems]
for change_t... | 5,308,404 |
def cli():
"""Custodian Docker Packaging Tool
slices, dices, and blends :-)
"""
logging.basicConfig(
level=logging.INFO, format="%(asctime)s:%(levelname)s %(message)s"
)
logging.getLogger("docker").setLevel(logging.INFO)
logging.getLogger("urllib3").setLevel(logging.INFO)
for n... | 5,308,405 |
def test_aggregation_unweighted(forecasters, aggfunc):
"""Assert aggfunc returns the correct values."""
y = make_forecasting_problem()
forecaster = EnsembleForecaster(forecasters=forecasters, aggfunc=aggfunc)
forecaster.fit(y, fh=[1, 2, 3])
actual_pred = forecaster.predict()
predictions = []
... | 5,308,406 |
def get_default_variables(defaults, source_id, model):
"""
Returns list of strings, representing selection default variable IDs
Keyword Parameters:
defaults -- List of strings, representing requested default query
names
source_id -- String, representing API ID of the selection source
... | 5,308,407 |
def set_config_tag_prefix_delimiter_hyphen():
"""set config"""
# change config
system_importer_file_csv_config_model = (
SystemImporterFileCsvConfigModel.objects.get(
system_importer_file_csv_config_name='SystemImporterFileCsvConfig'
)
)
system_importer_file_csv_config_m... | 5,308,408 |
def search_nlucell():
"""Search NluCell 搜索问答节点
Get:返回所有问答节点
POST:返回所有包含搜索关键词的问答节点
"""
data = {
'skb': database.skb,
'result': []
}
state = {
'success' : 0,
'message' : "请先选择知识库再搜索节点"
}
if not database.skb:
return json.dumps(state)... | 5,308,409 |
def generate_gate_swap_mat() -> np.ndarray:
"""Return the Hilbert-Schmidt representation matrix for a SWAP gate with respect to the orthonormal Hermitian matrix basis with the normalized identity matrix as the 0th element.
The result is a 16 times 16 real matrix.
Parameters
----------
Returns
... | 5,308,410 |
def disableRemoveIPCLog(cmd):
"""
function : disable remove IPCLog
input : cmd
output : NA
"""
(status, output) = subprocess.getstatusoutput(cmd)
if status != 0:
g_logger.debug("Failed to disbale RemoveIPC. Commands"
" for disbale RemoveIPC: %s." % cmd)
... | 5,308,411 |
def can_register(extra, password_meta):
"""
:param extra: {str: any?}, additional fields that the user will fill out when registering such as gender and birth.
:param password_meta: {'count': int, 'count_number': int, 'count_uppercase': int, 'count_lowercase': int,
'count_special'... | 5,308,412 |
def test_evo_search():
"""Test evolutionary search. Since we cannot mock random number generator,
we mocked the cost model to manually guide the evo search. If evo search works
as expected, it should find the target state after a sufficient number of iterations.
This unit test has been tested with 1,000... | 5,308,413 |
def cross_entropy(output, target):
"""Calculate Cross-entropy loss."""
return F.cross_entropy(input=output, target=target) | 5,308,414 |
def plate_to_genesift_sequencing_order_spreadsheet(plate, output_file,
sample_name_function,
well_filter=None,
direction='row'):
"""Generate an excel spreadsheet f... | 5,308,415 |
def hours_of_daylight(date, axis=23.44, latitude=39.87):
"""Compute the hours of daylight for the given date"""
#date = datetime.strptime(start_time, "%Y-%m-%d")
diff = date - pd.datetime(2000, 12, 21)
day = diff.total_seconds() / 24. / 3600
day %= 365.25
m = 1. - np.tan(np.radians(latitude... | 5,308,416 |
def reject(p, xs):
"""The complement of filter.
Acts as a transducer if a transformer is given in list position. Filterable
objects include plain objects or any object that has a filter method such
as Array"""
return filter(complement(p), xs) | 5,308,417 |
def mutable_cache(maxsize=10):
"""In-memory cache like functools.lru_cache but for any object
This is a re-implementation of functools.lru_cache. Unlike
functools.lru_cache, it works for any objects, mutable or not.
Therefore, it returns returns a copy and it is wrong if the mutable
object has cha... | 5,308,418 |
def filter_excluded_fields(fields, Meta, exclude_dump_only):
"""Filter fields that should be ignored in the OpenAPI spec
:param dict fields: A dictionary of of fields name field object pairs
:param Meta: the schema's Meta class
:param bool exclude_dump_only: whether to filter fields in Meta.dump_only
... | 5,308,419 |
def parse_xmpp_addresses(text):
"""."""
xmpp_addresses = ioc_grammars.xmpp_address.searchString(text)
return _listify(xmpp_addresses) | 5,308,420 |
def login_user():
""" This route handles user login """
user_info = request.get_json()
user_instance = UserModel.query.filter_by(email=user_info["email"]).first()
if not user_instance:
return {
"message": "Your email or password is not correct",
"status": "failed",
... | 5,308,421 |
def init():
"""
Initializes the original abstract classes, registering them to the api
module when necessary
"""
import abstractexceptionrouter
import abstractuserprops
import abstractundocontext
import abstractapplication
import abstractscene
import abstractscenewrapper
import abstractsceneobjec... | 5,308,422 |
def test_email(
email_to: EmailStr,
current_user: models.User = Depends(deps.get_current_active_superuser),
) -> Any:
"""
Test emails.
"""
send_test_email(email_to=email_to)
return {"msg": f"Test email sent to {email_to}"} | 5,308,423 |
def euclidean_distance(vects):
"""Compute Euclidean Distance between two vectors.
Euclidean distance is defined as the length of a line
segment between the two points.
d(p,q) = √ [Σ(qi – pi)^2]
Args:
vects : vectors
Returns:
euclidean distance between vects.
"""
x, y ... | 5,308,424 |
def process_typedef(line):
"""处理类型定义"""
content = line.split(' ')
type_ = type_dict[content[1]]
keyword = content[2]
if '[' in keyword:
i = keyword.index('[')
keyword = keyword[:i]
else:
keyword = keyword.replace('\n', '') # 删除行末分号
keyword = keyword.replace('\r'... | 5,308,425 |
def findNearestNeighbourPixel(img, seg, i, j, segSize, fourConnected):
"""
For the (i, j) pixel, choose which of the neighbouring
pixels is the most similar, spectrally.
Returns tuple (ii, jj) of the row and column of the most
spectrally similar neighbour, which is also in a
clump of size... | 5,308,426 |
def _load_json_as_list(path: str) -> list:
"""Load json file and convert it into list.
:param path: path to json file
:type path: str
:return: dict
:rtype: dict
"""
with open(path, "r") as json_data:
data = json.load(json_data)
if isinstance(data, list):
return data
... | 5,308,427 |
def flavor_create(context, values, projects=None):
"""Create a new instance type. In order to pass in extra specs,
the values dict should contain a 'extra_specs' key/value pair:
{'extra_specs' : {'k1': 'v1', 'k2': 'v2', ...}}
"""
specs = values.get('extra_specs')
specs_refs = []
if specs:
... | 5,308,428 |
def dictlike(var: Any) -> Boolean:
"""
Determine whether or not var is dict-like (Can
contain dict-like items).
:param var: Any variable to check
:return: Boolean
"""
try:
var.items()
return True
except (TypeError, AttributeError):
return False | 5,308,429 |
def plot_vehicle_tri(ax, coords, yaw, color=(0, 0, 1, 0.5), zorder=None):
"""Plot a marker representing a vehicle (either ground truth or
estimate)"""
vertices = [
[0, 0],
[0.77, -0.5],
[0, 0.5],
[-0.77, -0.5]
]
tri = patches.Polygon(
vertices, closed=True, fa... | 5,308,430 |
async def async_action():
"""Demonstrate the syntax necessary for an async function."""
print("Begin async action")
await Actions.sleep(1.0)
print("End async action") | 5,308,431 |
def PatchDword(ea, value):
"""
Change value of a double word
@param ea: linear address
@param value: new value of the double word
@return: 1 if successful, 0 if not
"""
return idaapi.patch_long(ea, value) | 5,308,432 |
def ZZ(q0, q1):
"""
Honeywell native entangling gate
diag(1 + 1j, 1 - 1j, 1 - 1j, 1 + 1j)/sqrt(2)
diag(c0,c1,c1,c0)
"""
qbit0 = min(q0, q1)
qbit1 = max(q0, q1)
shape = (2**qbit0, 2, 2**(qbit1 - qbit0 - 1), 2, -1, Qreg.n)
Qreg.inQ.shape = shape
Qreg.outQ.shape = shape
Qreg.o... | 5,308,433 |
def draw_fixed_lines(canvas):
"""
Erases all existing information on the given canvas and then
draws the fixed background lines on it.
Input:
canvas (Tkinter Canvas): The canvas on which we are drawing.
Returns:
This function does not return any value.
"""
canvas.delete('al... | 5,308,434 |
def vgg16_mura_model(path):
"""Get a vgg16 model.
The model can classify bone X-rays into three categories:
wrist, shoulder and elbow.
Args:
path: A string,
if there's no model in the path,
it will download the weights automatically.
Return:
A tf.keras mode... | 5,308,435 |
def _addquotes(vistr: str) -> str:
"""Add quotes to '=attribute' attributes"""
vistr = re.subn(r'=(?!")(.*?)([\s>])', _quote, vistr)[0]
return vistr | 5,308,436 |
def application(
environ: Dict[str, Any],
start_response: 'StartResponse'
) -> Iterable[bytes]:
"""The entry point of this WSGI app."""
try:
body = "OK"
content_length = int(environ['CONTENT_LENGTH'])
payload = environ["wsgi.input"].read(content_length).decode("utf-8")
... | 5,308,437 |
def readFile(filename: str) -> List[str]:
"""
Reads a file and returns a list of the data
"""
try:
with open(filename, "r") as fp:
return fp.readlines()
except:
raise Exception(f"Failed to open {filename}") | 5,308,438 |
def chunked(iterable, n):
"""Break an iterable into lists of a given length::
>>> list(chunked([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7]]
If the length of ``iterable`` is not evenly divisible by ``n``, the last
returned list will be shorter.
This is useful for splitting up... | 5,308,439 |
def calculate_residuals(df, fit, names):
"""Calculates residuals values by comparing values in df and in fit.
Arguments:
df (pandas.DataFrame):
Holds the data to be fitted. Either concentrations vs time
or charge passed vs time depending on the situation.
fit (numpy.nda... | 5,308,440 |
def ted():
"""
When A POST request with json data is made to this uri,
Read the example from the json, predict probability and
send it with a response
"""
# Get decision score for our example that came with the request
data = flask.request.json
print(data)
X = data#["example"])
#... | 5,308,441 |
def stop():
"""
STOP
command. Ends the running of the procedure in which it appears.
Control is returned to the context in which that procedure was
invoked. The stopped procedure does not output a value.
"""
raise LogoOutput(None) | 5,308,442 |
def user_post_save_receiver(instance, created, *args, **kwargs):
"""
Handle creating the profile when a user finishes
the signup process
"""
if created:
Profile.objects.get_or_create(
user=instance
) | 5,308,443 |
def init_meeting_times():
"""
Initializes the meeting times list.
"""
flask.session['meeting_times'] = get_meeting_times(
flask.session['free_times']) | 5,308,444 |
def yaml_load(source, loader=yaml.Loader):
"""
Wrap PyYaml's loader so we can extend it to suit our needs.
Load all strings as unicode: http://stackoverflow.com/a/2967461/3609487.
"""
def construct_yaml_str(self, node):
"""Override the default string handling function to always return Unic... | 5,308,445 |
def test_private_std(example_private_table: PrivateTable):
"""check private std implementation using Age in adult dataset."""
noisy_std = example_private_table.std('Age', PrivacyBudget(10000.))
check_absolute_error(noisy_std, 13.640432553581146, 1.)
del noisy_std | 5,308,446 |
def start_new_command(session):
""" Triggers the necessary requests to see available dishes. """
session.get(url_new_order_get)
session.post(url_new_order_post)
session.post(url_start_order) | 5,308,447 |
def test_callback_handler_works_within_logging_framework():
"""Check that the callback handler can be used by Python logging
and works as expected."""
cbmock = mock.Mock()
logmsg = "Test message for callback"
log = logging.getLogger("workflows.tests.logging.callback")
log.setLevel(logging.INFO)
... | 5,308,448 |
def _item_to_instance(iterator, instance_pb):
"""Convert an instance protobuf to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type instance_pb: :class:`~google.spanner.admin.instance.v1.Instance`
:param... | 5,308,449 |
def check_sklearn_model(model, task="regression"):
"""Check the sklearn method in use."""
if task == "regression":
if not (isinstance(model, BaseEstimator) and isinstance(model, RegressorMixin)):
raise RuntimeError(
"Needs to supply an instance of a scikit-learn regression cl... | 5,308,450 |
def speedsolve(self) -> dict:
"""
Solve the cube as fast as you can and give statistics on solve.
The cube is scrambled with the default method, and will start timing
once the first turn is made, or once 15 seconds (inspection) is
reached.
Enter moves to solve the cube. Other functions... | 5,308,451 |
def get_trunc_hour_time(obstime):
"""Truncate obstime to nearest hour"""
return((int(obstime)/3600) * 3600) | 5,308,452 |
def normalize_package_name(python_package_name):
"""
Normalize Python package name to be used as Debian package name.
:param python_package_name:
The name of a Python package as found on PyPI (a string).
:returns:
The normalized name (a string).
>>> from py2deb import normalize_... | 5,308,453 |
def get_solstudio_version(conf, fc):
"""Get the compiler version"""
version_re = re.compile(r"Sun Fortran 95 *(?P<major>\d*)\.(?P<minor>\d*)", re.I).search
cmd = fc + ['-V']
out, err = fc_config.getoutput(conf,cmd,stdin=False)
if out:
match = version_re(out)
else:
match = version_re(err)
if not match:
co... | 5,308,454 |
def test_value_mutant():
"""Test ValueMutant functionality.
"""
df = plainframe.PlainFrame.from_dict({"foo:str": ["bar"]})
df_test = plainframe.PlainFrame.from_dict({"foo:str": ["foo"]})
mutant = mutants.ValueMutant("foo", 0, "foo")
mutation = mutants.Mutation("foo", 0, "foo")
assert muta... | 5,308,455 |
def resolve_all(x):
"""Recursively resolves the given object and all the internals.
Make sure there is no indirect reference within the nested object.
This procedure might be slow.
"""
while isinstance(x, PDFObjRef):
x = x.resolve()
if isinstance(x, list):
x = [ resolve_all(... | 5,308,456 |
def p_carg_statsfnexpr_over_by(p):
"""carg : statsfnexpr OVER simplefield splitbyclause"""
over = ParseTreeNode('FUNCTION', raw='over')
p[3].role = ''.join(['OVER_', p[3].role])
over.add_children([p[1].children[0], p[3]])
p[4][0].children.insert(0, over)
over.parent = p[4][0]
p[0] = p[4] | 5,308,457 |
def logout():
"""View of logout"""
logout_user()
flash('Administrator Logged out')
return redirect(url_for('main.index')) | 5,308,458 |
def create_data_language(
text, vocabulary, window_size=2, fill_strategy="zeros", verbose=False
):
"""Create a supervised dataset for the characte/-lever language model.
Parameters
----------
text : str
Some text.
vocabulary : list
Unique list of supported characters. Their corr... | 5,308,459 |
def format_datetime(value, datetime_format="medium"):
"""Converts a datetime str to a format that is understood by the db.
Args:
value: A str representing a datetime
datetime_format: A str representing the desired format of the returned
datetime, accepted values are ('full', 'medium... | 5,308,460 |
def getDialect(filename):
"""Get the dialect of the given csv file."""
with open(filename, 'rb') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(1024))
return dialect | 5,308,461 |
def sort_list(source, target):
"""
This function is used to sort the source and target list on the
basis of key found in the source and target list.
:param source:
:param target:
:return:
"""
# Check the above keys are exist in the dictionary
if len(source) > 0:
tmp_key = is_... | 5,308,462 |
def hstep(trials, params, config):
"""Wrapper of hyperparameters tuning"""
if not config["Hstep"]:
return
gp.optimize(trials, params, config) | 5,308,463 |
def seg_checkpoint_saver(config):
"""
Load segmentation checkpoint and re-save it without optimizer (memory footprint is reduced).
"""
model_builder = get_model_seg_builder(config)
model = model_builder.build_model()
compression_state = load_compression_state(config.ckpt_path)
compression_c... | 5,308,464 |
def get_audio_source(input=None, **kwargs):
"""
Create and return an AudioSource from input.
Parameters
----------
input : str, bytes, "-" or None (default)
source to read audio data from. If `str`, it should be a path to a valid
audio file. If `bytes`, it is used as raw audio data.... | 5,308,465 |
def test_histogram_score():
"""
Tests whether HistogramForColumns works for projections
"""
test_code = cleandoc("""
import pandas as pd
from sklearn.preprocessing import label_binarize, StandardScaler
from sklearn.tree import DecisionTreeClassifier
import... | 5,308,466 |
def test_merge_func_code(logging_mixin: Any, simple_test_functions: Any,
function_list_names: List[int], expected_result: List[str],
expected_argument_positions: List[List[int]]) -> None:
""" Test merging function codes for a list of functions. """
funcs = simpl... | 5,308,467 |
def commit_changes(repo: Repo, branch_name: str, path: str):
"""
Commit a changed file in a new branch
:param repo: Repository to make a commit
:param branch_name: Proposal branch
:param path: Path to a changed file
:return: None
"""
repo.git.checkout("-b", branch_name)
repo.index.a... | 5,308,468 |
def delete_prtg_device(prtg_single_device_obj):
"""
deletes the host at PRTG WITHOUT confirmation
"""
result = prtg_single_device_obj.delete(confirm=False)
return result | 5,308,469 |
def plot_time(time_li, algo_names=None, save_path='', block=False):
"""
算法耗时直方图, 时间单位是小时
Args:
time_li ([type]): [description]
algo_names ([type]): [description]
save_path (str, optional): [description]. Defaults to ''.
block (bool, optional): [description]. Defaults to Fals... | 5,308,470 |
def get_abstract_dist(dist):
"""
Returns an abstract representation of the distribution.
For now, it hacks in a way to deal with non-homogeneous Cartesian product
sample spaces.
"""
if dist.is_homogeneous():
n_variables = dist.outcome_length()
n_symbols = len(dist.alphabet[0])
... | 5,308,471 |
def write_to_sns(payload, region):
""" Publish to SNS Topic. """
SNS_CLIENT.publish(
TopicArn=f'arn:aws:sns:{region}:{CENTRAL_ACCOUNT_NUMBER}:{CENTRAL_SNS_TOPIC}',
Message=json.dumps(payload)
)
print("Published the payload to the central SNS topic successfully") | 5,308,472 |
def dice_loss(y_true, y_pred, logits=True):
"""
Dice loss
Parameters
---------------
y_true: np.ndarray
True mask
y_pred: np.ndarray
Predicted mask
logits: bool, optional
Flag for whether prediction is probability distribution or a... | 5,308,473 |
def fuse_bg_features(feats):
"""
:param feats:
:return:
"""
fused_feats = []
for feat in feats:
feat = feat.flatten(1)
feat = feat.mean(dim=0)
fused_feats.append(feat)
return fused_feats | 5,308,474 |
def set_preset_mode(hass, preset_mode, entity_id=None):
"""Set new preset mode."""
data = {
ATTR_PRESET_MODE: preset_mode
}
if entity_id:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_SET_PRESET_MODE, data) | 5,308,475 |
def welcome():
"""List all available api routes."""
return (f"Welcome to the SQL-Alchemy APP API!<br/>"
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/[start_date format:yyyy-mm-dd]<br/>"
f"/... | 5,308,476 |
def interact(res, val, min_val, max_val):
"""
Interact with user
"""
if res == ">=":
if(val >= max_val):
return val, min_val, max_val, True
min_val = val
val = ceil((val + max_val) / 2)
elif res == "<":
if(val < min_val):
return val, min_val, m... | 5,308,477 |
def staff_of_group(group_id: int) -> list:
"""
Return collection of students in group
:param group_id, required - group' ID.
"""
return get("staffOfGroup", groupOid=group_id) | 5,308,478 |
def url_join(*args):
"""Join combine URL parts to get the full endpoint address."""
return '/'.join(arg.strip('/') for arg in args) | 5,308,479 |
def run_main(params):
"""Function to run multiple iterations for testing
Args:
params: dictionary of parameter values
Returns:
the field data
"""
return pipe(
dict(e11=0.0, e12=0.0, e22=0.0, eta=None, step_counter=0),
iterate_(one_iter(params), params["iterations"]),
... | 5,308,480 |
def test_S1PV1(file_path="OnePortTouchstoneTestFile.s1p"):
"""Tests the s1pv1 class"""
os.chdir(TESTS_DIRECTORY)
new_table=S1PV1(file_path)
print(new_table)
print_s1p_attributes(new_table=new_table)
new_table.change_data_format(new_format='DB')
print_s1p_attributes(new_table=new_table)
n... | 5,308,481 |
def filter_word_ids_with_non_zero_probability(word_ids, probas, pad_id=None):
"""
Filter out entries of word_ids that have exactly zero probability or are
mapped to pad positions (if pad_id is not None).
Args:
word_ids (torch.LongTensor): tensor with word ids.
Shape of (batch_size, ... | 5,308,482 |
def transcribe(fpath, appid, api_key, api_secret):
"""
科大讯飞ASR
"""
global wsParam, gResult
gResult = ''
wsParam = Ws_Param(appid, api_key, APISecret=api_secret, AudioFile=fpath)
websocket.enableTrace(False)
wsUrl = wsParam.create_url()
ws = websocket.WebSocketApp(wsUrl, on_message=on... | 5,308,483 |
def profile(request, username):
"""
Simple view of user profile.
Template: people/profile.html
Context:
p_user - user to display profile of
"""
user = get_object_or_404(User, username=username)
return render_to_response('people/profile.html', {'p_user':user},
... | 5,308,484 |
def install_with_constraints(session: Session, *args: Any, **kwargs: Any) -> None:
"""Wrapper for nox.Session installation.
Shoutout to HyperModern python for this helper
https://cjolowicz.github.io/posts/hypermodern-python-03-linting/
"""
with tempfile.NamedTemporaryFile() as requirements:
... | 5,308,485 |
def p_operation(p):
"""operation : '{' operation_chain '}'
| simple_operation"""
if len(p) > 2:
p[0] = p[2]
else:
p[0] = p[1] | 5,308,486 |
def generate_qutiprc(rc_file="qutiprc"):
"""
Generate a blank qutiprc file.
"""
# Check for write access to home dir
qutip_rc_file = _full_path(rc_file)
qutip_conf_dir = os.path.dirname(qutip_rc_file)
os.makedirs(qutip_conf_dir, exist_ok=True)
if os.path.isfile(qutip_rc_file):
t... | 5,308,487 |
def accuracy_at_stg_change_trials(df, subj_unq, prev_w=10, nxt_w=10, conv_w=10):
"""
The function returns the mean and standard deviation of the changes
from a stage to another.
Parameters
----------
df : dataframe
dataframe containing data.
subj_unq : numpy.ndarray
array of... | 5,308,488 |
def quoteattr(data, entities={}):
"""Escape and quote an attribute value.
Escape &, <, and > in a string of data, then quote it for use as
an attribute value. The \" character will be escaped as well, if
necessary.
You can escape other strings of data by passing a dictionary as
the optional e... | 5,308,489 |
def test_unreachable_pair():
"""Tests for an unreachable pair of nodes."""
G = DiGraph([(0, 1), (0, 2), (1, 2)])
assert not is_reachable(G, 1, 0) | 5,308,490 |
def makedirs_with_mtime(dest, mtime):
"""
Sets the mtime of all created dirs to 'mtime'
and keeps the mtime of the parent of the top created dir
unchanged.
"""
dirs = []
p = join('.', dest)
while True:
if exists(p): break
dirs.append(p)
p = dirname(p)
if len(dirs) == 0: return #skip mtime... | 5,308,491 |
def get_base_classes(node, keep=keep_all):
"""
node is a class
yields the nodes to the public base class.
"""
for c in node.get_children():
if c.kind == CursorKind.CXX_BASE_SPECIFIER and keep(c):
yield jump_to_declaration(c.type) | 5,308,492 |
def is_pairwise_disjoint(sets):
"""
This function will determine if a collection of sets is pairwise disjoint.
Args:
sets (List[set]): A collection of sets
"""
all_objects = set()
for collection in sets:
for x in collection:
if x in all_objects:
retur... | 5,308,493 |
def get_incident_recency(prev_incident: submit_schema.Form, current_incident: submit_schema.Form, timeframe: int):
"""
Returns a value between min_value and 1 depending on the previous incident type's recency scaled by the timeframe.
"""
min_value = 0.6
prev_incident.occurrence_time = prev_incident.... | 5,308,494 |
def test_sorted_list():
"""A sorted list will return unchanged"""
lst = ['A', 'B', 'C', 'D', 'E']
expected = ['A', 'B', 'C', 'D', 'E']
actual = quicksort(lst)
assert actual == expected | 5,308,495 |
def _select_given_names(work_dir,infile,translist,remove=True):
""" select names by list """
cdo=Cdo()
tmplist=[]
if not (os.path.exists(work_dir + os.sep + "temp")):
os.makedirs(work_dir + os.sep + "temp")
for element in translist:
tmpfile=work_dir + os.sep + "temp" + os.sep ... | 5,308,496 |
def key_of(dic, value):
""" Returns the key corresponding to the specified value in the
supplied dict. """
if isinstance(value, np.ndarray):
return [k for k, v in dic.items() if all(v == value)][0]
return [k for k, v in dic.items() if v == value][0] | 5,308,497 |
def test_db_update_one_doc(client):
"""
tests updating nonexistent doc,
encodes filter and updated doc with
bson.
"""
filt = {'node_ip': '-1.-1.-1.-1'}
update = {'node_ip': '-1.-1.-1.-1', 'new_field': 101}
# non-existent document
filt = json.dumps(filt)
uri = '/v1/storage/update... | 5,308,498 |
def project_has_hook_attr_value(project, hook, attr, value):
"""Finds out if project's hook has attribute of given value.
:arg project: The project to inspect
:type project: pagure.lib.model.Project
:arg hook: Name of the hook to inspect
:type hook: str
:arg attr: Name of hook attribute to insp... | 5,308,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.