content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_quickstart_removes_git_files():
"""Quickstart removes git files after cloning
Check for the existence of any file that starts with `.git`.
This will report the existent files.
"""
import os
runner = CliRunner()
with runner.isolated_filesystem():
git_files = []
runn... | 5,351,400 |
def pre_process_string_data(item: dict):
"""
remove extra whitespaces, linebreaks, quotes from strings
:param item: dictionary with data for analysis
:return: cleaned item
"""
try:
result_item = {key: item[key] for key in KEYS + ['_id']}
for prop in result_item:
... | 5,351,401 |
def check_configs(config_wildcards: Sequence = ("config.*yaml",)):
"""
- Check if config files exist
- Offer to use the config files that match the wildcards
- For config.yaml, check its contents against the defaults to make sure nothing is missing/wrong
:param config_wildcards:
:return:
""... | 5,351,402 |
def log_ks_statistic(y_true, y_pred, experiment=None, channel_name='metric_charts', prefix=''):
"""Creates and logs KS statistics curve and KS statistics score to Neptune.
Kolmogorov-Smirnov statistics chart can be calculated for true positive rates (TPR) and true negative rates (TNR)
for each threshold an... | 5,351,403 |
def load_profile_update_output(contents, filename):
"""
Decode the uploaded load profile
Returns TypeError if not a csv file
Saves dataframe to txt file within create_load_txt function
"""
if contents is not None:
#GLOBAL_CONTENTS = contents
# decode output from file upload
... | 5,351,404 |
def create_snapshot(parent,src,dst):
"""
:param parent:
:param src:
:param dst:
:return:
"""
import btrfsutil
subv_src=os.path.join(parent, src)
subv_dst=os.path.join(parent, dst)
btrfsutil.create_snapshot(subv_src,subv_dst)
return | 5,351,405 |
def remove_cmds_from_title(title):
"""
Função que remove os comandos colocados nos títulos
apenas por uma questão de objetividade no título
"""
arr = title.split()
output = " ".join(list(filter(lambda x: x[0] != "!", arr)))
return output | 5,351,406 |
async def test_sign_in_failed(hass, config_entry, controller, caplog):
"""Test sign-in service logs error when not connected."""
await setup_component(hass, config_entry)
controller.sign_in.side_effect = CommandFailedError("", "Invalid credentials", 6)
await hass.services.async_call(
DOMAIN,
... | 5,351,407 |
def test_annot_io():
"""Test I/O from and to *.annot files"""
# copy necessary files from fsaverage to tempdir
tempdir = _TempDir()
subject = 'fsaverage'
label_src = os.path.join(subjects_dir, 'fsaverage', 'label')
surf_src = os.path.join(subjects_dir, 'fsaverage', 'surf')
label_dir = os.pat... | 5,351,408 |
def load_config(file_path):
"""Loads the config file into a config-namedtuple
Parameters:
input (pathlib.Path):
takes a Path object for the config file. It does not correct any
relative path issues.
Returns:
(namedtuple -- config):
Contains t... | 5,351,409 |
def main():
""" A simple example """
import torchvision.transforms as transforms
root = '../data/'
split = 'train'
dataset = Talk2Car(root, split, './utils/vocabulary.txt', transforms.ToTensor())
print('=> Load a sample')
sample = dataset.__getitem__(15)
img = np.transpose(sample['i... | 5,351,410 |
def describe_maintenance_windows(Filters=None, MaxResults=None, NextToken=None):
"""
Retrieves the maintenance windows in an AWS account.
See also: AWS API Documentation
Exceptions
:example: response = client.describe_maintenance_windows(
Filters=[
{
'Ke... | 5,351,411 |
def parse_version_number(raw_version_number):
# type: (str) -> Tuple[int, int, int]
"""
Parse a valid "INT.INT.INT" string, or raise an
Exception. Exceptions are handled by caller and
mean invalid version number.
"""
converted_version_number = [int(part) for part in raw_version_number.split(... | 5,351,412 |
def get_error_directory_does_not_exists(dir_kind):
"""dir kind = [dir, file ,url]"""
return f"Error: Directory with {dir_kind} does not exist:" | 5,351,413 |
def field_interact(compute, style=None, title="", figsize=(1.5, 1), **kwargs):
"""Field computed on-the-fly controlled by interactive sliders."""
kw = lambda k: pop_style_with_fallback(k, style, kwargs)
title = dash(kw("title"), title)
ctrls = compute.controls.copy() # gets modified
output ... | 5,351,414 |
def var_text(vname, iotype, variable):
"""
Extract info from variable for vname of iotype
and return info as HTML string.
"""
if iotype == 'read':
txt = '<p><i>Input Variable Name:</i> <b>{}</b>'.format(vname)
if 'required' in variable:
txt += '<br><b><i>Required Input Va... | 5,351,415 |
def test_logout_view_request_timeout(hass, cloud_client):
"""Test timeout while logging out."""
cloud = hass.data['cloud'] = MagicMock()
cloud.logout.side_effect = asyncio.TimeoutError
req = yield from cloud_client.post('/api/cloud/logout')
assert req.status == 502 | 5,351,416 |
def line_search_reset(binary_img, left_lane, right_line):
"""
#---------------------
# After applying calibration, thresholding, and a perspective transform to a road image,
# I have a binary image where the lane lines stand out clearly.
# However, I still need to decide explicitly which pixels ar... | 5,351,417 |
def get_primary_language(current_site=None):
"""Fetch the first language of the current site settings."""
current_site = current_site or Site.objects.get_current()
return get_languages()[current_site.id][0]['code'] | 5,351,418 |
def test_atoms_read(batch=50):
"""test on randomly sampled entries"""
shuffle(raw_entries)
for e in raw_entries[:batch]:
print(e["aurl"])
entry = Entry(**e)
# Read the CONTCAR.relax, which should always present
atoms = entry.atoms()
assert atoms is not None | 5,351,419 |
def plot_Xy(X_in, y_in, title="2D Xs with y color coding",
s=25):
"""Plot the Xs in x0,x1 space and color-code by the ys.
"""
# set figure limits
xmin = -1.0
xmax = 1.0
ymin = -1.0
ymax = 1.0
plt.title(title)
axes = plt.gca()
axes.set_xlim([xmin, xmax])
axes.set_... | 5,351,420 |
def download_s3_file(bucket_name, file_path, file_name):
"""
download s3 file, if bucket is not exist, create it first.
"""
bucket = s3.Bucket(bucket_name)
try:
s3.meta.client.head_bucket(Bucket=bucket_name)
except ClientError:
print("The log state file bucket "+ bucket_name +"... | 5,351,421 |
def get_Theta_ref_cnd_H(Theta_sur_f_hex_H):
"""(23)
Args:
Theta_sur_f_hex_H: 暖房時の室内機熱交換器の表面温度(℃)
Returns:
暖房時の冷媒の凝縮温度(℃)
"""
Theta_ref_cnd_H = Theta_sur_f_hex_H
if Theta_ref_cnd_H > 65:
Theta_ref_cnd_H = 65
return Theta_ref_cnd_H | 5,351,422 |
def test_bad_refund_amount(amount):
""" Test that an invalid refund amount raises an exception"""
enrollment = BootcampRunEnrollmentFactory.create()
with pytest.raises(EcommerceException) as exc:
create_refund_order(
user=enrollment.user, bootcamp_run=enrollment.bootcamp_run, amount=amou... | 5,351,423 |
def get_tool_info(arduino_info, tool_name):
"""."""
tool_info = {}
has_tool = False
sel_pkg = arduino_info['selected'].get('package')
inst_pkgs_info = arduino_info.get('installed_packages', {})
inst_pkg_names = inst_pkgs_info.get('names', [])
pkg_info = get_package_info(inst_pkgs_info, sel_p... | 5,351,424 |
def hpat_pandas_series_shape(self):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.Series.shape
Examples
--------
.. literalinclude:: ../../../examples/series/series_shape.py
:language: python
:lines: 27-
... | 5,351,425 |
def WarnAndCopyFlag(old_name, new_name):
"""Copy a value from an old flag to a new one, warning the user.
Args:
old_name: old name of flag.
new_name: new name of flag.
"""
if FLAGS[old_name].present:
logging.warning(
'Flag --%s is deprecated and will be removed. Please '
'switch to... | 5,351,426 |
def download_apps(artifacts_url, appstack):
"""
Downloads applications artifacts from specified source. Url should include '{name}'
parameter like here: http://artifacts.com/download/{name}
"""
if not validators.url(artifacts_url):
_log.error('Value %s is not valid Url.', artifacts_url)
... | 5,351,427 |
async def port_utilization_range(
port_id: str, direction: str, limit: int, start: str, granularity: int, end=None,
):
"""Get port utilization by date range."""
async with Influx("telegraf", granularity=granularity) as db:
q = (
db.SELECT(f"derivative(max(bytes{direction.title()}), 1s) *... | 5,351,428 |
def test_md018_bad_multiple_within_paragraph_separated_collapsed_image_multi():
"""
Test to make sure we get the expected behavior after scanning a good file from the
test/resources/rules/md018 directory that has multiple possible atx headings within
a single paragraph.
"""
# Arrange
scanne... | 5,351,429 |
def composer_includes(context):
"""
Include the composer JS and CSS files in a page if the user has permission.
"""
if context.get('can_compose_permission', False):
url = settings.STATIC_URL
url += '' if url[-1] == '/' else '/'
js = '<script type="text/javascript" src="%sjs/compo... | 5,351,430 |
def craft(crafter, recipe_name, *inputs, raise_exception=False, **kwargs):
"""
Access function. Craft a given recipe from a source recipe module. A
recipe module is a Python module containing recipe classes. Note that this
requires `settings.CRAFT_RECIPE_MODULES` to be added to a list of one or
more... | 5,351,431 |
def load_data(
data,
*,
keys: Iterable[Union[str, int]] = (0,),
unique_keys: bool = False,
multiple_values: bool = False,
unique_values: bool = False,
**kwargs,
) -> Union[List[Any], Dict[Any, Union[Any, List[Any]]]]:
"""Load data.
If no values are provided, then return a list from ... | 5,351,432 |
async def test_async_state_transit():
"""Test async state transit contextmanager."""
state = AsyncState()
state.set(None)
with state.transit(initial=1, success=2, fail=3):
assert state.get() == 1
assert state.get() == 2
state.set(None)
with suppress(ValueError):
with state... | 5,351,433 |
def get_avg_wind_speed(data):
"""this function gets the average wind speeds for each point in the fetched data"""
wind_speed_history = []
for point in data:
this_point_wind_speed = []
for year_reading in point:
hourly = []
for hour in year_reading['weather'][0]['hourl... | 5,351,434 |
def publish_collection(collection_path, api, wait, timeout):
"""Publish an Ansible collection tarball into an Ansible Galaxy server.
:param collection_path: The path to the collection tarball to publish.
:param api: A GalaxyAPI to publish the collection to.
:param wait: Whether to wait until the import... | 5,351,435 |
def get_uris_of_class(repository: str, endpoint: str, sparql_file: str, class_name: str, endpoint_type: str,
limit: int = 1000) -> List[URIRef]:
"""
Returns the list of uris of type class_name
:param repository: The repository containing the RDF data
:param endpoint: The SPARQL end... | 5,351,436 |
def nspath_eval(xpath: str) -> str:
"""
Return an etree friendly xpath based expanding namespace
into namespace URIs
:param xpath: xpath string with namespace prefixes
:returns: etree friendly xpath
"""
out = []
for chunks in xpath.split('/'):
namespace, element = chunks.split... | 5,351,437 |
def basic_streamalert_config():
"""Generate basic StreamAlert configuration dictionary."""
return {
'global': {
'account': {
'aws_account_id': '123456789123',
'kms_key_alias': 'stream_alert_secrets',
'prefix': 'unit-testing',
'r... | 5,351,438 |
def _read_elastic_moduli(outfilename):
"""
Read elastic modulus matrix from a completed GULP job
:param outfilename: Path of the stdout from the GULP job
:type outfilename: str
:returns: 6x6 Elastic modulus matrix in GPa
"""
outfile = open(outfilename,'r')
moduli_array = []
while Tr... | 5,351,439 |
def test_process_tags_directive_and(tmpdir):
"""Test AND
"""
source_dir = tmpdir.mkdir('source')
source_dir.mkdir('ns1')
target_dir = tmpdir.mkdir('target')
create_markdown_file(source_dir.join('ns1', 'file1.md'),
{'title': 'Page One',
'tags':... | 5,351,440 |
def test_update_db(client):
"""
Test that database status correctly reports that the schema in the DB and
in the code match.
"""
response = client.get('/status/db')
print(response.data)
expected = 'DB schema at %s, code schema at %s, no action taken' % (SCHEMA_VERSION, SCHEMA_VERSION)
assert response.da... | 5,351,441 |
def predict_koopman(lam, w, v, x0, ncp, g, h, u=None):
"""Predict the future dynamics of the system given an initial value `x0`. Result is returned
as a matrix where rows correspond to states and columns to time.
Args:
lam (tf.Tensor): Koopman eigenvalues.
w (tf.Tensor): Left eigenvectors.
... | 5,351,442 |
def test_sparse_balance(): # pylint: disable=too-many-locals
"""Test sparse balance"""
for n_features in range(1, 4):
no_of_samples = 100
config_no_penalty = (
LimeConfig()
.withPerturbationContext(
PerturbationContext(jrandom, DEFAULT_NO_OF_PERTURBATIONS... | 5,351,443 |
def scree_plot(analysis_actors_dict, dir_path, pcs_on_scree_plot=50, variance_ratio_line=0.75):
"""
Creates a plot with the scree plots for each ligand and saves it on the specified ``dir_path``. With blue color is
class 1 and with orange color class 2.
Args:
analysis_actors_dict: ``{ "Agonists... | 5,351,444 |
def test_raise_cmp_2():
"""
Show that not raising has no effect on the passing of results to the last action.
"""
add1 = Add1()
result = list_x.UntilFailure(
actions=[add1, add1, list_x.RaiseCmp(cmp=0, value=1), add1, add1]
).execute()
assert result.result == 4 | 5,351,445 |
def handle_registration():
""" Show the registration form or handles the registration
of a user, if the email or username is taken, take them back to the
registration form
- Upon successful login, take to the homepage
"""
form = RegisterForm()
email = form.email.data
userna... | 5,351,446 |
def test_Lam_Hole_51_0N2(machine):
"""Test machine plot hole 51 with no magnet_1
"""
machine.rotor.hole[0].magnet_0 = Magnet()
machine.rotor.hole[0].magnet_1 = None
machine.rotor.hole[0].magnet_2 = Magnet()
machine.rotor.plot()
fig = plt.gcf()
fig.savefig(join(save_path, "test_Lam_Hole_s... | 5,351,447 |
def conll_to_brat(file_name: str, output_directory: str, format: str) -> None:
"""
Converts the content of the CoNLL file file_name into Brat files containing
each 5 sentences. The CoNLL format here is the CoNLL05 with columns for SRL
data. Writes also the
Parameters:
fi... | 5,351,448 |
def func_xy_args_kwargs_annotate(
x: "0", y, *args: "2", **kwargs: "4"
) -> typing.Tuple:
"""func.
Parameters
----------
x, y: float
args: tuple
kwargs: dict
Returns
-------
x, y: float
args: tuple
kwargs: dict
"""
return x, y, None, None, args, None, None, kwa... | 5,351,449 |
def mp_nerf_torch(a, b, c, l, theta, chi):
""" Custom Natural extension of Reference Frame.
Inputs:
* a: (batch, 3) or (3,). point(s) of the plane, not connected to d
* b: (batch, 3) or (3,). point(s) of the plane, not connected to d
* c: (batch, 3) or (3,). point(s) of the pla... | 5,351,450 |
def makemarkers(nb):
""" Give a list of cycling markers. See http://matplotlib.org/api/markers_api.html
.. note:: This what I consider the *optimal* sequence of markers, they are clearly differentiable one from another and all are pretty.
Examples:
>>> makemarkers(7)
['o', 'D', 'v', 'p', '<', 's'... | 5,351,451 |
def test_grad_diffoutdim(eval_data_loader, model, num_classes,
output_dir='pred', has_gt=True, save_vis=False, downsize_scale=1, args=None):
"""
Evaluates the effect of increasing output dimension on the norm of the gradient.
Monte Carlo sampling will be used and the result would be... | 5,351,452 |
def org_facility_onvalidation(form):
"""
Default the name to the Street Address
"""
form_vars = form.vars
name = form_vars.get("name", None)
if name:
return
address = form_vars.get("address", None)
if address:
form_vars.name = address
else:
# We need a de... | 5,351,453 |
def uselist(*, schema: types.Schema, schemas: types.Schemas) -> typing.Optional[bool]:
"""
Retrieve the x-uselist of the schema.
Raises MalformedSchemaError if the x-uselist value is not a boolean.
Args:
schema: The schema to get x-uselist from.
schemas: The schemas for $ref lookup.
... | 5,351,454 |
def getIPRules():
"""
Fetches a json representation of the Iptables rules on the server
GET: json object with the all the iptables rules on the system
"""
return jsonify({"result" : True, "rules" : hl.getIptablesRules()}) | 5,351,455 |
def process_indices(symbols, start_date, end_date, model_dir):
"""
:param symbols: list of index symbols to fetch, predict and plot
:param start_date: earliest date to fetch
:param end_date: latest date to fetch
:param model_dir: location to save model
:return:
"""
data_reader = StooqDat... | 5,351,456 |
def _get_only_relevant_data(video_data):
"""
Method to build ES document with only the relevant information
"""
return {
"kind": video_data["kind"],
"id": video_data["id"],
"published_at": video_data["snippet"]["publishedAt"],
"title": video_data["snippet"]["title"],
... | 5,351,457 |
def get_mask(img):
"""
Convert an image to a mask array.
"""
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
return mask | 5,351,458 |
def b32encode(hex_values, pad_left=True):
"""
Base32 encoder algorithm for Nano.
Transforms the given hex_value into a base-32 representation. The allowed letters are:
"13456789abcdefghijkmnopqrstuwxyz"
:param hex_values:
Hexadecimal values (string) or byte array containing the dat... | 5,351,459 |
def get_mfp(g, gv):
"""Calculate mean free path from inverse lifetime and group velocity."""
g = np.where(g > 0, g, -1)
gv_norm = np.sqrt((gv**2).sum(axis=2))
mean_freepath = np.where(g > 0, gv_norm / (2 * 2 * np.pi * g), 0)
return mean_freepath | 5,351,460 |
def collate_participant_tables(subject_ids, base_dir):
"""
Generate a pandas dataframe across all subjects
Parameters
----------
subject_ids: list
a list of subject identifiers in
base_dir: str
path to a mindboggle output base directory (mindboggled)
Returns
-------
... | 5,351,461 |
def convert_to_format(file: str, output: str, output_format: str):
"""
Converts a HOCON file to another format
Parameters
----------
file : str
hocon file to convert
output : str
output file to produce
output_format : str
format of the output file
Returns
--... | 5,351,462 |
def test_stop(transfer, ts):
"""Intersect at end"""
transfer(0, 1, 100)
transfer(0, 2, 100)
transfer(0, 3, 42)
transfer(3, 2, 19)
transfer(3, 2, 22)
transfer(3, 2, 1)
ts(4) | 5,351,463 |
def summarizeByDate(dict1):
"""
Takes dictionary of RSS Items per media outlet and returns a Seaborn
swarmplot/violinplot grouped by dates
Parameters
----------
dict1 : dict
DESCRIPTION key values of Feed Names and FeedParserDicts
Returns
-------
swarm : Swarmplot
... | 5,351,464 |
def find_prime_root(l, blum=True, n=1):
"""Find smallest prime of bit length l satisfying given constraints.
Default is to return Blum primes (primes p with p % 4 == 3).
Also, a primitive root w is returned of prime order at least n.
"""
if l == 1:
assert not blum
assert n == 1
... | 5,351,465 |
async def test_agreement_already_set_up(
hass, aiohttp_client, aioclient_mock, current_request
):
"""Test showing display form again if display already exists."""
await setup_component(hass)
MockConfigEntry(domain=DOMAIN, unique_id=123).add_to_hass(hass)
result = await hass.config_entries.flow.async... | 5,351,466 |
def set_parameters(_configs, new=False):
"""
Sets configuration parameters
Parameters
----------
_configs :
Dictionary containing configuration options from the config file (config.json)
new : bool
Do you want to start from a new file?
Returns
-------
_configs :
... | 5,351,467 |
def _commandDisown(args):
"""
Disown a User
:param args: System Arguments Passed
"""
vaultFile = args.vault_file
privateKeyFile = args.private_key_file
publicKeyFile = args.public_key_file
_debugMessage('Bootstrapping Identity, this will take some time ...')
identity = Identity(priv... | 5,351,468 |
def create_all_files(sizes):
"""Create all files.
Parameters
----------
sizes : a list of lists of the form [(filesize,[block_size_1, block_size_2,...])]
Returns
-------
List of file names, a dictionary of measurements
"""
Stats=[]; files=[]
try:
for file_size,block_si... | 5,351,469 |
def read_requirements(filename='requirements.txt'):
"""Reads the list of requirements from given file.
:param filename: Filename to read the requirements from.
Uses ``'requirements.txt'`` by default.
:return: Requirements as list of strings
"""
# allow for some leeway with the... | 5,351,470 |
def vgg16(mask_init='1s', mask_scale=1e-2, threshold_fn='binarizer', **kwargs):
"""VGG 16-layer model (configuration "D")."""
model = VGG(make_layers(cfg['D'], mask_init, mask_scale, threshold_fn),
mask_init, mask_scale, threshold_fn, **kwargs)
return model | 5,351,471 |
def sort(X):
"""
Return sorted elements of :param:`X` and array of corresponding
sorted indices.
:param X: Target vector.
:type X: :class:`scipy.sparse` of format csr, csc, coo, bsr, dok, lil,
dia or :class:`numpy.matrix`
"""
assert 1 in X.shape, "X should be vector."
X = X.flatten(... | 5,351,472 |
def get_query(sf, query_text, verbose=True):
"""
Returns a list of lists based on a SOQL query with the fields as
the header column in the first list/row
"""
# execute query for up to 2,000 records
gc = sf.query(query_text)
records = gc['records']
if verbose:
print('Reading fro... | 5,351,473 |
def trf(args):
"""
%prog trf outdir
Run TRF on FASTA files.
"""
from jcvi.apps.base import iglob
cparams = "1 1 2 80 5 200 2000"
p = OptionParser(trf.__doc__)
p.add_option("--mismatch", default=31, type="int",
help="Mismatch and gap penalty")
p.add_option("--minsco... | 5,351,474 |
def strip_blank(contents):
"""
strip the redundant blank in file contents.
"""
with io.StringIO(contents) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",", quotechar='"')
rows = []
for row in csvreader:
rows.append(",".join(['"{}"'.format(x.strip()) for x in... | 5,351,475 |
def generate_id() -> str:
"""Generates an uuid v4.
:return: Hexadecimal string representation of the uuid.
"""
return uuid4().hex | 5,351,476 |
def perms_of_length(n, length):
"""Return all permutations in :math:`S_n` of the given length (i.e., with the specified number of inversion).
This uses the algorithm in `<http://webhome.cs.uvic.ca/~ruskey/Publications/Inversion/InversionCAT.pdf>`_.
:param n: specifies the permutation group :math:`S_n`.
... | 5,351,477 |
def test_rename_model_name():
"""Assert that an error is raised when name is a model's acronym."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
with pytest.raises(ValueError, match=r".*model's acronym.*"):
atom.branch.rename("Lda") | 5,351,478 |
def compare_sequence():
"""
This function is a common test used by all insert row functions. This
simply compares the contents of the original and resulting file.
"""
original = openpyxl.load_workbook('test_multiplication_table.xlsx')
original_sheet = original.active
result = openpyxl.load_w... | 5,351,479 |
def rank_by_entropy(pq, kl=True):
""" evaluate kl divergence, wasserstein distance
wasserstein: http://pythonhosted.org/pyriemann/_modules/pyriemann/utils/distance.html
"""
# to avoid Inf cases
pq = pq + 0.0000001
pq = pq/pq.sum(axis=0)
if kl: # entropy actually can calculate KL diverge... | 5,351,480 |
def test_dynamic_partitions_multiple_indices(store):
"""
Do not specify partitions in metadata, but read them dynamically from store
"""
suffix = "suffix"
dataset_uuid = "uuid+namespace-attribute12_underscored"
partition0_core = create_partition_key(
dataset_uuid,
"core",
... | 5,351,481 |
def generate_graph_properties(networks):
"""
This function constructs lists with centrality rankings of nodes in multiple networks.
Instead of using the absolute degree or betweenness centrality, this takes metric bias into account.
If the graph is not connected, the values are calculated for the large... | 5,351,482 |
def anova_old(
expression, gene_id, photoperiod_set, strain_set, time_point_set, num_replicates
):
"""One-way analysis of variance (ANOVA) using F-test."""
num_groups = len(photoperiod_set) * len(strain_set) * len(time_point_set)
group_size = num_replicates
total_expression = 0
# First scan: cal... | 5,351,483 |
def _make_ext_reader(ext_bits, ext_mask):
"""Helper for Stroke and ControlPoint parsing.
Returns:
- function reader(file) -> list<extension values>
- function writer(file, values)
- dict mapping extension_name -> extension_index
"""
# Make struct packing strings from the extension details
infos = []
... | 5,351,484 |
def resolve_covariant(n_total, covariant=None):
"""Resolves a covariant in the following cases:
- If a covariant is not provided a diagonal matrix of 1s is generated, and symmetry is checked via a comparison with the datasets transpose
- If a covariant is provided, the symmetry is checked
args:... | 5,351,485 |
def create_generic_constant(
type_spec: Optional[computation_types.Type],
scalar_value: Union[int,
float]) -> building_blocks.ComputationBuildingBlock:
"""Creates constant for a combination of federated, tuple and tensor types.
Args:
type_spec: A `computation_types.Type` contain... | 5,351,486 |
def all_same(lst: list) -> bool:
"""test if all list entries are the same"""
return lst[1:] == lst[:-1] | 5,351,487 |
def binary_find(N, x, array):
"""
Binary search
:param N: size of the array
:param x: value
:param array: array
:return: position where it is found. -1 if it is not found
"""
lower = 0
upper = N
while (lower + 1) < upper:
mid = int((lower + upper) / 2)
if x < arr... | 5,351,488 |
def _add_data_entity(app_context, entity_type, data):
"""Insert new entity into a given namespace."""
old_namespace = namespace_manager.get_namespace()
try:
namespace_manager.set_namespace(app_context.get_namespace_name())
new_object = entity_type()
new_object.data = data
ne... | 5,351,489 |
def scalarmat(*q):
"""multiplies every object in q with each object in q. Should return a unity matrix for an orthonormal system"""
ret=[]
for a in q:
toa=[]
for b in q:
toa.append(a*b)
ret.append(toa)
return ret | 5,351,490 |
def frames_per_second():
""" Return the estimated frames per second
Returns the current estimate for frames-per-second (FPS).
FPS is estimated by measured the amount of time that has elapsed since
this function was previously called. The FPS estimate is low-pass filtered
to reduce noise.
This ... | 5,351,491 |
def _absolute_flat_glob(pattern):
"""
Glob function for a pattern that do not contain wildcards.
:pattern: File or directory path
:return: Iterator that yields at most one valid file or dir name
"""
dirname, basename = os.path.split(pattern)
if basename:
if os.path.exists(pattern)... | 5,351,492 |
def modularity(partition, graph, weight='weight'):
"""Compute the modularity of a partition of a graph
Parameters
----------
partition : dict
the partition of the nodes, i.e a dictionary where keys are their nodes
and values the communities
graph : networkx.Graph
the networkx g... | 5,351,493 |
def config_lst_bin_files(data_files, dlst=None, atol=1e-10, lst_start=0.0, fixed_lst_start=False, verbose=True,
ntimes_per_file=60):
"""
Configure lst grid, starting LST and output files given input data files and LSTbin params.
Parameters
----------
data_files : type=list ... | 5,351,494 |
def list_members(t):
"""
List members
"""
owner, slug = get_slug()
# Get members
rel = {}
next_cursor = -1
while next_cursor != 0:
m = t.lists.members(
slug=slug,
owner_screen_name=owner,
cursor=next_cursor,
include_entities=False)
... | 5,351,495 |
def get_str_arr_info(val):
""" Find type of string in array val, and also the min and max length. Return
None if val does not contain strings."""
fval = np.array(val).flatten()
num_el = len(fval)
max_length = 0
total_length = 0
for sval in fval:
len_sval = len(sval)
if len_s... | 5,351,496 |
def generate_priors(image_size=300,
layer_sizes=None,
pool_ratios=None,
min_sizes=None,
max_sizes=None,
aspect_ratios=None):
# TODO update feature maps, min_sizes, max_sizes for inputs size 5xx
"""
This metho... | 5,351,497 |
def delete_properties_file(id):
""" Deletes a property file by its id
Parameters:
id (): a special number identifying the material system, as an int.
Returns: None
"""
os.remove("property_calculations/properties_"+str(id)+".txt")
return | 5,351,498 |
def listFiles(dir):
"""
Walks the path and subdirectories to return a list of files.
Parameters
----------
dir : str
the top directory to search
subdirectories are also searched
Returns
-------
listname: list
a list of files in dir and subdirectories
No... | 5,351,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.