content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def random(samples, key=(0, 0), counter=(0, 0), sampler="gaussian", threads=False):
"""Generate random samples from a distribution for one stream.
This returns values from a single stream drawn from the specified
distribution. The starting state is specified by the two key values and
the two counter v... | 5,322,500 |
def save(dlls: list, filename: str, path: str) -> None:
"""Método criar o arquivo ``include_files.py``.
Posteriormente o arquivo gerado deverá ser importado no
arquivo `setup.py`.
Args:
dlls (list): Lista tuplas contendo o caminho (path) até a
``dll`` e o nome da ``dll``.
path ... | 5,322,501 |
def random_effect_2level_model(dataframe):
"""
Multi-level model_1_sci includes intercept, variable as fixed and the
interaction term
random on country level.
:param dataframe: a data frame with student ID, school ID, country ID,
science, math, reading, and other five selected variables... | 5,322,502 |
def read_part_sess_long_ids_from_tsv(tsv_file):
"""Extract participant, session and longitudinal from TSV file.
TODO: Find a way to merge with utils/filemanip.py::read_participant_tsv into one util
"""
import os
import pandas
from colorama import Fore
from clinica.utils.exceptions import Cl... | 5,322,503 |
def get_model_data(model_name: str):
"""
Return model data saved in demisto (string of encoded base 64)
:param model_name: name of the model to load from demisto
:return: str, str
"""
res_model = demisto.executeCommand("getMLModel", {"modelName": model_name})[0]
if is_error(res_model):
... | 5,322,504 |
def write_flying_chairs(
root_dir: Union[str, Path],
img_size: Tuple[int, int] = (384, 512)
) -> None:
"""Generate a dummy version of the Flying Chairs dataset.
The original dataset is available at:
https://lmb.informatik.uni-freiburg.de/resources/datasets/FlyingChairs.en.htm
Parameters
-... | 5,322,505 |
def get_bprop_batch_norm(self):
"""Grad definition for `BatchNorm` operation."""
is_training = self.is_training
input_grad = G.BatchNormGrad(is_training, self.epsilon, self.data_format)
def bprop(x, scale, b, mean, variance, out, dout):
if is_training:
saved_reserve_1 = out[3]
... | 5,322,506 |
def deg_to_num(lat_deg, lon_deg, zoom):
"""
degree to num
"""
lat_rad = radians(lat_deg)
n = 2.0 ** zoom
xtile_f = (lon_deg + 180.0) / 360.0 * n
ytile_f = (1.0 - log(tan(lat_rad) + (1 / cos(lat_rad))) / pi) / 2.0 * n
xtile = int(xtile_f)
ytile = int(ytile_f)
pos_x = int((xtile_f ... | 5,322,507 |
def parse_cmdline():
""" Parse command-line arguments
"""
parser = ArgumentParser(prog=__file__)
parser.add_argument("-i", "--indir", dest="indirname",
action="store", default='multiplexed_data', type=str,
help="Parent directory for multiplexed subfolders"... | 5,322,508 |
def get_google_api_books(query_dict: dict, params: dict = None, page: int = 1) -> tuple:
"""Get books from google api from given page."""
query = google_api_query(query_dict)
if not params:
params = {}
params.update(GOOGLE_API_QUERY_PARAMS)
start_index = (page - 1) * PAGINATE_BY
params.... | 5,322,509 |
def get_messages():
"""
Query the data base for messages and returns a container of database message objects.
"""
return Messages.select(Messages, MediaType).join(MediaType) | 5,322,510 |
def create_db(x, y, train_size=0.8, bs=96, random_state=42):
"""
Take dataframe and convert to Fastai databunch
"""
X_train, X_test, y_train, y_test = train_test_split(x, y, train_size=train_size)
train_ds = TrainData(X_train, y_train)
val_ds = TrainData(X_test, y_test)
bs = min(bs, len(tr... | 5,322,511 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up HomeSeer lock-type devices."""
lock_devices = []
homeseer = hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id]
for device in homeseer.devices:
if issubclass(type(device), GenericDoorLock):
dev = HSLock... | 5,322,512 |
def bootstrap(resolver):
"""Lookup the root nameserver addresses using the given resolver
Return a Resolver which will eventually become a C{root.Resolver}
instance that has references to all the root servers that we were able
to look up.
"""
domains = [chr(ord('a') + i) for i in range(13)]
... | 5,322,513 |
def estimate_prior_limits(param_space, prior_limit_estimation_points, objective_weights):
"""
Estimate the limits for the priors provided. Limits are used to normalize the priors, if prior normalization is required.
:param param_space: Space object for the optimization problem
:param prior_limit_estimat... | 5,322,514 |
def intercept_logging(logger: logging.Logger, level: int = None) -> Generator[StringIO, None, None]:
"""
Context manager. Add a temporary stream handler to a logger.
:param logger: a python logger
:param level: a python log level
:return: yields the stream (use .get_value() to extract the stuff!)
... | 5,322,515 |
def rotate_by_point_and_angle(vector, origin, angle):
"""
Rotate vector at origin to angle
:param vector: DB.XYZ
:param origin: DB.XYZ of origin
:param angle: Angle to rotate
:type angle: float
:return: DB.XYZ
"""
transform = DB.Transform.CreateRotationAtPoint(DB.XYZ.BasisZ, angle,... | 5,322,516 |
def load_xviii_bayer_from_binary(binary_data, image_height, image_width):
"""Read XVIII binary images into bayer array
Parameters
-----------
binary_data : numpy.ndarray
binary image data from XVIII
image_height : int
image height
image_width : int
image width
Retur... | 5,322,517 |
def apply_dialects(
source: str, names: Union[str, Iterable[str]], filename: Optional[str] = None
) -> ast.AST:
"""Utility for applying dialect transpilers to source code."""
reducer = dialect_reducer(names, filename)
source = reducer.transform_src(source)
tree = reducer.transform_ast(ast.parse(sour... | 5,322,518 |
def test_integration_forecast_and_report(
mocker, sample_data_df, expected_predictions, tmp_path # noqa: F811
): # pylint: disable=redefined-outer-name
"""Test prediction workflow with reporting."""
# TODO: Test adding saver to flow
test_run_name = "test_integration_forecast_and_report"
saver_data... | 5,322,519 |
def get_atoms(smiles):
"""
Process a SMILES.
SMILES string is processed to generate a sequence
of atoms.
Arguments:
smiles (str): a SMILES representing a molecule.
Returns:
a list of atoms.
"""
tokens = process_smiles(smiles)
return [
REVERSED_ATOM_MAPPING[t... | 5,322,520 |
def clean_path(path):
"""
cleans up paths and resolves ~ and symlinks
"""
realpath = Path(path).expanduser().resolve()
if not realpath.exists():
#FIXME this is a shitty solution, we should deal with conditional include statements
warnings.warn(realpath.name+" doesn't exist")
... | 5,322,521 |
def wide_article_preview_card(
box: str,
persona: Component,
image: str,
title: str,
name: Optional[str] = None,
aux_value: Optional[str] = None,
caption: Optional[str] = None,
items: Optional[List[Component]] = None,
commands: Optional[List[Comman... | 5,322,522 |
def upload_thumbnail(versionable, thumbnail_source_full_path, size=conf.thumbnail_size):
"""Uploads the given thumbnail for the given versionable
:param versionable: An instance of
:class:`~oyProjectManager.models.entity.VersionableBase` which in
practice is an :class:`~oyProjectManager.models.... | 5,322,523 |
def calc_water_year(df: pd.DataFrame):
"""Calculates the water year.
Parameters
----------
df : pandas.DataFrame
Flow timeseries with a DataTimeIndex.
Returns
-------
pandas.DataFrame.index
A pandas.DataFrame index grouped by water year.
"""
return df.index.ye... | 5,322,524 |
def count_and_dissect_tlvs(buf):
"""
Count and dissect TLVs. Return length of LLDP layer
buf -- buffer to dissect
return -- parsed_bytes_total, [(clz, bts), ...]
"""
shift = 0
tlv_type, tlv_len = 1, 1
clz_bts_list = []
while (tlv_type | tlv_len) != 0:
type_and_len = unpack_H(buf[shift:shift + TLV_HEADER_LE... | 5,322,525 |
def get_encoded_access_granter():
"""Add REMS metadata as base64 encoded json. Uses data from user session."""
saml = session["samlUserdata"]
metadata_provider_user = saml[SAML_ATTRIBUTES["CSC_username"]][0]
email = saml[SAML_ATTRIBUTES["email"]][0]
name = "{} {}".format(
saml[SAML_ATTRIBUTE... | 5,322,526 |
def output(prim_data: Dict) -> Dict:
""" Sort the dictionary so that key (score) in descending order, value (time) in ascending order
Args:
prim_data: The original data where key reps score, value reps time
Returns:
a "sorted" dictionary that has score in descending order and time in ascen... | 5,322,527 |
def _create_dummy_graph(triples_count):
"""This creates test data of a given size."""
test_graph_input = rdflib.Graph()
for triples_index in range(triples_count):
test_graph_input.add((
rdflib.term.URIRef("subject:%d" % triples_index),
rdflib.term.URIRef("predicate:%d" % trip... | 5,322,528 |
def _get_magic_var(hostobj, varname, default=""):
"""Use Ansible coordination of inventory format versions
:param hostobj: parsed Ansible host object
:param varname: key of MAGIC_VARIABLE_MAPPING, representing variations of
Ansible inventory parameter
:param default: value, that wil... | 5,322,529 |
def test_cherenkov_instability( show=False ):
"""
Run a simulation with the standard and Galilean scheme respectively
and check that the first one is unstable while the second one is stable
"""
# Dictionary to record the final value of E
slope_Erms = {}
for scheme in [ 'standard', 'galilean... | 5,322,530 |
def sentence_bleu(hypothesis, reference, smoothing=True, order=4, **kwargs):
"""
Compute sentence-level BLEU score between a translation hypothesis and a reference.
:param hypothesis: list of tokens or token ids
:param reference: list of tokens or token ids
:param smoothing: apply smoothing (recomm... | 5,322,531 |
def CPU_temperature():
"""Returns the temperature of the Raspberry Pi's CPU."""
try:
res = os.popen('vcgencmd measure_temp').readline()
return(res.replace("temp=","").replace("'C\n",""))
except:
pass | 5,322,532 |
def write_text(obj: object, file: str, encoding: str = None):
"""
Write an object as string to a text file.
:param obj: The data object.
:param file: The text file path.
:param encoding: Optional encoding, e.g. "utc-8".
"""
if isinstance(file, str):
with open(file, 'w', encoding=enc... | 5,322,533 |
def at_pcmd(seq, progressive, lr, fb, vv, va):
"""
Makes the drone move (translate/rotate).
Parameters:
seq -- sequence number
progressive -- True: enable progressive commands, False: disable (i.e.
enable hovering mode)
lr -- left-right tilt: float [-1..1] negative: left, positive: righ... | 5,322,534 |
def assert_all_less_than(tensor, value):
"""Make sure that all elements of tensor are less than value
Parameters
----------
tensor : torch.tensor
input tensor
value : float
numerical value to check against
Raises
------
RangeException
If one or more elements of tensor... | 5,322,535 |
def generate_representation(coordinates, nuclear_charges,
max_size=23, neighbors=23, cut_distance = 5.0, cell=None):
""" Generates a representation for the FCHL kernel module.
:param coordinates: Input coordinates.
:type coordinates: numpy array
:param nuclear_charges: List of nuclear charges.
... | 5,322,536 |
def standardize_selected_features(X_df, gene_features):
"""Standardize (take z-scores of) selected real-valued features.
Note this should be done for train and test sets independently. Also note
this doesn't necessarily preserve the order of features (this shouldn't
matter in most cases).
"""
X... | 5,322,537 |
def crop_and_align_one(image: Image.Image, polygon: np.array):
"""
Crop and warp image so that it only contains the word selected by the bounding polygon, horizontally aligned
:param image:
:param polygon:
:return:
"""
polygon = np.array(polygon).astype(np.float32)
rect = cv2.minAreaRec... | 5,322,538 |
def _calculate_file_hashes(full_path, f_hashers):
"""
Returns a dictionary of (algorithm, hexdigest) values for the provided
filename
"""
if not os.path.exists(full_path):
raise BagValidationError("%s does not exist" % full_path)
try:
with open(full_path, 'rb') as f:
... | 5,322,539 |
def get_ldap():
"""connects to ldap and returns ldap connection"""
# if not hasattr(g, 'ldap'):
# g.ldap = ldap.initialize(app.config['LDAP_URL'])
# return g.ldap
return None | 5,322,540 |
def _animate_traffic(
traffic: List, time_step: float, plot_f: Callable[[int], None], save: str,
):
"""Animate traffic with given plotting function."""
frames = len(traffic)
def _plot_f(time_index):
print_i(f"Animating time = {time_index * time_step:.3f} s", end="\r")
plot_f(time_index)... | 5,322,541 |
def _sqrt_l2_prox(ww, reg):
"""The proximal operator for reg * ||ww||_2 (not squared)."""
backend = get_backend()
norm_ww = backend.norm(ww, axis=0)
mask = norm_ww == 0
ww[:, mask] = 0
ww[:, ~mask] = backend.clip(1 - reg[~mask] / norm_ww[~mask], 0,
None)[None] *... | 5,322,542 |
def outer_f1(cmds: Cmds,
descs: ThreadPairDescs,
) -> None:
"""Outer function to test ThreadPair.
Args:
cmds: Cmds object to tell alpha when to go
descs: tracks set of ThreadPairDesc items
"""
logger.debug('outer_f1 entered')
t_pair = ThreadPair(group_name... | 5,322,543 |
def modify_content(request, page_id, content_type, language_id):
"""Modify the content of a page."""
page = get_object_or_404(Page, pk=page_id)
perm = PagePermission(request.user).check('change', page=page,
lang=language_id, method='POST')
if perm and request.method == 'POST':
conten... | 5,322,544 |
def _extend_data_with_sampled_characteristics(df, optim_paras, options):
"""Sample initial observations from initial conditions.
The function iterates over all state space dimensions and replaces NaNs with values
sampled from initial conditions. In the case of an n-step-ahead simulation with
sampling a... | 5,322,545 |
def needs_update(targ_capacity, curr_capacity, num_up_to_date):
"""Return whether there are more batch updates to do.
Inputs are the target size for the group, the current size of the group,
and the number of members that already have the latest definition.
"""
return not (num_up_to_date >= curr_ca... | 5,322,546 |
def build_get_array_item_empty_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get an array of array of strings [['1', '2', '3'], [], ['7', '8', '9']].
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return... | 5,322,547 |
def get_single_image_results(gt_boxes, pred_boxes, iou_thr):
"""Calculates number of true_pos, false_pos, false_neg from single batch of boxes.
Args:
gt_boxes (list of list of floats): list of locations of ground truth
objects as [xmin, ymin, xmax, ymax]
pred_boxes (dict): dict of di... | 5,322,548 |
def generate_test_experiments(n=2):
"""Make a test experiment list"""
experiments = ExperimentList()
exp_dict = {
"__id__": "crystal",
"real_space_a": [1.0, 0.0, 0.0],
"real_space_b": [0.0, 1.0, 0.0],
"real_space_c": [0.0, 0.0, 2.0],
"space_group_hall_symbol": " C 2y"... | 5,322,549 |
def MakeProjectIssueConfig(
project_id, well_known_statuses, statuses_offer_merge, well_known_labels,
excl_label_prefixes, templates, col_spec):
"""Return a ProjectIssueConfig with the given values."""
# pylint: disable=multiple-statements
if not well_known_statuses: well_known_statuses = []
if not stat... | 5,322,550 |
def moderate(request):
"""
View for moderation actions on a single item.
"""
microcosm_id = request.POST.get('microcosm_id')
if request.method == 'POST':
if request.POST.get('action') == 'move':
if request.POST.get('item_type') == 'event':
event = Event()
... | 5,322,551 |
def get_our_config(
repository: str,
default_branch: str,
) -> Dict[str, Dict[str, Any]]:
"""
Parse our config from the ``pyproject.toml`` file from GitHub.
:param repository: The repository to obtain the file from (in the form ``<user>/<repo>``).
:param default_branch: The repository's default branch (e.g. ... | 5,322,552 |
def private_invite_code(invite_code_key, invite_code):
"""
内测邀请码校验
:param invite_code_key:
:param invite_code:
:return:
"""
error_dict = 0
if not invite_code:
error_dict = {'captcha_not_blank': ['内测邀请码不能为空']}
else:
# if settings.ENABLE_VERIFY_CAPTCHA:
# s... | 5,322,553 |
def build_collector_url(webmap=None, center=None, feature_layer=None, fields=None, search=None, portal=None, action=None, geometry=None, callback=None, callback_prompt=None):
"""
Creates a url that can be used to open Collector for ArcGIS
================== ============================================... | 5,322,554 |
async def test_async_track_state_change_filtered(hass):
"""Test async_track_state_change_filtered."""
single_entity_id_tracker = []
multiple_entity_id_tracker = []
@ha.callback
def single_run_callback(event):
old_state = event.data.get("old_state")
new_state = event.data.get("new_st... | 5,322,555 |
def load_creator(_, context):
"""Load the record creator."""
old_data = context.get('record')
if old_data:
return old_data.get('created_by', missing)
# TODO a validation error must be raised in each case
return context.get('user_id', missing) | 5,322,556 |
def test_log_follow():
""" Test --follow """
# verify output
with app(FOLLOW, 'follow'):
proc = subprocess.Popen(['dcos', 'task', 'log', 'follow', '--follow'],
stdout=subprocess.PIPE)
# mark stdout as non-blocking, so we can read all available data
# ... | 5,322,557 |
def index_comments(ids, update_only=False):
"""
Index a list of comments by id
Args:
ids(list of int): List of Comment id's
update_only (bool): Update existing index only
"""
index_items(serialize_bulk_comments(ids), COMMENT_TYPE, update_only) | 5,322,558 |
async def unblockpm(unblock):
""" .unblock """
if unblock.reply_to_msg_id:
reply = await unblock.get_reply_message()
replied_user = await unblock.client.get_entity(reply.from_id)
name0 = str(replied_user.first_name)
await unblock.client(UnblockRequest(replied_user.id))
... | 5,322,559 |
def summary(state, figsize=(11, 7), hemisphere="both", center_lon=180, pv_cmap="viridis",
pv_max=None, v_max=None):
"""4-panel plot showing the model state in terms of vorticity and wind."""
grid = state.grid
roll, configure_lon_x = roll_lons(grid.lons, center_lon)
# Scale PV to 10e-4 1/s
pv... | 5,322,560 |
def savings_initial_sol(dist: np.array, nodes: List[dict], vehicles: int, clients: int, limit:int, penalidade:float=0.2) -> List[np.array]:
"""
Cria solucao inicial considerando penalidade usando o metodo de Economia para criacao de solucoes.
"""
# Calcula todas as economias
best_savings = calculat... | 5,322,561 |
def teardown_module(module):
"""teardown any state that was previously setup with a setup_module
method.
"""
import os
import time
# temp file will be removed soon
time.sleep(1.0)
for p in [data_pk, data_pk_gz, data_js, data_js_gz]:
try:
os.remove(p)
except:... | 5,322,562 |
def features_to_matrix(features):
"""
features_to_matrix(features)
This function takes a list of feature matrices as argument and returns
a single concatenated feature matrix and the respective class labels.
ARGUMENTS:
- features: a list of feature matrices
RETURNS:
- f... | 5,322,563 |
def click(xy, offset_xy=(0,0)):
"""
click with left mouse button with offset
"""
(x,y) = xy
(offset_x, offset_y) = offset_xy
x = x + offset_x
y = y + offset_y
move_to((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_... | 5,322,564 |
def union_all(*selects, **kwargs):
"""Return a ``UNION ALL`` of multiple selectables.
The returned object is an instance of
:class:`.CompoundSelect`.
A similar :func:`union_all()` method is available on all
:class:`.FromClause` subclasses.
\*selects
a list of :class:`.Select` instances.... | 5,322,565 |
def run_autode(configuration, max_force=None, method=None, n_cores=1):
"""
Run an orca or xtb calculation
--------------------------------------------------------------------------
:param configuration: (gaptrain.configurations.Configuration)
:param max_force: (float) or None
:param method: (... | 5,322,566 |
def lstm_test():
"""Test function to make sure the dimensions are working"""
# Create an instance of the model
model = LSTM()
# Try out both the options below (all zeros and random)
# shape is: number of examples (mini-batch size), width, height, depth
x_np = np.random.rand(1, 1, 5, 8, 2)
... | 5,322,567 |
def initialize_bert2bert_from_pretrained_bert(
bert_encoder: tf.keras.layers.Layer,
bert_decoder: tf.keras.layers.Layer,
init_checkpoint: Optional[Text] = None) -> None:
"""Helper function to initialze Bert2Bert from Bert pretrained checkpoint."""
ckpt = tf.train.Checkpoint(model=bert_encoder)
logging... | 5,322,568 |
def set_count_and_flavor_params(role, baremetal_client, compute_client):
"""Returns the parameters for role count and flavor.
The parameter names are derived from the role name:
<camel case role name, no hyphens>Count
Overcloud<camel case role name, no hyphens>Flavor
Exceptions from this ... | 5,322,569 |
def extract_tb(tb, limit=None):
"""This implementation is stolen from traceback module but respects __traceback_hide__."""
if limit is None:
if hasattr(sys, "tracebacklimit"):
limit = sys.tracebacklimit
tb_list = []
n = 0
while tb is not None and (limit is None or n < limit):
... | 5,322,570 |
def test_icons_to_html() -> None:
"""It returns the correct HTML representation of an icon."""
i = icons.ICONS["headerlink"]
html = icons.html(i)
assert len(html) == 1
svg = html("svg")
assert len(svg) == 1
path = html("path")
assert len(path) == 1
assert path[0].parent.name == "svg" | 5,322,571 |
def remove_common(counter):
"""
Given a counter remove common words
:param counter:Counter Counter containing words used in the chat
:return: counter Returns the sanitized Counter
"""
# TODO fix remove common it removes stuff it shouldn't - maybe smaller curated list
# Top 10000 common engli... | 5,322,572 |
def test_build_api_request_uri_nbm(cbcsdk_mock):
"""Test _build_api_request_uri method of NewBaseModel"""
api = cbcsdk_mock.api
# if there's no _model_unique_id, _build_api_request_uri should return just cls.urlobject
event = Event(api, model_unique_id=None)
assert event._build_api_request_uri() ==... | 5,322,573 |
def is_dir_exist(path):
"""Whether the directory exists"""
path_info = Path(path)
return path_info.is_dir() | 5,322,574 |
def m1m2count(data):
"""
Reads the counts of epitopes for -1 and -2 mutations by HLA in a dataset.
"""
hlas = list(data["HLA"].sort_values().unique())
mutations = list(data["ID"].sort_values().unique())
m_1 = [mut for mut in mutations if mut.endswith("_m1")]
m_2 = [mut for mut in mutations if mut.endswith... | 5,322,575 |
def get_pyextension_imports(modname):
"""
Return list of modules required by binary (C/C++) Python extension.
Python extension files ends with .so (Unix) or .pyd (Windows).
It's almost impossible to analyze binary extension and its dependencies.
Module cannot be imported directly.
Let's at le... | 5,322,576 |
def density_map(points: PointsData,
radius:float = 50) -> ImageData:
"""
Generate a density map from points data.
Parameters
----------
points : PointsData
radius : float, optional
The local neighborhood is specified as the radius around each sample
position (eac... | 5,322,577 |
def filter_segments(array: np.ndarray, min_len: int = 50) -> None:
"""Filter segments greater or equal to minimum length (inplace).
Args:
array (np.ndarray): Labels.
min_len (int): Minumum length for one segment (default 50)
"""
indices = np.where(array > 0)[0]
next_idx = 0
for ... | 5,322,578 |
def compute_permutation_sample(perm_num, all_conditions_power, trial_indices,
permutation_indices, times, freqs, chs, config,
comp, exp):
""" Helper function to compute the permuted toi band power difference for
a particular permutation of trials bet... | 5,322,579 |
def test_error_unknown_cal_type(tmp_path):
"""
Test an error is raised when writing an unknown cal type.
"""
cal_in = UVCal()
testfile = os.path.join(DATA_PATH, "zen.2457698.40355.xx.delay.calfits")
write_file = str(tmp_path / "outtest_firstcal.fits")
cal_in.read_calfits(testfile)
cal_i... | 5,322,580 |
def get_users():
"""
The endpoint is for now publicly available.
Returns:
JSON of all users
"""
users = User.query # no need to order
users_data = [user.to_dict() for user in users.all()]
return jsonify(users=users_data) | 5,322,581 |
def test_average_rank_quantile_normalization():
"""
Validate testing method that demonstrates first order ranking quantile
normalization.
"""
dataframe, expected = wikipedia_test_set_with_r_expect()
compare = quantile_normalization_preprocesscore_test_method(dataframe)
assert Match(compare, ... | 5,322,582 |
def _lower_neighbours(G, u):
"""Given a graph `G` and a vertex `u` in `G`, we return a list with the
vertices in `G` that are lower than `u` and are connected to `u` by an
edge in `G`.
Parameters
----------
G : :obj:`Numpy Array(no. of edges, 2)`
Matrix storing the edges of the graph.
... | 5,322,583 |
def find_f_include_statement(line):
"""
Determine whether line contains a Fortran INCLUDE statement. If so,
return the file name being INCLUDE'd.
line is a line of code from the Fortran file being processed.
If the INCLUDE'd file is in the exclude_finc_files set, then simply
return None. We ... | 5,322,584 |
def get_phase_from_ephemeris_file(mjdstart, mjdstop, parfile,
ntimes=1000, ephem="DE405",
return_pint_model=False):
"""Get a correction for orbital motion from pulsar parameter file.
Parameters
----------
mjdstart, mjdstop : float
... | 5,322,585 |
def create_hash(ls):
"""this function takes in the treecolor matrix and returns a tuple of the hash code and the hash vector that
uniquely identifies a particular combination of colors"""
index_vector = [x for x in range(20)] # creates a vector of the indexes
hash_vector = matrixvector_multiply(modify_treecolorm... | 5,322,586 |
def arguments():
"""Parse the arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('SONG_NAME', help="Name of the song to download.",
default=None, nargs='?', type=str)
parser.add_argument('-q', '--quiet',
help="Don't ask the user to selec... | 5,322,587 |
def dict_inject(base_dct, injection_dct, add_keys=True):
""" Recursively inject inject_dict into base_dict. Recurses down into dicts nested
to an arbitrary depth, updating keys.
Will not alter base_dct or injection_dct, but return a deep copy without references to any of the former.
The optional argum... | 5,322,588 |
def create_pruning_param_scorer(
params: List[Parameter],
score_type: Union[str, MFACOptions],
) -> PruningParamsScorer:
"""
:param params: List of Parameters for the created PruningParamsScorer to track
:param score_type: String name of scoring type to use. Valid options are
'magnitude', 'm... | 5,322,589 |
def calculate_new_age(table):
"""Calculates new age and adds it to the dataframe"""
date_now = datetime.now()
def get_age(birthday):
if birthday:
return relativedelta(date_now, birthday).years
table['age'] = table.apply(lambda birthday: get_age)
return table | 5,322,590 |
def get_wl(full_dir):
"""
Get the NIR wavelength used for this Video session.
:param full_dir: directory containing SVM/SVR files
:return: a string containing the wavelength
"""
return channels[str(get_channel(full_dir))] | 5,322,591 |
def calculate_v(nfs):
"""Calculates V(n+1/n) values. Useful for establishing the quality of
your normalization regime. See Vandesompele 2002 for advice on
interpretation.
:param DataFrame nfs: A matrix of all normalization factors, produced by
`calculate_all_nfs`.
:return: a Series of values... | 5,322,592 |
def export_ruptures_csv(ekey, dstore):
"""
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
oq = dstore['oqparam']
if 'scenario' in oq.calculation_mode:
return []
dest = dstore.export_path('ruptures.csv')
header = ('rupid multiplicity ... | 5,322,593 |
def get_arguments():
"""Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments.
"""
parser = argparse.ArgumentParser(description="DeepLabLFOV NetworkEv")
parser.add_argument("--pred-path", type=str, default='',
help="Path to predicted segmen... | 5,322,594 |
def count_down(count):
""" Holds all the functionality of counting """
count_min = math.floor(count / 60) # Converts the counting sec to min to make them display on the screen like clock
count_sec = count % 60 # Holds the remaining sec to make them display on the screen0
# Use to display two digits o... | 5,322,595 |
def create_power_spectrum(subject, spectrum_name, intervals,
fmin, fmax, nfft, overlap):
""" Creates a power spectrum item.
"""
# get raw objects organized with average groups as keys
ival_times, raw_block_groups = get_raw_blocks_from_intervals(subject,
... | 5,322,596 |
def get_google_auth(state=None, token=None):
"""Helper function to create OAuth2Session object."""
if token:
return requests_oauthlib.OAuth2Session(Auth.CLIENT_ID, token=token)
if state:
return requests_oauthlib.OAuth2Session(Auth.CLIENT_ID,
state=state,
... | 5,322,597 |
def test_token_hic():
"""Check if submitting of a token is tackled properly"""
# no token, no token header, no authentication in request header
hic = Waterinfo("hic")
hic.clear_cache()
assert hic._token_header is None
_, res = hic.request_kiwis({"request": "getRequestInfo"})
assert "Authoriz... | 5,322,598 |
def test_resize(row_data_ishan: List) -> None:
"""Test to see if Resize works for the ideal case"""
reference_tensor = REPT(rows=row_data_ishan)
original_tensor = reference_tensor.copy()
new_shape = original_tensor.flatten().shape
reference_tensor.resize(new_shape)
assert reference_tensor.shape... | 5,322,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.