content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def loadings_histograms(
pca, feature_labels, n_components='all', bins=50,
n_features_to_label=10, max_text_len=35,
text_kws={'color': 'white',
'bbox': {'facecolor': 'k', 'alpha': 0.7, 'pad': 1}},
save_fig=None):
"""Plot histograms of the loadings for each principal... | 5,292,400 |
def test_delete_project():
"""Test command delete project with mocked response."""
command = [
'delete-project',
'--project', '1',
'--apikey', 'secretAPI',
]
runner = CliRunner()
with mock.patch('anonlinkclient.cli.create_rest_client', side_effect=create_rest_client_response)... | 5,292,401 |
def password_string(value):
"""密码输入类型"""
if len(value) < 8 or len(value) > 20 or re.match(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$', value) is None:
raise ValueError('密码至少包含 数字和英文,长度6-20,不能出现非法字符')
return value | 5,292,402 |
def get_axes_texts(img, axis_entities):
"""The function for getting the texts in the axis"""
try:
data = []
# No axes in the image
if img is None or axis_entities is None:
return data
(img_height, img_width) = img.shape[:2]
for axis_id, axis_entity in enumerat... | 5,292,403 |
def mixture_component_selection_embedding_(subset_embeds: typing.Mapping[str, Tensor], s_key: str, flags,
weight_joint: bool = True) -> Tensor:
"""
For each element in batch select an expert from subset.
subset_embeds: embeddings of each subset.
s_key: keys of ... | 5,292,404 |
def set_logging_level(level):
"""Convenince function to set level for the root and package logger."""
if isinstance(level, str):
level = getattr(py_logging, level.upper())
py_logging.root.setLevel(level)
logger = getLogger()
logger.setLevel(level) | 5,292,405 |
def xdoctest(session: Session) -> None:
"""Run examples with xdoctest."""
args = session.posargs or ["all"]
# install modern_python_setup, as both xdoctest & example need it
session.run("poetry", "install", "--no-dev", external=True)
install_with_constraints(session, "xdoctest")
session.run("pyt... | 5,292,406 |
def rle_printer(counts):
"""Compare pairs and print"""
pair_counts = []
for pair in counts:
if pair[1] == 1:
pair[1] = ''
pair_counts.append(''.join(map(str, pair)))
print(''.join(map(str, pair_counts))) | 5,292,407 |
def build_engine(onnx_file_path, engine_file_path, mode='fp32', verbose=False):
"""Takes an ONNX file and creates a TensorRT engine."""
TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE) if verbose else trt.Logger()
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(*EXPLICIT_BATCH) as network, trt.On... | 5,292,408 |
def filter_same_smiles(dset):
"""
Filter out species whose conformers don't all have the same SMILES. Can happen
because, for example, CREST simulations can be reactive. This won't happen if
conformers are generated using RDKit.
Args:
dset (nff.data.dataset): NFF dataset
Returns:
... | 5,292,409 |
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
# setup command line parser
parser = E.OptionParser(version="%prog version: $Id$",
usage=globals()["__doc__"])
par... | 5,292,410 |
def retry_integration_events(obj, pretty_print, beep,
headers,
payload,
active_validation):
"""Allows retry of multiple failed ITSM event instances. The retry request payload can be given as a list of strings: ["instance1","insta... | 5,292,411 |
def user_popup(request):
"""/user_popup - Pop up to show the user info."""
try:
return _user_popup(request)
except Exception as err:
logging.exception('Exception in user_popup processing:')
# Return HttpResponse because the JS part expects a 200 status code.
return HttpHtmlResponse(
'<font... | 5,292,412 |
def tokenize_word(text,
normalise_case=True,
keep_numerics=False,
shortwords=3,
remove_stopwords=True,
lemmatize=True,
gaps=False,
addl_stopwords=[]):
"""
Tokenisation function, accepts ... | 5,292,413 |
def read_video(fname):
"""
Parameters
----------
fname
Returns
-------
"""
cap = cv2.VideoCapture(fname)
frames = []
it = 0
while True:
retval, image = cap.read()
if image is not None:
frames.append(image)
it += 1
if no... | 5,292,414 |
def build_bankruptcy_definition(years):
"""Build a bankruptcy definition
Notes:
This function is set according to a line of best fit from Year 0 at -10% ROI to 10% ROI by Year 7.
Args:
years (int): No. of years for analysis
Returns:
Bankruptcy definitio... | 5,292,415 |
def run_pylint(source, msg_ids, *cmd_args):
"""Run pylint on some source, collecting specific messages.
`source` is the literal text of the program to check. It is
dedented and written to a temp file for pylint to read.
`msg_ids` is a comma-separated string of msgids we are interested
in. Use "al... | 5,292,416 |
def resting_datagrab(c,name="resting_datagrabber"):
"""Returns a datagrabber nipype node. The datagrabber looks for the following files:
* reg_file : bbregister file
* mean_image : mean image after motion correction
* mask : mask image
* func : functional output of preprocessing
.. admonition:: Warning
This f... | 5,292,417 |
def choice_demo():
"""从一个序列中获取一个随机元素"""
a = random.choice([0, 1, "a"])
print(a, type(a)) | 5,292,418 |
def test_exclude(tmpdir, qitest_action):
""" Test Exclude """
tests = [
{"name": "foo", "cmd": [sys.executable, "--version"]},
{"name": "bar", "cmd": [sys.executable, "-c", "import sys ; sys.exit(1)"]}
]
qitest_json = tmpdir.join("qitest.json")
qitest_json.write(json.dumps(tests))
... | 5,292,419 |
def create_and_train(data_folder,
training_subfolder = '/train/',
validation_subfolder = '/valid/',
batch_size = 64,
arch = 'densenet121', hidden_units = [], dropout = 0, bn = False,
epochs = 10, learning_rate = 0.... | 5,292,420 |
def compute_rot_scale_skew(lazAC, i=0, scaleFactor=1.):
"""
same as displayRotScaleSkew but without text output
"""
xshift = lazAC.Alm[i, 0] * scaleFactor
yshift = lazAC.Alm[i, lazAC.Nalm] * scaleFactor
if lazAC.k > 2:
idx_forXterm = np.where(lazAC.polynomialTermOrder == 'x')[0]
... | 5,292,421 |
def readsav(file_name, idict=None, python_dict=False,
uncompressed_file_name=None, verbose=False):
"""
Read an IDL .sav file
Parameters
----------
file_name : str
Name of the IDL save file.
idict : dict, optional
Dictionary in which to insert .sav file variables
... | 5,292,422 |
def top_results_overall(databases= 'all', n_entries= 10):
"""
Creates a table summarizing the overall performances
Args:
databases (str): 'all'/'high_ir'/'low_ir'/'high_n_min'/'low_n_min'/'high_n_attr'/'low_n_attr'
n_entries (int): number of entries to show
"""
results= pickle.load(o... | 5,292,423 |
def clean_data(data):
"""
Clean data from Kobo
:param data: Pandas DataFrame containing data from Kobo
:return: Pandas DataFrame
"""
# Remove unnecessary columns
drop_cols = ['subscriberid', 'deviceid', '_uuid', '_submission_time', '_validation_status', '_id', 'start', 'end',
... | 5,292,424 |
def ignore_sparse_panel_future_warning(func):
"""
decorator to ignore FutureWarning if we have a SparsePanel
can be removed when SparsePanel is fully removed
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
if isinstance(self.panel, SparsePanel):
with assert_produces_w... | 5,292,425 |
def test_mahon_calculate_with_ci_setup():
"""Assure setup and some sanity checks."""
bins = 10
reg = Mahon()
reg.calculate_with_ci(
MAHON_XDAT, MAHON_YDAT, MAHON_XDAT_UNC, MAHON_YDAT_UNC, bins=bins
)
assert reg.ci_yax_pos is not None
assert reg.ci_yax_neg is not None
ci_xax_expe... | 5,292,426 |
def join_report_files(annotations_path):
"""Joins the seven report files generated by the IHP tool (see docstring from divided_directory) in one final report file
:param annotations_path: per directory annotations path
:return: file with joined report files
"""
final_report = open(annotations_path... | 5,292,427 |
async def test_update_system_data_v3(
event_loop, v3_server, v3_sensors_json, v3_subscriptions_json):
"""Test getting updated data for a v3 system."""
async with v3_server:
v3_server.add(
'api.simplisafe.com',
'/v1/users/{0}/subscriptions'.format(TEST_USER_ID), 'get',
... | 5,292,428 |
def bad_unpacking():
""" one return isn't unpackable """
if True:
return None
return [1, 2] | 5,292,429 |
def build_slices_from_list_of_arrays(list_of_arrays, n_his, n_feat, verbose=0):
"""
This function creates a list of slices of shape (n_his + 1, n_feat)
"""
assert list_of_arrays[0].shape[1] == n_feat, "list_of_arrays[0].shape[1]={} but n_feat={}".format( list_of_arrays[0].shape[1], n_feat)
X_sl... | 5,292,430 |
def eval_tracks(
path_tracker_output: str,
path_dataset: _PathLike,
d_min: float,
d_max: float,
out_file: TextIO,
centroid_method: str,
) -> None:
"""Evaluate tracking output.
Args:
path_tracker_output: path to tracker output
path_dataset: path to dataset
d_min: ... | 5,292,431 |
def most_similar(text, topn=10):
"""检索最相近的topn个句子
"""
token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen)
vec = encoder.predict([[token_ids], [segment_ids]])[0]
vec /= (vec**2).sum()**0.5
sims = np.dot(a_vecs, vec)
return [(kkk_all[i], sims[i]) for i in sims.argsort()[::-1][:topn]... | 5,292,432 |
def orient_by_rois(streamlines, roi1, roi2, in_place=False,
as_generator=False, affine=None):
"""Orient a set of streamlines according to a pair of ROIs
Parameters
----------
streamlines : list or generator
List or generator of 2d arrays of 3d coordinates. Each array contains... | 5,292,433 |
def luhn_checksum(check_number):
"""http://en.wikipedia.org/wiki/Luhn_algorithm ."""
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(check_number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = 0
checksum += sum(odd_digits)
for d in even_... | 5,292,434 |
def _data_api():
"""Returns a Data API.
This relies on Django settings to find the appropriate data API.
"""
# We retrieve the settings in-line here (rather than using the
# top-level constant), so that @override_settings will work
# in the test suite.
api_path = getattr(settings, "ENROLLME... | 5,292,435 |
def setup_log_file_handler(config, logfile, fmt):
"""Setup file debug logging."""
log_file_path = os.path.join(config.logs_dir, logfile)
try:
handler = logging.handlers.RotatingFileHandler(
log_file_path, maxBytes=2 ** 20, backupCount=1000)
except IOError as error:
raise erro... | 5,292,436 |
def get_system_log_queue():
"""
Json格式为:
{'alias':'w01'
'host':'192.168.1.100'
'timestamp':123213123
'type': 'reboot' or 'shutdown' or 'power' 三个值中其中一个
}
"""
system__log_queue ='ztq:queue:system_log'
return get_limit_queue(system__log_queue, 200) | 5,292,437 |
def remove_directory(dir_to_remove):
""" :param dir_to_remove: Directory to remove from system. """
if os.path.exists(dir_to_remove):
print(script_tab + "Removing directory %s" % dir_to_remove)
shutil.rmtree(dir_to_remove)
else:
print(script_tab + "Directory %s was not found." % dir_... | 5,292,438 |
def blockchain_timeframe_summary(final_df, config) -> dict:
"""
Get summary statistics
:param final_df: The full dataframe of address information from the blockchain
:param config: configuration file for including start/end times in output dataframe
"""
print("Getting summary counts of... | 5,292,439 |
def test_device_method_from_module_to_leaf_device_fi():
"""
invoke a method call from the test module and respond to it from the leaf device
"""
module_client = connections.connect_test_module_client()
leaf_device_client = connections.connect_leaf_device_client()
do_device_method_call(
... | 5,292,440 |
def user_has_custom_top_menu(domain_name, couch_user):
"""
This is currently used for a one-off custom case (ewsghana, ilsgateway)
that required to be a toggle instead of a custom domain module setting
"""
return (toggles.CUSTOM_MENU_BAR.enabled(domain_name) and
not couch_user.is_superus... | 5,292,441 |
def b2x(b):
"""Convert bytes to a hex string"""
return binascii.hexlify(b).decode('utf8') | 5,292,442 |
def get_size_k_subgraphs(graph, min_region_count, k=1, keep_grammars=[]):
"""for size k, get all unique subgraphs
"""
total = 0
subgraphs = []
current_subgraph_len = 0
for node_subset in itertools.combinations(graph, k):
subgraph = graph.subgraph(node_subset)
# check if all conn... | 5,292,443 |
def test_set_time_step():
"""
Test the function `Monolayer.set_time_step` in monolayer.py
"""
x = OS_model.Monolayer()
assert x.time_step == 0.005
x.set_time_step(10)
assert x.time_step == 10 | 5,292,444 |
def list_to_blackbird(A, var_name):
"""Converts a Python nested list to a Blackbird script array type.
Args:
A (list[list]): 2-dimensional nested list
var_name (str): the array variable name
Returns:
list[str]: list containing each line representing the
Blackbird array ... | 5,292,445 |
def CreateOptim(parameters, lr=0.001, betas=(0.5, 0.999), weight_decay=0,
factor=0.2, patience=5, threshold=1e-03, eps=1e-08):
""" Creates optimizer and associated learning rate scheduler for a model
Paramaters
----------
parameters : torch parameters
Pytorch network parameters ... | 5,292,446 |
def find_path_by_regexp(default_dir, search_regexp, allow_environment_path=True) -> list:
"""
Search regexp or path in default directory and directory by environment path.
Args:
default_dir (str): Default directory to search application
search_regexp (str): Regex t search application by nam... | 5,292,447 |
def try_decorator(error_ret=None):
"""
Decorator that tries something, OR returns a safe_value if failure happens (and continues)
usage:
@try_or_return_none
def foo():
if rand() > 0.9:
raise Error
else:
return rand()
"""
def real_decorator(function):
... | 5,292,448 |
def swap_weight_and_bias(cfg: fdl.Config[business_logic.BulkInferenceRunner]):
"""A sample fiddler."""
tmp = cfg.model.w
cfg.model.w = cfg.model.b
cfg.model.b = tmp | 5,292,449 |
def prepare_images_tensorflow(images: np.ndarray) -> np.ndarray:
"""
Prepares an image ndarray to fit into the tensorflow NHWC
Args:
images: The images in an nxmxm format
Returns:
The images in the NHWC tensorflow format.
"""
return images.reshape(*images.shape, 1) | 5,292,450 |
def line_width_option(**kwargs):
"""Get line width option for the plots"""
def custom_line_width_option(func):
def callback(ctx, param, value):
ctx.meta["line_width"] = value
return value
return click.option(
"--line-width",
type=FLOAT,
... | 5,292,451 |
def test_expansion_with_scheduling_failure(
client, core_api, volume_name, pod): # NOQA
"""
Test if the running volume with scheduling failure
can be expanded after the detachment.
Prerequisite:
Setting "soft anti-affinity" is false.
1. Create a volume, then create the corresponding P... | 5,292,452 |
def fig_boss_badz():
""" Scatter plot of highNHI from G16 with large but not too large dz
"""
outfil='fig_boss_badz.pdf'
# Read Vet file
missing_g16 = Table.read('../Vetting/G16_highNHI_misses.ascii', format='ascii.fixed_width')
# Cut on dz
cutz = np.abs(missing_g16['dz12']) < 0.05
pri... | 5,292,453 |
def make_array_ctype(ndim):
"""Create a ctypes representation of an array_type.
Parameters
-----------
ndim: int
number of dimensions of array
Returns
-----------
a ctypes array structure for an array with the given number of
dimensions
"""
c_intp = ctypes.c_ssi... | 5,292,454 |
def get_popular_article():
"""Get top 3 most popular articles"""
query_command = "SELECT * from popular_posts LIMIT 3"
query_data = run_query(query_command)
return query_data | 5,292,455 |
def get_json_request_header():
"""
Return the header for JSON request
:return:
"""
return {'Accept': 'application/json', 'Authorization': 'Token sessionTokenHere==', 'Accept-Language': 'en'} | 5,292,456 |
def diffraction_limited_mtf(fno, wavelength, frequencies=None, samples=128):
"""Give the diffraction limited MTF for a circular pupil and the given parameters.
Parameters
----------
fno : `float`
f/# of the lens.
wavelength : `float`
wavelength of light, in microns.
frequencies ... | 5,292,457 |
def describe_suggesters(DomainName=None, SuggesterNames=None, Deployed=None):
"""
Gets the suggesters configured for a domain. A suggester enables you to display possible matches before users finish typing their queries. Can be limited to specific suggesters by name. By default, shows all suggesters and include... | 5,292,458 |
async def echo(message, _):
"""Responds with 'echo' and shows the current latency
Category: SERVER
"""
await message.channel.send(f'echo {int(client.latency*1000)} ms') | 5,292,459 |
def warrior2_label_csv(pose_df, side='right'):
"""
takes averages of all rows (2d_points)
OLD order: head_front, sholders, arms, torso forward,
torso backward hips, knee acute, knee obtuse, step wider
1 - needs to be adjusted
0 - good
Order for 9 digit labeling:
1. arms
2. front_knee... | 5,292,460 |
def ddmin(c, n, test):
"""
The original delta debugging algorithm
:param c: Current input
:param n: Current granularity
:param test: Test function used to determine if a particular input leads to a fault, a return value of True
indicates a failure
:return: Minimal subset of c leading to... | 5,292,461 |
def check_client_method():
"""
Helper to test an API method -- returns a tuple of
(test_api_client, check_assertions) where check_assertions will
verify that the API method returned the data from http.request,
and that http.request was called with the correct arguments.
check_assertions' signat... | 5,292,462 |
def CMDdiff(parser, args):
"""Displays local diff for every dependencies."""
parser.add_option('--deps', dest='deps_os', metavar='OS_LIST',
help='override deps for the specified (comma-separated) '
'platform(s); \'all\' will process all deps_os '
... | 5,292,463 |
def remove_accessory():
"""
Remove the accessory from the database. Inform user if it was successful or not.
"""
add_accessory_form = AddAccessoryLiftForm()
remove_accessory_form = RemoveAccessoryLiftForm()
accessory_lifts = AccessoryLift.query.filter_by(lifter=current_user)
remove_accessor... | 5,292,464 |
def Pwr(a, b):
"""
a to the power of b
:param a the base
:param b the power value
:return a^b
"""
c = 0
if a == 0:
c = 0
elif b == 0:
c = 1
else:
i = 0
c = 1
while i < b:
c = Mul(c, a)
i = i + 1
return c | 5,292,465 |
def check_subgroup_outputs(output_dir, experiment_id, subgroups, file_format='csv'):
"""
Check to make sure that the subgroup outputs
look okay. Raise an AssertionError if they do not.
Parameters
----------
output_dir : str
Path to the `output` experiment output directory for a test.
... | 5,292,466 |
def random(pages : int = 1, wiki : str = WIKI, language : str = LANG):
"""
Get a list of random fandom article titles.
Returns the results as tuples with the title and page id.
.. note:: Random only gets articles from namespace 0, meaning only articles
:param pages: the number of random pages returned (max... | 5,292,467 |
def xilogxi(x):
""" x: scalar """
if 0 == x:
return 0
else:
return x*np.log(x) | 5,292,468 |
def remove_ipfs(ipfs_hash):
""" Removes pin from IPFS hash in Blockfrost """
ipfs_remove_url = f"https://ipfs.blockfrost.io/api/v0/ipfs/pin/remove/{ipfs_hash}"
headers = {"project_id": f"{config.BLOCKFROST_IPFS}"}
res = requests.post(ipfs_remove_url, headers=headers)
res.raise_for_status()
if re... | 5,292,469 |
def migrate_system_connections(src_sc: str, dest_sc: str) -> bool:
""" Migrate the contents of a system-connections dir
:param dest_sc: The system-connections to copy to. Will be created if it
does not exist
:param src_sc: The system-connections to copy from
:return: True if anythin... | 5,292,470 |
def solution_list(request, cc_biz_id):
"""
套餐列表
"""
solution_list = Solution.objects.filter(cc_biz_id=cc_biz_id, ).order_by('-id')
solution_types = dict(fta_std.SOLUTION_TYPE_CHOICES)
now = timezone.now()
last_week = now - timedelta(days=7)
date_range = '%s to %s' % (last_week.strftime... | 5,292,471 |
def test_patch_course_run(user_drf_client, course_runs):
"""Test the view that handles a request to patch a CourseRun"""
course_run = course_runs[0]
request_url = reverse("course_runs_api-detail", kwargs={"pk": course_run.id})
resp = user_drf_client.patch(request_url, {"title": "New CourseRun Title"})
... | 5,292,472 |
def get_broker_output(id: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetBrokerResult]:
"""
Resource Type definition for AWS::AmazonMQ::Broker
"""
... | 5,292,473 |
def fasta2ids(faf, verbose=False):
"""
Extract IDs from a fasta file
:param faf: fasta file
:param verbose: more output
:return: a set of IDS
"""
if verbose:
sys.stderr.write(f"{bcolors.GREEN} Reading IDs from fasta file: {faf}{bcolors.ENDC}")
f = read_fasta(faf, whole_id=False)... | 5,292,474 |
def get_uname():
"""Get uname."""
# Preferable to running a system command
uname = " ".join(platform.uname())
return uname | 5,292,475 |
def find_run_tap_log_file(stdout, sync_engine=None):
"""Pipelinewise creates log file per running tap instances in a dynamically created directory:
~/.pipelinewise/<TARGET_ID>/<TAP_ID>/log
Every log file matches the pattern:
<TARGET_ID>-<TAP_ID>-<DATE>_<TIME>.<SYNC_ENGINE>.log.<STATUS>
... | 5,292,476 |
def _kim_cnn_model(params, args, nb_classes, embedding_matrix):
"""
fully functional API style so that we can see all model details.
params will obtain model related parameters
:param params:
:param args:
:param nb_classes: # of labels to classify
:param embedding_matrix:
:return: a com... | 5,292,477 |
def everything_except(excluded_types):
"""hypothesis utility to generate everything but the types in excluded_types"""
return everything().filter(lambda x: not isinstance(x, tuple(excluded_types))) | 5,292,478 |
def get_country_names() -> list[str]:
"""Return country names."""
return [country.name for country in get_countries()] | 5,292,479 |
def save_text(path, context):
"""保存 txt 文档"""
with open(path, "a") as f:
f.write(str(context)) | 5,292,480 |
def reindent(str, spaces=''):
"""
Removes any leading empty columns of spaces
"""
lines = str.splitlines()
lspace = [len(l) - len(l.lstrip()) for l in lines if l.lstrip()]
margin = len(lspace) and min(lspace)
return '\n'.join((spaces + l[margin:]) for l in lines) | 5,292,481 |
def run_arg_hotreload(_: str, **_kwargs: Any) -> None:
"""
Sets up the file reloading, if changes are detected
"""
# Check if a project directory as been referenced
# Through the <files> keyword argument
# If it was not, the hot-reloading will fail.
project_dir: str | None = cli_store_get('... | 5,292,482 |
def plotGini(adataGini,**kwargs):
"""
Umap visualization of rare clusters.
Params
------
adata: Anndata
The annotated data matrix of shape `n_obs` × `n_vars`.
Rows correspond to cells and columns to genes.
method: string, optional (Default: 'umap')
'method' should be 'uma... | 5,292,483 |
def iter_posts(conditional, limit=None):
"""Iterate over all the posts that conditional(post) == True"""
blog = bf.config.controllers.blog
num_yielded = 0
for post in blog.posts:
if conditional(post):
num_yielded += 1
yield post
if limit and num_yielded >= limit:
... | 5,292,484 |
def legal_dissonances(a_list, b_list):
"""
Takes two NoteList objects.
Return format is identical to vertical_intervals() above.
Returned tuples here, however, will only represent intervals that are
illegal in first species counterpoint, but legal in second species.
Second Species Exception:
... | 5,292,485 |
def mass2_batch(ts, query, batch_size, top_matches=3, n_jobs=1):
"""
MASS2 batch is a batch version of MASS2 that reduces overall memory usage,
provides parallelization and enables you to find top K number of matches
within the time series. The goal of using this implementation is for very
large tim... | 5,292,486 |
def getPretrainedModel(loss_module='ArcFace', model_path=CFG.model_path_arcface, device=CFG.device):
"""
Method to get pretrained model from file path
Args:
loss_module (string): loss function Arcface, softmax
model_path (nn.Modiule): Model path
device (torch.device): cpu or gpu... | 5,292,487 |
def handle_topic_data(json_data):
"""
- check if user start new topic
- check if user still talk about same topic
"""
intent = json_data['outcomes'][0]['intent']
"""
if session.expected_saying == intent:
#get last topic handler
#handle old topic
msg = handle_intent(se... | 5,292,488 |
def get_closest_parameter(driver_name, curve_name, normalize=False):
"""
for nurbs curves only. get the closest parameter value.
:param driver_name: <str> the driving object.
:param curve_name: <str> the mesh object.
:param normalize: <bool> if set True, returns a normalized parameter value.
:r... | 5,292,489 |
def apply_mlp_svd_voting(object_id="M 79", topk=10, return_df=False, ignore_articles=None): # "* sig Ori"
"""
combines both results from above (MLP and SVD) to deliver a final scoring on most probably intersting
papers related to a given object
:param object_id:
:param topk: how many artic... | 5,292,490 |
def init_database() -> Database: # pragma: no cover-behave
"""Initialize the database connection and contents."""
database_url = os.environ.get("DATABASE_URL", "mongodb://root:root@localhost:27017")
client = pymongo.MongoClient(database_url)
set_feature_compatibility_version(client.admin)
database ... | 5,292,491 |
def income_percentiles(row, percentiles, prefix="total"):
"""
Estimate income percentiles from counts in the census income ranges.
Parameters
==========
row: pandas.Series
A series that contains binned incomes in the ranges given by
CENSUS_INCOME_RANGES.
percentiles: ... | 5,292,492 |
def process_zabbix(target):
"""Process a Zabbix target
Args:
target: the config file portion for this specific target.
Returns: None
"""
mm = MetricManager(target['name'])
zbxapi = SimpleZabbix(
url=target['api_url'],
user=target['api_user'],
password=target['ap... | 5,292,493 |
def get_column_names(df_object):
"""Get column names for a dataframe ojbect"""
if isinstance(df_object, DataFrame):
columns = list(df_object.columns) # TODO: Update this for numpy arrays etc. later
elif isinstance(df_object, Series):
columns = [df_object.name]
elif isinstance(df_object,... | 5,292,494 |
def set_git_isolation(value):
"""Set Git isolation."""
ctx = click.get_current_context()
ctx.meta[GIT_ISOLATION] = value | 5,292,495 |
def _fetch_global_config(config_url):
"""
Fetch the index_runner_spec configuration file from a URL to a yaml file.
"""
logger.info(f'Fetching config from url: {config_url}')
# Fetch the config directly from config_url
with urllib.request.urlopen(config_url) as res: # nosec
return yaml.... | 5,292,496 |
def readColorLUT(infile, distance_modulus, mag_1, mag_2, mag_err_1, mag_err_2):
"""
Take in a color look-up table and return the signal color evaluated for each object.
Consider making the argument a Catalog object rather than magnitudes and uncertainties.
"""
reader = pyfits.open(infile)
dist... | 5,292,497 |
def parse_config(conf, env):
"""Get the specific environment, expand any relative paths, and return
a url for create_engine
:param str conf: Name of config file without the file extension
:param str env: Name of the environment within the config file
"""
if env not in conf:
raise Config... | 5,292,498 |
def download_all():
"""
Mark all datasets as needing download.
:return: None
"""
global license_db, census_tracts_db, neighborhood_db, neighborhood_tracts_map_db
license_db = BusinessLicenses(True)
census_tracts_db = CensusTracts(True)
neighborhood_db = Neighborhoods(True)
Socioecono... | 5,292,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.