content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def admin_get_user(action):
""" Gets a user by email; login must be included in the POST. Calls the
response method of the User Object associated with <action>. """
utils.check_api_key()
# try to get the 'login' var from POST JSON; fallback to form content
try:
user_login = flask.request.g... | 8a244978b6e0fb499b02545f6243d438a07ec0ac | 73,000 |
def homography_adaptation(image, net, config):
"""Perfoms homography adaptation.
Inference using multiple random warped patches of the same input image for robust
predictions.
Arguments:
image: A `Tensor` with shape `[N, H, W, 1]`.
net: A function that takes an image as input, performs i... | 86766a0656c960bf71b7fb08d08c03d9f34ae8ed | 73,001 |
def get_most_recent_bundle(key):
"""
Returns the most recent bundle for the given key.
:param key:
:return:
"""
max = {'updated': '01-01-1965 00:00:00Z'}
for version in bundles[key].keys():
bundle = bundles[key][version]
if parse(bundle['updated']) > parse(max['updated']):
... | bbecb4c576e5046dbc331358a247653a824a0174 | 73,002 |
def get_image_dimensions(img_file):
""" return width, height """
shape = load_image_as_numpy_array(img_file).shape
width = shape[1]
height = shape[0]
return width, height | 9b96d79e6f3a16d84093b3174ab25f155fcae8bf | 73,003 |
def create_record():
"""Creates a record from user input.
Asks the user for name, age, and height. Then prints the possible record.
Only if the user accepts with 'y' or 'Y', the record is returned.
Otherwise, the user is asked again.
Returns:
A dictionary representing a person.
"""
... | a916ef25b63e9cfee2788bcae2c16db3719f5e3f | 73,004 |
import os
def collect_data(data_files, col_dict=col_dict):
"""
Takes a list of file names and reads them into a pandas dataframe.
data_files: list of filenames
col_dict: dictionary of columns to rename
returns: dataframe of temperature data from files
"""
if isinstance(data_files, dict): ... | 5aaa1cb56f4ca0fce1f3fc1d64a87734daf4939f | 73,005 |
def euler_curve(diagram, m=101, k_max=None, f="linear", **kwargs):
"""
Return an m-dimensional array of Euler characteristic up to dimension k_max.
Parameters
----------
diagram: list of ndarrays
list of arrays of k-dimensional persistence diagram
m: int or list of floats or ndarray of ... | 727e0de5a6ab5a268f37b7740ea40a8678568c35 | 73,006 |
import json
def read_config():
"""Retrieve config."""
with open(CONFIG) as f:
config = json.load(f)
return config | 0c628424d3e3a7726ac607cb02ccb25dcab89482 | 73,007 |
import re
async def eval_command(ctx: lightbulb.context.Context) -> None:
"""
Dynamically evaluate a script in the bot's environment.
This can only be used by the bot's owner.
Example:
;eval ```py
for x in range(5):
print('Hello World')
```
"""
assert ctx.event.message is ... | 9001d4fbb05bed7fdbc8eb85129f3d784c8ed7fb | 73,008 |
def diameter(G, e=None, usebounds=False):
"""Return the diameter of the graph G.
The diameter is the maximum eccentricity.
Parameters
----------
G : NetworkX graph
A graph
e : eccentricity dictionary, optional
A precomputed dictionary of eccentricities.
Returns
-------
... | f5a1a3238fb8ab2f236d2ddd355bb0d030f5f2fb | 73,009 |
def remove_redundant_objs(objs, cmp_f):
"""Remove redundant objects from objs and return non-redundant objects.
objs --- a list of sorted objects.
cmp_f --- cmp_f(aobj, bobj) return 0 if aobj 'equals' bobj and -1 if aobj is less than bobj, and 1 otherwise.
"""
ret = []
for obj in objs:
i... | 405d2193b74e46e65637563bb664d3a7c0dd8740 | 73,010 |
def make_sg_rules(cidrs=None, group_ids=None, ports=None, proto="tcp"):
"""
Args:
cidrs: (list): List of cidr blocks to add to the security group
rules.
group_ids: (list): List of group_uds to add to the security group
rules.
port_ranges: (list): List of ports to ... | f0da2b108ebd82bf20777a2c870c5d211f809e6a | 73,011 |
from datetime import datetime
def create_article(title, text, days):
"""
Create a article with the given `title` and `text`. Published the
given number of `days` offset to now (negative for articles published
in the past, positive for articles that have yet to be published).
"""
time = timezon... | b63ddc9a60f5d1ccad0d188f6be2e360777cf1c1 | 73,012 |
def surface_fit(struct,order=3, mask=True, minlevel=0):
"""Fit a surface to an image
return struct
"""
# Determine the number of extensions
nextend=len(struct)
#flat field the data
for i in range(nextend):
if struct[i].name=='SCI' or len(struct)==1:
#create the med... | a7f122901fd2562816eb8574c16a099d1486d7ae | 73,013 |
import argparse
def parse_args(argv):
"""Parses command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--input", help="Path to dataset.", required=True,
)
parser.add_argument(
"--job-dir",
help="Output directory for exporting model and other ... | 8aaaf8239a02ae4316afe16ddc6e14bbe331d2a2 | 73,014 |
def tensor_polar2cartesian(x):
"""
x: tensor of the shape [size, 2] (polar coordinate)
return: tensor of the shape [size, 3] (cartesian coordinate)
"""
return tf.stack(
[tf.cos(x[:, 0]) * tf.sin(x[:, 1]),
tf.sin(x[:, 0]) * tf.sin(x[:, 1]),
tf.cos(x[:, 1])],
... | a4f86da197f0ff8d3e1d75269bfbdbd3d0633ed8 | 73,015 |
def normalise_background(data, header):
"""
Normalise the background brightness level across the data HDU in the given
HDUList
"""
# Remove negative values and cosmic rays
# TODO: get parameters for detect_cosmics and sigma_clip from settings
_, imdata = detect_cosmics(
data.clip(0... | b1d52410488a8970b8ad7d0730af5f5f6c34973b | 73,016 |
def build_numpy_array(fnames):
"""return numpy array built from data read from list of filenames"""
arr = np.empty((0, 1), dtype=np.float32)
print 'building array...'
for fname in fnames:
# read data from file
a = padread(fname, columns=1)
a[:, 0] = a[:, 0] - a[:, 0].mean(axis=0)... | 27a4487439ef0145570005d9eb0870222134b5b9 | 73,017 |
from sherpa.astro.data import DataARF
from sherpa.astro.instrument import ARF1D
def derive_identity_arf(name, arf):
"""Create an "identity" ARF that has uniform sensitivity.
*name*
The name of the ARF object to be created; passed to Sherpa.
*arf*
An existing ARF object on which to base this o... | ab9c0666a100fd9c4b67c09d82a6ec3669f9e3d2 | 73,018 |
from typing import Dict
from typing import Optional
def visitor(request: HttpRequest) -> Dict[str, SimpleLazyObject]:
"""Add visitor context to template context (if found on the request)."""
def _get_val() -> Optional[dict]:
if request.visitor:
return request.visitor.serialize()
r... | a09f718f918ae1c7b95f0d94fb4a7273f176c1b1 | 73,019 |
def parse(file):
"""parse out information from data_text and get information about image size, and class names"""
(str_height, str_width, str_names) = file.readlines()[0].split("*")
(height, width) = (int(str_height), int(str_width))
names = str_names.strip("][").replace("'", "").split(", ")
return... | 554bc1bf07671aecbe7da2ba2cfbb0bd51aa511c | 73,020 |
def ISTEXT(*args) -> Function:
"""
Checks whether a value is text.
Learn more: https//support.google.com/docs/answer/3093297
"""
return Function("ISTEXT", args) | a20bf55e4c15d88a7312e54d799bef94bf43f364 | 73,021 |
def CityscapesConfig(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:return: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = """`Cityscapes <http://www.cityscapes-dataset.com/>`_... | 3908c2a7e19495775cea0ac5e15ff745545e961d | 73,022 |
def get_game(i: int, cfg: Config = None):
"""
Create a game-object.
:param i: Game-ID
:param cfg: Config object
:return: Game or GameCy object
"""
config = cfg if cfg else Config()
return Game(game_id=i,
config=config,
silent=True) | 59c8a530ae3c71557f49309d1eb1b1d2e4ee6bc6 | 73,023 |
def rsync_project(remote_dir, local_dir=None, exclude=[], delete=False,
extra_opts=''):
"""
Synchronize a remote directory with the current project directory via rsync.
Where ``upload_project()`` makes use of ``scp`` to copy one's entire
project every time it is invoked, ``rsync_project()`` uses th... | 276a9d71382915f319a644aba1a28665cd6b504f | 73,024 |
def burninConvergence(lnprob, tol=0.25, slice_size=100, cutoff=0):
"""Checks early lnprob vals with final lnprob vals for convergence
Parameters
----------
lnprob : [nwalkers, nsteps] array
tol : float
The number of standard deviations the final mean lnprob should be
within of the ... | 70bace0b3fa38fb891b8c17acf6007c7c6bc5082 | 73,025 |
from typing import Optional
def solve(program: MPQP_Program, active_set=None, num_cores=-1) -> Optional[Solution]:
"""
This solved the multiparametric program using the geometric algorithm described in Spjotvold et al.
https://www.sciencedirect.com/science/article/pii/S1474667016369154
:param progra... | a257cefd25811f9c7fb484b76d50cf522a12f4a2 | 73,026 |
def generate_and_embed_metadata(music_file, id, clientKey, clientSecret):
"""Fetch a song's metadata from Spotify."""
# token is required to grab metadata
token = generate_token(clientKey, clientSecret)
spotify = spotipy.Spotify(auth=token)
try:
meta_tags = spotify.track(id)
except:
... | 5503090d8dc7e242746b7d6f38628e34312e5f81 | 73,027 |
def unify(left, right, substitution):
"""unify is a helper function and the core for eq. unify will
recursively look up both `left` and `right` in substitution using the `walk`
function.
After getting each of their associated values, they are compared.
If they are equal either as variables or li... | 71c8be6c189e8beac8afc7cb6271844e9870373c | 73,028 |
def get_data(name: str, override: bool=True) -> str:
"""
Obtiene el contenido del archivo SVG que coincida con el nombre.
Si override es False, se lanzará una excepción en caso de no encontrar el
archivo con el nombre indicado.
"""
if "/" in name:
name = name.split("/")[-1]
if not ... | 68bd843f250c13c53ed1466b38c5ea43572cdf1f | 73,029 |
def hamiltonian(position, velocity, energy_function):
"""Computes the Hamiltonian of the current position, velocity pair
H = U(x) + K(v)
U is the potential energy and is = -log_posterior(x)
Parameters
----------
position : atreus_ml.Variable
Position or state vector x (sample from the ta... | f4fba2d856a43c726e14f656f069a0505fe94846 | 73,030 |
def hardmax(data, axis):
"""hardmax operator.
Parameters
----------
data : tvm.te.Tensor
input data
Returns
-------
out : tvm.te.Tensor
Tensor with shape same as input data.
"""
def _hardmax(data, out_buf, axis):
ib = tir.ir_builder.create()
input_... | 0117681ad87ab3687dfe8817ff34aebdfa724d54 | 73,031 |
from typing import Dict
import math
def position_distance(a: Dict[str, float], b: Dict[str, float]) -> float:
"""Compute the distance between two positions."""
return math.sqrt((a['x'] - b['x'])**2 + (a['y'] -
b['y'])**2 + (a['z'] - b['z'])**2) | c6b29c8e84c4d8f15c27f32e7f9d2a13ecf6fd45 | 73,032 |
import torch
def get_device(inputs):
""" Get used device of a tensor or list of tensors. """
if isinstance(inputs, torch.Tensor):
device = inputs.device
elif isinstance(inputs, (tuple, list)):
device = inputs[0].device
else:
raise TypeError(f'Inputs can be a tensor or list of t... | eb67cb3a5ae226c4136bc172d37225ba6a64b45f | 73,033 |
import uuid
def _wrapper(wrapped, instance, args, kwargs):
"""
General wrapper for requests instrumentation.
:param wrapped: wrapt's wrapped
:param instance: wrapt's instance
:param args: wrapt's args
:param kwargs: wrapt's kwargs
:return: None
"""
# Inject header to support tracin... | 079962c0e43f469ed9f104c47933dd221d6be2a4 | 73,034 |
def agent_action_to_environment(noop_action, agent_action):
"""
Turn an agent action (an integer) into an environment action.
This should match `environment_action_batch_to_agent_actions`,
e.g. if attack=1 action was mapped to agent_action=0, then agent_action=0
should be mapped back to attack=1.
... | 21f23fe91519eaefb15e0b008fd207b33bac3226 | 73,035 |
from typing import List
def get_nested_fieldnames(csv_entries: List[dict]) -> set:
"""Fieldnames with '.' should be converted to nested dictionaries. This function will return a set of
fieldnames for nested dictionaries from the highest to second lowest levels.
E.g these fieldnames: dc.date.available, dc.... | c1e4b7ff1349200eda43b82c36ca682862b48260 | 73,036 |
def cvSplit(*args):
"""cvSplit(CvArr src, CvArr dst0, CvArr dst1, CvArr dst2, CvArr dst3)"""
return _cv.cvSplit(*args) | dab91ff4994592a4d8d2ab0f9a56cbf1378ca9af | 73,037 |
def pythagorean_distance_equation(path1, path2):
"""Pythagorean Distance Equation.
Function for counting distance,
derived from the Pythagorean theorem.
"""
# point path dot X1
dotX1 = path1[0]
# point path dot X2
dotX2 = path2[0]
# point path dot Y1
dotY1 = path1[1]
# p... | a16f9d2a3f4ba824ebeb020ed2e5b1bb4068cc0e | 73,038 |
import re
def cleaning(token):
""" This function will remove unnecessaries values in the sentence i.e links, emails, and punctuations
"""
link = r'(https?:\/\/[^\s]+)|(www\.[^\s]+)|(meet\.google\.[^\s]+)|(bit\.ly[^\s]+)'
email = r'([a-zA-Z0-9\.\_\-]+@+[a-zA-Z0-9.]+)'
punct = r'[^a-zA-Z0-9\[\]]'
... | 63eabc07eb69238f34a7d98a397aa41b2dbb2624 | 73,039 |
def _many_z_to_single_z(focal_qubit, pauli_sum):
"""Convert many Z's to single Z.
Returns the gate set required for transforming an arbitrary tensor product
of pauli-z's into a product of all identites and a single pauli-Z.
Args:
focal_qubit: central qubit among CNOT gates.
pauli_sum: `c... | d65e1db0c9ea1a7912630d6810ed03ef4b7c312e | 73,040 |
from vcdm.container import _remove_child
def delete(avatar, fullpath, on_behalf=None):
""" Delete a blob. """
log.msg("Deleting %s" % fullpath)
uid, vals = vcdm.env['ds'].find_by_path(fullpath, object_type='blob',
fields=['parent_container',
... | 6ff33aec89d4b384b1cc698c41817da49e852b75 | 73,041 |
def _pack_with_tf_ops(dataset, keys,
length):
"""Helper-function for packing a dataset which has already been batched.
Helper for pack_dataset() Uses tf.while_loop.
Args:
dataset: a dataset containing padded batches of examples.
keys: a list of strings
length: an dict from fea... | 94b7896f64381bcf17eaa73213e52ad107f45a0f | 73,042 |
def vendor_view(request):
"""
Render main view for vendors.
:rtype: HttpResponse
"""
user = request.user
if user.is_authenticated():
vendor = Vendor.get_vendor(user)
items = Item.objects.filter(vendor=vendor)
else:
items = []
context = {
'user': user,
... | 91996baeecf38cf74cde9b55d305bbb879d54abb | 73,043 |
from typing import Dict
def create_column_translation(path: str) -> Dict:
"""Translates an excel sheet of column name links to a dict of column name translations"""
link_dataframe = read_excel(path)
translated_columns = {}
# Transform dataframe to dict
data_dict = link_dataframe.to_dict("index")
... | b01ec956df1e745b8597c4d4f0ee2f6884dea9c1 | 73,044 |
def G3_prime(crystal, i, e_type, ni, functional='Cosine',
Rc=6.5, k=10, p=1, q=0):
"""
Calculate derivative of the G3 symmetry function.
Parameters
----------
crystal: object
Pymatgen crystal structure object.
i: int
The index of core element.
e_types: str
... | 3b3fd994201dcdfd9be2a34deea27d021bb68d35 | 73,045 |
import logging
def end_of_week(date_: date, week_starts_on: int = 7, iso: bool = True) -> date:
"""
Find the last day of the week which contains date_.
Python standard days of the week have a range of 0 - 6, with 0 being Monday.
Iso standard days of the week have a range of 1 - 7, with 1 being Monday... | f7b4e2056374f4bd1cbeba436233f68e501f95c7 | 73,046 |
def _read_pdas(filename, **kwargs):
"""
Reads a PDAS file and returns an ObsPy Stream object.
.. warning::
This function should NOT be called directly, it registers via the
ObsPy :func:`~obspy.core.stream.read` function, call this instead.
:type filename: str
:param filename: PDAS ... | 503422c1959bb28c4b6972baffd189a724bcd2a1 | 73,047 |
import os
def get_path_from_git_root(file_name: str, super_module: bool) -> str:
"""Get the git path from the root of the tree.
:param super_module: like get_client_root()
"""
git_root = get_client_root(super_module) + "/"
abs_path = os.path.abspath(file_name)
dbg.dassert(abs_path.startswith(... | 965a8eaa5e2a70d7c503da5aac97d47297012592 | 73,048 |
from typing import Sequence
from typing import Optional
from typing import Tuple
def welch_ttest(first_set: Sequence[Trace], second_set: Sequence[Trace], dof: bool = False, p_value: bool = False) -> Optional[Tuple[CombinedTrace, ...]]:
"""
Perform the Welch's t-test sample wise on two sets of traces `first_se... | 240a6afae15d9f93b0f344710d9338c98b1aa9d6 | 73,049 |
def ga_optimise_from_args(func_caller, worker_manager, max_capital, mode, mutation_op,
is_rand=False, crossover_op=None, options=None,
reporter='default'):
""" GA optimisation from args. """
if options is None:
reporter = get_reporter(reporter)
options = l... | af0bf2e7cec99618ccc306086eeea2949b1c5b8c | 73,050 |
def MaybeGetKmsKeyFromDict(args, messages, current_value):
"""Gets the Cloud KMS CryptoKey reference for a boot disk's initialize params.
Args:
args: A dictionary of a boot disk's initialize params.
messages: Compute API messages module.
current_value: Current CustomerEncryptionKey value.
Returns:
... | ba930480f1442a96acb3899faee65241ee89a9ba | 73,051 |
def parse_module_lines(lines, net_manager):
"""
Parse lines that make up a module. Add the module to the proper nets using
the specified NetManager.
Returns an IvlModule object.
"""
module_meta = lines[0]
module_data = lines[1:]
name, supertype, module_type_raw, inst_type = module_meta.... | 5e848da7d2d785eccb675c68380d7c383a350b47 | 73,052 |
import uuid
import os
def bedtools_closest(f1,f2):
"""perform bedtools closest for input file 1 and 2"""
outFile = str(uuid.uuid4()).split("-")[-1]
sort1 = str(uuid.uuid4()).split("-")[-1]
sort2 = str(uuid.uuid4()).split("-")[-1]
sort_bed(f1,sort1)
sort_bed(f2,sort2)
command = "bedtools closest -a %s -b %s -d ... | 4acf1eeea6254bb3d4c87aa9085fcfa2ce4e52ee | 73,053 |
import argparse
def _build_parser():
"""Define command line args
"""
examples = """
examples:
# plot data from stdin
$ cat data.txt | plotext scatter
# plot data from a file
$ plotext scatter -f data.txt
# bar plot of second-first column
$ cat data.txt | plotext bar --colum... | 44481d6a295553a4f90e4a07ed2930a699e88e02 | 73,054 |
def read_data(input_path):
"""Read nasdaq stocks data.
Args:
input_path (str): directory to nasdaq dataset.
Returns:
X (np.ndarray): features.
y (np.ndarray): ground truth.
"""
df = pd.read_csv(input_path)
df_no_date = df.drop(["Close", 'Date'], axis=1)
X = df_no_date... | 85fb3091f5e07d83b2aece682aef634f2dba1212 | 73,055 |
def test_configurable__get_partial():
""" Test if `@configurable#get_configured_partial` is able to export a partial with expected
configuration.
"""
@configurable
def configured(arg):
return arg
expected = ''
add_config({configured: HParams(arg=expected)})
partial = configured... | 2b4c744a425bfe5fa0dd0ff4f4342b6808c17bc7 | 73,056 |
def parse_xform_instance(xml_str):
"""
'xml_str' is a str object holding the XML of an XForm
instance. Return a python object representation of this XML file.
"""
xml_obj = minidom.parseString(xml_str)
root_node = xml_obj.documentElement
# go through the xml object creating a corresponding p... | 73be29233b5c54b1aaf76cead029cc82fe2889b8 | 73,057 |
def generate_output_filename(file_name, suffix, file_type="csv"):
""" Adds a suffix to the input csv to track progress through data pipeline. """
parts = file_name.split('.')
if len(parts) == 2:
output_filename = parts[0] + suffix + '.' + file_type
return output_filename | 20352bb31b4e56202b85f88f15c2eefcbb76d9c7 | 73,058 |
from sklearn.externals.joblib import Parallel, delayed
import copy
def mcc_rgb(
data,
scales=[0.5, 1, 1.5],
tols=[0.3, 0.3, 0.3],
threshs=[1, 0.1, 0.01],
training_scales=None,
training_tols=None,
n_train=int(1e3),
max_iter=20,
n_jobs=1,
seed=None,
use_las_codes=False,
v... | d210a73363e8f7c47061118708ad2cd0cdbaaf49 | 73,059 |
def broadcast(tensor, src, group=None, async_op=False):
"""
Broadcasts the tensor to the whole group.
``tensor`` must have the same number of elements in all processes
participating in the collective.
Args:
tensor (Tensor): Data to be sent if ``src`` is the rank of current
proc... | b81eae02c8b14e1d349e503e1426c45c6c1eca0a | 73,060 |
import os
import sys
import tarfile
def download_dip(amclient, dip_uuid, dip_basename):
"""Download and extract DIP to desktop.
:param amclient: AMclient object instance
:param dip_uuid: DIP UUID (str)
:param dip_basename: DIP basename (str)
:returns local_dip_path: Path to DIP on desktop (str)
... | 6bb4a1765b52cabc704dcf3a8ee09086ac432f10 | 73,061 |
import base64
def get_chubby_bat_img_base64():
"""
:return: bytes
"""
with open(CHUBBY_BAT_IMAGE_PATH, 'rb') as fp:
return base64.b64encode(fp.read()) | 00da9bc3498283ea172db866fddd9e2779bb0354 | 73,062 |
def get_county_hospitals():
"""
Get county hospital inpatient v outpatient statistics
"""
mysql = MySQL.MySQL(MYSQL_URL, MYSQL_USER, MYSQL_PASS)
data = mysql.get_county_hospitals()
return_package = {
'data': data
}
del mysql
return jsonify(return_package) | f5886b3ab13812c296e70ccb2ec58a397c537ab4 | 73,063 |
from typing import Tuple
from typing import Any
from typing import Set
def neighbors(quilt: Tuple[Tuple[Any, ...], ...], x: int, y: int) -> Set[Any]:
"""
Get the color of all neighbors.
.. note::
The color of block (`x`, `y`) is included in the colors returned.
:param quilt: The quilt conta... | 3237e86d2beaeefb8b76dfeed10720b1ee37bf43 | 73,064 |
from typing import Union
from typing import Dict
from typing import Any
import typing
def Checkbox(
description: str = "",
description_tooltip: str = None,
disabled: bool = False,
indent: bool = True,
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {},
style: ... | 06c9d8a0a32eecff56e06cbe5647615bdd3a44f5 | 73,065 |
import json
def directory_researches_group(request):
"""GET: получение списка исследований для группы. POST: добавление новой или выбор существующей группы и привязка исследований к ней"""
return_result = {}
if request.method == "GET":
return_result = {"researches": []}
gid = int(request.G... | 0a1821ee1ccf8c8167ac81d6950cd3c4a722715a | 73,066 |
def get_model_list(session):
"""Return a list of all models, for advanced search."""
model_list = (session
.query(Model.bigg_id)
.order_by(Model.bigg_id)
)
list = [x[0] for x in model_list]
list.sort()
return list | 02d19214fc91161ecfe546ebbea51f25cc01c6a2 | 73,067 |
def score_multithreshold(pred, gt, shore_root, distance_tolerance=200, shore_tolerance=2, costly_dist=False) -> pd.DataFrame:
"""Compute xView3 aggregate score from
Args:
pred ([pd.Dataframe)): contains inference results for all scenes
gt (pd.Dataframe): contains ground truth labels for all sce... | 23518eb95e2f6fc8c1f37e224dd4db14e166e7b3 | 73,068 |
import pprint
def dummyRF2(online, settings, _password=None):
"""
Function that accesses the same data files and dumps what rF2 would do with it
"""
pp = "This is the result of the 'Dummy_rF2' checkbox on the Options tab which is used for debugging.\n\n"
if online == 'Offline':
pp += 'Car... | 49babf0ec36f263027cd2f426032bf60e3e54c92 | 73,069 |
def quick_sort(sequence: list) -> list:
"""Simple implementation of the quick sort algorithm in Python
:param sequence: some mutable ordered collection with heterogeneous comparable items inside
:return: the same collection ordered by ascending
"""
if len(sequence) < 2:
return sequence
... | 73470224b8f149568b84c7b723097fc0c2ef353f | 73,070 |
import csv
from datetime import datetime
def get_weather_modifications(csv_file):
"""
Given a CSV file like:
DATE,PRCP,TAVG
01/01/2001,0,-6
01/02/2001,0,-7
01/03/2001,0,-8
where PRCP is in CM and TAVG is in C, converts it into a JSON
modifications object that can override gis_data. A... | 31cd78a67ff1f511b46cf510318e570b83013c3b | 73,071 |
def _is_gradient_task(task_id, num_tasks):
"""Returns True if this task should update the weights."""
if num_tasks < 3:
return True
return 0 <= task_id < 0.6 * num_tasks | 11d37b1095e40ef0be840c63a0c184e63630e945 | 73,072 |
from typing import Dict
from typing import Any
from typing import Union
from typing import List
def pt_whois_search_command(client_obj: Client, args: Dict[str, Any]) -> Union[List[CommandResults], str]:
"""
Gets WHOIS information records based on field matching queries
:param client_obj: client object wh... | 9d825ca96832b61dceb81b5a2f9de977a6d83b41 | 73,073 |
def __getcoordinatearrays__(rotate=True, representation='Cylindrical',
**kwargs):
""" This function will create a 2D/3D array from the requested shape in
kwargs['shape']. It can either return this array into cartesian,
polar/cylindrical or spherical coordinates. Using the option... | cf61d32caade1f453480b6fe38ac862452bd08ec | 73,074 |
def cct(pvals, weights=None):
"""
Python port of the CCT function as defined in the STAAR R-package (https://github.com/xihaoli/STAAR/blob/2f67fafec591a45e81a54eca24564b09ce90e252/R/CCT.R)
An analytical p-value combination method using the Cauchy distribution.
takes in a numeric vector of p-values, a ... | 31d898744048b5c5b89b9b69f0d93d41233a8816 | 73,075 |
def score_tup(t):
"""
Score an ngram tuple returned from a database ngram table. A higher scoring
term is more deserving of inclusion in the resulting acrostic
:param t: (Term string, initials string, Corpus count, Used count)
:return: Fitness score for this term
"""
term = t[0]
inits = ... | eea34dbf2d6a7dec37dc95cde289560a77c72f7e | 73,076 |
import sys
def show_features(core):
"""
Show the parsed features
"""
# set needed configuration
world.config.write_steps_once = True
if not sys.stdout.isatty():
world.config.no_ansi = True
runner = Runner(HookRegistry(), show_only=True)
runner.start(core.features_to_run, m... | 493e032d401a95efaf128e910c494a06e03390cd | 73,077 |
import pathlib
def fits_file():
"""
Return the path of an example FITS file.
The FITS file whose path is returned shows a 10 arcsecond by 10 arcsecond sky area
centered on the right ascension 10 degrees and the declination -60 degrees.
Returns
-------
`pathlib.Path`
The path to t... | 095d582e5a8b6127cf273c610219ba984fdbb48a | 73,078 |
import torch
def get_optimizer(parameters, lr, weight_decay):
"""
Initiate Adam optimizer with fixed parameters
Args:
parameters: filter, parameters to optimize
lr: float, initial learning rate
weight_decay: float, between 0.0 and 1.0
Return:
a torch.optim.Adam optimizer
"""
return torch.optim.Adam(p... | 54b4c6a4cd02672ebfc8ff9c850f0d601fc6510f | 73,079 |
def reissue_notification(alert, definition, notification):
""" Create another (re-issue notification) as a part of esclation process (for alerts only)
"""
result = None
try:
ticket_id = 0
# If red mine enabled:
if notification.use_redmine:
ticket_id = reissue_notific... | b08dde81906cf2816cf40970762e27787544a5f3 | 73,080 |
import warnings
def check_weather_data(weather_df):
"""
Check weather Data Frame.
- Raise warning if there are nan values.
- Convert columns if heights are string and not numeric.
"""
# Convert data heights to integer. In some case they are strings.
weather_df.columns = pd.MultiIndex.fro... | 58c63897b9820ea5af2166c7eba4ae9837a3db13 | 73,081 |
def DoesMoleculeContainsPAINSPattern(Mol, PAINSPatternMols):
"""Check presence of PAINS pattern in the molecule"""
MolMatched = False
for PatternMol in PAINSPatternMols:
if Mol.HasSubstructMatch(PatternMol, useChirality = True):
MolMatched = True
break
retu... | 15b8684b69c02508f24b075db654efcb4c903188 | 73,082 |
import os
import time
def select_gfas(infiles, maglim=18, numproc=4, tilesfile=None,
cmx=False, mindec=-30, mingalb=10, addurat=True):
"""Create a set of GFA locations using Gaia and matching to sweeps.
Parameters
----------
infiles : :class:`list` or `str`
A list of input fil... | 1d061578f0d9d1dc9d3499d7f09acf1bf2f6666f | 73,083 |
from re import T
def rmsprop(cost, params, lr=0.001, alpha=0.2, beta=0.2, epsilon=1e-6, decay_rate=0.0, data_part=0.0):
"""RMSprop and AdaGrad"""
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
acc = shared(p.get_value() * 0.)
acc_new = acc - beta * ... | d1932641b34937b4644935f414ef141e389807d2 | 73,084 |
def read_forces_2d(op2, se):
"""Read forces for a 1D structural element
Parameters
----------
op2 : PyNastran's OP2 results
OP2 result class from PyNastran.
se : :class:`.SE` object
The structural element for which the forces should be read.
"""
se_forces = {}
for vec... | f4bfdbc497ea2ec7f9a5bee155ee0d943b4e0778 | 73,085 |
def _retentionsFromCSV(csv):
"""Parse the command separated ints in `csv` into a list of tuples
Used to deserialise the retention policy.
"""
ints = map(int, csv.split(','))
return zip(ints[::2], ints[1::2]) | 85047d64a152ab9b65116e0b9539e4f5950fc0b0 | 73,086 |
def to_serialized_field(tensor_info):
"""Convert a `TensorInfo` object into a feature proto object."""
# Select the type
dtype = tensor_info.dtype
# TODO(b/119937875): TF Examples proto only support int64, float32 and string
# This create limitation like float64 downsampled to float32, bool converted
# to ... | f08c8e001c5d35b2d4d1a7f933aaa8268285919c | 73,087 |
def dropbox_factory(request):
""" expects the id of an existing dropbox and returns its instance"""
try:
return request.registry.settings['dropbox_container'].get_dropbox(request.matchdict['drop_id'])
except KeyError:
raise HTTPNotFound('no such dropbox') | 236b759e47cf98c387e66e31614d1c97ed8e3b60 | 73,088 |
def _get_affine_inv_wmae(prediction,
depth,
depth_conf,
irls_iters=5,
epsilon=1e-3):
"""Gets affine invariant weighted mean average error."""
# This function returns L1 error, but does IRLS on epsilon-invariant L1 er... | 46871b38bca4a45866b4c274040f04c5604093b8 | 73,089 |
def add(arr):
""" Exercise 4.1 """
"""
Answer in book
def sum(list):
if list == []:
return 0
return list[0] + sum(list[1:])
"""
if arr is None: # base case
return 0
if len(arr) == 1: # base case
return arr[0]
return arr[0] + add(removeFirst... | b880e4a997f370138b26566e85d78ec62b259a41 | 73,090 |
import logging
def update_status_in_database(workspace_repo: WorkspaceRepository, message: DeploymentStatusUpdateMessage):
"""Updates the deployment sub document with message content
Args:
workspace_repo ([WorkspaceRepository]): Handle to the workspace repository
message ([DeploymentStatusUpd... | 9670d581086ff5bdf20a787ef874dbc96609ea6b | 73,091 |
import timeit
def list_dequeue(N, num):
"""Run a single trial of num dequeue requests. Make sure that num < N."""
return 1000*min(timeit.repeat(stmt='''
for i in range({}):
q.pop(0)'''.format(num),
setup = 'q = list(range({}))'.format(N), repeat=5, number=1)) | b6b4c5dbdb153b6aff13357cc707243d8e2c5175 | 73,092 |
import copy
import torch
def mutate(net, seed, noise_std, copy_net=True):
"""
Mutates the given network parameters. Based on the applied seed a normal distributed noise is added to the network parameters
"""
# copy current net
mutated_net = copy.deepcopy(net) if copy_net else net
# set see... | e67ad3778be8a27734cee3056fc0ff1a2c956669 | 73,093 |
def encrypt_decrypt():
"""Decide whether to encrypt or decrypt."""
while True:
choice = input("Enter E for encryption or D for decryption:")
if choice == "E":
return "E"
elif choice == "D":
return "D"
else:
print("Wrong input! Please try again.... | 1361e86939cf333680ba9c640487bf246a8faf2d | 73,094 |
import numpy
def MAtoSeries(Series):
"""
Convert a masked array to a numpy ndarray with masked elements set to c.missing_value.
Useage:
Series, WasMA = MAtoSeries(Series)
where:
Series (input) is the data series to be converted.
WasMA (returned) is a logical, True if the input se... | 17cae7eea68fdec5f9b8ec5d295c2106cbd36ac0 | 73,095 |
import os
def lyotstop(wf, RAVC=None, APP=None, get_pupil='no', dnpup=50):
"""Add a Lyot stop, or an APP."""
# load parameters
npupil = 1#conf['NPUPIL']
pad = int((210 - npupil) / 2)
# get LS misalignments
LS_misalignment = (np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) * npupil).astype(int)
... | 5e51dd5109e0888318783ad15dd72b14d292d542 | 73,096 |
import os
def _providers():
"""Return all the providers in the current package."""
providers = []
for name in os.listdir(os.path.dirname(__file__)):
if name.endswith(".py") and name != "__init__.py":
providers.append(_load(name[:-3]))
return providers | f52bc869fdbb3f831058afa6a9207bee644a2805 | 73,097 |
def get_P_Elc_toilet_seat_heater(theta_ave_d, P_Elc_toilet_seat_heater_rtd):
"""暖房時の消費電力を計算する
Parameters
----------
theta_ave_d : float
日付dにおける平均外気温度(地域、季節によらず 11.23), ℃
P_Elc_toilet_seat_heater_rtd : float
便座暖房時の定格消費電力, W
Returns
----------
P_Elc_toilet_se... | 48ca59bbf2ca88e4e93febb4c83c80564050757b | 73,098 |
def shepp_logan(shape):
"""
Creates the Shepp Logan Phantom.
Args:
shape: Shape (in [Y, X]) of Shepp Logan phantom to create.
Returns:
Shepp Logan of shape as np.array
"""
# Definition of Shepp Logan Phantom
# Ellipse Center Major Axis Minor Axis Phi ... | d92789ca5b8ceef6c4b8929b4a9ddb56168f6120 | 73,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.