content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def parse_generic(data, key):
"""
Returns a list of (potentially disabled) choices from a dictionary.
"""
choices = []
for k, v in sorted(data[key].iteritems(), key=lambda item: item[1]):
choices.append([v, k])
return choices | 90d2f2188d5cca7adb53eebca80a80f2c46b04a7 | 72,100 |
def get_ct_solution_array(mechanism, library):
"""Obtain a Cantera SolutionArray object representative of an arbitrary library
Parameters
----------
mechanism: spitfire.chemistry.mechanism ChemicalMechanismSpec instance
the mechanism
library: a spitfire.chemistry.library... | 950b2c88c031ad26534dda21ba7c965601892d0e | 72,101 |
import glob
def _aux_fft_m(filename, t_step=None, t_ini=None, t_end=None, subtract_values='first', vertex_indices=None):
"""
Helper function to compute the Fourier transform of magnetisation
data, which is either read from a single .ndt file (for spatially
averaged magnetisation) or from a series of .... | 8464a4d95b5555758bbe7e1ffb258c90b93c3412 | 72,102 |
def read_layer(path, layer=0, index=None):
"""Create a vector layer from the specified path.
Will try to read using ogr.OpenShared.
Parameters
----------
path_or_str: string
path or json string
layer: integer
The layer number to use. Use ogrinfo to see
the available la... | f42903a780a4d37a9aaa9e0d3e1fe4a57a3e7272 | 72,103 |
import copy
def abut (source,*args):
"""
Like the |Stat abut command. It concatenates two lists side-by-side
and returns the result. '2D' lists are also accomodated for either argument
(source or addon). CAUTION: If one list is shorter, it will be repeated
until it is as long as the longest list. If this beh... | f8a2329b1f70e1483a2975244bb237ff3a02d437 | 72,104 |
def template(*args, **kwargs):
"""template function that injects context into each call"""
rendered = jinja2_template(
*args,
**kwargs
| dict(
queries=appState.queries,
errors=appState.errors,
path=request.path,
logged_in=appState.logged_in... | 96cb7da93b51d71c3ef6c82893f2baf818ac0937 | 72,105 |
def log_format_info(event_str, data = {}):
"""
log_format_info is a helper function. It will format an info message with
support for event data.
event_str A string describing the event
data A dictionary with info
returns string to pass to logger.info()
Example:
try:
...
except Exception as e:
log... | cc1c7dee4d566e95bb7f966943b4bfdb180c9ff2 | 72,106 |
def tag_pos(sentences: list) -> list:
"""Tag parts of speech of tokens in each sentence.
Args:
sentences (list): List of word tokenized sentences.
Returns:
list: List of part-of-speech tagged sentences.
"""
return [nltk.pos_tag(sentence) for sentence in sentences] | 20ffddf8c840460e2b184c613e096209e3aa39a7 | 72,107 |
def count_machines(filter: str = None,
configuration: Configuration = None,
secrets: Secrets = None) -> int:
"""
Return count of Azure virtual machine instance(s).
Parameters
----------
filter : str
Filter the virtual machine instance(s). If omitted a r... | 21266070b8ef34fbb98816778c2d587287d838fa | 72,108 |
def attrs_to_dict(attrs):
"""
Convert a list of tuples of (name, value) attributes to a single dict of attributes [name] -> value
:param attrs: List of attribute tuples
:return: Dict of attributes
"""
out = {}
for attr in attrs:
if out.get(attr[0]) is None:
out[attr[0... | ccf9440d29de2f8556e694f4ab87e95f0bfd9e8a | 72,109 |
import re
def sub(table, field, pattern, repl, count=0, flags=0):
"""
Convenience function to convert values under the given field using a
regular expression substitution. See also :func:`re.sub`.
.. versionadded:: 0.5
.. versionchanged:: 0.10
Renamed 'resub' to 'sub'.
"""... | 3246d45c2eac67bb9af8c3fc5281b135030f202d | 72,110 |
import sys
def do_add(gc, args):
"""DEPRECATED! Use image-create instead."""
try:
fields = get_image_fields_from_args(args.fields)
except RuntimeError as e:
print(e)
return FAILURE
image_meta = {
'is_public': utils.string_to_bool(
fields.pop('is_public', 'F... | 9b792318fbec7c21ffde5627a9a1aa0381af6e19 | 72,111 |
import os
def _get_horovod_rank_and_size():
"""Get rank and size from environment, return (rank, size), if failed, return (``None``, ``None``)"""
rank_env = ['HOROVOD_RANK', 'OMPI_COMM_WORLD_RANK', 'PMI_RANK']
size_env = ['HOROVOD_SIZE', 'OMPI_COMM_WORLD_SIZE', 'PMI_SIZE']
for rank_var, size_var in z... | d147624908773ea8adfc9c7a67a3f170c1b3b867 | 72,112 |
from typing import Dict
from typing import Any
from typing import Type
from re import T
def get_instance(config: Dict[str, Any], target_class: Type[T]) -> T:
"""Constructs an instance of type target_class from config.yml dict structure.
E.g.
{class: path.to.module.MyClass, constructor: {arg1: <arg1>}}
... | 9e7de1a80ed230a72229b31d2435e084df6cdc52 | 72,113 |
def count(i):
"""List or text. Returns the length as an integer."""
return len(i) | d8daf7cd325ce1acfb382723759ff190becd785f | 72,114 |
import yaml
def GenerateConfig(context):
"""Entry function to generate the DM config."""
content = {
'resources': [
_RuntimeConfig(context),
_Waiter(context),
],
'outputs': [
{
'name': 'config-url',
'value': _ConfigUrl(context)
... | 2aad00d49d9d657d79b1d9806e61f8559c1b530e | 72,115 |
def estimate_psd(t, k, n_zero=2_000, db=False):
"""Estimate the PSD from samples of the kernel.
Args:
t (vector): Time points of the kernel, which should be a linear space
starting from the origin.
k (vector): Kernel.
n_zero (int, optional): Zero padding. Defaults to `2_000`... | 77360454125c729cf894d4927a38cd7aeb764622 | 72,116 |
def approve(owner, spender, tokenId, amount):
"""
approve amount of the tokenId token to toAcct address, it can overwrite older approved amount
:param owner:
:param spender:
:param tokenId:
:param amount:
:return:
"""
res = int(owner)
RequireWitness(owner)
RequireScriptHash(o... | 9a6bd562b3d6ceb3648ebe3a78a86ef916abcbf8 | 72,117 |
def determine_fit_quality_mvm_interface(imglist, filtered_table, catalogs_remaining, ref_catalog_length,
align_pars, print_fit_parameters=True, loglevel=logutil.logging.NOTSET):
"""Simple interface to allow MVM code to use determine_fit_quality().
Parameters
--------... | d6b17fae04853731f341c4feb208e33e4fc812f5 | 72,118 |
import sys
import locale
def set_default_encoding(encoding=None):
"""set_default_encoding(encoding) - set the default character encoding
Set the default character encoding of the run-time. If 'encoding' is not
provided, the current locale's character encoding is used by default.
If current locale's encoding is... | 1e7cee1cb4d647df150934e20c837ea5b363aa24 | 72,119 |
from datetime import datetime
def started_streaming(before: discord.Member, after: discord.Member):
""" Return True if the member just started streaming, and did not do so recently. """
# The member is not streaming at the moment
if after.game is None or not after.game.type == 1:
return False
... | 905d40512bbe48ea29c41dbc7b99749af5617ad7 | 72,120 |
import os
def load_adni_longitudinal_rs_fmri(dirname='ADNI_longitudinal_rs_fmri',
prefix='wr*.nii'):
""" Returns paths of ADNI rs-fMRI
"""
# get file paths and description
images, subject_paths, description = _get_subjects_and_description(
base_dir=dirname, ... | 3ae8fc52a9e9606fcebdd647d404eca4d8151ab6 | 72,121 |
def score(hand):
"""
Compute the maximal score for a Yahtzee hand according to the
upper section of the Yahtzee score card.
hand: full yahtzee hand
Returns an integer score
"""
possible_scores = []
#Add each possible score to the list of possible scores
for num in list(hand):
... | da6ff8c5a0c640034ae063bc08a54351f4dd259e | 72,122 |
from functools import reduce
def lLog( A ):
"""Calculate the log of A: log(A)"""
if type(A) is list:
Ainv = lInvert( A )
Ap = [ lScalMult(Fraction(1, n), reduce( lSum, ( lScalMult( k, lConvolute( A[k], Ainv[n-k] ) ) for k in range(1,n+1) ) ) ) for n in range(1,len(A)) ]
return [lLog(A... | cf4792da0df7bab331d56a603cc00553fe665d59 | 72,123 |
import math
def fibonacci_sphere(samples=1):
"""Implementation from as https://stackoverflow.com/questions/9600801/evenly-distributing-n-points-on-a-sphere"""
points = []
phi = math.pi * (3. - math.sqrt(5.)) # golden angle in radians
for i in range(samples):
y = 1 - (i / float(samples - 1)) ... | 31a438be2b0c737cde8542369c777c600690a118 | 72,124 |
def ml(request):
"""A pytest fixture to provide access to the underlying coverage object."""
# Check with hasplugin to avoid getplugin exception in older pytest.
if request.config.pluginmanager.hasplugin('_test_ml'):
plugin = request.config.pluginmanager.getplugin('_test_ml')
if plugin.cov_... | f4625b642347e5c331a5850b7877bee1429565f7 | 72,125 |
def load_doc_topics(input_file, doc_topic_file, threshold=0.01):
"""Load topics in each document"""
articles = []
with open(doc_topic_file) as tfin:
for data in utils.read_json_list(input_file):
topic_line = tfin.readline()
if not topic_line:
break
... | 90668191c8aaa0791a17a33687db53362c7970cf | 72,126 |
def subsegment(data, frames, n_segments=4, axis=-1):
"""Sub-divide a segmentation by feature clustering.
Given a set of frame boundaries (``frames``), and a data matrix (``data``),
each successive interval defined by ``frames`` is partitioned into
``n_segments`` by constrained agglomerative clustering.... | bcad63724325e662ea86684d6ed5fa207e27b3bb | 72,127 |
from typing import Union
import pathlib
from typing import IO
from typing import Any
from typing import Dict
from typing import Callable
from typing import Optional
import io
def from_yaml(
yaml_str: Union[str, pathlib.Path, IO[Any]],
routing_strategy: Dict[str, Callable] = routing_strategy_factories,
lab... | 937cedae6c57dafc2629b6aaab7ffe1cf5b62995 | 72,128 |
def wehrli(smooth=True, unit=u.Unit('W/(m2 um)')):
"""Wehrli (1985) solar spectrum (at 1 AU).
Parameters
----------
smooth : bool, optional
Set to `True` to smooth the solar spectrum (see Notes).
unit : astropy Unit
Return flux in these units (must be spectral flux density).
Return... | 6c6f446a0e0e567cdb1e61914b4551bff8be62b1 | 72,129 |
def load_frm_bag(filename):
"""Loads specific topics from rosbag and stores data as np.arrays
Parameters
----------
filename : string, required
Name of .bag file
Outputs
----------
"""
bag = rosbag.Bag(filename)
outbag = rosbag.Bag(filename+'_new','w')
# topic_name =... | ae8e7b4af6cd2e8dd1125560e5de8549059ebc96 | 72,130 |
import math
def PlateStiffener (b, t, hw, tw, bf, tf, L, fyp, fyw = 0, fyf = 0, E = 210000):
""" """
# plate (flange) section
_b = b
_t = t
# web section
_hw = hw
_tw = tw
# flange section
_bf = bf
_tf = tf
# Fy plate
_Fyp = fyp
# Fy web
if fyw == 0: _Fyw = _Fyp... | 13321a27dd3580f99b0128daa859acfeb5dad5d7 | 72,131 |
def find_body(view):
"""
Find first package body declaration.
"""
return view.find(r'(?im)create\s+(or\s+replace\s+)?package\s+body\s+', 0) | b592199e4ef09d079645fc82ade8efbe3c92a895 | 72,132 |
def _get_files_project(sample, upload_config):
"""Retrieve output files associated with an entire analysis project.
"""
out = [{"path": sample["provenance"]["programs"]}]
if sample["summary"].get("project"):
out.append({"path": sample["summary"]["project"]})
for x in sample.get("variants", [... | 04d973a90372343fd43da4cc180ba861fde62125 | 72,133 |
from bs4 import BeautifulSoup
def add_currency_card(soup: BeautifulSoup,
conversion_details: dict) -> BeautifulSoup:
"""Adds the currency conversion boxes
to response of the search query
Args:
soup: Parsed search result
conversion_details: Dictionary of currency
... | 7fa7962288cbe7113f3d786c5a8ff6f5211e2ad0 | 72,134 |
def _should_send_own_updates(self):
"""Get whether a user wants to receive emails about their activity.
This is patched into the user object to make it easier to deal with missing
Profile objects.
"""
try:
return self.get_profile().should_send_own_updates
except Profile.DoesNotExist:
... | 9825fdffc6f20165b687b7f4fe4dc2be8d24a0dc | 72,135 |
def get_glibc_version():
# type: () -> Optional[Tuple[int, int]]
"""Based on PEP 513/600"""
import ctypes # pylint: disable=bad-option-value,import-outside-toplevel
try:
process_namespace = ctypes.CDLL(None)
gnu_get_libc_version = process_namespace.gnu_get_libc_version
except (Attr... | 02a950909a308bc811529588e1ca2cd72e0ff6f3 | 72,136 |
def generate_family_filenames(name, styles):
"""Name is the family name portion of a Noto filename. Styles is the
encoding of the styles, see _get_stylenames."""
stylenames = _get_stylenames(styles)
return [name + "-" + s + ".ttf" for s in stylenames] | cce985c0a1696d534c1276d1bdd25ffd1e232c41 | 72,137 |
def type_accept(*type_args, **type_kwargs):
"""Decorator to check function/method input types. Based on Python Cookbook 3rd ed. #9.7."""
def decorate(func):
# Map function argument names to supplied types
sig = signature(func)
bound_types = sig.bind_partial(*type_args, **type_kwargs).ar... | d37134e3f150ebf7d2c99c3980e17f2c30c09a33 | 72,138 |
def geonet_diffusion(demArray, diffusionMethod, nFilterIterations,
edgeThreshold, diffusionTimeIncrement,
diffusionSigmaSquared, pixelSize):
"""
References:
Based on diffusion() by Guy Gilboa
Code imported from GeoNet2.1 by Harish Sangireddy June 2014
... | 5f35cc6252e9187d3b9ae794ab4a5d941e34d003 | 72,139 |
def make_optimiser(name="adam", learning_rate=0.0001, **kwargs):
"""
Helper to create an optimiser from the command line.
:param name: name of optimisers
:param learning_rate: learning rate of optimiser
:param kwargs: kwargs that can be passed along to keras optmiser
:return:
"""
if name... | 86b3420c4faaa8cc09da36214f0488fa7cd9bccf | 72,140 |
def hid_logout():
""" Flask controller: kill the user's login session with Humanitarian.ID
GET parameters:
from - the URL of the page from which we were redirected
"""
path = flask.request.args.get('from', '/') # original path where user choose to log out
flask.session.clear() # clear the logi... | 097dfae9077feafdc013d60a3418d68c3ed152d0 | 72,141 |
def grabCut(image, labels, use_tresholds=True, thresholds=(0.2, 0.6, 0.8), iterations=2, clean=False):
"""Use the predicted mask and OpenCV's GrabCut algorithm to mask an image.
Parameters
----------
image : numpy.ndarray
input image to mask
labels : numpy.ndarray
labels for backgro... | f9c56aa906617d28435c0c4157926fd9f025c1d9 | 72,142 |
from typing import List
def get_resolutions() -> List[str]:
"""
Get available resolutions for DWD CDC Climate Data.
If `resolution_name` is None, all resolutions are returned.
:param str resolution_name: A string describing the resolution, either "hourly" or "10_minutes"
:returns: A list of res... | 99d1de6c2205d247b86b25c155b153c37b034a82 | 72,143 |
def renormalize(a: tp.MaybeArray[float], from_range: tp.Tuple[float, float],
to_range: tp.Tuple[float, float]) -> tp.MaybeArray[float]:
"""Renormalize `a` from one range to another."""
delta1 = from_range[1] - from_range[0]
delta2 = to_range[1] - to_range[0]
return (delta2 * (a - from_ra... | 1003f031fed6a9adbe48327760ee64fdc31b2a37 | 72,144 |
def jdn_to_rjd(jdn: int) -> int:
"""Return Reduced Julian Day (RJD) number from Julian day number (JDN).
Args:
jdn: Julian day number (JDN).
"""
return jdn - 2400000 | 73ffa9a6b56dfa6e543ebe581256428859311d8e | 72,145 |
import time
def bruteforceGeocoding(dict_address: dict, apiKey: str, waitTime: int):
"""
Geocoder trying the Bing API given the address
Args:
dict_address (dict): dictionary with the address to locate.
apiKey (str): Bing API key.
waitTime (int): Time to wait between a call and the... | ca53820e12138d3d575cd296ebede1b6227056a5 | 72,146 |
import math
def roll(entropy, n):
"""From 0 to n - 1."""
# Minimum bit depth to cover the full range.
# Note that more bits would be more fair.
bit_depth = math.ceil(math.log2(n))
x = entropy(bit_depth)
# Scale from total range to desired range.
# Numbers with higher odds will be evenly... | a714b1636cd6a97fb4d4ccc19e966795cadec76c | 72,147 |
def get_parsed_trigger_file(
trigger_file, s3_key, expected_keys=[], legacy_keys=[]
):
"""Check that trigger file has the correct keys, add default values,
and potentially fall back to a legacy format if the first set of
keys are not present"""
if all(key in trigger_file for key in expected_keys):
... | a637679d697984a0cf2ab3816dd88acd49c74d44 | 72,148 |
def _wait_for_instance(
aws_svc, instance_id, timeout=300, state='running'):
""" Wait for up to timeout seconds for an instance to be in the
'running' state. Sleep for 2 seconds between checks.
:return: The Instance object, or None if a timeout occurred
"""
log.debug(
'Waiting ... | 1c8c5532b9f35d34ebc8b617b7bd4961a1243898 | 72,149 |
def minibatch_iterator(minibatch_size = 1, epochs = 1, final_treatment = 'stop', single_channel = False):
"""
:param minibatch_size:
:param epochs:
:param final_treatment:
:param single_channel:
:return: A function that, when called with a Data Collection, returns an iterator.
"""
def i... | f834743617bf44b9e07dbe4e3638f85db610505d | 72,150 |
def create_ipv6_network(config_id, pool_cidr, pool_name):
"""create ipv6 network under configuration"""
parent = get_parent(config_id, pool_cidr)
parent_id = config_id
if parent is not None:
parent_id = parent['id']
return g.user.get_api()._api_client.service.addIP6NetworkByPrefix(parent_id,... | 4f42a8ac5bb6384908c9457288cf579bcd27f0a8 | 72,151 |
import random
def gen_sample_data(n_sample=300):
"""
Generate sample data
"""
survey_data = []
for _ in tqdm_notebook(range(n_sample)):
district = random.choice(possible_district)
age = random.choice(possible_age)
sex = random.choice(possible_sex)
increase_list = ra... | 40fc92b1f64bbe8f9a84c98b80b9a6318c0d254f | 72,152 |
def yaml_ssm_constructor(loader, node):
""" Implements the yaml tag !SSM
The tag takes the same arguments as SSM's GetParameter call:
http://boto3.readthedocs.io/en/latest/reference/services/ssm.html#SSM.Client.get_parameter
http://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParamete... | af977c6f68e2a99ad1d49424ad059bc09b21fa29 | 72,153 |
def check_pair_numpy_param(inputs_name, inputs, labels_name, labels):
"""
Dimension-equivalence check for `inputs` and `labels`.
Args:
inputs_name (str): Name of inputs.
inputs (Union[list, tuple, numpy.ndarray]): Inputs.
labels_name (str): Name of labels.
labels (Union[list... | 91e4f1b2388b6b54464ddf4994067e574836a6be | 72,154 |
import json
def page_json():
"""Return a Page JSON."""
page_str = json.dumps(
{
"name": "RVXXX1-AutoForward",
"capture_credentials": True,
"capture_passwords": False,
"redirect_url": "redirect.domain",
"html": AUTO_FORWARD,
}
)
... | aa220982c1c31e89f200817c6827435f4ee972c1 | 72,155 |
def index(request):
"""the homepage for learning log"""
return render(request, 'learning_logs/index.html') | 5d52e42a7d108f2085d64018e2114c4208ad13eb | 72,156 |
import re
def validate_search_service_engine_version(engine_version):
"""
Validate Engine Version for OpenSearchServiceDomain.
The value must be in the format OpenSearch_X.Y or Elasticsearch_X.Y
Property: Domain.EngineVersion
"""
engine_version_check = re.compile(r"^(OpenSearch_|Elasticsearch... | 4fd725b20578047afb1751da646381003289e9c4 | 72,157 |
import subprocess
import os
def get_peatclsm_data_table(variable, expected_header):
"""Return a tabulated variable as parameterized in PEATCLSM
"""
output = subprocess.check_output(
['Rscript', '--vanilla',
os.path.join(
os.path.dirname(__file__),
'peatclsm_hydr... | 3d21f05004c5deb77514c7021cd79abf20c325af | 72,158 |
import os
def get_mlnet_assemblies(chdir=False):
"""
Retrieves assemblies.
"""
if chdir:
cur = os.getcwd()
os.chdir(dll)
res = MamlHelper.GetLoadedAssembliesLocation(True)
if chdir:
os.chdir(cur)
dependencies = []
# addition = ["Core", "Data", "Maml", "Api"]
... | 2ac503c1d53af13e345c6aa61b82a77c62ef9ffb | 72,159 |
def find_models(*, extended_filters=(), **kwargs) -> ModelSet:
"""Fetch Models from AssetCentral with the applied filters, return an ModelSet.
This method supports the usual filter criteria, i.e.
Any named keyword arguments applied as equality filters, i.e. the name of the Model property is checked
aga... | 2a72b8f9010098f993f3f6ae5624210d26de54e0 | 72,160 |
import random
def generateDrops(imagePath, cfg, inputLabel = None):
"""
This function generate the drop with random position
"""
maxDrop = cfg["maxDrops"]
minDrop = cfg["minDrops"]
drop_num = randint(minDrop, maxDrop)
maxR = cfg["maxR"]
minR = cfg["minR"]
ifReturnLabel = cfg["return_label"]
edge_ratio = c... | 239aa2905ad1f6067b95065d2ac7b17cfb87998c | 72,161 |
import torch
def make_algebra_matrix(tau, mode):
"""
Generates the matrix on the Lie algebra of the transformation group for vector tau
Input:
:Tensor tau: parameter vector
:String mode: transformation set
Output:
:array B: 3x3 matrix on the Lie algebra of mode
"""
tau.squeeze_()... | 92080c5955a4127ff25d7afd5f7623df46f21831 | 72,162 |
def get_num_objects(tree):
""" Get number of objects in an image.
Args:
tree: Tree element of xml file.
Returns: Number of objects.
"""
num_obj = 0
for e in tree.iter():
if e.tag == 'object':
num_obj = num_obj + 1
return num_obj | 92f937cbbf2eabdc909ef6bc1f06ccb87e0148b7 | 72,163 |
import math
def generate_gate_piover8_daggered_hamiltonian_vec() -> np.ndarray:
"""Return the vector representation for the Hamiltonian of a pi/8 daggered (T^dagger) gate with respect to the orthonormal Hermitian matrix basis with the normalized identity matrix as the 0th element.
The result is a real vector... | 00f5a1c5431c6fa51da048cc6cc9c0850dc58ff0 | 72,164 |
def defer_to_threadpool(reactor, threadpool, f, *args, **kwargs):
"""
A wrapper for twisted.internet.threads.deferToThreadpool, which handles
logcontexts correctly.
Calls the function `f` using a thread from the given threadpool and returns
the result as a Deferred.
Creates a new logcontext fo... | 4f0c834cfcf79aff76de99aa8f96270e6c27eb5c | 72,165 |
def global_admin_css():
"""Add /static/css/custom.css to the admin."""
return format_html(
'<link rel="stylesheet" href="{}">',
static("css/wagtail-overrides.css")
) | 020ca665768aa6eb6d87e02070ed44e4021cb40e | 72,166 |
def list_service_offering(api_client, **kwargs):
"""Lists all available service offerings."""
cmd = {}
cmd.update(kwargs)
# [setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd['listall'] = True
return Response.list(api_clien... | da2102df4fe198972efb0def69739ed684fdfaef | 72,167 |
def read_fileset_vols(file):
"""
Read in the fileset volumes from the given file and returns the paths
:param file:
:return: [list] of paths
"""
with open(file) as r:
filesets = r.readlines()
paths = []
for fs in filesets:
fs_parts = fs.strip().split(' ')
#print... | 6a704097a58f83c8b3eb7c20b81a866353df5ca5 | 72,168 |
def get_scene_nodes():
"""
Returns al nodes in current scene as GamEX nodes
:return: list<gx.dcc.DCCNode>
"""
node_list = list()
_append_children(MaxPlus.Core.GetRootNode(), node_list)
return node_list, len(node_list) | 67da9ae796211f40fc784d44d2e2e4ce8416e022 | 72,169 |
def parse(r):
"""
Parse and return a pandas TimeSeries object
"""
# Create TimeSeries
try:
d = {}
for tup in r.json():
d[dt.datetime.fromtimestamp(tup[0])] = tup[1]
except:
print("-------> Problem with Flukso data parsing <-------")
... | 8fcb07f4e6795cf6a64550e547a6c10049f373b0 | 72,170 |
def shake_shake_skip_connection(x, output_filters, stride, is_training):
"""Adds a residual connection to the filter x for the shake-shake model."""
curr_filters = common_layers.shape_list(x)[-1]
if curr_filters == output_filters:
return x
stride_spec = [1, stride, stride, 1]
# Skip path 1.
path1 = tf.n... | 55c43fc838c7520ecbe8c33a1680854cf9ee7335 | 72,171 |
def rename_genome(genome, assembly_summary):
"""Rename FASTAs based on info in the assembly summary
"""
genome_id = parse_genome_id(genome)
infraspecific_name = assembly_summary.at[genome_id, "infraspecific_name"]
organism_name = assembly_summary.at[genome_id, "organism_name"]
if type(infraspeci... | 8f5f0a296ae0eeff008d1493d3ea9d6d063d25bb | 72,172 |
from typing import Union
from typing import List
from typing import Optional
def op_add_listing_details_at_aoi(id_shape: Union[int, List[int]]) -> Optional[str]:
""" Fetch and store into the database LISTING DETAILS for the LISTING_IDs found in the quad-grids
intersecting with AOI ID_SHAPEs.
This is an i... | 7b057cf7908a34c46f93a63afff1645e31325f8d | 72,173 |
import json
def autocomplete_autor():
"""
route for retrieving autocomplete entries for field autor
:return: list of entries for autocomplete
"""
return json.dumps(Publication.get_autocomplete_entries("autor", request.args['term'])) | 9b4a9d12d36940cad4d438aae73e46d685f59db7 | 72,174 |
import json
def makeData(version: str) -> str:
"""
writes all important minecraft data to a file and returns the path
Note that this wil crash if the version is below 1.14.
"""
version = version or get_latest_version()
# first test if the file already exists
directory = getVersionDir(ver... | 9ae9b8c60b9f570564c7b28daee32b84c1a92b68 | 72,175 |
def generate_data():
"""
"""
np.random.seed(2046)
d1 = np.random.normal(5, 5, 10)
d2 = np.random.normal(5, 5, 10)
groups = ["d1"] * 10 + ["d2"] * 10
d = {"A": np.concatenate((d1, d2)), "B": groups}
data = pd.DataFrame(d)
return data | ee4e34b7de82f9ad039b42203d810471c14b92b2 | 72,176 |
def show_about():
"""关于本站"""
site_desc = SiteDesc.query_by_id(1)
return render_template("main/about.html", site_desc=site_desc, channel_id=3) | 5c83c5013df3eed695043016b5cd5c84bcc561dd | 72,177 |
import math
def correlation(x,y,n):
"""
computes pearson correlation coefficient
"""
a=covariance(x,y,n)/math.sqrt(variance(x,n)*variance(y,n))
return a | f30178037f415a96df8eb4bf31d8a33c4d66a423 | 72,178 |
def partition(n, g):
"""
Returns the number of ways to partitions set of n
elements with a partition of size g
"""
if n == 1:
return 1
elif n == g:
return 1
elif g>n or g<=0:
return 0
else:
sum = 0
for i in range(g, n-g+1, 1):
sum += pa... | e0af35b413963c6ff600e87e5a55e8f4dbcc4b84 | 72,179 |
from typing import Union
def _get_tol_from_less_precise(check_less_precise: Union[bool, int]) -> float:
"""
Return the tolerance equivalent to the deprecated `check_less_precise`
parameter.
Parameters
----------
check_less_precise : bool or int
Returns
-------
float
Toler... | 375f7918a04fafb4a79f77abd3f0282cdc74e992 | 72,180 |
def benchmark(scale=1):
"""
Benchmark and return information regarding the relative performance of a
protocol which does not use the buffering mixin and a protocol which
does.
@type scale: C{int}
@param scale: A multiplier to the amount of work to perform
@return: A Deferred which will fir... | 61303746bc600926d9f64433ac1bb77c91957e06 | 72,181 |
def answer_card_api(state: State) -> flask.Response:
"""Verify A User's Answer
This route is intended for use by xhr/ajax
POST Parameters:
a: The answer to test against
Returns:
JSON with the fields:
correct (bool): indicates whether the answer was correct
scor... | 78deca17279e739d02158fc765eb530d89cc6c2f | 72,182 |
import os
import sys
import time
def handle_read(cmd_namespace):
"""
Authors: xuruiqi
"""
global SLEEP_DURATION
filepath_list = getattr(cmd_namespace, "file")
lpms = getattr(cmd_namespace, "lpms")
start = getattr(cmd_namespace, "start")
end = getattr(cmd_nam... | ae70e049242f8e8eab2a1e182a9fc690176917f6 | 72,183 |
def _check_data_params(obj, X, y, conf_score):
"""Extracted out of BaseHandler for WeightedBag & Costing"""
# Reproducibility
rns = check_random_state(obj.random_state)
for k, v in obj.get_params().items():
if isinstance(v, BaseEstimator) and 'random_state' in v.get_params():
v.set_... | a09f0db52a467ce22518a8464321c9429bca2ec6 | 72,184 |
def plot_photostim_effect(session_key, photostim_key, axs=None, title='', plot=True):
"""
For all trials in this "session_key", split to 4 groups:
+ control left-lick
+ control right-lick
+ photostim left-lick (specified by "photostim_key")
+ photostim right-lick (specified by "photostim_key")
... | 18ecb8532658241636d479013710e3d6bf8b09dd | 72,185 |
def calculate_mean_spectrum(msi):
""" reduce this image to only its mean spectrum.
If the msi.get_image() is a masked array these values will be ignored when
calculating the mean spectrum """
# reshape to collapse all but last dimension (which contains reflectances)
collapsedImage = collapse_image(m... | acda0a1df1f32bd765f971d184fb4a4b70ed422a | 72,186 |
def P_s_next(A, i, j, C, shape):
"""
Calculate the next probability at position i,j
"""
temp = Q_s(A, i, j, 1, C, shape) * A[i, j]
return temp / ((temp + (1.0 - A[i, j]) * Q_s(A, i, j, 0, C, shape)) + 0.000000001) | 5bbc35e4c190eeb9859b87f16a110c9a7bb87c68 | 72,187 |
import dask.dataframe as dd
def create_statistical_metrics(df_var, percentiles=None, iqr=True, diffs=True, num_workers=1, verbosity=0):
"""Calculate statistial metrics from a dataframe with pd.DateTimeIndex and a instance (e.g. pixels) dimension.
Parameters
----------
df_var : [type]
[de... | ff7ed4e4c507681757b51e09d07448efa793c082 | 72,188 |
def extract_nodegraph_info(filename):
"""Open the given nodegraph file and return a tuple of information.
Returns: the k-mer size, the table size, the number of tables, the version
of the table format, and the type of table flag.
Keyword argument:
filename -- the name of the nodegraph file to insp... | 026a3788fa7fdd180b6c7090e07aebdeec3ee997 | 72,189 |
def name():
"""Return the precise name for the software."""
return 'Python' | d3aa60120be2ef6eb90844aa9396c347d486cf62 | 72,190 |
def get_cold_start_rating(user_id, movie_id):
"""
Given user_id and movie_id, return a predicted rating
parameters
----------
user_id, movie_id
returns
-------
movie rating (float)
If current user, current movie = average rating of movie by cluster
If current user, NOT ... | 7f33ca28c778f9f94c15beaff28d44e858238299 | 72,191 |
import os
import json
def full_configuration():
"""Get test configuration information. Keys are:
host - WebDriver server host.
port - WebDriver server port.
capabilites - Capabilites passed when creating the WebDriver session
webdriver - Dict with keys `binary`: path to webdriver binary, and
... | e1a42fee16d0225f840326cc38f07d70afc4d86e | 72,192 |
def continuous_blocking(
radius: float,
source: _typing.Sequence[_typing.Sequence[float]]
) -> _typechecking.BlockingFunction[_typechecking.Record]:
"""Block on continuous variables.
Split the real number line into overlapping blocks. A quantity is in
exactly two blocks. Two quantities within `radi... | ad3a649af7ee17aea2eedc8f1a842425502896bd | 72,193 |
import numpy
def point(pose,px,py,pz):
"""
Project a 3D point into the camera.
Input:
pose -- camera pose
px,py,pz -- point in global frame
Output:
u,v -- pixel coordinates
"""
p = pose.dot(numpy.matrix([[px],[py],[pz],[1]]))
X = p[0,0]
Y = p[1,0]
Z = p[2... | 3393311323b285eaa973cbfb52fbbe301d3f78f0 | 72,194 |
def install(name, clean=True):
"""
Install a port from the ports tree. Installs using ``BATCH=yes`` for
non-interactive building. To set config options for a given port, use
:mod:`ports.config <salt.modules.freebsdports.config>`.
clean : True
If ``True``, cleans after installation. Equivale... | f4b3f3fdfd4f3a3b2e99541e26a118f6e13e33da | 72,195 |
from typing import Callable
def flip(f: Callable) -> Callable:
"""
Reverse the order of positional arguments of `f`
Example:
>>> f = lambda a, b, c: (a, b, c)
>>> flip(f)('a', 'b', 'c')
('c', 'b', 'a')
Args:
f: Function to flip positional arguments of
Returns:
... | 7f483f762b2a1c2cc7ac0643e037b6326a08377e | 72,196 |
def _accumulate(data_list, no_concat=()):
"""Concatenate a list of dicts `(name, array)`.
You can specify some names which arrays should not be concatenated.
This is necessary with lists of plots with different sizes.
"""
acc = Accumulator()
for data in data_list:
for name, val in data... | a16e1a60c0921866a5e5c0ced14bcbc7c4d62140 | 72,197 |
import os
def set_wifi(opt):
"""Enable AP."""
hif, lif, mac, vlan = _get_interface('ap', opt.interface_suffix)
if not hif:
return False
if opt.encryption == 'WEP':
raise utils.BinWifiException('WEP not supported')
stop_ap_wifi(opt)
try:
_ensure_initialized('ap')
_qcsapi('wifi_create_bs... | bb9c05c99fc52805d60c1e580768ad5d78b56694 | 72,198 |
def blck_if(preprocessor: Preprocessor, args: str, contents: str) -> str:
"""the if block
usage: {% if <condition> %} ...
[{% elif <condition> %} ...]
[{% else %}...]
{% endif %}
"""
value = condition_eval(preprocessor, args)
pos_0 = 0
desc = "in if block"
while True:
else_info = find_e... | 1713d67bd45efbc0c5bdeb8f3d00d2a733ee2d75 | 72,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.