content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_active_users(URM, popular_threshold=100):
"""
Get the users with activity above a certain threshold
:param URM: URM on which users will be extracted
:param popular_threshold: popularty threshold
:return:
"""
return _get_popular(URM, popular_threshold, axis=1) | 23,800 |
def default_data_to_device(
input, target=None, device: str = "cuda", non_blocking: bool = True
):
"""Sends data output from a PyTorch Dataloader to the device."""
input = input.to(device=device, non_blocking=non_blocking)
if target is not None:
target = target.to(device=device, non_blocking=n... | 23,801 |
def _get_diff2_data(request, ps_left_id, ps_right_id, patch_id, context,
column_width, tab_spaces, patch_filename=None):
"""Helper function that returns objects for diff2 views"""
ps_left = models.PatchSet.get_by_id(int(ps_left_id), parent=request.issue.key)
if ps_left is None:
return Http... | 23,802 |
def vec_add(iter_a, iter_b):
"""element wise addition"""
if len(iter_a) != len(iter_b):
raise ValueError
return (a + b for a, b in zip(iter_a, iter_b)) | 23,803 |
def run():
""" Read inputs into a dictionary for recursive searching """
for line in inputs:
# Strip the trailing "." and split
container, rest = line[:-1].split(" contain ")
# Strip the trailing " bags"
container = container[:-5]
contained = []
for bag in rest.sp... | 23,804 |
def _get_prolongation_coordinates(grid, d1, d2):
"""Calculate required coordinates of finer grid for prolongation."""
D2, D1 = np.broadcast_arrays(
getattr(grid, 'vectorN'+d2), getattr(grid, 'vectorN'+d1)[:, None])
return np.r_[D1.ravel('F'), D2.ravel('F')].reshape(-1, 2, order='F') | 23,805 |
async def dump_devinfo(dev: Device, file):
"""Dump developer information.
Pass `file` to write the results directly into a file.
"""
import attr
methods = await dev.get_supported_methods()
res = {
"supported_methods": {k: v.asdict() for k, v in methods.items()},
"settings": [at... | 23,806 |
def push_image(tag):
"""Push docker image via gcloud context to resolve permission issues."""
gcloud.docker('--', 'push', tag, _out=sys.stdout, _err=sys.stderr) | 23,807 |
def get_sorted_filediffs(filediffs, key=None):
"""Sorts a list of filediffs.
The list of filediffs will be sorted first by their base paths in
ascending order.
Within a base path, they'll be sorted by base name (minus the extension)
in ascending order.
If two files have the same base path and... | 23,808 |
def get_info(obj):
"""
get info from account obj
:type obj: account object
:param obj: the object of account
:return: dict of account info
"""
if obj:
return dict(db_instance_id=obj.dbinstance_id,
account_name=obj.account_name,
account_status=o... | 23,809 |
def vlookup(x0, vals, ind, approx=True):
"""
Equivalent to the spreadsheet VLOOKUP function
:param vals: array_like
2d array of values - first column is searched for index
:param x0:
:param ind:
:param approx:
:return:
"""
if isinstance(vals[0][0], str):
x0 = str(x0)... | 23,810 |
def matmul(a00, a10, a01, a11, b00, b10, b01, b11):
"""
Compute 2x2 matrix mutiplication in vector way
C = A*B
C = [a00 a01] * [b00 b01] = [c00 c01]
[a10 a11] [b10 b11] [c10 c11]
"""
c00 = a00*b00 + a01*b10
c10 = a10*b00 + a11*b10
c01 = a00*b01 + a01*... | 23,811 |
def random_sample_with_weight_and_cost(population, weights, costs, cost_limit):
"""
Like random_sample_with_weight but with the addition of a cost and limit.
While performing random samples (with priority for higher weight) we'll keep track of cost
If cost exceeds the cost limit, we stop selecting
B... | 23,812 |
def hardnet68ds(pretrained=False, **kwargs):
""" # This docstring shows up in hub.help()
Harmonic DenseNet 68ds (Depthwise Separable) model
pretrained (bool): kwargs, load pretrained weights into the model
"""
# Call the model, load pretrained weights
model = hardnet.HarDNet(depth_wise=True, arc... | 23,813 |
def taxiProgram():
"""
Taxi program implementation here.
Parameters: None
Returns: None
"""
logger.error("main/taxiProgram: Taxi Program Started")
# Set up data structures for first POGI retrieval
pogiInitPipeline = mp.Queue()
firstTelemetry = None
while True:
# Read po... | 23,814 |
def session_validity_stats():
"""Output statistics about how many sessions were valid."""
valid = db.session_data(only_valid=True)
all = db.session_data(only_valid=False)
print("Session Validity stats")
print(f"total: {len(all)}")
print(f"valid: {len(valid)}")
print(f"invalid: {len(all) ... | 23,815 |
def get_config():
"""Base config for training models."""
config = ml_collections.ConfigDict()
# How often to save the model checkpoint.
config.save_checkpoints_steps: int = 1000
# Frequency fo eval during training, e.g. every 1000 steps.
config.eval_frequency: int = 1000
# Total batch size for training.... | 23,816 |
def slave_addresses(dns):
"""List of slave IP addresses
@returns: str Comma delimited list of slave IP addresses
"""
return ', '.join(['{}:53'.format(s['address'])
for s in dns.pool_config]) | 23,817 |
def processAndLabelStates(role, states, reason, positiveStates=None, negativeStates=None, positiveStateLabelDict={}, negativeStateLabelDict={}):
"""Processes the states for an object and returns the appropriate state labels for both positive and negative states.
@param role: The role of the object to process states... | 23,818 |
def _views(config, wapp, plugins):
"""initialize core api handlers"""
log.debug('init views')
wapp.route('/_/', 'GET', status.view, name = 'core.status',
apply = plugins) | 23,819 |
def alpha_setup_backtest(strategy, from_date, to_date, base_timeframe=Instrument.TF_TICK):
"""
Simple load history of OHLCs, initialize all strategy traders here (sync).
"""
for market_id, instrument in strategy._instruments.items():
# retrieve the related price and volume watcher
watche... | 23,820 |
def shape_for_stateful_rnn(data, batch_size, seq_length, seq_step):
"""
Reformat our data vector into input and target sequences to feed into our
RNN. Tricky with stateful RNNs.
"""
# Our target sequences are simply one timestep ahead of our input sequences.
# e.g. with an input vector "wherefor... | 23,821 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Sets up appliance binary sensors"""
hub: Hub = hass.data[DOMAIN][config_entry.entry_id]
# Dehumidifier sensors
async_add_entities(
TankFullSensor(c) fo... | 23,822 |
def setup_features(dataRaw, label='flux', notFeatures=[], pipeline=None, verbose=False, resample=False, returnAll=None):
"""Example function with types documented in the docstring.
For production level usage: All scaling and transformations must be done
with respect to the calibration dat... | 23,823 |
def plot_marginal_effects(model: ModelBridge, metric: str) -> AxPlotConfig:
"""
Calculates and plots the marginal effects -- the effect of changing one
factor away from the randomized distribution of the experiment and fixing it
at a particular level.
Args:
model: Model to use for estimatin... | 23,824 |
def update_user_config_in_db(config: UserConfig, io: IO, month_year: tuple[int, int]) -> None:
"""
Updates UserConfig based on latest calendar Month/Year view preference. Saves UserConfig to db
:param config: instance of UserConfig
:param io: instance of IO object
:param month_year: tuple[int, int] ... | 23,825 |
def _client_row_class(client: dict) -> str:
"""
Set the row class depending on what's in the client record.
"""
required_cols = ['trust_balance', 'refresh_trigger']
for col in required_cols:
if col not in client:
return 'dark'
try:
if client['trust_balance'] > clien... | 23,826 |
def num2ord(place):
"""Return ordinal for the given place."""
omap = { u'1' : u'st',
u'2' : u'nd',
u'3' : u'rd',
u'11' : u'th',
u'12' : u'th',
u'13' : u'th' }
if place in omap:
return place + omap[place]
elif place.isdigit():
... | 23,827 |
def _get_dist_class(
policy: Policy, config: AlgorithmConfigDict, action_space: gym.spaces.Space
) -> Type[TFActionDistribution]:
"""Helper function to return a dist class based on config and action space.
Args:
policy: The policy for which to return the action
dist class.
confi... | 23,828 |
def gen_all_param2vals(param2requests: Dict[str, list],
param2default: Dict[str, Any],
) -> List[Dict[str, Any]]:
"""
return multiple param2val objects,
each defining the parameter configuration for a single job
"""
# check that requests are lists and ... | 23,829 |
def logout():
"""
Logout current user.
"""
controller.clear_user()
typer.echo(f"Logged out. Bye!") | 23,830 |
def expectation_values(times, states, operator):
"""expectation values of operator at times wrt states"""
def exp_value(state, operator, time):
if len(state.shape) == 2: #DensityMatrix
return np.trace(np.dot(state, operator(time)))
else: #Stat... | 23,831 |
def compute_f_all(F1,fft_size,windowing,dtype_complex,F_frac=[],F_fs=[],F_refs=[],freq_channel=0,\
F_first_sample=[],F_rates=[],F_pcal_fix=[],F_side=[],F_ind=[],F_lti=[]):
"""
Compute FFTs for all stations (all-baselines-per-task mode), and correct for fractional sample correction (linear ... | 23,832 |
def bookmark(request):
"""
Add or remove a bookmark based on POST data.
"""
if request.method == 'POST':
# getting handler
model_name = request.POST.get('model', u'')
model = django_apps.get_model(*model_name.split('.'))
if model is None:
# invalid model -> b... | 23,833 |
def visualize_map_features_row_separate(args, seq, seq_agents_df, map_feature_row):
"""Visualize a row of map features and the scene."""
print("Visualizing sequence {}, agent {}, with {} candidates.".format(map_feature_row["SEQUENCE"], map_feature_row["TRACK_ID"], len(map_feature_row["CANDIDATE_CENTERLINES"]))... | 23,834 |
def start_nodenetrunner(nodenet_uid):
"""Starts a thread that regularly advances the given nodenet by one step."""
nodenets[nodenet_uid].is_active = True
if runner['runner'].paused:
runner['runner'].resume()
return True | 23,835 |
def transform_coordinates_3d(coordinates, RT):
"""
Input:
coordinates: [3, N]
RT: [4, 4]
Return
new_coordinates: [3, N]
"""
if coordinates.shape[0] != 3 and coordinates.shape[1]==3:
coordinates = coordinates.transpose()
coordinates = np.vstack([coordinates, np.on... | 23,836 |
def upload_to_s3(
file: Path, bucket: str = f"arr-packit-{getenv('DEPLOYMENT', 'dev')}"
) -> None:
"""Upload a file to an S3 bucket.
Args:
file: File to upload.
bucket: Bucket to upload to.
"""
s3_client = boto3_client("s3")
try:
logger.info(f"Uploading {file} to S3 ({b... | 23,837 |
def _get_misclass_auroc(preds, targets, criterion, topk=1, expected_data_uncertainty_array=None):
"""
Get AUROC for Misclassification detection
:param preds: Prediction probabilities as numpy array
:param targets: Targets as numpy array
:param criterion: Criterion to use for scoring on misclassifica... | 23,838 |
def test_preprocess_data_weighted():
"""Copied from sklearn/linear_model/tests/test_base.py, with small
modifications.
"""
n_samples = 200
n_features = 2
X = rng.rand(n_samples, n_features)
y = rng.rand(n_samples)
sample_weight = rng.rand(n_samples)
expected_X_mean = np.average(X, ax... | 23,839 |
def test_grpc_list_refresh_tokens():
""" gRPC: Test listing refresh tokens """
dex = make_client()
refresh_tokens = dex.list_refresh(*test_http_args) | 23,840 |
def flatten(l: Iterable) -> List:
"""Return a list of all non-list items in l
:param l: list to be flattened
:return:
"""
rval = []
for e in l:
if not isinstance(e, str) and isinstance(e, Iterable):
if len(list(e)):
rval += flatten(e)
else:
... | 23,841 |
def create_note(dataset_id, fhir_store_id, note_id): # noqa: E501
"""Create a note
Create a note # noqa: E501
:param dataset_id: The ID of the dataset
:type dataset_id: str
:param fhir_store_id: The ID of the FHIR store
:type fhir_store_id: str
:param note_id: The ID of the note that is b... | 23,842 |
def load_credential_from_args(args):
"""load credential from command
Args:
args(str): str join `,`
Returns:
list of credential content
"""
if ',' not in args:
raise
file_path_list = args.split(',')
if len(file_path_list) != 2:
raise
if not file_path_list... | 23,843 |
def encode(string: str, key: str) -> str:
"""
Encode string using the Caesar cipher with the given key
:param string: string to be encoded
:param key: letter to be used as given shift
:return: encoded string
:raises: ValueError if key len is invalid
"""
if len(key) > 1:
raise Val... | 23,844 |
def compile_binary(binary, compiler, override_operator=None, **kw):
"""
If there are more than 10 elements in the `IN` set, inline them to avoid hitting the limit of \
the number of query arguments in Postgres (1<<15).
""" # noqa: D200
operator = override_operator or binary.operator
if operato... | 23,845 |
def flat_map(
fn: Callable[[_T], Iterable[_S]], collection: Iterable[_T]
) -> Iterator[_S]:
"""Map a function over a collection and flatten the result by one-level"""
return itertools.chain.from_iterable(map(fn, collection)) | 23,846 |
def add_origin(folder: PurePath, remote_path: str):
"""Add a remote pointing to GitHub repository.
:param folder: project repository.
:param remote_path: remote repository path."""
remote_repo = f"https://github.com/{remote_path}"
try:
helpers.execute_subprocess(
["git", "remote... | 23,847 |
def create_vector_clock(node_id, timeout):
"""This method builds the initial vector clock for a new key.
Parameters
----------
node_id : int
the id of one node in the cluster
timeout : int
the expire timeout of the key
Returns
-------
dict
the vector clock as di... | 23,848 |
def ParseStateFoldersFromFiles(state_files):
"""Returns list of StateFolder objects parsed from state_files.
Args:
state_files: list of absolute paths to state files.
"""
def CreateStateFolder(folderpath, parent_namespace):
del parent_namespace # Unused by StateFolder.
return state_lib.StateFolde... | 23,849 |
def broadcast(bot, event, *args):
"""broadcast a message to chats, use with care"""
if args:
subcmd = args[0]
parameters = args[1:]
if subcmd == "info":
"""display broadcast data such as message and target rooms"""
conv_info = [ "<b><pre>{}</pre></b> ... <pre>{}<... | 23,850 |
def spectral_norm(inputs, epsilon=1e-12, singular_value="left"):
"""Performs Spectral Normalization on a weight tensor.
Details of why this is helpful for GAN's can be found in "Spectral
Normalization for Generative Adversarial Networks", Miyato T. et al., 2018.
[https://arxiv.org/abs/1802.05957].
Args:
... | 23,851 |
def rs_for_staff(user_id):
"""Returns simple JSON for research studies in staff user's domain
---
tags:
- User
- ResearchStudy
operationId: research_studies_for_staff
parameters:
- name: user_id
in: path
description: TrueNTH user ID, typically subject or staff
... | 23,852 |
def from_hetionet_json(
hetionet_dict: Mapping[str, Any],
use_tqdm: bool = True,
) -> BELGraph:
"""Convert a Hetionet dictionary to a BEL graph."""
graph = BELGraph( # FIXME what metadata is appropriate?
name='Hetionet',
version='1.0',
authors='Daniel Himmelstein',
)
# F... | 23,853 |
def validate_memory(_ctx, _param, value):
"""Validate memory string."""
if value is None:
return None
if not re.search(r'\d+[KkMmGg]$', value):
raise click.BadParameter('Memory format: nnn[K|M|G].')
return value | 23,854 |
def load_db_dump(dump_file):
"""Load db dump on a remote environment."""
require('environment')
temp_file = os.path.join(env.home, '%(project)s-%(environment)s.sql' % env)
put(dump_file, temp_file, use_sudo=True)
sudo('psql -d %s -f %s' % (env.db, temp_file), user=env.project_user) | 23,855 |
def BlockAvg3D( data , blocksize , mask ):
"""
3-D version of block averaging. Mainly applicable to making superpixel averages of datfile traces.
Not sure non-averaging calcs makes sense?
mask is a currently built for a 2d boolean array of same size as (data[0], data[1]) where pixels to be averaged a... | 23,856 |
def plot(b_csvs, g_csvs, g_x, g_y, b_x, b_y, trials, seeds, plt_file, env_id,
x_label, y_label):
"""
Plot benchmark from csv files of garage and baselines.
:param b_csvs: A list contains all csv files in the task.
:param g_csvs: A list contains all csv files in the task.
:param g_x: X colu... | 23,857 |
def build(buildconfig: BuildConfig, merge_train_and_test_data: bool = False):
"""Build regressor or classifier model and return it."""
estimator = buildconfig.algorithm.estimator()
if merge_train_and_test_data:
train_smiles, train_y = buildconfig.data.get_merged_sets()
else:
train_smile... | 23,858 |
def GetXML(filename, output=OUTPUT_ELEMENT, **params):
"""
Get the XML representation of a file, as produced by the Databrowse library
Arguments:
filename - Relative or absolute path to file of interest
output - Determines the type of output to be returned from the function
... | 23,859 |
def stellar_radius(M, logg):
"""Calculate stellar radius given mass and logg"""
if not isinstance(M, (int, float)):
raise TypeError('Mass must be int or float. {} type given'.format(type(M)))
if not isinstance(logg, (int, float)):
raise TypeError('logg must be int or float. {} type given'.fo... | 23,860 |
def clean_dir(directory):
"""
Creates (or empties) a directory
:param directory: Directory to create
:return: None
"""
if os.path.exists(directory):
import shutil
logging.warning('<<< Deleting directory: %s >>>' % directory)
shutil.rmtree(directory)
os.makedirs(d... | 23,861 |
def set_plus_row(sets, row):
"""Update each set in list with values in row."""
for i in range(len(sets)):
sets[i].add(row[i])
return sets | 23,862 |
def bytes_to_string(
bytes_to_convert: List[int], strip_null: bool = False
) -> Union[str, None]:
"""
Litteral bytes to string
:param bytes_to_convert: list of bytes in integer format
:return: resulting string
"""
try:
value = "".join(chr(i) for i in bytes_to_convert)
if stri... | 23,863 |
def completion(shell):
"""
Output odahuflowctl completion code to stdout.\n
\b
Load the zsh completion in the current shell:
source <(odahuflowctl completion zsh)
\b
Load the powershell completion in the current shell:
odahuflowctl completion > $HOME\.odahuflow\odahu_completion.p... | 23,864 |
def test_sad_bad_project_prevents_seeing_custom_field():
"""
raises an error on attempt to identify that a known custom field
exists with an invalid project identifier
"""
jp = JiraProxy(GOOD_VANILLA_SERVER_CONFIG)
cfs = jp.getCustomFields(PROJECT_KEY_1, 'Bug')
assert "RallyItem" in... | 23,865 |
def interpolate(t,y,num_obs=50):
"""
Interpolates each trajectory such that observation times coincide for each one.
Note: initially cubic interpolation gave great power, but this happens as an artifact of the interpolation,
as both trajectories have the same number of observations. Type I error wa... | 23,866 |
def uniqids(seqdata, trimdefline=True, checkrevcom=True, fastq=False,
paired=False):
"""
Given a file of Fasta sequences `seqdata`, determine unique sequences and
provide their IDs. Generator function yields lists of sequence IDs.
"""
seqids = group_seqids_by_sha1(
seqdata,
... | 23,867 |
def tc_request_send(telecommand_number, telecommand_data, telecommand_data_type, is_continuous):
""" Check data type of Telecommand Request before formatting and send over COM Port. """
try:
type_error = ""
telecommand_number = int(telecommand_number)
except ValueError as err:
print(... | 23,868 |
def locktime_from_duration(duration):
"""
Parses a duration string and return a locktime timestamp
@param duration: A string represent a duration if the format of XXhXXmXXs and return a timestamp
@returns: number of seconds represented by the duration string
"""
if not duration:
raise V... | 23,869 |
def black_payers_swaption_value_fhess_by_strike(
init_swap_rate,
option_strike,
swap_annuity,
option_maturity,
vol):
"""black_payers_swaption_value_fhess_by_strike
Second derivative of value of payer's swaption with respect to strike
under black model.
See :py:fun... | 23,870 |
def get_resource(cls):
""" gets the resource of a timon class if existing """
if not cls.resources:
return None
resources = cls.resources
assert len(resources) == 1
return TiMonResource.get(resources[0]) | 23,871 |
def get_data():
"""
Esta función sirve para recopilar datos del UART y almacenar los datos filtrados
en una variable global.
"""
global serial_object
global filter_data
while(1):
try:
serial_data = serial_object.readline()
temp_data = serial_data.decode('utf-8')
#filter_data = temp... | 23,872 |
def blobs(program, *tags):
"""Usage: [tag ...]
List all blobs reachable from tag[s].
"""
for replicas in program.blobs(*tags):
print('\t'.join(replicas)) | 23,873 |
def _log(x):
"""_log
to prevent np.log_log(0), caluculate np.log(x + EPS)
Args:
x (array)
Returns:
array: same shape as x, log equals np.log(x + EPS)
"""
if np.any(x < 0):
print("log < 0")
exit()
return np.log(x + EPS) | 23,874 |
def gauss_distribution(x, mu, sigma):
"""
Calculate value of gauss (normal) distribution
Parameters
----------
x : float
Input argument
mu :
Mean of distribution
sigma :
Standard deviation
Returns
-------
float
Probability, values from range [0-1... | 23,875 |
def extend_vocab_OOV(source_words, word2id, vocab_size, max_unk_words):
"""
Map source words to their ids, including OOV words. Also return a list of OOVs in the article.
WARNING: if the number of oovs in the source text is more than max_unk_words, ignore and replace them as <unk>
Args:
source_w... | 23,876 |
def isint(s):
"""**Returns**: True if s is the string representation of an integer
:param s: the candidate string to test
**Precondition**: s is a string
"""
try:
x = int(s)
return True
except:
return False | 23,877 |
def create_app(config_name):
"""function creating the flask app"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(config[config_name])
app.config.from_pyfile('config.py')
app.register_blueprint(v2)
app.register_error_handler(404, not_found)
app.register_error_han... | 23,878 |
def test_lorent_norm():
"""Test 1d lorentzian
"""
p = np.array([0., 0., 1., -30., 3., 1., 30., 3.])
x = np.linspace(-1e6, 1e6, int(8e6) + 1)
y = functions.lorentzian(p, x)
integ = simps(y, x)
assert (abs(integ - 2.) < 1e-5) | 23,879 |
def build_attention_network(features2d,
attention_groups,
attention_layers_per_group,
is_training):
"""Builds attention network.
Args:
features2d: A Tensor of type float32. A 4-D float tensor of shape
[batch_size, height,... | 23,880 |
def INDIRECT(cell_reference_as_string):
"""Returns a cell reference specified by a string."""
raise NotImplementedError() | 23,881 |
def get_catalog_config(catalog):
"""
get the config dict of *catalog*
"""
return resolve_config_alias(available_catalogs[catalog]) | 23,882 |
def manhatten(type_profile, song_profile):
"""
Calculate the Manhatten distance between the profile of specific
output_colums value (e.g. specific composer) and the profile of a
song
"""
# Sort profiles by frequency
type_profile = type_profile.most_common()
song_profile = song_profile.mo... | 23,883 |
def raven(request):
"""lets you know whether raven is being used"""
return {
'RAVEN': RAVEN
} | 23,884 |
def _non_max_suppress_mask(
bbox: np.array,
scores: np.array,
classes: np.array,
masks: Union[np.array, None],
filter_class: int,
iou: float = 0.8,
confidence: float = 0.001,
) -> tuple:
"""Perform non max suppression on the detection output if it is mask.
:param bbox: Bbox outputs.
... | 23,885 |
def edit(client: ModelDeploymentClient, md_id: str, file: str, wait: bool, timeout: int, image: str):
"""
\b
Update a deployment.
You should specify a path to file with a deployment. The file must contain only one deployment.
For now, CLI supports YAML and JSON file formats.
If you want to updat... | 23,886 |
def pdu_create(ctx, name, pdu_type, interface, description, vim_account, descriptor_file):
"""creates a new Physical Deployment Unit (PDU)"""
logger.debug("")
# try:
check_client_version(ctx.obj, ctx.command.name)
pdu = {}
if not descriptor_file:
if not name:
raise ClientExce... | 23,887 |
def main(args):
"""
In order to detect discontinuity, two lines are loaded. If the timestamp differs
by more than the threshold set by -time-threshold, then the distance between
points is calculated. If the distance is greater than the threshold set by
-distance-threshold then the points are assumed to be discon... | 23,888 |
def notify_resource_event(
request, parent_id, timestamp, data, action, old=None, resource_name=None, resource_data=None
):
"""Request helper to stack a resource event.
If a similar event (same resource, same action) already occured during the
current transaction (e.g. batch) then just extend the impac... | 23,889 |
def _mark_untranslated_strings(translation_dict):
"""Marks all untranslated keys as untranslated by surrounding them with
lte and gte symbols.
This function modifies the translation dictionary passed into it in-place
and then returns it.
"""
# This was a requirement when burton was written, but... | 23,890 |
def pull_models():
"""
Pulls models from current project
"""
create_process("mlm pull models") | 23,891 |
def build(app, path):
"""
Build and return documents without known warnings
:param app:
:param path:
:return:
"""
with warnings.catch_warnings():
# Ignore warnings emitted by docutils internals.
warnings.filterwarnings(
"ignore",
"'U' mode is deprecat... | 23,892 |
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Fasta parser for GC content',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'fasta', metavar='FILE', nargs='+', help='FASTA file(s)')
parser.add_argume... | 23,893 |
def SMWatConstrained(CSM, ci, cj, matchFunction, hvPenalty = -0.3, backtrace = False):
"""
Implicit Smith Waterman alignment on a binary cross-similarity matrix
with constraints
:param CSM: A binary N x M cross-similarity matrix
:param ci: The index along the first sequence that must be matched to c... | 23,894 |
def check_images(
coords,
species,
lattice,
PBC=[1, 1, 1],
tm=Tol_matrix(prototype="atomic"),
tol=None,
d_factor=1.0,
):
"""
Given a set of (unfiltered) frac coordinates, checks if the periodic images are too close.
Args:
coords: a list of fractional coordinates
... | 23,895 |
def run_search(win: Surface, graph_: Grid, auto=False):
"""
Calls the Algorithm class to visualize
the pathfinder algorithm using the Visualize class
"""
print('Visualization started with:', pf.settings.default_alg.title())
if not graph_.has_bomb:
node_list = [graph_.start, graph_.end]
... | 23,896 |
def get_hamming_distances(genomes):
"""Calculate pairwise Hamming distances between the given list of genomes
and return the nonredundant array of values for use with scipy's squareform function.
Bases other than standard nucleotides (A, T, C, G) are ignored.
Parameters
----------
genomes : list... | 23,897 |
async def codec(gc: GroupControl):
"""Codec settings."""
codec = await gc.get_codec()
click.echo("Codec: %s" % codec) | 23,898 |
def serialize(name: str, engine: str) -> Dict:
"""Get dictionary serialization for a dataset locator.
Parameters
----------
name: string
Unique dataset name.
engine: string
Unique identifier of the database engine (API).
Returns
-------
dict
"""
return {'name': ... | 23,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.