content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from pathlib import Path
def main(logger, args):
"""
Main function
Args:
logger: logger object
args: arguments from command line
Returns:
None
"""
# variables
train_data_path = args.train_data_path
output_data_path = args.out_process_path
logger.info('initi... | e678444f0d248670853c0f3ed351a10453321948 | 40,700 |
from pybitmessage import pathmagic
import sys
import unittest
import random
def unittest_discover():
"""Explicit test suite creation"""
if sys.hexversion >= 0x3000000:
pathmagic.setup()
loader = unittest.defaultTestLoader
# randomize the order of tests in test cases
loader.sortTestMethodsU... | 8a84489921fdf37cb031d5587d0b24f4d983396a | 40,701 |
import requests
def weather_data(
latitude: float, longitude: float, date_: date, weather_stations: pd.DataFrame
):
"""
Get weather data for given location and date using the closest weather station
Args:
latitude (float): Latitude
longitude (float): Longitude
date_ (date): Da... | 6bee1852e0e84ae7c126078eafbc199ede578649 | 40,702 |
import re
def separate_words(text, min_word_return_size):
"""
Utility function to return a list of all words that are have a length greater than a specified number of characters.
@param text The text that must be split in to words.
@param min_word_return_size The minimum no of characters a word must h... | ca6bf51740ecf6f20bd35d0931dcd885f052a141 | 40,703 |
def LogControl(control: Control, depth: int = 0, showAllName: bool = True) -> None:
"""
Print and log control's properties.
control: `Control` or its subclass.
depth: int, current depth.
showAllName: bool, if False, print the first 30 characters of control.Name.
"""
def getKeyName(theDict, t... | af97e8385de97b6b6f912601e9e151ca16508cb1 | 40,704 |
def getSelectedObjectChannels(oSel=None, userDefine=False, animatable=False):
"""Get the selected object channels.
Arguments:
oSel (None, optional): The pynode with channels to get
userDefine (bool, optional): If True, will return only the user
defined channels. Other channels will... | f9dbd53585c2f07798b4a5658eb4301677ba1df2 | 40,705 |
def admin_urlify(column, help_text=None): # pragma: no cover
"""
Can be used to add a link to a model referenced in another admin.
Example:
fields = [admin_urlify("user")]
"""
def inner(*args):
if len(args) > 1:
obj = args[1]
else:
obj = args[0]
_obj = getattr(obj, column)
if _obj is None:
ret... | 34df5e572ec8fce70f2479759b95708fe7c848fe | 40,706 |
def getMS(start, stop):
"""
Get time difference in milliseconds
"""
diff = stop - start
return getMSDiff(diff) | 68161813b37bbb79baae5ea5b42f0e313f4333fe | 40,707 |
def allowedExperiments(reagents, maxConcentration, minConcentration=None):
""" Find the allowed ConvexHull given the reagent definitions and max/min concentration.
Note that, relative to the Mathematica code, the location of max and min concentration in the function arguments are swapped. This allows for the ... | b24fae4216456c8620d56e73132b6c1ee370027d | 40,708 |
def basicauth_dump_request_endpoint(request):
"""
Dump a HttpRequest to files in a directory.
"""
uname, passwd, user = _basicauth(request)
print(uname, passwd, user)
if user is None:
# Either they did not provide an authorization header or
# something in the authorization attem... | 5ff855e39b4cc88502b3d9d199e49dbcf7a630c5 | 40,709 |
import time
def load_metadata(paths, quiet=False):
"""
--> makes hashtable -> filepath : fcs file class instance
meta_keys == all_keys w any new keys extended
replaced -> meta_keys = ['FILEPATH'] with 'SRC_FILE'
Arg:
paths: iterable of fcs filepaths
Returns:
fcs_o... | 3c3453d12970f7993c0910718d6201dfb080c40d | 40,710 |
from typing import Callable
from typing import Any
from typing import Tuple
import inspect
def combine_args_kwargs(
func: Callable[..., Any], *args: Any, **kwargs: Any
) -> Tuple[Any, ...]:
"""
Combine args and kwargs into args.
This is needed because we allow users to pass custom kwargs to adapters,... | 03e5c310462b3d15e3ab69cf6d8717744a95caa4 | 40,711 |
def get_tensor_backend(tensor):
"""
Determine the tensor backend for a given tensor.
Args:
tensor: A tensor type of any of the supported backends.
Return:
The backend class which providing the interface to the tensor library
corresponding to ``tensor``.
Raises:
:py... | cbad0351c81816c6ecb5fc3e56b54c9a4bf358ff | 40,712 |
import math
def generate_primes_up_to(max_prime):
"""Generates an array of prime numbers up to @max_prime"""
primes = [2, 3]
i = 4
while i < max_prime:
prime = True
for divisor in xrange(2, int(math.sqrt(i)) + 1):
if i % divisor == 0:
prime = False
break
if prime is True:
primes.append(i)
... | b18faf069e01d722e66fe7817016ae081a4821fd | 40,713 |
import matplotlib.pyplot as plt
def _plot2D(self, funcname, *args, **kwargs):
""" generic plotting function for 2-D plots
"""
if len(self.dims) != 2:
raise NotImplementedError(funcname+" can only be called on two-dimensional dimarrays.")
#ax = plt.gca()
if 'ax' in kwargs:
ax... | 07a48dd13b1fac77b9c91109b87d8a5c7d8c5aca | 40,714 |
def _get_from_members_items_or_properties(obj, key):
"""TODO_Sphinx."""
try:
if hasattr(obj, key):
return obj.id
if hasattr(obj, 'properties') and key in obj.properties:
return obj.properties[key]
except (KeyError, TypeError, AttributeError): pass
try:
... | ef2c6632fb00e959c96e78f2077e12264eb84f3c | 40,715 |
import json
def get_package_list_arch(repo, arch):
"""Return all packages in a repository with given architecture."""
filters = _filters_from_args(request.args)
filters['repo'] = repo
filters['arch'] = arch
pkgs = pkgdb.find(**filters)
_json = list(map(_json_from_pkg, pkgs))
return json.du... | 2055be354197d708ee13b7e1d38b96f425c95483 | 40,716 |
def h(k, n, td, tb, tau):
"""Term in Eq. 35 in Zhang+95."""
# Typo in Zhang+95 corrected. k * tb, not k * td
if k * tb < n * td:
return 0
return (k - n*(td + tau) / tb +
tau / tb * Gn((k * tb - n * td)/tau, n)) | 4d744bf9efd4121d82333151cf53f163a5c429be | 40,717 |
def definers (ioc, name) :
"""Return the classes defining `name` in `mro` of `ioc`"""
try :
mro = ioc.__mro__
except AttributeError :
mro = ioc.__class__.__mro__
def _gen (mro, name) :
for c in mro :
v = c.__dict__.get (name)
if v is not None :
... | f5d90118ca1ad719d47143d0260bfcbda2749124 | 40,718 |
def dict_to_yaml_snippet (dictionary, indent = ' ', level = 2, newline = '\n'):
"""Convert a dataframe Dictionary to a formated yaml snippet
Parameters
----------
dictionary : dict
dictionary with keys INDEX, ORDER, and the values of INDEX and ORDER
indent : str, optional
level : int ,... | 34f02c497e68558506e495b90b3f93aa02ab3955 | 40,719 |
def datetime_display_renderer(widget, data, value=None):
"""Note: This renderer function optionally accepts value as parameter,
which is used in favor of data.value if defined. Thus it can be used as
utility function inside custom blueprints with the need of datetime
display rendering.
"""
value... | 7a24364118997bc64df0ffc1ed1c9175515a1239 | 40,720 |
def get_bbc_dataset():
"""Extract a return the train and test data for the bbc corpus."""
dataset = pd.read_csv('bbc_dataset.csv', index_col=0)
dataset_train = dataset[dataset.set == 'train']
dataset_test = dataset[dataset.set == 'test']
X_train = dataset_train[['Utterance']]
y_train = dataset_... | 46504ca8ff5050f5bb810fea0382e984383d51d9 | 40,721 |
def get_course_url(course_id, course_json, platform):
"""
Get the url for a course if any
Args:
course_id (str): The course_id of the course
course_json (dict): The raw json for the course
platform (str): The platform (mitx or ocw)
Returns:
str: The url for the course i... | 22865459e0a0636f1f116630bab50cb3157f008b | 40,722 |
from typing import Any
def load_model(helper: PredictHelper, config: PredictionConfig, path_to_model_weights: str) -> Any:
""" Loads model with desired weights. """
return ConstantVelocityHeading(config.seconds, helper) | 0cda0cd393a7221a628739753aebbc45aad02904 | 40,723 |
import torch
from typing import Union
from typing import Callable
from typing import Optional
from typing import Any
def create_supervised_trainer(
model: torch.nn.Module,
optimizer: torch.optim.Optimizer,
loss_fn: Union[Callable, torch.nn.Module],
device: Optional[Union[str, torch.device]] = None,
... | 918536b588cc5a238621558d792bb9ce7c44f2cc | 40,724 |
def add_dest(df_conc, dest_labware, dest_start=1):
"""Setting destination locations for samples & primers.
Adding to df_conc:
[dest_labware, dest_location]
"""
dest_start= int(dest_start)
#try:
# dest_labware = dest_labware_index[dest_type]
#except KeyError:
# raise KeyError(... | d3e066148fc07bd5ed47d496d56c39e24062315c | 40,725 |
def load_ratings_data(path_data='ratings.csv'):
"""
Returns a list of triples (a, i, r)
"""
data = []
with open(path_data) as f_data:
for line in f_data:
(uid, iid, rating, timestamp) = line.strip().split(",")
data.append([int(uid), int(iid), float(rating)])
prin... | d5565f0e9c5098f606d3d1dcf4607d2455b43fc1 | 40,726 |
def image_has_any_human_annotations(image):
"""
Return True if the image has at least one human-made Annotation.
Return False otherwise.
"""
human_annotations = Annotation.objects.filter(image=image).exclude(user=get_robot_user()).exclude(user=get_alleviate_user())
return human_annotations.count... | b20dd78c280a92e6b1433cfcd24b7629945ce047 | 40,727 |
from typing import Dict
from datetime import datetime
def build_fix_from_line(line: Dict) -> GpsFix:
"""
Builds a GpsFix parsing the specified line
:param line: The line to parse
:return: A GpsFix object
"""
date = datetime.strptime(line["timestamp"], '%Y-%m-%d %H:%M:%S')
latitude = float(... | 3773a6ef825a1ef6fd00626036997df99d6a0def | 40,728 |
def top(Q):
"""Inspects the top of the queue"""
if Q:
return Q[0]
raise ValueError('PLF ERROR: empty queue') | 16327db2698fbef4cad1da2c9cb34b71158a2a6c | 40,729 |
def get_valid_handles_domain_only():
"""
Define valid domain handles
"""
return ["cli", "web", "gui", "pub"] | 64dc04fbbecbc442b1fd99279161c04461332a87 | 40,730 |
def qc_board_and_constraints(board, constraints):
"""
Purpose: When the board first comes in, do a check to see if any of the
fixed values are duplicates
@param board The Sudoku board: A list of lists of variable class instances
@param constraints The unallowed values for each cell, list of tuples... | 82c8013c12eda3fd548295be96e713d760587985 | 40,731 |
def spdot(A, x):
""" Dot product of sparse matrix A and dense matrix x (Ax = b) """
return A.dot(x) | b44c9434a42974be54e2c4794b6f063f86836707 | 40,732 |
def ecef2eci(R_ECEF,time):
"""
# Function to compute rotation matrix from ECEF to ECI (simple model)
# Formulas taken from the US Naval Observatory
"""
#
# T is the Julian Date in julian centuries
#
d = time - 2451545.0;
T = d/ 36525;
#
# Compute Greenwich Mean s... | c5eb8cade1e4962c6f68756a191f6d85b70daf2d | 40,733 |
def get_months(year: str) -> list[str]:
"""Make all Prompts dates for a given year into a unique set.
For some months in 2017, November 2020, and in 2021 and beyond,
there are multiple Hosts per month giving out the prompts.
While the individual dates are stored distinctly,
we need a unique month l... | 04bedefa175efb259188bb55a8604502956cd41b | 40,734 |
def translate_user(user):
""" translates trac user to pivotal user
"""
return user | 69a439a12188239a557b69fa9f858473f1509a26 | 40,735 |
def _clean_int(value, default):
"""Convert a value to an int, or the default value if conversion fails."""
try:
return int(value)
except (TypeError, ValueError), _:
return default | 7c14156cee3313e605a7b928adca2777ba181924 | 40,736 |
import os
def get_target_imagepath(image_path,category_num):
"""
category:
0-userid,
1-isbad,
2-gender: 1 male,0 female,
3-age
"""
basename=os.path.basename(image_path).split(".")[0].split("_")
an=int(basename[category_num])
return an | 131466cea39de6bc1e68b8603c2b065981d3d386 | 40,737 |
import operator
def wait_for_first(ds):
""" Returns a deferred that is callbacked/errbacked with whatever deferred in `ds` fires first. """
d = defer.DeferredList(ds, fireOnOneCallback=True, fireOnOneErrback=True, consumeErrors=True)
d.addCallback(operator.itemgetter(0))
d.addErrback(get_maybe_first_e... | b12687080d8d3c25fdc5049ba6382dbd443ab721 | 40,738 |
import pickle
def offline_analysis(data_folder: str = None,
parameters: dict = {}, alert_finished: bool = True):
""" Gets calibration data and trains the model in an offline fashion.
pickle dumps the model into a .pkl folder
Args:
data_folder(str): folder of the da... | 1a6bd7d60f44a0ebd57c48a83bc459f7d644c7fc | 40,739 |
def filterSignal(mriSignal, acqTime, timePhysioRegrid, valuesPhysioRegrid, cardiacPeriod, freqDetection='temporal'):
"""
Define function to apply last 2 steps (breathing frequencies filtering and final smoothing) in one single call
:param mriSignal:
:param acqTime:
:param timePhysioRegrid:
:pa... | f762f3037254852c4a40c2ea703542f739001d13 | 40,740 |
def write_string(val: str) -> bytes:
"""Returns the OSC string equivalent of the given python string.
Raises:
- BuildError if the string could not be encoded.
"""
try:
dgram = val.encode('utf-8') # Default, but better be explicit.
except (UnicodeEncodeError, AttributeError) as e:
... | 3e0ca5db6203b9ff27d46b805f0b3cb2f2f7e77a | 40,741 |
def split_in_columns(message=message):
"""Split the message by newline (\n) and join it together on '|'
(pipe), return the obtained output"""
pipe = "|"
message_split = message.split("\n")
message_join = pipe.join(message_split)
return message_join | e0d05c9418f10c87d61ed5fcf4dd366fa77c6d5d | 40,742 |
def detail(container: str):
"""
Inspect a container on Azure Blob Storage
"""
# Get container info
container_client = service_client.get_container_client(
container=container)
container = container_client.get_container_properties()
# Get the blobs inside this container
blobs =... | 588044011c086469ae79f89289214647422d689c | 40,743 |
from datetime import datetime
import shutil
def sync_cp_dump(server, args_array, **kwargs):
"""Function: sync_cp_dump
Description: Locks the database and then copies the database files to a
destination directory.
Arguments:
(input) server -> Database server instance.
(input) a... | f33aee9b22ed0f17dd00e8212218a79bec72ed1c | 40,744 |
import PIL
def create_image (width, height, color='white'):
"""
Creates an empty image.
:param width: image width
:param height: image height
:param color: background color
:return: the image
"""
image = PIL.Image.new("RGBA", (width, height), color)
return image | 77cae1dc440d97e6d4fb46eab3cd270e07223289 | 40,745 |
def convert_image_resize1d(attrs, inputs, tinfos, desired_layouts):
"""Convert Layout pass registration for image resize1d op.
Parameters
----------
attrs : tvm.ir.Attrs
Attributes of current resize op
inputs : list of tvm.relay.Expr
The args of the Relay expr to be legalized
ti... | d2c455ce931cd95887803a9f7271a239acbe4523 | 40,746 |
import json
def index(metadata_context: BaseContext = Provide[ApplicationContainer.context_factory]):
"""Handler for base level URI for the features endpoint.
Supports GET and POST methods for interacting."""
if request.method == constants.HTTP_GET:
with metadata_context.get_session() as session:
... | 098cab3df8f0754ccf0025205d3b56c0328ce66f | 40,747 |
def select_area(ds, lon, lat, g_step=0.25):
"""
Select data for given location or rectangular area from dataset.
In case data for a single location is requested, the nearest data point
for which weather data is given is returned.
Parameters
-----------
ds : xarray.Dataset
Dataset w... | 4760ebdfd0b580403ea2f0e3214f23e9b4806f1d | 40,748 |
import os
def spatial_clustering(mask, algorithm="DBSCAN", min_cluster_size=5, max_distance=None):
"""Counts and segments portions of an image based on distance between two pixels.
Masks showing all clusters, plus masks of individual clusters, are returned.
Inputs:
mask = Mask/binary imag... | b1ce203a9705c97779090f7ba0af9f54b6ab761f | 40,749 |
def get_ordered_dataset(file_pattern, blocks_only=True, shuffle=True):
"""Given a file pattern,return the dataset contained.
If specified, shuffle the dataset group-wise.
:param blocks_only: whether to only use records with 'is_extracted_block' == True
:type blocks_only: bool
:param file_pattern: t... | 3cbd08e1d3ef72ed13a5605804b757512107f8de | 40,750 |
def build_vxlan_header(encapsulation_header, ethernet_header):
"""
Build NSH header with underlying ethernet header
:param encapsulation_header: VXLAN or GRE NSH header
:type encapsulation_header: `:class:nsh.common.VXLANGPE|GREHEADER`
:param base_header: base NSH header
:type base_header: `:cl... | 304c0d4f4ac06d11073195695a6750507471b7eb | 40,751 |
from typing import OrderedDict
def _new_obj(original_function):
"""Decorator to deepcopy unaltered states into new object
Parameters
----------
original_function : callable
Callable must return None or a Mapping with some or all of
_state_attrs defined.
Returns
-------
ne... | c7e9de3b1dbc6f415c8df87c4feaaefae383c59b | 40,752 |
import logging
def Aggregate_median_SABV(rnaseq):
"""Compute median TPM by gene+tissue+sex."""
logging.info("=== Aggregate_median_SABV:")
logging.info(f"Aggregate_median_SABV IN: nrows = {rnaseq.shape[0]}, cols: {str(rnaseq.columns.tolist())}")
rnaseq = rnaseq[["ENSG", "SMTSD", "SEX", "TPM"]].groupby(by=["ENS... | 99689df7058f9d0d96bae1672076ccca50c11aee | 40,753 |
from typing import Dict
from typing import Any
def is_similar_except_in_shape(
definition_or_instance_1: Dict[str, Any],
definition_or_instance_2: Dict[str, Any],
only_x_dimension: bool = False
) -> bool:
"""Return whether the two given objects are similar in color
(material category) and size (di... | cda59f51908ed76dca8ddf356236a8516e86b174 | 40,754 |
import os
def scandir(dir_path, suffix=None, recursive=False, full_path=False):
"""
From BasicSR: https://github.com/xinntao/BasicSR
Scan a directory to find the interested files.
Args:
dir_path (str): Path of the directory.
suffix (str | tuple(str), optional): File suffix that we are... | 0aa1cf6fb3e3c4a27281048866a1755f73963db6 | 40,755 |
import requests
def simpleapi():
"""Cross-Microservice call"""
url = getservice(APP.node, "simple-api")
key = requests.get(url + "/simple-api/version", timeout=1)
return (key.text, 200) | 62b7cbecfb30e03c1ec0ac3386aa46c29b37a73c | 40,756 |
def mac_address(name, value):
"""Validate that the value represents a MAC address
:param name: Name of the argument
:param value: A string value representing a MAC address
:returns: The value as a normalized MAC address, or None if value is None
:raises: InvalidParameterValue if the value is not a ... | b1d7f49a8032986af06b5aef8e3da9d6a5210b32 | 40,757 |
def total_dist_from_point(data: CachingDataStructure, start_point: tuple,
max_prop_level: int = INF) -> tuple:
"""
For some CachingDataType, it calculates the distance in linear
space for all different propagation levels. Returns a tuple of three
arrays; (1) an array of propaga... | cfd8d1985554db2f38d1a4c8fcca8e8ad3991404 | 40,758 |
def compute_curve(labels, predictions, num_thresholds=None, weights=None):
""" Compute precision-recall curve data by labels and predictions.
Args:
labels (numpy.ndarray or list): Binary labels for each element.
predictions (numpy.ndarray or list): The probability that an element be
... | d0079807c8f46c9399342f17b642da6c38f563fa | 40,759 |
import os
import pickle
def read_database():
"""
Deserialize the database and read into a list of sets for easier selection
and O(1) complexity. Initialize the multiprocessing to target the main
function with cpu_count() concurrent processes.
"""
database = [set() for _ in range(4)]
count = len(os.listdir(DA... | a8f35fe8963502764ff994d79d4b2c52bdf2f896 | 40,760 |
def _split_series(df, series_id, target, by='quantiles', cuts=5, split_col='Cluster'):
"""
Split series into clusters by rank or quantile of average target value
by: str
Rank or quantiles
cuts: int
Number of clusters
split_col: str
Name of new column
Returns:
-----... | 05e5536b4d0b853801c1612aeff6d9dba5f889b7 | 40,761 |
def extract_data_with_labels(npy_file_path, subject_labels, config):
"""Extracts train_val and test data and subjects from npy and csv file
Args:
config (Omegaconf dict): contains configuration parameters
Returns (subjects as dataframe, data as numpy array):
train_val_subjects, train_val_da... | 6244650d68487a2069d846319990ab0f2d643360 | 40,762 |
def content_disposition_filename(filename):
"""
Sanitize a file name to be used in the Content-Disposition HTTP
header.
Even if the standard is quite permissive in terms of
characters, there are a lot of edge cases that are not supported by
different browsers.
See http://greenbytes.de/tech/t... | de0c584adef10430a374983d5d8db74e79515e90 | 40,763 |
import json
def new_query(event, *args):
"""Add new query session <kind of deprecated>
Args:
url: review/{review_id}/query
body:
"search" <search dict (wrapper/input_format.py)>
Returns:
{
"review": review object,
"new_query_id": ne... | fdc3d890fd8e01d293ec4c1ed5d1e5a02c30d199 | 40,764 |
import os
from functools import reduce
import operator
from typing import Dict
def GraphHistograms( histFiles, outFile = None, xlabel = '', ylabel = '', title = '',
labels = (), colors = 'brcmygkbrcmygkbrcmygkbrcmygk',
relWidth = 0.4,
xbound = None, yboun... | a5cf69b8bc553d5a01694fdb16a7d259438781e8 | 40,765 |
def update(gen, test: dict, context: dict, event):
"""
:param gen: 一个generator对象
:param test: 传入的本次测试配置(来自config.yaml)
:param context: 测试运行时的上下文,包括当前空闲线程、时间等信息
:param event: 事件,通常是一个op
:return: gen2: 通过该次调用传入的generator的状态得到了更新,返回更新后的generator
"""
if gen is None:
return None
... | 14492f840f966c2fb9049840586dd0bd26502a9b | 40,766 |
import os
def get_rig_list(path):
""" Recursively searches for rig types, and returns a list.
"""
rigs = []
MODULE_DIR = os.path.dirname(__file__)
RIG_DIR_ABS = os.path.join(MODULE_DIR, utils.RIG_DIR)
SEARCH_DIR_ABS = os.path.join(RIG_DIR_ABS, path)
files = os.listdir(SEARCH_DIR_ABS)
f... | 38aa24d0206445f2378d2d6edcdef9e0b74b6f7c | 40,767 |
import time
def get_time_at(time_in=None, time_at=None, out_fmt="%Y-%m-%dT%H:%M:%S"):
"""
Return the time in human readable format for a future event that may occur
in ``time_in`` time, or at ``time_at``.
"""
dt = get_timestamp_at(time_in=time_in, time_at=time_at)
return time.strftime(out_fmt,... | ea84f08a0a4a72f8d9408932a07117c4fff7d41d | 40,768 |
def synchronized(lock):
"""
Synchronization decorator.
"""
def wrap(f):
def new_function(*args, **kw):
lock.acquire()
try:
return f(*args, **kw)
finally:
lock.release()
return new_function
return wrap | 99e04c15bd141bd7d4e131eb0e5de6f5c73f347c | 40,769 |
def make_snippet(snippets, location):
"""Makes a colored html snippet."""
output = "<br>".join(sentence.replace(
location, f'<i style="background-color: yellow;">{location}</i>') for sentence in snippets)
return output | 57bebb05df3ae34b45f57e589f6b105425609b8c | 40,770 |
def read_data(filenames, mode):
"""
The main function to read all the back calculated files
Parameters
----------
filenames: dict
This parameter is a dictionary of properties with their relative path to the data file.
mode: str
This parameter must be one of the following:
... | 3c1bebf165fdedb52b55207c56e7a5f9fe88de81 | 40,771 |
def is_identity(mat, eps=None):
"""Checks if a matrix is an identity matrix.
If the input is not even square, ``False`` is returned.
Args:
mat (numpy.ndarray): Input matrix.
eps (float, optional): Numerical tolerance for equality. ``None``
means ``np.finfo(mat.dtype).eps``.
... | 98b00c3492056c4f7bf0a53d6a15017c03d32dbe | 40,772 |
import glob
import os
def get_pem_entries(glob_path):
"""
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
"""
ret =... | 26d2cf5fcb40c6ff9c000ab507fb11557a66af97 | 40,773 |
def connect_to_db_via_ssh(ssh_info, db_info):
"""
Connects to a remote PostgreSQL db, via SSH tunnel.
Args:
ssh_info (obj): All ssh connection info.
db_info (obj): All db related connection info.
Returns:
:class:`psycopg2.extensions.connection`: Live connection suitable for que... | 64e9048bd2b301bcfcd162b87a4d637076909746 | 40,774 |
def kid_2():
"""Return a second JWT key ID to use for tests."""
return "test-keypair-2" | c1bbe824ee90470c17ac62cbc3096cff4e3ddb1a | 40,775 |
import os
def get_world_size():
"""
Get the size of the world.
"""
if 'WORLD_SIZE' in os.environ:
return int(os.environ['WORLD_SIZE'])
else:
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_siz... | 5e58b4424b783f868f88d8ae8c017b8f5a9e2f84 | 40,776 |
import torch
def cosine_sim(x1, x2, dim=-1, eps=1e-8):
"""Returns cosine similarity between x1 and x2, computed along dim."""
w12 = torch.sum(x1 * x2, dim)
w1 = torch.norm(x1, 2, dim)
w2 = torch.norm(x2, 2, dim)
return (w12 / (w1 * w2).clamp(min=eps)).squeeze() | bdc2ba499ed4b0293d999b8e0d01a8c1972a98ba | 40,777 |
def overlap(b4_reg, b7_reg, sep):
"""
function to find ds9 ellipse regions that match or overlap between band 4 and band 7
"""
# define some other little functions
def match_function(c, c_array, sep):
""" c would be a single band 4 dust region
c_array would be array of the band 7 regions
"""
# find wher... | 7b85c46ecc849ec75a59ef8f0bb1f8b7932bfd3c | 40,778 |
from typing import Optional
from typing import Any
from typing import Tuple
def tile_array_2d(array: np.ndarray, tile_size: int, channels_first: Optional[bool] = True,
**pad_kwargs: Any) -> Tuple[np.ndarray, np.ndarray]:
"""Split an image array into square non-overlapping tiles.
The array w... | 3d1e94435e4d846b8e77c58a0f1dd5af56ac764d | 40,779 |
from src.praxxis.sqlite import connection
def get_filenames(ruleset_db, rule):
"""returns a list of all filenames for a rule in a ruleset"""
conn = connection.create_connection(ruleset_db)
cur = conn.cursor()
list_filenames = 'SELECT Filename FROM "Filenames" WHERE Rule = ?'
cur.execute(list... | 519932300fd8f11afe5465964a08c7e7352378a0 | 40,780 |
def toy_features():
"""
Generate a sample feature dataframe with one column that isn't a
feature.
"""
feat = pd.DataFrame({"A": [1, 2, 3],
"B": [4, 5, 6],
"C": [7, 8, 9],
"D": ["a", "b", "c"]})
return (feat, feat.loc[:, ... | d72a7a54767dfb5a415662982e97e1ae92ec1ab3 | 40,781 |
def cube_px_resampling(array, scale, imlib='opencv', interpolation='bicubic',
scale_y=None, scale_x=None):
""" Wrapper of frame_px_resample() for resampling the frames of a cube with
a single scale. Useful when we need to upsample (upsacaling) or downsample
(pixel binning) a set of f... | d9c5c2a7c64b3f053e2302e134163b557065e81d | 40,782 |
import traceback
def tint_raw(img, color, opacity=255):
"""Tint the image."""
if isinstance(img, str):
try:
img = sublime.load_binary_resource(img)
except Exception:
_log('Could not open binary file!')
_debug(traceback.format_exc(), ERROR)
retur... | fcb0a6319df0378fba72c22d55d7d78d0e241953 | 40,783 |
def move_items_back(garbages):
"""
Moves the items/garbage backwards according to the speed the background is moving.
Args:
garbages(list): A list containing the garbage rects
Returns:
garbages(list): A list containing the garbage rects
"""
for garbage_rect in garbages: # Loop... | 9ffd28c7503d0216b67419009dac6ff432f3b100 | 40,784 |
def optimize(inputs, output, sizes):
"""
Produces an optimization path similar to the greedy strategy
:func:`opt_einsum.paths.greedy`. This optimizer is cheaper and less
accurate than the default ``opt_einsum`` optimizer.
:param list inputs: A list of input shapes. These can be strings or sets or
... | f9052884859534782854d996e836681890aded0e | 40,785 |
from typing import List
def variation(inlist:List(float))->float:
"""
Returns the coefficient of variation, as defined in CRC Standard
Probability and Statistics, p.6.
Usage: lvariation(inlist)
"""
return 100.0*variability.samplestdev(inlist)/float(central_tendency.mean(inlist)) | e2abb6394131851a9e4354db7e6569b1020cc28c | 40,786 |
def process_zdr_column(procstatus, dscfg, radar_list=None):
"""
Detects ZDR columns
Parameters
----------
procstatus : int
Processing status: 0 initializing, 1 processing volume,
2 post-processing
dscfg : dictionary of dictionaries
data set configuration. Accepted Config... | 2565aebec15ee19a03b904f7cf42d3b8ca63cd5c | 40,787 |
import re
def _mask_pattern(dirty: str):
"""
Masks out known sensitive data from string.
Parameters
----------
dirty : str
Input that may contain sensitive information.
Returns
-------
str
Output with any known sensitive information masked out.
"""
# DB credenti... | b75ae1e6ea128628dd9b11fadb38e4cbcfe59775 | 40,788 |
def cleanString(currentString):
""" Remove extra spaces and final punctuation from string.
"""
cleanstring = currentString.strip()
cleanerString = removePunctuationField(cleanstring)
return cleanerString | 37a44fa1a5b042590803bac4ef12a4dab153273a | 40,789 |
import re
def getFilename_fromCd(cd):
"""
Get filename from content-disposition
"""
if not cd:
return None
fname = re.findall("filename=(.+)", cd)
if len(fname) == 0:
return None
return fname[0] | 3c516b0e7bfe2adfd05922a221d5919823177bd7 | 40,790 |
import urllib
def redirect_view(request, url):
"""
Redirect all requests that come here to an API call with a view parameter.
"""
dest = '/api/%.1f/%s' % (legacy_api.CURRENT_VERSION,
urllib.quote(url.encode('utf-8')))
dest = get_url_prefix().fix(dest)
return HttpR... | cad47b547257f8b2c58fe6a66120467ee2b2c656 | 40,791 |
def arch_matches(arch, alias):
"""
Check if given arch `arch` matches the other arch `alias`. This is most
useful for the complex any-* rules.
"""
if arch == alias:
return True
if arch == 'all' or arch == 'source':
# These pseudo-arches does not match any wildcards or aliases
... | 308e3fbe90aedfd0d089444875d459bc850b8496 | 40,792 |
import numpy
def calc_m_q_inv_m(m, q, flag_m: bool = False, flag_q: bool = False):
"""
q is quadratic form q_11, q_22, q_33, q_12, q_13, q_23
m is matrix m_11, m_12, m_13, m_21, m_22, m_23, m_31, m_32, m_33
Output is matrix o
"""
m_11, m_12, m_13 = m[0], m[1], m[2]
m_21, m_22, m_23 ... | 0875a6f0889232d1ceb558cde4e77130c405f86f | 40,793 |
def divisors(n):
"""
Returns a list of all positive integer divisors of the nonzero
integer n.
INPUT:
- ``n`` - the element
EXAMPLES::
sage: divisors(-3)
[1, 3]
sage: divisors(6)
[1, 2, 3, 6]
sage: divisors(28)
[1, 2, 4, 7, 14, 28]
s... | ca33ab9b15f2fc422a5a2b0c5a392144b4ac8ccd | 40,794 |
def list_to_hash(lst):
"""Convert a flat list of key value pairs to a hash"""
return {lst[i]: lst[i+1] for i in range(0, len(lst), 2)}; | 44e3ce2e919a6e0f0cd605e6b712ff738949c457 | 40,795 |
from typing import Union
from typing import Tuple
def get_multiparm_instance_indices(
parm: Union[hou.Parm, hou.ParmTuple], instance_index: bool = False
) -> Tuple[int, ...]:
"""Get the multiparm instance indices for this parameter tuple.
If this parameter tuple is part of a multiparm, then its index in ... | e4e3c42b3c2f57c2bf2f4df4766b26e7ac2880cb | 40,796 |
def first_time(series, value, window=None):
""":func:`aggfunc` to:
- Return the first index where the
series == value
- If no such index is found
+inf is returned
:param series: Input Time Series data
:type series: :mod:`pandas.Series`
:param window: A tuple indicating a time win... | cf4788b9c34089da21f2839fb7517718467e17a7 | 40,797 |
from typing import Union
from typing import List
from textwrap import dedent
import torch
def prepare_filter_triples(
mapped_triples: MappedTriples,
additional_filter_triples: Union[None, MappedTriples, List[MappedTriples]] = None,
) -> MappedTriples:
"""Prepare the filter triples from the evaluation trip... | 999afbbe5d4016778dbd44f00b5c1ddb7eb2fc3b | 40,798 |
def create():
"""
Progress can be added to any/all goal(s) displayed.
"""
goals = fetch_goals()
if request.method == "POST":
data_id = request.form.getlist("id")
data_progress = request.form.getlist("progress")
data_quality = request.form.getlist("grade")
data = {... | ca2d15e27bcc692b64d7436cb045060e68065da4 | 40,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.