content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def plot(
key: Array,
gp: gpx.Prior,
params: dict,
data: gpx.Dataset,
n_samples: int = 10,
title: str = None,
ax=None,
):
"""
Plot samples from the Gaussian process prior distribution.
:param key: A Jax PRNGKey object to ensure reproducibility when sampling from the prior distri... | 35,200 |
def deconv4x4_block(in_channels,
out_channels,
stride=1,
padding=3,
ext_padding=(2, 1, 2, 1),
out_padding=0,
dilation=1,
groups=1,
bias=False,
... | 35,201 |
def main():
"""Program main, called after args are parsed into FLAGS.
Example:
python runner.py --workspace=/workspace
--bench-home=/mxnet_repo/incubator-mxnet/example/image-classification
--train-data-dir=/mxnet_repo/train/data
"""
test_runner = TestRunner(
FLAGS.workspace, FLAGS.bench_home... | 35,202 |
def get_package_requirements():
""" Used to read requirements from requirements.txt file.
:return: list of requirements
:rtype: list
"""
requirements = []
for line in read_file_contents("requirements.txt").splitlines():
line = line.strip()
if line == "" or line.startswith("#"):
... | 35,203 |
def dem_coregistration_custom(masterDEM, slaveDEM, glaciermask=None, landmask=None, outdir='.', pts=False, full_ext=False,magnlimit=1.):
#This coreg code is from Robert McNaab and Chris Nuth: pybob
"""
Iteratively co-register elevation data, based on routines described in Nuth and Kaeaeb, 2011.
Paramet... | 35,204 |
def check_types_of_edge_constraint(sub_graph):
""" Go through the subgraph for operations and checks that the constraints\
are compatible.
:param sub_graph: the subgraph to search through
:return:
"""
for partition in sub_graph.partitions:
fixed_key = utility_calls.locate_constraint... | 35,205 |
def setup_args():
"""Setup training arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--is_distributed", type=str2bool, default=False,
help="Whether to run distributed training.")
parser.add_argument("--save_path", type=str, default="output",
... | 35,206 |
def graph2tree(mat, root, closedset=None):
"""Convert a graph to a tree data structure"""
if closedset is None:
closedset = set()
tree = Tree()
def walk(name):
node = TreeNode(name)
node.dist = 0
closedset.add(name)
for child in mat[name]:
if child n... | 35,207 |
def test_simple_roundtrip_tuple(cls_and_vals, dv: bool):
"""
Simple classes with metadata can be unstructured and restructured.
"""
converter = Converter(
unstruct_strat=UnstructureStrategy.AS_TUPLE, detailed_validation=dv
)
cl, vals, _ = cls_and_vals
inst = cl(*vals)
unstructure... | 35,208 |
def is_hex(hex_str):
"""Helper function to verify a string is a hex value."""
return re.fullmatch('[0-9a-f]+', hex_str) | 35,209 |
def choose_conv_method(in1, in2, mode='full', measure=False):
"""
Find the fastest convolution/correlation method.
This primarily exists to be called during the ``method='auto'`` option in
`convolve` and `correlate`, but can also be used when performing many
convolutions of the same input shapes an... | 35,210 |
def jet(data, range=None, exp=1.0):
"""
Creates a JET colormap from data
Parameters
----------
data : np.array [N,1]
Data to be converted into a colormap
range : tuple (min,max)
Optional range value for the colormap (if None, use min and max from data)
exp : float
Ex... | 35,211 |
def get_context(context):
"""Returns the application documentation context.
:param context: application documentation context"""
context.brand_html = "ERPNext OCR"
context.source_link = source_link
context.docs_base_url = docs_base_url
context.headline = headline
context.sub_heading = sub_... | 35,212 |
def collatz_seq(n, collatz_dict={}):
""" Takes an integer n and returs the resulting Collatz sequence as a list. """
seq = [n]
while n > 1:
n = next_collatz(n)
if n in collatz_dict:
seq.extend(collatz_dict[n])
collatz_dict[seq[0]] = seq
return seq
... | 35,213 |
def create_app():
"""
Create a Flask application using the app factory pattern.
:param settings_override: Override settings
:return: Flask app
"""
app = Flask(__name__)
app.config.from_object('config.settings')
app.register_blueprint(contact)
return app | 35,214 |
def config_update():
"""
上传dockerfile和相关配置文件
:return:
"""
config_build()
config_upload() | 35,215 |
def get_prebuilt_piccolo():
"""
:return: pair of picollo feature model filename and fm.json as a string
"""
DEFAULT_PREBUILT_PICCOLO = f'/home/besspinuser/tool-suite/tutorial/piccolo-simple-pregen.fm.json'
with open(DEFAULT_PREBUILT_PICCOLO, 'r') as f:
feature_model = f.read()
return 'p... | 35,216 |
def conflict_algorithm_session(date, start_time, end_time, venue):
#converting string to datetime type variable
"""
conflict_algorithm_session:
this algorithm is used to find if there any avaiable slot for the given date , stat_time ,end_time and venue
from the session_info to book the slot else it retu... | 35,217 |
def get_income_share_summary(df_centile, k):
"""
:param df_centile: pd.DataFrame
preprocessed {region}_{unit}_centile.csv !! (rank is 1~100)
:param k: str
key
"""
centile_range = {
'하위 20%': (0, 20),
'다음 30%': (20, 50),
'하위 50%': (0, 50),
'중위 30%': (50... | 35,218 |
def _get_cmdline_descriptors_for_hashtree_descriptor(ht):
"""Generate kernel cmdline descriptors for dm-verity.
Arguments:
ht: A AvbHashtreeDescriptor
Returns:
A list with two AvbKernelCmdlineDescriptor with dm-verity kernel cmdline
instructions. There is one for when hashtree is not dis... | 35,219 |
def setup_global_errors():
"""
This updates HTTPException Class with custom error function
"""
for cls in HTTPException.__subclasses__():
app.register_error_handler(cls, global_error_handler) | 35,220 |
def show_hex(byte_array, out=None):
"""
Prints byte array in hex display format, matching that of xxd
(try :%!xxd in vi editor)
"""
out = out if out else sys.stdout
line = ['.'] * 16
i = 0
for by in byte_array:
if i % 16 == 0:
out.write(" {0}\n{1:07x}: ".format("".joi... | 35,221 |
def assign_time():
"""Get latest time stamp value"""
return datetime.strftime(datetime.now(), format='%Y-%m-%d %T') | 35,222 |
def main(hub, ref, use_tag, override_ref, overrides, interactive, quiet,
reverse, skip_invalid, dry, orgs, branches):
"""Create/remove tags & branches on GitHub repos for Open edX releases."""
repos = openedx_release_repos(hub, orgs, branches)
if not repos:
raise ValueError(u"No repos mark... | 35,223 |
def read_pb2(filename, binary=True):
"""Convert a Protobuf Message file into mb.Compound.
Parameters
----------
filename : str
binary: bool, default True
If True, will print a binary file
If False, will print to a text file
Returns
-------
root_compound : mb.Compound
... | 35,224 |
def _OneSubChunk(wav_file):
"""Reads one subchunk and logs it.
Returns:
Returns a chunk if a chunk is found. None otherwise.
"""
chunk_id = _ReadChunkId(wav_file)
if not chunk_id:
return None
size = _ReadSize(wav_file)
data = wav_file.read(size)
logging.info('Subchunk: {} ... | 35,225 |
def _convert_tensorshape_to_tensor(value, dtype=None):
"""Copied from TF's TensorShape conversion."""
if not value.is_fully_defined():
raise ValueError(
'Cannot convert a partially known TensorShape to a Tensor: {}'.format(
value))
value_list = value.as_list()
int64_value = 0
for dim i... | 35,226 |
def delete_account(account_name: str):
"""Removes account from database"""
conn = create_connection()
with conn:
cursor = conn.cursor()
cursor.execute(f"DELETE FROM balances WHERE account= '{account_name}'")
conn.commit() | 35,227 |
def superglue_convert_examples_to_features(
examples,
tokenizer,
max_length=512,
task=None,
label_list=None,
output_mode=None,
pad_on_left=False,
pad_token=0,
pad_token_segment_id=0,
mask_padding_with_zero=True,
):
"""
Loads a data file into a list of ``InputFeatures``
... | 35,228 |
def get_upside_capture(
nav_data,
benchmark_nav_data,
risk_free_rate=None,
window=250 * 3,
annualiser=250,
tail=True,
):
"""
The up-market capture ratio is the statistical measure of an investment manager's overall
performance in up-markets. It is used to evaluate how well an investm... | 35,229 |
def generateToken(username, password, portalUrl):
"""Retrieves a token to be used with API requests."""
context = ssl._create_unverified_context() if NOSSL else None
params = urllib.urlencode({'username' : username,
'password' : password, 'client' : 'referer',
'referer': portalU... | 35,230 |
def get_logreg(prof, tm, j, prods):
"""
Train logistic regression (Markov-chain approach).
prof: task-mode data generated using lhs.py
tm: task-mode
j: name of unit
prods: list of products
"""
# Filter relevant data
dfj = prof.loc[prof["unit"] == j, ].copy()
dfj["... | 35,231 |
def slowness2speed(value):
"""invert function of speed2slowness"""
speed = (31 - value) / 30
return speed | 35,232 |
def complex_covariance_from_real(Krr, Kii, Kri):
"""Summary
Parameters
----------
Krr : TYPE
Description
Kii : TYPE
Description
Kri : TYPE
Description
Returns
-------
TYPE
Description
"""
K = Krr + Kii + 1j * (Kri.T - Kri)
Kp = Krr - Kii ... | 35,233 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the USPS platform."""
if discovery_info is None:
return
usps = hass.data[DATA_USPS]
add_entities([USPSPackageSensor(usps), USPSMailSensor(usps)], True) | 35,234 |
def is_in_cap(objs, radecrad):
"""Determine which of an array of objects lie inside an RA, Dec, radius cap.
Parameters
----------
objs : :class:`~numpy.ndarray`
An array of objects. Must include at least the columns "RA" and "DEC".
radecrad : :class:`list`, defaults to `None`
3-entr... | 35,235 |
def get_lcmv_vector(atf_vectors, response_vector, noise_psd_matrix):
"""
:param atf_vectors: Acoustic transfer function vectors for
each source with shape (targets k, bins f, sensors d)
:param response_vector: Defines, which sources you are interested in.
Set it to [1, 0, ..., 0], if you ar... | 35,236 |
def _ensure_list(value: Any) -> List[Any]:
"""If value is a scalar, converts it to a list of size 1."""
if isinstance(value, list):
return value
if isinstance(value, str) or isinstance(value, numbers.Number):
return [value]
raise TypeError(
f'Value must be a list, number or a string. Got {type(v... | 35,237 |
def _ExtractMetaFeature( # pylint: disable=invalid-name
extracts: types.Extracts,
new_features_fn: Callable[[types.FeaturesPredictionsLabels],
types.DictOfFetchedTensorValues]
) -> types.Extracts:
"""Augments FPL dict with new feature(s)."""
# Create a new feature from existin... | 35,238 |
def parse_notebook_index(ntbkpth):
"""
Parse the top-level notebook index file at `ntbkpth`. Returns a list of
subdirectories in order of appearance in the index file, and a dict
mapping subdirectory name to a description.
"""
# Convert notebook to RST text in string
rex = RSTExporter()
... | 35,239 |
def import_requirements():
"""Import ``requirements.txt`` file located at the root of the repository."""
with open(Path(__file__).parent / 'requirements.txt') as file:
return [line.rstrip() for line in file.readlines()] | 35,240 |
def _get_timestamp_range_edges(
first: Timestamp,
last: Timestamp,
freq: BaseOffset,
closed: Literal["right", "left"] = "left",
origin="start_day",
offset: Timedelta | None = None,
) -> tuple[Timestamp, Timestamp]:
"""
Adjust the `first` Timestamp to the preceding Timestamp that resides ... | 35,241 |
def create_export(request, username, id_string, export_type):
"""
Create async export tasks view.
"""
owner = get_object_or_404(User, username__iexact=username)
xform = get_form({'user': owner, 'id_string__iexact': id_string})
if not has_permission(xform, owner, request):
return HttpRes... | 35,242 |
def main() -> None:
"""Example program for tcod.event"""
event_log: List[str] = []
motion_desc = ""
with tcod.context.new(width=WIDTH, height=HEIGHT) as context:
console = context.new_console()
while True:
# Display all event items.
console.clear()
c... | 35,243 |
def draft_bp(app):
"""Callable draft blueprint (we need an application context)."""
with app.app_context():
return BibliographicDraftResource(
service=BibliographicRecordService()
).as_blueprint("bibliographic_draft_resource") | 35,244 |
def _unpack(stream: bytes, path: str) -> str:
"""Unpack archive in bytes string into directory in ``path``."""
with tarfile.open(fileobj=io.BytesIO(stream)) as tar:
tar.extractall(path)
return path | 35,245 |
def create_client(client):
"""Creates a new client."""
rv = client.post('/v1/oauth/', follow_redirects=True, data={
'submit': 'Add Client',
})
db.app = jobaddservice.app
oauth_clients = Client.query.all()
client_id = oauth_clients[0].client_id
return client_id | 35,246 |
def get_payload(configs):
"""Common Xpaths were detected so try to consolidate them.
Parameter
---------
configs: list of {xpath: {name: value}} dicts
"""
# Number of updates are limited so try to consolidate into lists.
xpaths_cfg = []
first_key = set()
# Find first common keys for... | 35,247 |
def FPS(name, sort, explicit_name=None):
"""
Creates a floating-point symbol.
:param name: The name of the symbol
:param sort: The sort of the floating point
:param explicit_name: If False, an identifier is appended to the name to ensure uniqueness.
:return: ... | 35,248 |
def showCumulOverlap(mode, modes, *args, **kwargs):
"""Show cumulative overlap using :func:`~matplotlib.pyplot.plot`.
:arg modes: multiple modes
:type modes: :class:`.ModeSet`, :class:`.ANM`, :class:`.GNM`, :class:`.PCA`
"""
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLoc... | 35,249 |
def download(data_dir, yaml_path, overwrite=False):
"""Download the data files specified in YAML file to a directory.
Return false if the downloaded file or the local copy (if not overwrite) has a different checksum.
"""
sample_data = _loadYAML(yaml_path)
logger.info("Downloading data for %s", samp... | 35,250 |
def look_up_socrata_credentials() -> Tuple[str, str]:
"""Collect Socrata auth credentials from the local environment.
Looks up credentials under several common Socrata environment
variable names, and returns the first complete pair it finds. Raises
a MissingCredentialsError if no complete pair is found... | 35,251 |
def _calc_cat_outlier(df: dd.DataFrame, col_x: str, threshold: int = 1) -> Intermediate:
"""
calculate outliers based on the threshold for categorical values.
:param df: the input dataframe
:param col_x: the column of df (univariate outlier detection)
:return: dict(index: value) of outliers
"""
... | 35,252 |
def add_precursor_mz(spectrum_in: SpectrumType) -> SpectrumType:
"""Add precursor_mz to correct field and make it a float.
For missing precursor_mz field: check if there is "pepmass"" entry instead.
For string parsed as precursor_mz: convert to float.
"""
if spectrum_in is None:
return None... | 35,253 |
def echo_result(function):
"""Decorator that prints subcommand results correctly formatted.
:param function: Subcommand that returns a result from the API.
:type function: callable
:returns: Wrapped function that prints subcommand results
:rtype: callable
"""
@functools.wraps(function)
... | 35,254 |
def load_cifar10():
""" Load the CIFAR-10 dataset.
"""
def post(inputs, labels):
return inputs.astype(numpy.float32) / 255, labels.flatten().astype(numpy.int32)
return NumpySet.from_keras(tf.keras.datasets.cifar10.load_data, post=post) | 35,255 |
def parse_names(filename):
"""
Parse an NCBI names.dmp file.
"""
taxid_to_names = dict()
with xopen(filename, 'rt') as fp:
for n, line in enumerate(fp):
line = line.rstrip('\t|\n')
x = line.split('\t|\t')
taxid, name, uniqname, name_class = x
... | 35,256 |
def nancy(root_path, meta_file):
"""Normalizes the Nancy meta data file to TTS format"""
txt_file = os.path.join(root_path, meta_file)
items = []
with open(txt_file, 'r') as ttf:
for line in ttf:
id = line.split()[1]
text = line[line.find('"')+1:line.rfind('"')-1]
... | 35,257 |
def parse(pm, doc):
""" Parse one document using the given parsing model
:type pm: ParsingModel
:param pm: an well-trained parsing model
:type fedus: string
:param fedus: file name of an document (with segmented EDUs)
"""
pred_rst = pm.sr_parse(doc)
return pred_rst | 35,258 |
def two_sum(nums, target):
"""
Given an array of integers, return indices of the two numbers such that
they add up to a specific target.
You may assume that each input would have exactly one solution, and you
may not use the same element twice.
:type nums: List[int]
:type target: int
:... | 35,259 |
async def joined(ctx, member: guilded.Member):
"""Says when a member joined."""
print(dir(member))
await ctx.send('{0.name} joined in {0.joined_at}'.format(member)) | 35,260 |
def remove_columns(tx, header, columns_to_remove):
"""
Removes the given features from the given set of features.
Args:
tx: the numpy array representing the given set of features
header: the header line of the .csv representing the data set
columns_to_remove: The indices of the featu... | 35,261 |
def run_CEH(notebookDir, params_filename, ceh_options,
verbose=True):
""" Run the continuous enzymatic hydrolysis operation.
This function runs the CEH unit operation.
Through the ``ceh_options`` widgets, the user controls the following
values:
* DMR material prop... | 35,262 |
def vol_clear():
"""CLEAR VOLUME DISPENSED"""
cmd = (str(pump)+'CLDWDR\x0D').encode()
ser.write(cmd)
cmd = (str(pump)+'CLDINF\x0D').encode()
ser.write(cmd)
ser.readline() | 35,263 |
def pangenome(groups_file, fasta_list):
#creating the len_dict
"""
The len_dict is used to remember all of the common names and lengths of EVERY gene in each species, which are matched to the arbitrary name.
The len_dict is in form len_dict = {speciesA:{arb_name1:[com_name, length], arb_name2:[com_name,len... | 35,264 |
def argmin(x):
"""Deterministic argmin.
Different from torch.argmin, which may have undetermined result if the are
multiple elements equal to the min, this argmin is guaranteed to return the
index of the first element equal to the min in each row.
Args:
x (Tensor): only support rank-2 tens... | 35,265 |
def check_geometry_size(footprint):
"""
Excessive large geometries are problematic of AWS SQS (max size 256kb) and cause
performance issues becuase they are stored in plain text in the JSON
blob.
This func reads the geojson and applies a simple heuristic to reduce the
footprint size through si... | 35,266 |
def get_global_comments():
"""Returns all global comments"""
return GlobalComment.query.all() | 35,267 |
def job_complete_pr_status(job, do_status_update=True):
"""
Indicates that the job has completed.
This will update the CI status on the Git server and
try to add a comment.
"""
if job.event.cause == models.Event.PULL_REQUEST:
git_api = job.event.build_user.api()
if do_status_upda... | 35,268 |
def is_descending(path):
"""
Return ``True`` if this profile is a descending
profile.
"""
return _re_search(path, _re_descending) | 35,269 |
def mises_promo_gain_cote(cotes, mise_minimale, rang, output=False):
"""
Calcule la répartition des mises pour la promotion "gain en freebet de la cote gagnée"
"""
mis = []
gains = cotes[rang] * 0.77 + mise_minimale * cotes[rang]
for cote in cotes:
mis.append((gains / cote))
mis[rang... | 35,270 |
def recalculateResult(request, question_id):
"""Called when poll owner wants to recalculate result manually."""
question = get_object_or_404(Question, pk=question_id)
getPollWinner(question)
return HttpResponseRedirect(request.META.get('HTTP_REFERER')) | 35,271 |
def covden_win(cov_resampled, lut):
"""
Method to associate resampled vegitation coverage to PRMS covden_win
Parameters
----------
cov_resampled : np.ndarray
lut : dict
Returns
-------
gsflow.prms.ParameterRecord object
"""
covden = covden_sum(cov_resampl... | 35,272 |
def login_webauthn_route():
"""login webauthn route"""
user = User.query.filter(User.id == session.get('webauthn_login_user_id')).one_or_none()
if not user:
return login_manager.unauthorized()
form = WebauthnLoginForm()
if form.validate_on_submit():
try:
assertion = cbo... | 35,273 |
def generate_feature_matrix(genotypes, phenotypes, reg_type,phewas_cov=''): # diff - done
"""
Generates the feature matrix that will be used to run the regressions.
:param genotypes:
:param phenotypes:
:type genotypes:
:type phenotypes:
:returns:
:rtype:
"""
feature_matrix = np.zeros((3, genotypes.s... | 35,274 |
def import_journals(json_file: str, session: Session):
"""Fachada com passo a passo de processamento e carga de periódicos
em formato JSON para a base Kernel"""
try:
journals_as_json = reading.read_json_file(json_file)
journals_as_kernel = conversion.conversion_journals_to_kernel(
... | 35,275 |
def get_entity(db: SQLAlchemy, id: str) -> EntityOut:
"""Get and entity by id."""
db_session = db.session_class()
entry = repository.get_entity(db_session, id)
if not entry:
raise exc.NotFound()
return EntityOut(entry) | 35,276 |
def main(*args):
"""
Runs the Git trace extractor.
"""
parser = create_parser()
options = parser.parse_args()
try:
extractor = gitrace.TraceExtractor(options.outpath, header=options.header)
extractor.extract(options.repos, options.branch)
except Exception as e:
pars... | 35,277 |
def remove_low_confidence(confidence, data, target, feature_labels):
"""Remove data points with low confidence
Parameters
----------
confidence : float
Minimum confidence value
data : list
The data to be transformed
target : list
The labels for the data to be ... | 35,278 |
def cov(sources):
"""
Given the array of sources for all image patches, calculate the covariance
array between all modes.
Parameters
----------
sources : numpy array (floats)
The {NUM_MODES x NUM_PATCHES} array of sources.
Returns
-------
numpy array (floats)
The {N... | 35,279 |
def update_threat_intel_set(DetectorId=None, ThreatIntelSetId=None, Name=None, Location=None, Activate=None):
"""
Updates the ThreatIntelSet specified by the ThreatIntelSet ID.
See also: AWS API Documentation
Exceptions
:example: response = client.update_threat_intel_set(
DetectorI... | 35,280 |
def VerifierMiddleware(verifier):
"""Common wrapper for the authentication modules.
* Parses the request before passing it on to the authentication module.
* Sets 'pyoidc' cookie if authentication succeeds.
* Redirects the user to complete the authentication.
* Allows the user to ret... | 35,281 |
def hls_stream(hass, hass_client):
"""Create test fixture for creating an HLS client for a stream."""
async def create_client_for_stream(stream):
stream.ll_hls = True
http_client = await hass_client()
parsed_url = urlparse(stream.endpoint_url(HLS_PROVIDER))
return HlsClient(http... | 35,282 |
def AsinhNorm(a=0.1):
"""Custom Arcsinh Norm.
Parameters
----------
a : float, optional
Returns
-------
ImageNormalize
"""
return ImageNormalize(stretch=AsinhStretch(a=a)) | 35,283 |
def sub(x, y):
"""sub two numbers"""
return y-x | 35,284 |
def addSplashScreen(splashSDKName, decompileDir):
""" add splash screen
channel hasn't Splash if channel["bHasSplash"] = 0
otherwise channel["bHasSplash"] express orientation and color
"""
channelHasSplash ="0";
try:
#read has splash to funcellconfig.xml
config =... | 35,285 |
def load_batch(f_path, label_key='labels'):
"""Internal utility for parsing CIFAR data.
# Arguments
fpath: path the file to parse.
label_key: key for label data in the retrieve
dictionary.
# Returns
A tuple `(data, labels)`.
"""
with open(f_path, 'rb'... | 35,286 |
def get_k8s_helper(namespace=None, silent=False):
"""
:param silent: set to true if you're calling this function from a code that might run from remotely (outside of a
k8s cluster)
"""
global _k8s
if not _k8s:
_k8s = K8sHelper(namespace, silent=silent)
return _k8s | 35,287 |
def authenticate():
"""Authorize."""
return redirect(Vend().authenticate()) | 35,288 |
def non_device_name_convention(host):
"""
Helper filter function to filter hosts based targeting
host names which do NOT match a specified naming convention
Examples:
- lab-junos-08.tstt.dfjt.local
- dfjt-arista-22.prd.dfjt.local
- lab-nxos-001.lab.dfjt.local
:param host: T... | 35,289 |
def enable_accessify():
"""
Enabling the accessify.
"""
try:
del os.environ['DISABLE_ACCESSIFY']
except KeyError:
pass | 35,290 |
def recursive_swagger_spec(minimal_swagger_dict, node_spec):
"""
Return a swager_spec with a #/definitions/Node that is
recursive.
"""
minimal_swagger_dict['definitions']['Node'] = node_spec
return Spec(minimal_swagger_dict) | 35,291 |
def _get_base_parts(config):
"""
Builds the base ip array for the first N octets based on
supplied base or on the /N subnet mask in the cidr
"""
if 'base' in config:
parts = config.get('base').split('.')
else:
parts = []
if 'cidr' in config:
cidr = config['cidr']
... | 35,292 |
def diff_exp(counts, group1, group2):
"""Computes differential expression between group 1 and group 2
for each column in the dataframe counts.
Returns a dataframe of Z-scores and p-values."""
mean_diff = counts.loc[group1].mean() - counts.loc[group2].mean()
pooled_sd = np.sqrt(counts.loc[group1].va... | 35,293 |
def run():
"""
Run doba
:return:
"""
containers = get_containers()
required_handlers = get_required_handlers(containers)
preflight_data_handlers(required_handlers)
for container in containers:
backup(container) | 35,294 |
def load(source):
"""HTSフルコンテキストラベル(Sinsy用)を読み取る
source: path, lines
"""
song = HTSFullLabel()
return song.load(source) | 35,295 |
def _binary_clf_curve(y_true, y_score, pos_label=None):
"""Calculate true and false positives per binary classification threshold.
Parameters
----------
y_true : array, shape = [n_samples]
True targets of binary classification
y_score : array, shape = [n_samples]
Estimated probabil... | 35,296 |
def apply_config(config: Dict[str, Callable[[], None]]):
"""Apply curried config handlers."""
for prepped in config.values():
prepped() | 35,297 |
def term_open_failed(data=None):
"""
Construct a template for a term event
"""
tpl = term()
tpl.addKey(name='event', data="open-failed")
if data is not None:
tpl.addKey(name='data', data=data)
return tpl | 35,298 |
def create_error_payload(exception, message, endpoint_id):
"""
Creates an error payload to be send as a response in case of failure
"""
print(f'{exception}: {message}')
error_payload = {
'status': 'MESSAGE_NOT_SENT',
'endpointId': endpoint_id if endpoint_id else 'NO_ENDPOINT_ID',
'message': f'{ex... | 35,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.