content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def translate(bboxes, x, y):
"""Map bboxes from window coordinate back to original coordinate.
Args:
bboxes (np.array): bboxes with window coordinate.
x (float): Deviation value of x-axis.
y (float): Deviation value of y-axis
Returns:
np.array: bboxes with original coordina... | 61,500 |
def position_encoding(sentence_size, embedding_size):
"""
Position Encoding described in section 4.1 [1]
"""
encoding = np.ones((embedding_size, sentence_size), dtype=np.float32)
ls = sentence_size+1
le = embedding_size+1
for i in range(1, le):
for j in range(1, ls):
enc... | 61,501 |
def import_(path):
"""
Import string format module, e.g. 'uliweb.orm' or an object
return module object and object
"""
if isinstance(path, str):
v = path.split(':')
if len(v) == 1:
x = path.rsplit('.', 1)
if len(x) == 2:
module, func = x
... | 61,502 |
def table_init():
"""
表结构初始化
:return:
"""
db.drop_all()
db.create_all() | 61,503 |
def animate(i):
"""
Animation function. Paints each frame. Function for Matplotlib's
FuncAnimation.
"""
img.set_data(mod_psis[i]) # Fill img with the modulus data of the wave function.
img.set_zorder(1)
return img, | 61,504 |
def add_con_vars(
recipe: MyRecipe,
name: tp.Union[str, None] = None,
params: tp.Union[None, str, tp.List[str]] = "a"
):
"""Add variables at contribution level.
The name is the name of the contribution. If None, all the contribution will be searched and added.
"""
if not name:
for c... | 61,505 |
def linear(input_, output_size, stddev=0.02, bias_start=0.0, activation_fn=None, name='linear'):
"""
Fully connected linear layer
:param input_:
:param output_size:
:param stddev:
:param bias_start:
:param activation_fn:
:param name:
:return:
"""
shape = input_.get_shape().a... | 61,506 |
def aupr(preds, labels):
"""Calculate and return the area under the Precision Recall curve using unthresholded predictions on the data and a binary true label.
preds: array, shape = [n_samples]
Target scores, can either be probability estimates of the positive class, confidence values, or non-thresh... | 61,507 |
def create_app(name=__name__,
init_mode=False, destroy_mode=False,
worker_mode=False, testing_mode=False,
skip_endpoint_mapping=False,
**kwargs):
""" Create the server istance for Flask application """
if PRODUCTION and testing_mode:
log.exit(... | 61,508 |
def gui_check_ready():
"""
This GUI-related function is called when a user clicks on the "Update
my course!" button.
It ensures that the user has marked the checkbox indicating that they
have a backup of their old course files. It also confirms that both
source and destination .imscc file paths ... | 61,509 |
def read_elementtree(xml_file):
"""Creates an ElementTree from an XML file"""
return ET.parse(xml_file) | 61,510 |
def get_config_options():
"""
get config options list
"""
result = []
for class_name in dir(sys.modules['RepositoryModule']):
if class_name[0].isupper() and class_name != 'Repository':
result.append(class_name)
return result | 61,511 |
def make_node() -> Node:
"""Make a dummy node."""
bel = f'p(HGNC:{n()})'
return Node(type=PROTEIN, bel=bel, md5=hashlib.md5(bel.encode('utf-8')).hexdigest(), data={}) | 61,512 |
def cryptoBook(symbol, token="", version="stable", filter="", format="json"):
"""This returns a current snapshot of the book for a specified cryptocurrency. For REST, you will receive a current snapshot of the current book for the specific cryptocurrency. For SSE Streaming, you will get a full representation of the... | 61,513 |
def noConsecDups(theList):
"""
noConsecDups is a function that takes a list of items or
a string and returns a copy of that string list with no
consecutive duplicates
produces: the same list with any consecutive duplicates remove
example: noConsecDups([2,3,3,3,4,4,5,6,6,2,2,1,5,3,3,2]
produ... | 61,514 |
def user_toggle_international(session, context):
"""Toggle the international flag of the user."""
user = context.user
user.international = not user.international
session.commit()
update_settings(context) | 61,515 |
def apply_repro_analysis_analysis(dataset, thresholds=[3.0], method = 'crfx'):
"""
perform the reproducibility analysis according to the
"""
nsubj, dimx, dimy = dataset.shape
func = np.reshape(dataset,(nsubj, dimx*dimy)).T
var = np.ones((dimx*dimy, nsubj))
xyz = np.reshape(np.indices(... | 61,516 |
def run(config, Rs, Ts, cloud, tracks, masks):
"""
Entry point function for bundle adjustment. Parses input, feeds it to optimizes and parses the result back to same format
:param config: config object. See config.py for more information
:param Rs: list of R matrices
:param Ts: list of T vectors
... | 61,517 |
def get_notice(xml):
"""
Get NOTICE_DATA Information: some general information related to the
notice, or information which is extracted from the notice
:param xml:
:return: dictionary:
- NO_DOC_OJS: Notice number in TED
- ORIGINAL_NUTS: Region code(s) of the place of performance
... | 61,518 |
def test_renderer(output_path):
"""Verifies that the base report renderer works as expected"""
renderer = ReportRenderer(output_path)
# Tables
df = pd.DataFrame(columns=['A', 'B'], data=[['a', 0], ['b', 1]])
renderer.add_table('table1', df)
renderer.add_table('table2', df)
for name in ['ta... | 61,519 |
def dQ_dX(time):
"""Derivative of transformation matrix for nutation/presession with regards to the X coordinate of CIP in GCRS
"""
# Rotation matrices
R3_E = R3(E(time))
R3_s = R3(s(time))
R2_md = R2(-d(time))
R3_mE = R3(-E(time))
dR3_s = dR3(s(time))
dR3_E = dR3(E(time))
dR3_mE... | 61,520 |
def set_config(**settings) -> None:
"""Sets global configuration setting(s)
Parameters
----------
settings
The setting(s) in the global configuration to update.
"""
global _GLOBAL_CONFIG
_GLOBAL_CONFIG = _update_config(_GLOBAL_CONFIG, **settings)
return | 61,521 |
def gcn(request, userDefinedListNumber):
"""Create a text only Discovery ATel list"""
userDefinedListRow = get_object_or_404(TcsObjectGroupDefinitions, pk=userDefinedListNumber)
listHeader = userDefinedListRow.description
initial_queryset = WebViewUserDefined.objects.filter(object_group_id = userDefin... | 61,522 |
def test_examples(example_file_path):
"""Test that the example run without errors."""
run_script_file(example_file_path) | 61,523 |
def feature_action_values(feature, action, timestamp=None, request=None, response=None):
"""
**Recupero dello stato corrente per una specifica azione di una specifica feature**"""
return features_actions_values(feature, action, timestamp, request=request, response=response) | 61,524 |
def do_check(args):
"""
Check processes the input to produce
:param args:
:return:
"""
exp = Experiment(args.root).find(args.idx)
aggregate_task(exp)
metrics = compute_metrics(exp)
# Print metrics.
print("=== Metrics ===")
yaml.safe_dump(metrics, sys.stdout)
check_task... | 61,525 |
def compute_ctf(freqs,rots,akv,cs,wgh,dfmid1f,dfmid2f,angastf,dscale,bfactor=None):
""" Evaluate the CTF at a set of frequences, rotated by a certain amount """
av = akv * 1e3 # Convert kilovots to volts
cs = cs * 1e7 # Convert spherical aberation from mm to A
# wavelength of electrons
elambda... | 61,526 |
def sens_all(d_in, var, param_name, figure, func="mean"):
"""Plot seasonal sensitivity to a parameter."""
sens_out = {}
fig, axis = figure
cols_nh = ['2o', '3o', '2.', '1v']
cols_sh = ['2o', '0x', '1v', '2.']
param_vals = d_in[param_name]
nh_seas = d_in['{}_nh'.format(var)]
sh_seas = d_... | 61,527 |
def validate(value, ceiling):
"""
Checks if val is positive and less than the ceiling value.
:param value: The value to be checked (usually an int)
:param ceiling: The highest value "val" can be. (usually an int)
:return: True if val is less than ceiling and not negative
"""
value = int(val... | 61,528 |
def tab_in_leading(s):
"""Returns True if there are tabs in the leading whitespace of a line,
including the whitespace of docstring code samples."""
n = len(s)-len(s.lstrip())
if not s[n:n+3] in ['...', '>>>']:
check = s[:n]
else:
smore = s[n+3:]
check = s[:n] + smore[:len(sm... | 61,529 |
def config_resolve_class_sorted(cookie, class_id, in_filter, in_size, in_hierarchical=YesOrNo.FALSE):
""" Auto-generated UCSC XML API Method. """
method = ExternalMethod("ConfigResolveClassSorted")
meta_class_id = coreutils.find_class_id_in_mo_meta_ignore_case(class_id)
if meta_class_id is not None:
... | 61,530 |
def mean_encoding(data: pd.DataFrame) -> Output(output_data=pd.DataFrame):
"""Mean encoding of categorical columns.
Args:
data: pd.DataFrame
"""
try:
data_processor = DataProcessor()
data = data_processor.mean_encoding(data)
return data
except ValueError:
log... | 61,531 |
def erratum_check(agr_data, value):
"""
future: check a database reference has comment_and_corrections connection to another reference
:param agr_data:
:param value:
:return:
"""
# when comments and corrections loaded, check that an xref is made to value e.g. PMID:2 to PMID:8
return 'S... | 61,532 |
def test_construction():
"""Simplest test that we can make a PACKMOL object"""
instance = packmol_step.Packmol()
assert str(type(instance)) == "<class 'packmol_step.packmol.Packmol'>" | 61,533 |
def describe_resource_permissions(AuthenticationToken=None, ResourceId=None, PrincipalId=None, Limit=None, Marker=None):
"""
Describes the permissions of a specified resource.
See also: AWS API Documentation
Exceptions
:example: response = client.describe_resource_permissions(
Auth... | 61,534 |
def draw_screen_text(text, color, position, font_size=20, font_name="arial"):
""" Draw some text on the screen (screen coordinates).
Args:
text: string to show
color: color to show text as
position: where to center text on
font_size: font size of text
font_name: name of ... | 61,535 |
def filter_features(ex):
"""Filters example features, keeping only valid model features."""
return {k: v for k, v in ex.items() if k in _MODEL_FEATURES} | 61,536 |
def longestConsecutive3(list,missing=1):
""" assume list is a list
budget missing """
if len(list) == 0:
return 0
longest = 0
# print(range(len(list)-1))
starts = [ x for x in range(len(list)) ]
# print(starts)
for sindex in starts:
currentlen = 0
allow = missing
... | 61,537 |
def ComputeAncillaryFiles(cluster, redist):
"""Compute files external to Ganeti which need to be consistent.
@type redist: boolean
@param redist: Whether to include files which need to be redistributed
"""
# Compute files for all nodes
files_all = set([
pathutils.SSH_KNOWN_HOSTS_FILE,
pathutils.CO... | 61,538 |
def parse_args() -> argparse.Namespace:
"""
Parse the arguments.
Returns:
The argument namespace.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--coords',
type=str,
help=("Right Ascens... | 61,539 |
def test_textmate_gen_cli_console_with_coloring(lang, coloring_model_path):
"""Test generating textmate syntax file with specific generator, which is not
currently implemented.
Command:
textX generate --target textmate ./examples/workflow/workflow.tx
--name Workflow --syntax-spec PATH_T... | 61,540 |
def GhostNet(annotation_type, fixed_positions=None, memory_demanding=False):
"""
Get the GhostNet pipeline which will crop the face :math:`112 \\times 112` and
use the :py:class:`GhostNet` to extract the features
.. warning::
If you are at Idiap, please use the option `-l sge-gpu` while runnin... | 61,541 |
def delta_to_json(delta_path, json_path):
"""
Read delta table and write to json file.
:param delta_path: path to delta table
:param json_path: path to json table
"""
cfg = ConfigSet()
overwrite_json = cfg.get_value(DATA_CFG + '::$.overwrite_json')
if os.path.exists(json_path):
... | 61,542 |
def TrainBaumWelsch(init_start, transitions, emissions, weights, observations, mutrates):
"""
Trains the model once, using the forward-backward algorithm.
"""
fractorials = np.zeros(len(observations))
for i, obs in enumerate(observations):
fractorials[i] = np.log(math.factorial(obs))
... | 61,543 |
def locale_switcher(current_locale=None):
"""Locale dropdown to switch user locale on localizer pages."""
return {
'current_locale': current_locale,
'locales': settings.AMO_LANGUAGES + settings.HIDDEN_LANGUAGES,
'languages': product_details.languages,
} | 61,544 |
def gen_vocab_dict(train_data):
"""
generate dict from training set's caption file (txt)
format of txt file:
id1 video_id1 caption1
id2 video_id2 caption2
...
"""
vocab = {}
inv_vocab = {}
vocab[''] = len(vocab)
inv_vocab[len(vocab) - 1] = ''
for line in train_data:
... | 61,545 |
def fork_count(self, repo_group_id, repo_id=None):
"""
Returns the latest fork count
:param repo_group_id: The repository's repo_group_id
:param repo_id: The repository's repo_id, defaults to None
:return: Fork count
"""
if not repo_id:
fork_count_SQL = s.sql.text("""
SE... | 61,546 |
def get_cards():
"""Download card data"""
params = "?" + urllib.parse.urlencode({"q": consts.card_query, "order": "released"})
next_page = consts.api_root + consts.search_endpoint + params
total_cards = None
cards = {
"last_updated": time_now().strftime(consts.time_format),
"data": ... | 61,547 |
def select_workloads(argv, # type: Iterable[str]
batch_size=None, # type: Optional[Union[Iterable[TBatchSize], TBatchSize]]
batch_num=None, # type: Optional[Union[Iterable[int], int]]
executor=None # type: Optional[Union[Iterable[Executor... | 61,548 |
def calculate_frequency(lst: list) -> Dict[str, int]:
"""Calculate the frequency from a list."""
frequencies = {}
for item in lst:
if item in frequencies:
frequencies[item] += 1
else:
frequencies[item] = 1
return frequencies | 61,549 |
def return_on_equity(stock, date=None, lookback_period: timedelta = timedelta(days=0), period: str = 'FY'):
"""
The return on equity ratio measures how efficiently a company is using its equity to generate profit
:param stock: ticker(s) in question. Can be a string (i.e. 'AAPL') or a list of strings (i.e. ... | 61,550 |
def _list_existing(filesystem, glob, paths):
"""
Get all the paths that do in fact exist. Returns a set of all existing paths.
Takes a luigi.target.FileSystem object, a str which represents a glob and
a list of strings representing paths.
"""
globs = _constrain_glob(glob, paths)
time_start ... | 61,551 |
def test_dataset_registry_registered_new_dataset() -> None:
"""
test, that the new generated dataset component "TestDataset" can be registered and retrieved from registry
"""
@dataset_registry.register("testdata")
class TestDataset(DatasetBase):
"""
TestDataset
"""
... | 61,552 |
def main():
"""
"""
target_train_size=200
partition_n=2
_=make_directories(partition_n,target_train_size)
target_model_simulation(partition_n,target_train_size,output_dir="../model_output/n{}_p{}/".format(target_train_size,partition_n))
standard_da_simulation(partition_n,target_train_size,ou... | 61,553 |
def adjust_match_start_offset(text: Dict[str, any], match_string: str,
match_offset: int) -> Union[int, None]:
"""Adjust the start offset if it is not at a word boundary.
:param text: the text object that contains the candidate match string
:type text: Dict[str, any]
:para... | 61,554 |
def val2str(val):
"""
Converts a float to the string format required for loading the CRRL models.
:param val: Value to convert to a string.
:type val: float
:returns: The value of val represented as a string in IDL double format.
:rtype: string
:Example:
>>> val2str(200)
... | 61,555 |
def get_sale_date(link):
"""Return the date of the livestock sale."""
sale_date = dateutil.parser.parse(link, fuzzy=True)
return sale_date | 61,556 |
def run_task(cmd, logger, msg=None, check_error=False):
"""Run task, report errors and log overall status.
Run given task using ``subprocess.Popen``. Log the commands
used and any errors generated. Prints stdout to screen if
in verbose mode and returns it regardless. Prints stderr to
screen always.... | 61,557 |
def count_tiles_amount(product_id, product_version, core):
"""
This method counting actual amount transferred and exists on storage
:param product_id: str -> resource id of the layer to sync
:param product_version: version of discrete
:param core: "A" [send] | "B" [received]
:return: int -> tota... | 61,558 |
def _checkunknownfiles(repo, wctx, mctx, force, actions, mergeforce):
"""
Considers any actions that care about the presence of conflicting unknown
files. For some actions, the result is to abort; for others, it is to
choose a different action.
"""
conflicts = set()
warnconflicts = set()
... | 61,559 |
def getelts(nda, indices):
"""From the given nda(ndarray, list, or tuple), returns the list located at the given indices"""
ret = [];
for i in indices:
ret.extend([nda[i]]);
return numpy.array(ret); | 61,560 |
def get_template_attribute(template_name, attribute):
"""Loads a macro (or variable) a template exports. This can be used to
invoke a macro from within Python code. If you for example have a
template named `_cider.html` with the following contents:
.. sourcecode:: html+jinja
{% macro hello(na... | 61,561 |
def test_simulation(sim_dict, expected_dict):
"""Test instantiating and running a simulation."""
# Create simulation
sim = Simulation(size=sim_dict['size'], spacing=sim_dict['spacing'],
max_speed=sim_dict['max_speed'], time_step=sim_dict['time_step'],
pml_thickness=sim_dict.get('pml_thi... | 61,562 |
def _RoundTowardZero(value, divider):
"""Truncates the remainder part after division."""
# For some languanges, the sign of the remainder is implementation
# dependent if any of the operands is negative. Here we enforce
# "rounded toward zero" semantics. For example, for (-5) / 2 an
# implementation may give ... | 61,563 |
def check_args(method, args) -> Optional[BoundArguments]:
"""Checks if arguments are suitable for given method.
Returns BoundArguments, or None on failure.
"""
try:
bound_args = signature(method).bind(*args)
bound_args.apply_defaults()
for name, param in bound_args.signature.par... | 61,564 |
def prepare(img, label=False):
"""
:param img: img(3d) or lab(2d), np
:param label: whether label
:return:
"""
if not label:
img = norm(img.copy())
img = torch.FloatTensor(img).cuda().float()
img = img.transpose(1,2).transpose(0,1)
return img.unsqueeze(0)
else:
lab = img.copy()
la... | 61,565 |
def rebin(bins):
"""
Take in an array of bin edges and convert them to bin centers.
"""
bins = np.array(bins)
result = np.zeros(bins.size - 1)
for i, element in enumerate(result):
result[i] = (bins[i] + bins[i + 1]) / 2.
return result | 61,566 |
def __load_exported_activities() -> List[DiscoveredActivities]:
"""
Extract metadata from actions and probes exposed by this extension.
"""
activities = []
activities.extend(discover_actions("chaosazure.machine.actions"))
activities.extend(discover_probes("chaosazure.machine.probes"))
activi... | 61,567 |
def shuffling_MI(symbol_counts, number_of_bins_d):
"""
Estimate the mutual information between current and past activity
in a spike train using the shuffling estimator.
To obtain the shuffling estimate, compute the plug-in estimate and
a correction term to reduce its bias.
For the plug-in esti... | 61,568 |
def main():
"""
Function called on program initialization
"""
# generate the Config object
config_obj = config.Config()
# initialize the Controller object
current_controller = controller.Controller(config_obj)
# initialize the Model object
current_model = model.Model(current_contro... | 61,569 |
def determine_component_investment_cost(component, eM):
"""ex post determination method of roi"""
return value(investment_cost(component, eM)) | 61,570 |
def should_stop(experiment_path):
""" Checks if liftoff should exit no mather how much is left to run.
"""
return os.path.exists(os.path.join(experiment_path, ".STOP")) | 61,571 |
def income_quintile(households):
"""
Household income quintile at the MSA level.
"""
return pd.Series(
pd.qcut(
households['income'], 5, [1, 2, 3, 4, 5]),
index=households.index
) | 61,572 |
def get_attr_type(attr):
"""get attribute name by its type"""
from pyhomee.const import ATTRIBUTE_TYPES_LOOKUP
return ATTRIBUTE_TYPES_LOOKUP.get(attr.type, ATTRIBUTE_TYPES_LOOKUP[0]) | 61,573 |
def get_step_name(monitoring_info_proto):
"""Returns a step name for the given monitoring info or None if step name
cannot be specified."""
# Right now only metrics that have a PTRANSFORM are taken into account
return monitoring_info_proto.labels.get(PTRANSFORM_LABEL) | 61,574 |
def field_isomorphism(a, b, *, fast=True):
"""Construct an isomorphism between two number fields. """
a, b = sympify(a), sympify(b)
if not a.is_AlgebraicNumber:
a = AlgebraicNumber(a)
if not b.is_AlgebraicNumber:
b = AlgebraicNumber(b)
if a == b:
return a.coeffs()
n =... | 61,575 |
async def test_validation_solar(hass, mock_energy_manager, mock_get_metadata):
"""Test validating missing stat for device."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{"type": "solar", "stat_energy_from": "sensor.solar_production"}
]
}... | 61,576 |
def main(
prep_script_path: Path = typer.Option(Path("./safe-driver/src/prep"), exists=True, dir_okay=True, file_okay=False),
train_script_path: Path = typer.Option(Path("./safe-driver/src/train"),
exists=True, dir_okay=True, file_okay=False),
evaluate_script_path:... | 61,577 |
def generate_proto(source):
"""Invokes the Protocol Compiler to generate a _pb2.py."""
output = source.replace('.proto', '_pb2.py')
if (not os.path.exists(output) or
(os.path.exists(source) and
os.path.getmtime(source) > os.path.getmtime(output))):
print('Generating %s...' % output)
if not... | 61,578 |
def first_dup(s):
"""
Find the first character that repeats
in a String and return that character.
:param s:
:return:
"""
for char in s:
if s.count(char) > 1:
return char
return None | 61,579 |
def update(weka, revision, svn=None, dry_run=False, verbose=False):
"""
Updates the code base startin from the specified revision.
:param weka: the directory with the Weka subversion checkout (HEAD)
:type weka: str
:param revision: the revision to start from
:type revision: int
:param svn: ... | 61,580 |
def SegRename(ea, name):
"""
Change name of the segment
@param ea: any address in the segment
@param name: new name of the segment
@return: success (boolean)
"""
seg = idaapi.getseg(ea)
if not seg:
return False
return idaapi.set_segm_name(seg, name) | 61,581 |
def clean_df(df):
"""what it does: cleans the consolidated dataframe
arguments: takes a dataframe as argument
returns: the cleaned dataframe"""
df['published_date'] = pd.to_datetime(df['published_date'], errors='coerce')
# Convert list of authors to one single str of authors
authors... | 61,582 |
def type_check(tags):
"""Perform a type check on a list of tags"""
if type(tags) in (list, tuple):
single = False
elif tags == None:
tags = []
single = False
else:
tags = [tags]
single = True
if len([t for t in tags if type(t) not in (str,bytes)]) == 0:
valid = Tr... | 61,583 |
def open_pdf(file_name: str,
parent: QWidget) -> (Union[Doc, None], bool):
"""
open pdf file and return a fitz object if applied
:param file_name: pdf file name
:param parent: parent
:return (doc, bool)
"""
try:
doc = Doc(file_name)
except RuntimeError:
... | 61,584 |
def main():
"""mainly the sole function"""
argp = argparse.ArgumentParser(
description=(
"Print a random value using the specified parameters. The low and "
"high arguments must not be the same. The order of the low and high "
"arguments is not relevant."
)
... | 61,585 |
async def upload_complete(
request: Request,
uuid: str,
user: domain.User = Depends(dep.get_current_user),
config: Config = Depends(dep.config),
response_class=HTMLResponse,
):
"""Page that advises user to wait after upload."""
details = infra.parse.details_from_params(
... | 61,586 |
def load_Ttree(tree):
"""load TTree as dict"""
ret = {}
for i in tree.keys():
arr = tree.get(i).array()
if isinstance(arr, np.ndarray):
ret[i.decode()] = arr
return ret | 61,587 |
def traducir_resultados(i: dict) -> None:
"""
Traducir resultados // Translate results
#### Parametros:
* @param i: Diccionario con el resultado // Dictionary with the results
#### Returns:
* return _bTranslated: True: si fue traducido, False: si no // True: if it was translated, False: if not
"""
_bTransl... | 61,588 |
def test_drydock_health_skip_update_site(caplog):
"""
Ensure that an error is not thrown due to Drydock health failing during
update_site or deploy site
"""
expected_log = ('Drydock did not pass health check. Continuing '
'as "continue-on-fail" option is enabled.')
req = Re... | 61,589 |
def get_type_for_model(model):
"""
Return type name for a given model class.
"""
opts = model._meta.concrete_model._meta
return camelcase_to_underscore(opts.object_name) | 61,590 |
def trace_plot_all_clusters(processed_neurons, clus_df, time_arr, label_col, ix_col, color_palette = None,
max_ix= None, clus_num_list = None, **kwargs):
"""
Wrapper function to make a list of bokeh figures containing the distribution of traces
for visualization of clustering results.
Params
-------
proce... | 61,591 |
def run_subprocess(command, return_code=False, verbose=None, *args, **kwargs):
"""Run command using subprocess.Popen.
Run command and wait for command to complete. If the return code was zero
then return, otherwise raise CalledProcessError.
By default, this will also add stdout= and stderr=subproces.PI... | 61,592 |
def get_OUT_port(port: str) -> int:
""" Get number of OUT port, or None if 'port' is not a valid value. """
return get_port_nr(port, "OUT") | 61,593 |
def test_invalid_encoding():
"""Ensure that the encoder throws the correct error when a string cannot be
encoded.
"""
test_string = "nathan"
with pytest.raises(encoder.SymbolError):
assert encoder.encode(test_string) | 61,594 |
def input_position():
"""
input the position option for pasted QR code
"""
option = input('Please select the position (1:left-top, 2:right-top, 3:left-bottom, 4:right-bottom, 5:left-middle, 6:right-middle) for QR code: ')
if option == '':
pos = 1
print(' Use the default position, ... | 61,595 |
def tow_to_datetime(tow, week):
"""
Convert a GPS Week and Time Of Week to Python datetime object.
Does *not* convert from GPST to UTC.
Fractional seconds are supported.
Parameters
----------
tow : time of week in seconds
weeks : gps week
Returns
-------
t : datetime
... | 61,596 |
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--dataset', dest='dataset',
help='training dataset',
default='hico_full', type=str)
parser.add_argument('--cfg', dest='c... | 61,597 |
def load_batch(batchsize, mode, gt_type):
"""
This function loads a batch for mlnet training.
:param batchsize: batchsize.
:param mode: choose among [`train`, `val`, `test`].
:param gt_type: choose among [`sal`, `fix`].
:return: X and Y as ndarray having shape (b, c, h, w).
"""
assert m... | 61,598 |
def Helheim_map(service='ESRI_Imagery_World_2D', epsg=3413, xpixels=2000):
"""Function using Basemap to plot map for only Helheim Glacier
"""
m = Basemap(projection='npstere', boundinglat=70, lon_0=315, epsg=epsg, llcrnrlon=320.3, llcrnrlat=66.1, urcrnrlon=322.4, urcrnrlat=67.6, resolution='h')
plt... | 61,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.