content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def batched_soft_nms(boxes, scores, idxs, method, sigma, threshold):
"""
Performs soft non-maximum suppression in a batched fashion.
Each index value correspond to a category, and NMS
will not be applied between elements of different categories.
Args:
boxes (Tensor[N, 4]):
... | ebe231fe2114fa437b01ac8fc0e05ddd10fe20a1 | 3,610,600 |
import re
def match_id(url):
"""匹配歌单ID"""
try:
res = re.findall('id=(\d{4,12})', url)
return res[0]
except Exception as e:
pass
return None | 8a84cfe0ca0ebea154c451064ce838d4816e62d6 | 3,610,601 |
def base_kinesis_firehose_delivery_stream(construct, **kwargs):
# TODO: ADD ROLES, BUCKETS, AND FIREHOSE MINIMUM SETTINGS
"""
Function that generates a Kinesis Firehose Delivery Stream.
:param construct: Custom construct that will use this function. From the external construct is usually 'self'.
:pa... | 2789c8bd406a2bbaa57cdcff8d027267cb5439e7 | 3,610,602 |
def decompress_files(filepaths, remove=False):
"""
This function ...
:param filepaths:
:param remove:
:return:
"""
# Initialize a list for the decompressed file paths
new_paths = []
# Loop over the files
for filepath in filepaths:
# Get the name of the file
fi... | a17134badfe9b259fdc599ec47ee294b40060951 | 3,610,603 |
def new_combo_column(title,
data_func=None,
changed_callback=None,
edited_callback=None,
editing_started_callback=None,
editing_canceled_callback=None,
spacing=0,
visible=True,
resizable=True,
sizing=1,
fixed_width=-1,
min_width=-1,... | 035fc4ebee4cc8cefe163c94ddaf4569da2facfb | 3,610,604 |
import contextlib
import sqlite3
def query_summary(fname):
"""Query and opsim database for visits
Args:
- fname :: the name of the sqlite3 database file
Returns:
a named tuple with the summary and proposal tables
"""
table_contents = []
with contextlib.closing(sqlite3.connect(f... | d2ae294e35ce6ccc5815a9a812a5e24d9ed7f0ac | 3,610,605 |
import os
def readuncombinedspinerfile(rfilepath):
"""
read spine data from uncombined data
input: file path to real or ficticious spine.r file
output: SpineData from uncombined data
"""
# construct the directory and call the other routine:
if not os.path.isabs(rfilepath):
... | 6e4d66731729ad2c6b77ff622f4b4669f434633b | 3,610,606 |
def prepare_pcoa(pcoa, number_of_features):
"""Selects top N biplot features by magnitude (coped from q2-emperor).
Parameters
----------
pcoa : skbio.stats.ordination.OrdinationResults
number_of_features : int
Returns
-------
skbio.stats.ordination.OrdinationResults
"""
feats =... | c5403b554ae40a1740733a2b6d9e6a61d8794b2b | 3,610,607 |
def _jupyter_bundlerextension_paths():
"""
Entrypoint for Jupyter Notebook Bundler
Shows up in the 'Download' menu on Jupyter Classic Notebook
"""
return [{
'name': 'chrome_pdf_export',
'label': 'PDF via Chrome (.pdf)',
'module_name': 'nbpdfexport.bundler',
'group': ... | 1d948a5eed6f4240e760c52bec776c3fbf291f14 | 3,610,608 |
def DecodeVigenereLongueurCle(message, mot=3):
"""
Cette fonction determine la longueur de la clé, elle
repère les groupes de trois lettres qui se répète dans le message codé
et suppose qu'il y a une très forte probabilité qu'un même groupe de trois
lettres soit codé avec les mêmes trois lettres du ... | 3ee2f974e82e9cb30d049bfd4550305605950815 | 3,610,609 |
def median(data_list):
"""
Finds the median in a list of numbers.
:type data_list list
"""
data_list = list(map(float, data_list))
length = len(data_list)
data_list.sort()
# Test whether the length is odd
if length & 1:
# If is is, get the index simply by dividing it in half... | c41a1336d17e5e991101bd91c9c56cb59624dc82 | 3,610,610 |
import functools
def on_package_attributes(**attr_dict):
"""Decorator: executes instance function only if object has attr valuses.
Executes the decorated method only if at the moment of calling the
instance has attributes that are equal to certain values.
Args:
attr_dict (dict): dictionary m... | 9c3f4be4bbe02d0d70b97ae5d9437480262b5e79 | 3,610,611 |
def filelineno():
"""
Return the line number in the current file. Before the first line
has been read, returns 0. After the last line of the last file has
been read, returns the line number of that line within the file.
"""
if not _state:
raise RuntimeError("no active input()")
retur... | d5c86e0c2232b35fa5b714226f832449b60c5b63 | 3,610,612 |
def create_dual_point_kernel(size, distance_apart, padding=0):
"""Generates a square float image with two, single-pixel point sources.
The top source has double the intensity of the bottom source. The sources
are distributed along the vertical center and are spaced a set distance apart.
:param size... | ebbfdc6d3843ba3f4b05f2c616ba1d123dd86a55 | 3,610,613 |
def auc(actual, posterior):
"""
auc
"""
r = tied_rank(posterior)
num_positive = len([0 for x in actual if x == 1])
num_negative = len(actual)-num_positive
sum_positive = sum([r[i] for i in range(len(r)) if actual[i] == 1])
auc = ((sum_positive - num_positive * (num_positive + 1) / 2.0) /... | cc3822ede98c25e89cabd9d25fc2218ff42b4e4e | 3,610,614 |
from django.test import SimpleTestCase as TestCase
from django.test import TestCase
def is_django_unittest(item):
"""Returns True if the item is a Django test case, otherwise False"""
try:
except ImportError:
if sys.version_info < (3, 0):
return (hasattr(item.obj, 'im_class') and
... | 13702023578bf029ea9d130114b13dff26592f3e | 3,610,615 |
def parametrized(f):
"""Is this function or object decorated with @parametrize or @matrix?"""
return Mark.marked(f, PARAMETRIZED) or Mark.marked(f, MATRIX) or Mark.marked(f, DEFAULTS) | b4cf00ab71a365a477678a11a276ece8248e5fcb | 3,610,616 |
import asyncio
def analyze_body(sdf, address=("127.0.0.1", 11346)):
"""
Single body analyzer. Opens a new connection, analyzes the
body, and returns the result. If you already have a manager
running doing other things, create an instance of `BodyAnalyzer`
instead.
:param sdf: SDF object consi... | 2b75241c6aedd0bac524eadbcd3968caf57f021a | 3,610,617 |
def cmd_trade_info(strategy: Strategy, strategy_trader: StrategyTrader, data: dict) -> dict:
"""
Get trade info according data on given strategy_trader.
@note If trade-id is -1 assume the last trade.
"""
results = {
'messages': [],
'error': False
}
trade_id = -1
... | eb89294444f28a80eff8f1527a048341d17bc88c | 3,610,618 |
def drift_confidence(df_resample, out_path, fps, pca=1, save_fig=0):
"""
Args:
df_resample:
out_path:
fps:
pca:
save_fig:
Returns:
"""
if pca:
flow_key = 'diffflow_pca'
acc_key = 'acc_pca'
else:
flow_key = 'diff_flowx'
ac... | e3dce48e9747c4f22ee71f4029faa16cd6864c75 | 3,610,619 |
def power_factor(s: np.ndarray) -> np.ndarray:
"""Given a numpy array of complex values, compute power factor.
If the power factor is lagging, a positive value will be returned.
If the power factor is leading, a negative value will be returned.
Reference:
Power System Analysis and Design, 5th Edit... | 0cc50fdeaa485e1194c2ab897322963a9b1a39a1 | 3,610,620 |
def pad_factor(input_image, spatial_dims, factor):
"""Pad `input_image` (N,C,H,W) such that H and W are divisible by `factor`."""
if isinstance(factor, int) is True:
factor_H = factor
factor_W = factor_H
else:
factor_H, factor_W = factor
H, W = spatial_dims[0], spatial_dims[1]
... | 7b07bf7fcca5f05ecdd47420ac2493b7aed37277 | 3,610,621 |
def zeropad(data, m=2):
"""Pad with zeros to make an array with an even multiple of m voxels in all dimensions
"""
if data.ndim < 2 or data.ndim > 3:
raise RuntimeError('Unsupported number of dimensions {}. We only supports 2 or 3D arrays.'.format(data.ndim))
if data.ndim == 2:
... | 43cf2e5974b4ad0b64e998d33bd9faf724d51300 | 3,610,622 |
import argparse
def main( argv ):
"""
Script execution entry point
@param argv Arguments passed to the script
@return Exit code (0 = success)
"""
# imports when using this as a script
# create and configure an argument parser
parser = argparse.ArgumentParser(
... | 5f2f92bb7daf886a663689efc8789fa91cc7b849 | 3,610,623 |
def h2fk5(rh, dh, drh, ddh, pxh, rvh):
"""
Wrapper for ERFA function ``eraH2fk5``.
Parameters
----------
rh : double array
dh : double array
drh : double array
ddh : double array
pxh : double array
rvh : double array
Returns
-------
r5 : double array
d5 : double... | 108e3f241bce70ed5dc6a6d6c36ca44b13d352d1 | 3,610,624 |
def Connect(*args, **kwargs):
"""Factory function for connection.Connection."""
return connection.Connection(*args, **kwargs) | 9b65dcd4fb73af1e52fa4dffa7b91cfc58532730 | 3,610,625 |
def get_post_by_user(user: str, start=None, end=None, now=None):
"""TODO: Docstring for get_user.
:user: TODO
:returns: TODO
"""
if start is not None and end is not None:
posts = Post.objects.filter(create_date__gte=start, create_date__lte=end, user__user_id=user)
elif start is not Non... | b32179f77ecd1e64f909a18a07e85b3237539425 | 3,610,626 |
def solve_lp_puzzle(lp, boxsize):
"""Solve a linear program Sudoku and return puzzle dictionary."""
lp.simplex()
for col in lp.cols:
col.kind = int
lp.integer()
return lp_to_dict(lp, boxsize) | b4ceee41dddbb74adc6be96ae31b762cd46ce582 | 3,610,627 |
def show_error_info(title, message, unknown_error=False, netflix_error=False):
"""Show a dialog that displays the error message"""
prefix = (30104, 30102, 30101)[unknown_error + netflix_error]
return xbmcgui.Dialog().ok(title, (common.get_local_string(prefix) + '\r\n' +
... | a0e2f5971debf94d0cbc6032126a9966ad3dd840 | 3,610,628 |
def is_token_expired(token):
"""Checks if given token is valid"""
try:
decoding = jwt.decode(token, config['jwt_secret'], config['jwt_algorithm'])
return False
except jwt.ExpiredSignatureError:
return True | 30bfc86d5b4d516b0257fa58755c51264dd2ec24 | 3,610,629 |
import re
import csv
def _getIdsFromQuery(queryString, syn, downloadLocation):
"""Helper function that extracts the ids out of returned query."""
if re.search('from syn\\d', queryString.lower()):
tbl = syn.tableQuery(queryString, downloadLocation=downloadLocation)
check_for_id_col = filter(l... | 3f38f02c01c87932317d1241645dca6fac3b484e | 3,610,630 |
def get_sshkey(sshkey):
"""
Get start ip for ip range
CLI Example:
.. code-block:: bash
salt 'maas-node' maasng.get_sshkey sshkey
salt-call maasng.get_sshkey sshkey
"""
try:
return list_sshkeys()[sshkey]
except KeyError:
return {"error": "SSH key not found ... | 774edde0d7f3e63b81d5365b7226599e979e1de7 | 3,610,631 |
from pathlib import Path
from typing import Dict
def process_image(in_img_path: Path, out_img_dir: Path) -> Dict[Path, Path]:
""" Extract EXIF data from image and return path mapping """
with open(in_img_path, "rb") as image_file_stream:
image = Image(image_file_stream)
if hasattr(image, "date... | 454f8a5ffec9ea06435bfd7bc9bbfcbc0de82687 | 3,610,632 |
def get_vars_maybe_avg(var_names, ema, **kwargs):
"""utility for retrieving polyak averaged params."""
vars_tf = []
for vn in var_names:
vars_tf.append(get_var_maybe_avg(vn, ema, **kwargs))
return vars_tf | 0e35821d8883031dceca0e05d31b792c92adbd78 | 3,610,633 |
from typing import Sequence
from typing import Optional
import os
import sys
from typing import List
from typing import Dict
from typing import Set
def parallel_exec_transform_with_prettyprint( # noqa: C901
transform: Codemod,
files: Sequence[str],
*,
jobs: Optional[int] = None,
unified_diff: Opt... | e20755426fcd9aefea472791d952208a9d38fec2 | 3,610,634 |
import traceback
def _create_lineage_by_table_name(
metadata: OpenMetadata,
from_table: str,
to_table: str,
service_name: str,
database: str,
query: str,
):
"""
This method is to create a lineage between two tables
"""
try:
from_raw_name = get_formatted_entity_name(str... | 797b1808cb5fef908d49b14e35120b46a04ab1af | 3,610,635 |
from typing import List
from typing import Tuple
def open_files(
file_names: List[str], mode: str = "readonly"
) -> Tuple[List[fits.HDUList], List[np.ndarray]]:
"""Gets the HDULS and data handles for all the files in file_names.
This is a convience function to opening multiple FITS files using
m... | c26a9f9d6348c6279851aeb4993f79682c7c0838 | 3,610,636 |
def multi_to_single(y, combinations):
"""Convert multilabel indices to singlelabel strings."""
single = []
for y_i in y:
y_i_str = ", ".join([str(i) for i in y_i])
single.append(combinations.index(y_i_str))
return single | 7e8839173b047cb0bb89d143ce2b30b928630f2d | 3,610,637 |
from typing import Tuple
from typing import Counter
import os
import tqdm
def read_csv(csv_folder: str, split: str, word_limit: int) -> Tuple[list, list, Counter]:
"""
Read CSVs containing raw training data, clean sentences and labels, and do
a word-count.
Parameters
----------
csv_folder : s... | fbdcbd03d587da8c81608f78c22d24767f5a26b1 | 3,610,638 |
from re import DEBUG
def fill_nan_pixels(image, noise_distribution=None):
"""Replace *in-place* `NaN` values in `image` by zeros or by random noise.
Images containing `NaN` values generate undesired harmonics with wavelet
image cleaning. This function should be used to "fix" images before each
wavele... | dad3ec7e5ff4125149d1635c978c2525322d5e57 | 3,610,639 |
def _parse_taxa_report(local_path, **kwargs):
"""Return a dict of taxa_name to read_counts."""
out, abundance_sum = {}, 0
with open(local_path) as taxa_file:
for line_num, line in enumerate(taxa_file):
line = line.strip()
tkns = line.split('\t')
if not line or len... | b3b18010820dbc409b66c8c1d5636430c052382d | 3,610,640 |
def build_conservation_status_message(data: list[str]) -> str:
"""
Builds a string describing the conservation status of the species.
:param data: Data containing conservation status information
:return: Description of the conservation status (or empty if no data)
"""
if data:
return CON... | 7457234d64300baa42047067d81799881a406ff8 | 3,610,641 |
def get_col_reduced_right(A, symb, T = None, return_internals = False):
"""
Takes a polynomial matrix A(s) and returns a unimod Transformation T(s)
such that A(s)*T(s) (i.e. right multiplication) is col_reduced.
Approach is taken from appendix of the PHD-Thesis of S. O. Lindert (2009)
:args:
... | 77a499f272848afedd6a6869fa6166c993e4e9ae | 3,610,642 |
def ivarName(value, position):
"""A name of a class."""
if not value[0] == '_' or not value[1].islower():
return Error(
'BadInstanceVariableName', 'Instance variable names start with _ and not be capitalized', position, LINES)
return None | 1ba3d34a949aaf6d2bee235fe8885fac827f0f9a | 3,610,643 |
def verilog_value_to_int(verilog_value):
""" Convert VerilogValue model to width, value, value_format """
width = None
if verilog_value.plain_decimal:
return width, int(verilog_value.plain_decimal), ValueFormat.PLAIN
if verilog_value.width:
width = int(verilog_value.width)
if veri... | e8d1c938cea56b8cd3277f445dd5d6eb85de60eb | 3,610,644 |
import random
def create_quiz_form(quiz):
"""Create quiz form with all its question choices,
shuffle the choices for quiz page"""
form = QuizForm()
for i in range(10):
form.questions[i].answers.choices = [
quiz.questions[i].correct_answer,
quiz.questions[i].wrong_... | 56c73d48532df049aec2f2c78d0ae35c89351cd7 | 3,610,645 |
from typing import Tuple
def drop_zeros_ctg(fhr: np.array, uc: np.array, time: np.array) -> Tuple[np.array, np.array, np.array]:
"""
Removes all missingvalues, encoded as zeros
Args:
uc, fhr signals: (np.arrays) 1D signals
time: (np.array) 1D time signal
Output: Tuple(n... | 19f0d90a5cf08057b08186754c262afe9d16d294 | 3,610,646 |
def report_and_reset_timings():
"""Returns the pass timings report and resets the LLVM internal timers.
Pass timers are enabled by ``set_time_passes()``. If the timers are not
enabled, this function will return an empty string.
Returns
-------
res : str
LLVM generated timing report.
... | 76fabaca3e99823182d1c6623e7c01126966c856 | 3,610,647 |
from typing import Union
from typing import Iterable
def transform_coords(x: Union[DataArray, Dataset],
targets: Union[str, Iterable[str]],
graph: GraphDict,
*,
rename_dims: bool = True,
keep_aliases: bool = True,... | b8777248c7ff4313f239a91a5ec5c6001ba0835c | 3,610,648 |
def Answer_f(text):
"""
:param text: The "text" of this Answer
"""
return '\\begin{block}{Answer}\n' + text + '\n\\end{block}\n' | 2de98b286d31e31f2b934760f715af1ecda83daa | 3,610,649 |
def gather_states(ii):
"""
Return the current state (position/probability/bias) of walkers in a given window.
Parameters
----------
ii : integer
The index of the umbrella to get the state of.
Returns
-------
state : list
The state of window ii.
"""
retu... | 46b2f3db3ff71fbca2f1b54b39f627f32e3a5ff5 | 3,610,650 |
def word_embeddings_rbo(list1, list2, p, index2word, word2vec, norm):
"""Complete RBO analysis (lower bound, residual, point estimate).
``list`` arguments should be already correctly sorted iterables and each
item should either be an atomic value or a set of values tied for that
rank. ``p`` is the proba... | 5fc29129d4722dc7381c6edbc6df465d993f0528 | 3,610,651 |
def drop_na_inputs(*, input_data: pd.DataFrame) -> pd.DataFrame:
"""
Check model inputs for na values and filter them
based on the ones the model knows how to handle.
"""
validated_data = input_data.copy()
new_vars_with_na = [
var
for var in config.model_config.inputs
if... | 0b757add023c34c8f081d58e56f01da59dc87ca4 | 3,610,652 |
import re
import json
def geojsonfeature(source, params=''):
"""
:params: A string with the following optional tokens:
"properties:field:srid"
"""
parse = re.search(r'(?P<properties>((\w+)(,\w+)*)?)(:(?P<field>(\w+)?))?(:(?P<srid>(\d+)?))?', params)
if parse:
parse = parse.gro... | 4fd0e2e8d9d461ff2775dd21ce39fceca1905118 | 3,610,653 |
def expected_return_time(M, backward=False):
"""Find the expected returning time.
Parameters
----------
M: :class:`~numpy.ndarray` (dimension n x n, where n is the cell number)
The transition matrix.
backward: bool (default False)
Whether the backward transition will... | 2a0963e20c09f92f7e1ae2177d4277f589052620 | 3,610,654 |
def att_moment_metric(mass, att_moment):
"""
This function calculates the metric for the attitude moment. It does not consider moments of inertia for the
satellite, nor passive sources of moment
:param mass:
:param att_moment:
:return:
"""
return np.float64(1.25 * (att_moment / mass)).cl... | 87ac22c1ddd58aa257fa4485fbd48189599215ce | 3,610,655 |
from typing import Sequence
from typing import Dict
def get_largest_area(rect: Rect, points: Sequence[Point]) -> int:
"""Find the largest bounded area around all the points.
This basically is creating a voronai using the manhattan distance, and throwing out any ties.
If any of the cells are on the edge o... | 0f6b3e0085b963435e2da40a399d12d5704a9acc | 3,610,656 |
import json
def body_part_to_headers_and_data(part):
"""
convert part (of multi-part body) to headers dict and content. de-serializes json if content-type is
application/json.
:param part: BodyPart decoded by MultipartDecoder
:return: tuple pair of headers dict and content
"""
if b'applic... | edd95f6dba9f4157c6a51b2dd6a6c4fb8a34e9db | 3,610,657 |
def flip_marker_states(aut):
"""
Return an automaton that has all marker states flipped
@param aut: Input automaton
@type aut: L{Automaton}
@return: Flipped automaton of L{aut}
@rtype: L{Automaton}
"""
new_aut = aut.copy()
for state in new_aut.get_states():
flip_single_ma... | e7fd6e539cb1dc3a35b41779fd4a6823a454a806 | 3,610,658 |
def find_all_presented_sfs(stim_df, ecc_step=1, ecc_range=(1, 12), size=1080,
max_visual_angle=24, stimulus_mask=None):
"""Find average spatial frequency presented in eccentricity bands for each stimulus.
Only works on square images.
Returns a dataframe with the average spatial ... | 67398f4fdfb01178acd38f676846943ef3c155dc | 3,610,659 |
def encapsulateTable(string_table,column_labels, caption,ttype=None):
"""Uses the output of makeTables to render a complete latex table"""
if ttype in ("kolmDiff3","kolmDiff3_","kolmSamp_","kolmSamp","textCorr","allFloat"):
header="\\begin{table*}[h!]\n\\begin{center}\n\\begin{tabular}{| l |"+" c |"*(st... | 63af2164b79ca73c3362cd535c4a98855495e18f | 3,610,660 |
from datetime import datetime
def convert_datetime(inpt):
"""Return value of input
dateTime formating assumed according to ISO standard:
* http://www.w3.org/TR/NOTE-datetime
* https://www.w3.org/TR/xmlschema-2/#dateTime
Examples: 2016-09-20T12:00:00, 2012-12-31T06:30:00Z,
2017-01-0... | fedd952c814b084817710f4cdb26a43a559ab04c | 3,610,661 |
from twistdb.sampletrack import Sample, PlateType
def bulk_to_temp_transform( db, bulk_plate_barcode, pca_plates ):
"""
returns a transform for consumption by echo_csv
"""
pd = primer_dict( db, pca_plates )
rows = []
primer_ct = defaultdict(int)
layout = db.query(PlateType).get('SPTT_000... | 331799b500b4d342a8bb58b6744210cae1485614 | 3,610,662 |
def gaussian1d_variant1(x, *p):
"""
Create a normalised gaussian (Area == 1) from mean and variance
:param x: [numpy array] x axis data (array/list)
:param p: [Tuple] (mean , variance)
Area of gaussian is 1 --> A = 1/(c*sqrt(2pi))
Returns a Gaussian array one value for each x valu... | 876b8b62ce4a6d632efc94539d0dfc54900b1e29 | 3,610,663 |
import urllib
import traceback
def evtimer(request, ettype, config_id, query=''):
"""
[メソッド概要]
タイマー管理するイベントを管理する
[引数]
ettype : イベント管理種別('cron' or 'timer')
config_id : イベント管理するシステム設定ID
"""
logger.logic_log('LOSI00001', 'ettype=%s, config_id=%s' % (ettype, config_id))
re... | 595f7508cbcfd2434636e78b3a9d71de0603761c | 3,610,664 |
def dc_node(request, hostname, data=None):
"""
Show (:http:get:`GET </dc/(dc)/node/(hostname)>`),
create (:http:post:`POST </dc/(dc)/node/(hostname)>`),
change (:http:put:`PUT </dc/(dc)/node/(hostname)>`) or
remove (:http:delete:`DELETE </dc/(dc)/node/(hostname)>`)
a compute node (hostname) asso... | 0cd7725319ea944c0a3da99c62610a669ee60550 | 3,610,665 |
from typing import Type
def get_appliance_api_type(appliance_type: ErdApplianceType) -> Type:
"""Get the appropriate appliance type"""
_LOGGER.debug(f"Found device type: {appliance_type}")
if appliance_type == ErdApplianceType.OVEN:
return OvenApi
if appliance_type == ErdApplianceType.FRIDGE:
... | 8404d233adc44f5e5b63258414c57b620913d865 | 3,610,666 |
from datetime import datetime
def parseDateTag(tag: bs4.element.Tag) -> str:
"""Parse date tag.
:param tag: html table data element
:return: date string
"""
date = datetime.strptime(tag.text, '%m/%d/%Y').strftime(DATE_FORMAT)
return date | 9be00eafe72b251e19ca480f1eb058da03ea7b1c | 3,610,667 |
def get_utm_zone(lon):
""" Calculate UTM zone.
Arguments:
lon: float
Longitude, in degrees. West: negative, East: positive.
Returns:
zone: int
UTM zone number.
"""
zone = int(1+(lon+180.0)/6.0)
return zone | cf8c0d596f146417ebf0d3a18cd0b70e825388aa | 3,610,668 |
def create_eyelid_follicle_system(driver_object="", selected_vertices=(), surface_mesh_name=""):
"""
creates follicle drivens that drives the joints that are driven by the driver controllers.
This is a complicated system that requires these steps:
1. select vertices.
2. get the closest UV from the s... | a580d4aa955511b05d33fabdefd664f5111b83c5 | 3,610,669 |
from typing import List
def create_chassis(world: b2World, vertices: List[b2Vec2], densities: List[float]) -> b2Body:
"""
Creates a chassis to be the body of the car.
"""
if len(vertices) != len(densities):
raise Exception('vertices and densities must be same length')
# Create body defini... | bd8ac60df9c9e217923099c3f8d7c2476f3360eb | 3,610,670 |
def napalm_cli(task, commands, hostname=None, username=None, password=None,
driver=None, timeout=60, optional_args=None):
"""
Run commands on remote devices using napalm
Arguments:
commands (list): list of commands to execute on the device
hostname (string, optional): default... | 00abff61eddfac22d3f867252c403ca70ffb43cf | 3,610,671 |
import torch
def _create_zero_states(model: RecurrentLM) -> ActivationDict:
"""Zero-initialized states if no init state is provided.
Returns
-------
init_states : ActivationTensors
Dictionary mapping (layer, name) tuple to zero-tensor.
"""
init_states: ActivationDict = {
a_nam... | 8ece9f249099b2de678e2f173f1428f8b635bb0d | 3,610,672 |
def append_iqa_scores(df):
"""Load image quality assessment scores and append to a dataframe of observation records"""
# Sort user IDs by number of observations (in the current dataset) per user
scores = load_iqa_scores()
first_result = list(scores.values())[0]
for key in first_result.keys():
... | 2f04bd2e2c8b440fd5159cddff9b1205eb4d974b | 3,610,673 |
from typing import List
def _setup_entities(hass, device_ids: List):
"""Set up Tuya Climate."""
device_manager = hass.data[DOMAIN][TUYA_DEVICE_MANAGER]
entities = []
for device_id in device_ids:
device = device_manager.deviceMap[device_id]
if device is None:
continue
... | bee211a1b67690ad064b05189b73d05e8a9841db | 3,610,674 |
import collections
def _iterateOverDicts(ob, func):
"""
This function iterates a function over a nested dict/list
see https://stackoverflow.com/questions/32935232/python-apply-function-to-values-in-nested-dictionary
"""
assert type(ob) == dict, '**** _iterateOverDicts requires a dict input'
fo... | 04aacf2513dd0a702379ec3506943255a9dce137 | 3,610,675 |
def mask_rcnn_functional(config: dict) -> tf.keras.Model:
"""
Construct a model in functional API
Args:
config: General MaskRCNN config, dict
Returns: tf.keras.Model:
"""
# Prevent creating keras names with index increment.
# It is important for weights setting from training to infe... | 1c73e43b3980e957c5a774d87da85997760a9e69 | 3,610,676 |
def ast_from_input(input, mode, transformer, parser):
"""converts a source input into an AST
- input : the source to be converted
- mode : 'exec', 'eval' or 'single'
- transformer : the transfomer instance to use to convert
the nested tuples into the AST
XXX: transformer co... | 23c8884736559f3b6334e288af2e6cc751b09045 | 3,610,677 |
def CvSepFilter_init_gaussian_kernel(*args):
"""
init_gaussian_kernel(CvMat kernel, double sigma=-1)
CvSepFilter_init_gaussian_kernel(CvMat kernel)
"""
return _cv.CvSepFilter_init_gaussian_kernel(*args) | e45f3cd87f17e3a2dfecbcf92bed7e7ff512ad7b | 3,610,678 |
def print_to_terminal(self, step, data, count, unassigned_array_length, method, re=False, second_pass=False):
"""
Prints some information to the terminal if verbose == True
"""
if (re is False) and (second_pass is False):
print('')
print('Beginning analysis...')
print('')
... | b905d0956602e22086a93245d694fb63c9c294ad | 3,610,679 |
def get_num_params(vocab_size, num_layers, num_neurons):
"""Returns the number of trainable parameters of an LSTM.
Args:
vocab_size (int): The vocabulary size
num_layers (int): The number of layers in the LSTM
num_neurons (int): The number of neurons / units per layer
Returns:
... | c9620e74206878cc3390895dacbf10c84da42829 | 3,610,680 |
import json
def serialize_model_object(obj):
"""
Serialize model into a dict representable as JSON
Args:
obj (django.db.models.Model): An instantiated Django model
Returns:
dict:
A representation of the model
"""
# serialize works on iterables so we need to wrap obj... | fdda44b00b4d779dd0034069bdf2af7f0b43a146 | 3,610,681 |
from typing import List
def secure_clauses(file_system: FileSystem, clauses: List[Clause]) -> List[Arc]:
"""Construct a "safe" version of the given renaming clauses and update the file system.
The resulting sequence is a reordered copy of the given clauses, with potentially the
insertion of intermediate ... | 91abf78068861e104bd0c7bd77e08ef7620490c7 | 3,610,682 |
from typing import Union
from typing import List
def create_benchmark_result(
project_id: str,
study_id: str,
benchmark_id: str,
data_sets: Union[DataSet, List[DataSet], DataSetCollection],
) -> BenchmarkResult:
"""Creates a benchmark result.
Parameters
----------
project_id
T... | f94192423faa14466b362c8875fc95c34b7e4994 | 3,610,683 |
from datetime import datetime
def claims_scroll(curr_page, scroll_status):
"""Performs the query to get claims on the specified page."""
if curr_page is None:
curr_page = 0
if scroll_status == "next":
if curr_page >= 0:
curr_page += 1
elif scroll_status == "init":
... | dcd033e42c306bed6e1a85db849f6b0851bdfbe7 | 3,610,684 |
def init():
"""
initialisation funtion for animation
"""
p.set_data([],[])
p_highlight.set_data([], [])
highlight_path.set_data([], [])
return p, p_highlight, highlight_path | c1b4e9ec5bd36b616252fa20d60f879dab6d762a | 3,610,685 |
from PIL import Image, ImageDraw, ImageFont
def add_text(img, text, coords=(0.02, 0.95), fontsize=0.03, fill=(0, 0, 0)):
"""
Adds text to a provided image in numpy.ndarray format.
Coords are in relative position
"""
img *= 255
img = Image.fromarray(img.astype(np.uint8))
width, height = img... | 9fb2d9a6f77178c0104cf02b3b9db26b35b32750 | 3,610,686 |
import os
import shutil
def DownloadData(output_folder, latlim, lonlim, dataset, level = None):
"""
This function downloads SoilGrids data from SoilGrids.org
Keyword arguments:
output_folder -- directory of the result
latlim -- [ymin, ymax] (values must be between -50 and 50)
lonlim -- [xmin, x... | 17e8ef82ece87002291acffe6b4a111fb08cf324 | 3,610,687 |
import logging
import os
def run_codeml_for_sicos(codeml_dir, genome_ids_a, genome_ids_b, sico_files):
"""Run codeml for representatives of clades A and B in each of the SICO files, to calculate dN/dS."""
logging.info('Running codeml for %s aligned and trimmed SICOs', len(sico_files))
codeml_files = []
... | 3009550b804f4e116c4b50e30a31673249b2c4bd | 3,610,688 |
import pickle
def import_data(object_name):
"""Extract data from data dir."""
with open(f"data/{object_name}.pkl","rb") as my_file:
return pickle.load(my_file) | d497048d53e3ba95bceccc172b7d47781c3bbc2c | 3,610,689 |
def convert_to_nullable(input_val, cast_function):
"""For non-null input_val, apply cast_function and return result if successful; for null input_val, return None.
Args:
input_val (Any): The value to attempt to convert to either a None or the type specified by cast_function.
The recognized ... | ba12f32d2bcced066257788188a2a9d91fcfec37 | 3,610,690 |
from typing import List
def maxSubArray(nums: List[int]) -> int:
"""
Time: O(n)
Space: O(1)
"""
local_max = 0
global_max = float('-inf')
for n in nums:
local_max = max(n, n + local_max)
if local_max > global_max:
global_max = local_max
return globa... | f466884aa7b9d5865464e4db3c625abc8add23ec | 3,610,691 |
def Nu_waste(Re_outtube_waste, Pr_coolwater_waste):
"""
Calculates the Nusselt criterion of coolwater.
Parameters
----------
Re_outtube_waste : float
The Reynold criterion, [dimensionless]
Pr_coolwater_waste : float
The Prandtl criterion, [dimensionless]
Returns
-------
... | ae2dfb2cb026b1c8f05fa71a2936456f518fffd1 | 3,610,692 |
def fig_fire_assessment(assessment: SituationAssessment.WildfireCurrentAssessment,
original_ignition: ty.Sequence[TimedPoint],
max_time: float = np.inf) -> display.GeoDataDisplay:
"""Assessed wildfire map"""
gdd = display.GeoDataDisplay.pyplot_figure(assessment.ge... | a9067b37a6f3df95e0d9de28a63774006876b8bf | 3,610,693 |
def calc_pi():
"""A crude (even for python) implentation of monte pi
"""
Nsample=100000000
x = np.random.rand(Nsample)
y = np.random.rand(Nsample)
count = np.sum(np.sqrt(x**2+y**2)<1)
return 4*count/Nsample | 4a99e5f2feeaef884a849cd88690ff86f6f8db93 | 3,610,694 |
def split_group(nsubj, ngroups):
"""Split the proposed group into random disjoint subgroups
Parameters
----------
nsubj (int) the number of subjects to be split
ngroups(int) Number of subbgroups to be drawn
Returns
-------
samples: a list of ngroups arrays containing
the i... | 4959819c55b871016840f2899e7c2d186b91a9ea | 3,610,695 |
def reduce_table(table, params, exclude_any=None, exclude_all=None):
"""Returns the subset of a table that satisfy the specified variables
table : pd.DataFrame
table to reduce (pandas table)
params : dict
params that must all be satisfied (each value must be scalar)
exclude : dict
... | 9bdb133771aed147a3ad588a96e5a208f3729491 | 3,610,696 |
def get_maya_main_window():
"""return the main window of maya
:rtype: QtWidgets.QMainWindow
"""
ptr = mui.MQtUtil.mainWindow()
return shiboken2.wrapInstance(long(ptr), qtgui.QMainWindow) | 5536443f9a485a74808a9fde522b3a2496225e1a | 3,610,697 |
def get_rank1(x, dict_y):
"""
Computes rank-1 distance between one vector given a set of other vectors. The higher the better.
:param x: vector of appearances of the query object
:param dict_y: dictionnary of appearances of the candidates objects
"""
# We create a 2D-array with all the feature... | b3dc3fbca3683df635863a5f951559548abc834b | 3,610,698 |
def _align_column(strings, alignment, minwidth=0, has_invisible=True):
"""
[string] -> [padded_string]
>>> list(map(str,_align_column( \
["12.345", "-1234.5", "1.23", "1234.5", \
"1e+234", "1.0e234"], "decimal")))
[' 12.345 ', '-1234.5 ', ' 1.23 ', \
' 1234.5 ', ' ... | 67f302883e287ad8b8b622f9241cba4b5be92db3 | 3,610,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.