content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def depair(z):
"""
Inverse of Cantor pairing function
"""
w = math.floor((math.sqrt(8 * z + 1) - 1) / 2)
t = (w**2 + w) / 2
y = int(z - t)
x = int(w - y)
return x, y | 92695c635ddbb60540d07e59ff1f495844e5e516 | 61,400 |
def _berkowitz_vector(M):
""" Run the Berkowitz algorithm and return a vector whose entries
are the coefficients of the characteristic polynomial of ``M``.
Given N x N matrix, efficiently compute
coefficients of characteristic polynomials of ``M``
without division in the ground doma... | c2cf5430c4ceeb6ff669f894264f71e1a4575208 | 61,401 |
def peppers():
"""Peppers.
Notes
-----
This image was downloaded from the Signal and Image Processing Institute at the
University of Southern California.
<http://sipi.usc.edu/database/database.php?volume=misc&image=11#top>
No known copyright restrictions, released into the public domain.
... | 60f3c8ac71432e77f12b69cd74e06a8d721f7b3f | 61,402 |
import socket
def get_gateway_socket(gateway):
"""Takes a gateway address string and returns a non-blocking UDP
socket to communicate with its NAT-PMP implementation on
NATPMP_PORT.
e.g. addr = get_gateway_socket('10.0.1.1')
"""
if not gateway:
raise NATPMPNetworkError... | 7b45cc2fa5b3dc54b08fcfc388f9547fa108e496 | 61,403 |
import os
def apply_warp(in_file, ref_file, field_file, output_dir, recalculate=False, **kwargs):
"""Wrapper for the Nipype FSL applywarp wrapper.
Please remember to set the kwarg interp='nn' if you are warping a file with discrete ROI's.
Args:
in_file: image to be warped
ref_file: the r... | 937d744b02ea992127084516fa1f335731c0b888 | 61,404 |
def get_lla_to_enu_R_matrix(lat, lng):
"""
Get a East, North, Up rotation matrix
Parameters
----------
lat : float, latitude in degrees [-90, 90]
lng : float, longitude in degrees [-180, 180]
h : float, height in meters
geoid : the ellipsoid model
Returns
-------
rotation_m... | 13089802ffed4cbe7a771930a6e086bcaf227464 | 61,405 |
from typing import List
def parse_sentence_to_word(sentence: str, stopwords: List[str]) -> List[str]:
"""read sentence, remove stopwords, and tokenize it into words"""
words = []
for word in jieba.cut(sentence):
if word not in stopwords and word != ' ':
words.append(word)
return words | 61c5d502a1c26eef4b5846376c0296b148977f86 | 61,406 |
def calc_likelihood(clazz, attribute_counts, test_data):
"""
Calculates total likelihood for all attributes in
test data according to attribute_count
"""
likelihoods = []
for idx in range(len(test_data)):
likelihoods.append(attribute_counts[idx][test_data[idx]] / len(clazz))
return ... | d0c392aebb3076c09730a21bfeb913eee98d0bff | 61,407 |
def break_after_nth_tick(ax, n, axis="x", occHeight=None, occWidth=None, where=0.5):
"""Visually break an axis x or y spine after the nth tick.
Places a white occluding box and black diagonals onto the axis.
Axis ticklabels must be changed manually.
Parameters
----------
ax : matplotlib.axis
... | d55cdb102a49eacb119e4f2a0df5682a7a2154e6 | 61,408 |
import os
def load_safety_model():
"""load the safety model"""
import autokeras as ak # pylint: disable=import-outside-toplevel
from tensorflow.keras.models import load_model # pylint: disable=import-outside-toplevel
from os.path import expanduser # pylint: disable=import-outside-toplevel
home... | da5163da45f96042104a033a391d6ecaa53922d9 | 61,409 |
import re
import os
def download_revealjs(
temp_folder=".",
unzip_to=".",
fLOG=print,
force_download=False,
location="https://github.com/hakimel/reveal.js/releases",
clean=True,
version=None):
"""
Download `reveal.js <https://github.com/hakimel/reveal.js... | 39d7bc7b7e814bc9379002aff133487d3f8f9eae | 61,410 |
import sys
def alert(msg, title=None, sub_msg=None, expanded=None, footer='',
ok=True, cancel=False, yes=False, no=False, retry=False,
warn_icon=True, options=None, exitscript=False):
"""Show a task dialog with given message.
Args:
msg (str): message to be displayed
title ... | 70752b1fe05c8ad71a1d78777e6a6b50855e34e4 | 61,411 |
def getisofill(Gfi_name_src='default'):
"""%s
:param Gfi_name_src: String name of an existing isofill VCS object
:type Gfi_name_src: `str`_
:returns: The specified isofill VCS object
:rtype: vcs.isofill.Gfi
"""
# Check to make sure the argument passed in is a STRING
if not isinstance(... | c9ed6433f02816e31cfc2754fd710ec8d326ecef | 61,412 |
def add_cell_annotations(adata, var_index):
""" This function adds annotation to anndata:
cell level:
total_counts, log10_total_counts, n_genes_detected, mito_frac, ribo_frac,
compl(exity)
gene_level:
n_cells
Arguments:
adata - anndata object, raw (unnormalized!)
... | 7fa6f8667715dae6c2571a27881c992f90f23553 | 61,413 |
def mean_image_subtraction(image, means):
"""Subtracts the given means from each image channel.
For example:
means = [123.68, 116.779, 103.939]
image = _mean_image_subtraction(image, means)
Note that the rank of `image` must be known.
Args:
image: a tensor of size [height, width, C] or [batch, heigh... | f95ed824c4925c4ef66c3a382014ca7812cd46e0 | 61,414 |
def apply_standard_scaler(dfs, scaler=None):
"""
apply sklearn standard scaler
"""
idx=pd.IndexSlice
multiindex_rolling_features= pd.MultiIndex.from_product((['measurement'], SURVEY_ROLLING_FEATURES+SURVEY_BASELINE_FEATURES+['weekofyear']*args.weekofyear))
# for item in multiindex_rolling_f... | 3a8b2dbf3dca49b7001201952ad764fb5a71cf3c | 61,415 |
def auto_correlation(mag, magerr):
"""The autocorrelation integral calculates the correlation of a given signal as a function of
the time delay of each measurement. Has been employed in previous research as a metric to
differentitate between lightcurve classes. See: (SIDRA: a blind algorithm for signal
... | d4fdb3cefa2d907ec381d382ba94d181f03c9b4f | 61,416 |
def generate_wiki_redirect_text(redirect_name: str) -> str:
"""Generate wikitext for redirect."""
return f'#REDIRECT [[{redirect_name}]]' | f6e55fa20004d836ea601a1d3966d070273df237 | 61,417 |
from typing import Union
def check_text_file(file_path: str, filename) -> Union[pd.DataFrame, str]:
"""Check user submitted results file."""
check_read_file = _read_text_file(file_path, filename)
# Check if file cannot be read and throw error
if isinstance(check_read_file, str):
return check_... | 0b2fd70def10b3f9ea92608a0c95c2184a39a018 | 61,418 |
import random
def calibrate_file(data_filename, output_level=2):
"""
Given an input file, calibrate it and return a new file.
Parameters
----------
data_filename: str
Fully specificied filename of the non-calibrated file (data level < 2)
output_level: int
The requested data le... | 777b5e38995de7cfb6448d2670b854e107e4a579 | 61,419 |
def _process_image_annotations(image):
"""Helper for processing annotation types from protobuf.
:type image: :class:`~google.cloud.grpc.vision.v1.image_annotator_pb2.\
AnnotateImageResponse`
:param image: ``AnnotateImageResponse`` from protobuf.
:rtype: dict
:returns: Dictionary p... | 942a8a414eeff48de1dbc4efc3d971ee029f23b0 | 61,420 |
def _chpi_locs_to_times_dig(chpi_locs):
"""Reformat chpi_locs as list of dig (dict)."""
dig = list()
for rrs, gofs in zip(*(chpi_locs[key] for key in ('rrs', 'gofs'))):
dig.append([{'r': rr, 'ident': idx, 'gof': gof,
'kind': FIFF.FIFFV_POINT_HPI,
'coord_fram... | 3fbbcdaee74eeb72a2c21bde0c11c3f491656ed1 | 61,421 |
import six
def flatten(nested_dict, separator="_", root_keys_to_ignore=set()):
"""
Flattens a dictionary with nested structure to a dictionary with no
hierarchy
Consider ignoring keys that you are not interested in to prevent
unnecessary processing
This is specially true for very deep objects
... | 5c011109bcd89449f0350528a908bcd0fcd6eb7d | 61,422 |
def generate_filtered_query(model, path, emitted_keys):
"""
Generate a query filtered on the primary key of the last model
in path.
:param model: A :ref:`declarative <sqla:declarative_toplevel>` class.
:param str path:
:param dict emitted_keys: A `dict` containing the key value
... | a3689bb4ef79db7bc7de02bf969f725191f417bd | 61,423 |
async def create_cart_button() -> InlineKeyboardButton:
"""Makes cart button."""
return InlineKeyboardButton(
text=emojize('🛒 Корзина'),
callback_data='go_to_cart',
) | 964e6b1ab55bdcb36d6072ff650bff8ec9453ed9 | 61,424 |
def entities_or_platform(obj):
"""Get entities, or platform if no entities."""
entity_ids = get_entity_ids(obj)
if entity_ids:
return entity_ids
return [obj[const.CONF_PLATFORM]] | 4917d6241cd317de59b0c457fdd52036279adaa0 | 61,425 |
import torch
def simulate(
num_time_steps,
num_regions,
num_strains,
*,
num_transit_covariates=4,
overdispersion=0.5,
transit_rate=1e-2,
mutation_rate=1e-2,
initial_infected=10,
min_total_infected=1000,
max_total_infected=10000,
case_rate=0.25,
death_rate=0.03,
... | 19d76a43419a6a61daaf96992b504e53dc4ec441 | 61,426 |
def dnnlib_shadow_submit_convert_path(txt):
"""Not sure what this really does, so just a no-op."""
return txt | 9a883453edeb6171386dca221557eead8f9058b2 | 61,427 |
def security_group_set(port):
"""
Returns the security group set for a port.
A security group set is a comma-separated,
sorted list of security group ids
"""
# There are 36 chars to a uuid, and in the description fits 255 chars
security_groups = sorted(port['security_groups'])
num_group... | d55930f85219b31cf7b68c4b3136c4a3edfbf1a2 | 61,428 |
import os
import warnings
def get_contour_file(path):
"""
Get contour file from a given path by searching for ROIContourSequence
inside dicom data structure.
More information on ROIContourSequence available here:
http://dicom.nema.org/medical/dicom/2016c/output/chtml/part03/sect_C.8.8.6.html
... | de382a91904e505f75504d2a27150d74c15d8d8c | 61,429 |
import importlib
import os
def attach(package_name, submodules=None, submod_attrs=None):
"""Attach lazily loaded submodules, functions, or other attributes.
Typically, modules import submodules and attributes as follows::
import mysubmodule
import anothersubmodule
from .foo import someatt... | a49427a22f2c56d371400dcbaeeb310d2d856691 | 61,430 |
def getcompression():
"""
Returns default compression filter.
"""
return NX_COMPRESSION | 938a060d5cd771f14c64eb2094ff8c3816e1b897 | 61,431 |
from datetime import datetime
def get_duration_and_dead_ratio(file_name):
"""Takes a log filename and extracts the amount of wasted core hours.
:returns: A tuple containing the sim duration, percent of time lost, number of cores with valid times and the time lost for each core"""
with open(file_name) as f... | 0a6e335a892b248669662861daa0719424076677 | 61,432 |
def make_request(address):
"""
Set the lat_long field, if the appropriate fields are filled
"""
geolocator = Nominatim()
try:
location = geolocator.geocode(address)
lat_long = {"type": "Point",
"coordinates": [location.longitude, location.latitude]}
except (Ge... | 1a74fdf10a812c72f6eddf4f2fa5b0c9079d01d0 | 61,433 |
import re
def read_html(htmlfile):
"""
Reads the HTML file to a string.
Removes some potential trouble makers.
"""
with open(htmlfile, "r") as infile:
html = infile.read()
# Clean out some unnecessary stuff
html = re.sub("<div class=\"wp-about-author.*?</div>", "", html, re... | bb0f724792cd817464a8720199ce7c7035e6b0f1 | 61,434 |
import os
def eqd_gsm_exclude(equery_dest=settings.equerypath, filesdir=settings.filesdir,
gsmv_fname="gsmv.txt", exclude_dpath=os.path.join("inst", "freeze_gsmv")):
""" eqd_gsm_exclude
Exclude GSM IDs from edirecty query objects
Arguments:
* gsmv_fname: Name of the file to load. Sho... | f89968bf66e4cbd7c8900e96cb90de064968a70b | 61,435 |
def customise_org_office_controller(**attr):
"""
Customise org_office controller
- Marker fn
"""
current.s3db.configure("org_office",
marker_fn = org_office_marker_fn,
)
return attr | f0cbfd9eacf4dd8d560129a52ce99e9f7d24cba7 | 61,436 |
def fdr_bh(fdr, p_values):
"""
Benjamini-Hochberg false-discovery rate adjustment procedure.
pdfs.semanticscholar.org/af6e/9cd1652b40e219b45402313ec6f4b5b3d96b.pdf
Parameters
----------
fdr : float
False Discovery Rate (q*), proportion of significant results that are
actually f... | d41bff53a9a0df9a16b9163361041465be653ec6 | 61,437 |
import json
def get_new_username():
"""提示用户输入名户名"""
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as file_object:
json.dump(username, file_object)
return username | 2d0f87131f551c135a229b48783886d533b81dd9 | 61,438 |
import re
def getCustomRead(alngt, compareList, readdic):
"""
Funtion which transforms an HTSeq alignment to a CustomRead class.
@type alngt: alignment
@param alngt: alignment from the sam file.
@type compareList: list
@param compareList: list which indicates differences between reference /... | 2c58db01d3a49a1753671b67ef448fc20238dfba | 61,439 |
import http
import tempfile
from pathlib import Path
import tarfile
import os
import json
import time
def create(config):
"""Create a Heroku server"""
# Connect to Heroku
connection = http.client.HTTPSConnection('api.heroku.com')
# Maybe install client
client_directory = reseval.CACHE / 'client'
... | 7ea3005828fcec49d5d975b1a682dc04cf053541 | 61,440 |
import random
def set_new_cherry_pos(snake_lst):
"""
Sets new cherry position.
:param snake_lst: List, containing all snake instances present in the game. This is needed
to check that cherry will not be placed onto a snake.
:type snake_lst: list of Snake
"""
new_cherry_... | 2a495a4e70635dc4722344d62bd29c893f15c43a | 61,441 |
def edit_description(request, pk):
"""
Edit the description attached to an action
:param request: AJAX request
:param pk: Action ID
:return: AJAX response
"""
# Try to get the workflow first
workflow = get_workflow(request)
if not workflow:
return JsonResponse({'form_is_val... | b5897e8730cb5369866b832110016cc4c9a07d1e | 61,442 |
import json
def newBatch(batchName, seq, org, pam, skipAlign=False):
""" obtain a batch ID and write seq/org/pam to their files.
Return batchId, position string and a 100bp-extended seq, if possible.
"""
batchId = makeTempBase(seq, org, pam, batchName)
if skipAlign:
chrom, start, end, stra... | da2d0f87e0716d34bd0c8e062cf1078b277138b3 | 61,443 |
def testconf_dict(testgrid) -> dict:
"""Returns a mock of the contents expected in `config.yml`."""
# Copy the base config
testconf = deepcopy(CONFIG_BASE)
testconf["path"] = TEST_HEROGRID_PATH
return testconf | cd6e7f010a3b1c8658bc8837c36b42336a5abe85 | 61,444 |
def se_block(input_feature, name, ratio=8):
"""Contains the implementation of Squeeze-and-Excitation block.
As described in https://arxiv.org/abs/1709.01507.
"""
kernel_initializer = tf.contrib.layers.variance_scaling_initializer()
bias_initializer = tf.constant_initializer(value=0.0)
with tf.variable_sco... | 86bb1b205aa52e637097a0bc1ebc3482d87959a0 | 61,445 |
def showfiles(**args):
"""List of strings. All files modified, added, or removed by this
changeset.
"""
return showlist('file', args['ctx'].files(), **args) | 1d49591d32b7709a3704f272639dc6dca1237301 | 61,446 |
def vtk_version_ok(major, minor, build):
"""
Check the VTK version.
:param major: Major version.
:param minor: Minor version.
:param build: Build version.
:return: True if the requested VTK version is greater or equal to the actual VTK version.
"""
needed_version = 10000000000 * int(maj... | cb760ee01d143aa0be2da53210b60a433fa05320 | 61,447 |
def _parabola(data):
"""
Makes a parabola that fits the input data at the two endpoints.
Used in the beads calculation so that ``data - _parabola(data)`` is close
to 0 on the two endpoints, which gives better fits for beads.
Parameters
----------
data : array-like, shape (N,)
The d... | e40f42cbd79f69b33047c67d58332658ec0e643c | 61,448 |
def get_values_cont_x_no_numba(data_vector, no_of_evalupoints):
"""Get cut-off points for tree splitting for continuous variables.
No longer used; only kept if no_numba version would be needed
Parameters
----------
sorted_data : Numpy-1D array. Sorted vector
no_of_evalupoints : Int. c_dic... | 2b99d5274a8a9b432b47ff1dc20db88cad0d9338 | 61,449 |
def get_population():
"""Get a dummy population with minimal configuration."""
cfg = Config()
cfg.game.duration = 1 # Small duration
cfg.game.fps = 10 # Games of low accuracy but faster
cfg.genome.rnn_prob_gru_nr = 0
cfg.genome.rnn_prob_gru_nu = 0
cfg.genome.rnn_prob_gru = 0
cfg.genome... | 15604241ae2c29a0be21c781ccab53b299683c72 | 61,450 |
def adjacency_ba(tfr_dfs):
"""A stub transform function."""
return tfr_dfs | 53212b83e590cd83358a67e5b05cc4de67474107 | 61,451 |
def run_required(func):
"""A wrapper to check that the simulation has been run before a method can be executed"""
@wraps(func)
def _run_required(*args, **kwargs):
"""Check that the 'tso' attribute is not None"""
if args[0].tso_order1_ideal is None:
print("No simulation found! Ple... | 27fcfac0769e11eee34c203746e45342508fc01a | 61,452 |
from typing import cast
import os
def read_ascents(dirname: str) -> _AscentsTable:
"""Read the ascents table."""
reader = TableReader(
[
("route", int, None),
("clean", float, None),
("page", int, None),
("style_page", int, -1),
]
)
retur... | 469d498dd3902638c5fc8e082bbb0fcbd5bf923d | 61,453 |
def detect_hotdog(image_bytes):
""" Checks image for hotdog label using Amazon Rekoginition's object and scene detection deep learning feature.
Args:
image_bytes (bytes): Blob of image bytes.
Returns:
(boolean)
True if object and scene detection finds hotdog in blob of image bytes.... | 1edabb803bc4bf357c97593394e590a83a4de017 | 61,454 |
import time
def get_datetime():
"""Return the current datetime in a database compatible format"""
return time.strftime('%Y-%m-%d %H:%M:%S') | 804166ac7f56899733043871ea5ec9fcce474ee7 | 61,455 |
def im_detect_keypoints_aug(model, im, boxes):
"""Computes keypoint predictions with test-time augmentations.
Arguments:
model (DetectionModelHelper): the detection model to use
im (ndarray): BGR image to test
boxes (ndarray): R x 4 array of bounding boxes
Returns:
heatmaps... | d000adb64c3b921340d1b4d9aca5407ca34ca23d | 61,456 |
import numpy as np
import scipy
import torch
from torch.autograd import Variable
import sklearn
def get_data(audio, eeg, audio_unatt=None, idx_eeg=None, num_batch=None, idx_sample=None, num_context=1, num_predict=1, dct_params=None):
"""Select a sequence of audio, audio_unattnd, and eeg data
Reshape the ... | 3d684d4e2e984b8da6662a52a7746997c9a7d224 | 61,457 |
def parse_data_loader(dataloader_cfg, dataset):
"""
:param dataloader_cfg: config dict
:param dataset: torch.utils.data.Dataset
:return: torch.utils.data.DataLoader
"""
data_loader = DataLoader(
dataset,
batch_size=dataloader_cfg.get("batch-size"),
shuffle=dataloader_cfg.... | e600d9361333a66d2f1b4638cd14156039dc19f3 | 61,458 |
import wget
def read_first_line(file):
"""Gets the first line from a file.
Returns
-------
str
the first line text of the input file
"""
with open(file, 'rt',encoding="utf-8") as fd:
first_line = fd.readline()
f = open(file, 'r',encoding="utf-8") # 開啟並讀取檔案
lines =... | 20fa4bc413d22011180c02624f1edc5e7b094fbc | 61,459 |
def sort_key(doc):
"""helper function - sort by 'sider.side_effect.frequency' """
# take the first element from the document
default_value = -101
s = next(key_value(doc, "side_effect.frequency"))
n = str(next(key_value(doc, "side_effect.name")))
# if no element then return default value, name
... | 685b5d45be00c7157f507f9c43770082bdb56e69 | 61,460 |
def delete(**_):
"""Delete a virtual network.
:param ctx: The Cloudify ctx context.
:return: The status code of the REST request.
:rtype: int
"""
utils.validate_node_property(constants.VIRTUAL_NETWORK_KEY, ctx.node.properties)
utils.validate_node_property(constants.DELETABLE_KEY, ctx.node.p... | 5a61deb7da3493e40455d456af769742017ded24 | 61,461 |
def bSearch(arr, target, start=0, end=-1):
"""
-- BINARY SEARCH --
if target is not in arr, the opposite number of the
first number's index larger than target will return
"""
if not arr:
return None
if end == -1:
end = len(arr) - 1
if end < start:
raise Exception(... | f38413b6097df35c942faff2fa3c1850f6202f39 | 61,462 |
import inspect
def expand_lambda_function(lambda_func):
"""
Returns a lambda function after expansion.
"""
lambda_function = inspect.getsource(lambda_func).split(",")[1].strip()
if lambda_function.endswith(")"):
return lambda_function[:-1]
return lambda_function | 7076ce6bdee4077f6cbf665d686cd28c2420d67e | 61,463 |
def _softplus(x):
"""A nice softplus.
This is a monotonous function that is equivalent to x at +inf and
-1 / (3PI x^2) at -inf. To prove this, use two facts:
1. For negative x, atan(x) = -PI/2 - artan(1/x)
2. Near 0, atan(x) = x - x^3/3 + O(x^5)
From these two things, you can deduce that as x -> -inf:
... | 843a7b35405aa48589b3ae886ff94b632ad6d056 | 61,464 |
import os
def extract_anchor_intervals(bams,
references,
known_transposons,
insert_size,
quality=0):
"""
Extract 'anchor' read inserts from one or more bam files
Anchor reads are paired rea... | ff9575a41fae88f467807c20ae52278a4b7c9e54 | 61,465 |
def utf8tounicode(arg):
"""Convert UTF8-encoded bytes to strings.
Only in Python 2. In Python 3 the errors are returned as strings.
"""
if PY2 and isinstance(arg, binary_type):
return arg.decode('utf-8')
return arg | ab69d98b088408e57e65d6886ee27b5393f86ad2 | 61,466 |
def get_bucket_usage(namespace, workspace):
"""Request google bucket usage for workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
Swagger:
https://api.firecloud.org/#!/Workspaces/getBucketUsage
"""
uri = "workspaces/{0}/{1}/... | ab059652e4c68f4538a6d97310eae92cf00efe73 | 61,467 |
def base2vectors(sbparams,cbparams,fbparams):
""" converts dictionary of base parameters to vector of parameters and then to pygom simulation parameters"""
global C_2s # scaling factor for c_2 (1000) to allow c_2 parameter to be same order of magnitude as other parameters
Exposure =sbparams['Exposure']
... | dbc277bac43bd04da09b8debb77556698e032a2f | 61,468 |
def inter_dists(sifts_result_i, sifts_result_j, structures=None,
atom_filter=None, intersect=False, output_prefix=None,
model=0, raise_missing=True):
"""
Compute inter-chain distances (between different entities)
in PDB file. Resulting distance map is typically not
symmet... | e6b809d0c4afe221b9e01729edb15f2147a1f32f | 61,469 |
def handle_400(e):
"""捕获abort(400)错误"""
rsp = {
'msg': 'Bad Request',
'err': 10
}
if isinstance(e.description, int):
rsp['err'] = e.description
if isinstance(e.description, dict):
rsp.update(e.description)
return jsonify(**rsp), 400 | 0e522eac390c211b1bed017631f6f62926fdcb5a | 61,470 |
def plugin_list(parser, options, args=None):
""" List github/external/built-in plugins. """
if args:
print_sub_help(parser, 'list')
return -1
# Requires Internet to access github.
if options.github: # pragma no cover
_list_github_plugins()
return 0
groups =... | 1c45126664d747403d172f22f641b0ca67862136 | 61,471 |
def dialog_open(starting_directory="", title="Open file", file_filter="All Files (*.*)"):
"""
Simple open dialog in Maya
Args:
starting_directory (unicode): Starting directory. (default: project root directory)
title (unicode): Dialog title. (default: "Open file")
file_filter (unicod... | db4f732c11e375ceebebc2f9ed546a59862e3c44 | 61,472 |
def get_messages():
"""
:return: all messages stored in database
"""
db = DataBase()
msgs = db.get_all_messages(MSG_LIMIT)
messages = remove_seconds_from_messages(msgs)
return jsonify(messages) | 04c5f052e8954204ead96f62bf96ef81ae80d4bf | 61,473 |
def key_matrix(rows, cols):
"""
first index is columns (so slightly backward from math)
:param rows:
:param cols:
:return:
"""
rv = [None] * cols
for i in range(0, cols):
rv[i] = key_vector(rows)
return rv | 9331c4a029df31c076e73809ac3ca892f662a791 | 61,474 |
def next_marker(xml_node, remaining_markers):
"""Try to determine the marker following the current xml_node. Remaining
markers is a list of other marks *within* the xml_node. May return
None"""
# More markers in this xml node
if remaining_markers:
return remaining_markers[0][0]
# Ch... | 4f9f28c14b24218ca46a07ffbf2cd5f292c76a2b | 61,475 |
def renumber_nodes(G, start=1):
"""Renumber nodes so that NeuronLand converter does not mess up.
Returns: (new_graph, node_map)
node_graph: a new DiGraph with the nodes numbered by bfs sequence.
node_map: dict mapping node number in G to that in node_graph
"""
ret = nx.DiGraph()
node_map... | 727d918882e398de70bdaa81517ac7b7dbad1915 | 61,476 |
def get_dict_from_params_str(params_str):
"""Get the dictionary of kv pairs in a string separated
by semi-colon."""
if params_str:
kvs = params_str.split(";")
params_dict = {}
for kv in kvs:
k, v = kv.strip().split("=")
params_dict[k] = eval(v)
return ... | 611f80b55c090ff5aa6afa78ee4b1b5db074cab0 | 61,477 |
def get_item_keyphrase_freq(keyphrase_freq,item):
"""
Get item's keyphrase frequency
"""
try:
count = keyphrase_freq[item].todense()
except:
count = keyphrase_freq[item]
return np.ravel(count/(np.sum(count)+0.001)) | ed91d3df2f4b112bd8e02d6f7bde245176639da3 | 61,478 |
def admin(func):
"""Require admin rights."""
def wrap(self, message, *args, **kwargs):
if message.source in self.session.admins:
return func(self, message, *args, **kwargs)
return message.dispatch("Sorry, you are not authorized to do that.")
wrap.__doc__ = func.__doc__
wrap.... | 78f8d0d3dab4b2c100ae51a4fd776f70b6fd3eda | 61,479 |
from datetime import datetime
def parse_timedelta(
delta,
min=None,
max=None,
min_included=True,
max_included=True,
):
"""
Parse time delta
"""
if isinstance(delta, str) and len(delta) > 0:
unit = delta[-1]
if unit in '0123456789':
unit = 's'
... | cb641166cb45eac781de13a20123c22990955edb | 61,480 |
def normalize(x_i):
"""
Normalize the vector
"""
min_i = tf.math.reduce_min(x_i)
max_i = tf.math.reduce_max(x_i)
x_i_normalized = (x_i - min_i) / (max_i - min_i)
return x_i_normalized | 2a3f9c98a5ae12b065259f67f5b7f1273f97ec84 | 61,481 |
def hmerge(dataset_left, dataset_right, on=None, left_on=None, right_on=None,
overwrite_text=False, from_set=None, merge_existing=None, verbose=True):
"""
Merge Quantipy datasets together using an index-wise identifer.
This function merges two Quantipy datasets (meta and data) together,
upda... | 34449f825742a6d84eefe1bfa25bfc55e6df4d20 | 61,482 |
def train_test_folds(features, labels_binary, cv_iterator, model_factory):
"""
Creates and trains an XGBoost model instance per fold from the feature matrix.
Train and test metrics are printed per fold.
The mean and std of the ROC AUC is printed at the end.
Returns all the trained models.
Argum... | 29fcd87eb1e36dbe81bdfba0e7d8d2e7a3df62ed | 61,483 |
def getSimScenarioFile(simId):
"""
Returns the path to sim's copy of the scenarios.xml file.
"""
return getSimXmlFile(simId, ScenarioFileName) | 4749ba1d4fde365d7be11b58c037b05342df5000 | 61,484 |
def bunchify(dict_tree):
"""
Traverses a dictionary tree and converts all sub-dictionaries to Bunch() objects.
"""
for k,v in dict_tree.iteritems():
if type(v) == type({}):
dict_tree[k] = bunchify(dict_tree[k])
return Bunch(dict_tree) | 3f7997f7b707ba0cf8099d06189b09f5b55df3c6 | 61,485 |
def bot(message):
"""Mocked instance of the bot"""
class Bot:
send_message = MagicMock()
return Bot() | d74c459bcbdc757017fb9ce34192875fc8d9721c | 61,486 |
from typing import Callable
from typing import Any
from typing import Optional
from typing import List
def run_simulation(
process: iterative_process.IterativeProcess,
client_selection_fn: Callable[[int], Any],
total_rounds: int,
file_checkpoint_manager: Optional[FileCheckpointManager] = None,
met... | 1913504613bda298cb099c9048b1a24ef63f5e51 | 61,487 |
import torch
def unique_first(x):
""" Torch function to get the first appearance unique items"""
unique, inverse = torch.unique(x, sorted=True, return_inverse=True)
perm = torch.arange(inverse.size(0), dtype=inverse.dtype, device=inverse.device)
inverse, perm = inverse.flip([0]), perm.flip([0])
pe... | f38fd73fddeec9a4ad220a40ae6c27cdc58097e3 | 61,488 |
def make_generator():
"""Creates a generator model that takes a 100-dimensional noise vector as a "seed", and outputs images
of size 28x28x1."""
model = Sequential()
model.add(Dense(1024, input_dim=100))
model.add(LeakyReLU())
model.add(Dense(128 * 7 * 7))
model.add(BatchNormalization())
... | 6cd56499c02500981a62f1ecb27f21506358488d | 61,489 |
from typing import List
def delete_policies(system_id: str, subject_type: str, subject_id: str, policy_ids: List[int]) -> None:
"""
删除权限
"""
url_path = "/api/v1/web/policies"
data = {"system_id": system_id, "subject_type": subject_type, "subject_id": subject_id, "ids": policy_ids}
permission_l... | a4827db7a4ebbd0470395c7d0240c333cd62d334 | 61,490 |
def WENOReconstruct( u_stencil, eps, p ):
"""WENO reconstruction. This reconstructs u_{i+1/2}
given cell averages \\bar{u}_i at each neighboring location.
See `High Order Weighted Essentially Nonoscillatory Schemes for
Convection Dominated Problems'.
Input
-----
u_stencil :
... | aa49be7b069f09c90c9b350d86575376eb5c9fbb | 61,491 |
def import_airfoil_polars(airfoil_polar_files):
"""This imports airfoil polars from a text file output from XFOIL or Airfoiltools.com
Assumptions:
Input airfoil polars file is obtained from XFOIL or from Airfoiltools.com
Source:
http://airfoiltools.com/
Inputs:
airfoil polar files ... | 1be5432bc5bbde5767c5591cbb06146f09547d90 | 61,492 |
from typing import List
def _get_representative_years(df_temp: pd.DataFrame, FS: pd.DataFrame) -> List[int]:
"""
Args:
df_temp(pd.DataFrame):
FS:
Returns:
List[int]: 月別の代表的な年
"""
df_threshold = pd.merge(df_temp, FS, on=['y', 'm'], suffixes=['_mean', '_fs']).sort_values(["m", ... | b0fb063fae3455dba28872575a87a8980f09b260 | 61,493 |
from toil.batchSystems.mesos.batchSystem import MesosBatchSystem
def loadBatchSystemClass(config):
"""
Returns a pair containing the concrete batch system class and a dictionary of keyword arguments to be passed to
the constructor of that class.
:param config: the current configuration
:param key... | c0e449fa0275b74559cf9a0bb8fa5b83fc034382 | 61,494 |
import warnings
def convert_feature_vector_to_time_series(feature_vector, sample_data):
""" Parse the feature name and reconstruct a time series object holding the equivalent data
In a feature vector object, a feature is determined by the feature
name and the feature value. When dealing with time do... | 1fd02054fb1d94bb2cf8fe38283b3bf0167dbbcd | 61,495 |
def _load_tpr(self, element):
"""Implement the gromacs.load_tpr operation.
Updates the minimum width of the workflow parallelism. Does not add any API object to the graph.
Arguments:
self: The Context in which this operation is being loaded.
element: WorkElement specifying the operation.
... | 30f5c1d72fd114fc3b6521b1053c3dcfab7a5606 | 61,496 |
import inspect
def generate_cache_key(namespace, f, *args, **kwargs):
"""Generates a string key, based on a given function
as well as arguments to the returned function itself.
"""
argspec = inspect.getargspec(f)
has_self = bool(argspec[0]) and argspec[0][0] in ('self', 'cls')
if has_self:
... | b9f69980784560989d9c40426f091332f032eba9 | 61,497 |
import inspect
import os
def importAbove(pyFileName, star=False, mode="", cwd=False, startAbove=False):
"""Import a python file from here or some directory above.
This function examines the current module's directory, its parent directory
and the parent's parent directory, etc., until the named python fi... | 1a277625ad34e66f624a1a342c26b443606a2832 | 61,498 |
def total_error(y_true, y_pred):
"""
I think this is simply the variance, but as a sum...
"""
return K.sum(K.square(y_true - K.mean(y_true))) | 5364239bf16be7603149d45f09663fd9a651f454 | 61,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.