content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from clinica.utils.dwi import merge_volumes_tdim
import os.path as op
import os
def merge_noddi_ped(in_file, in_bvec, in_bval, alt_file, alt_bvec, alt_bval):
"""
This is to merge the two ped images and also concatenate the bvecs and bvals
:return:
"""
out_bvals_tab = op.abspath('merged.bval')
... | 07c0a49fcf6d0362625b5361a5ee4800d1824b71 | 3,634,100 |
import numpy
def _xml_column_name_orig_to_new(column_name_orig):
"""Converts name of XML column from original (segmotion) to new format.
:param column_name_orig: Column name in original format.
:return: column_name: Column name in new format.
"""
orig_column_flags = [c == column_name_orig for c ... | 4f5302381d6a94d74d311355e1aad8c79e1e0cbe | 3,634,101 |
import os
def copy_from_file(conn, df, table):
"""
Here we are going save the dataframe on disk as
a csv file, load the csv file
and use copy_from() to copy it to the table
"""
# Save the dataframe to disk
tmp_df = "./tmp_dataframe.csv"
df.to_csv(tmp_df, header=False)
f = open(tmp_... | f49cddc4cc38fa3797eac91514a00ad4dd805d1f | 3,634,102 |
import os
def get_ocp_repo(rhel_major_version=None):
"""
Get ocp repo file, name will be generated dynamically based on
ocp version.
Args:
rhel_major_version (int): Major version of RHEL. If not specified it will
take major version from config.ENV_DATA["rhel_version"]
Returns... | 3997f513b59e8acc3290d9907b14d80f46552cc6 | 3,634,103 |
def ndwi(raster):
"""
Normalized Difference Water Index (NDWI)
NDWI := factor * (Green - NIR1) / (Green + NIR1)
:param raster: xarray or numpy array object in the form (c, h, w)
:return: new band with SI calculated
"""
nir1, green = _get_band_locations(
raster.attrs['band_names'], ['... | 64e8d553b8ace8c3fc3ea2a7fed98c43fcadf22a | 3,634,104 |
def get_settings():
"""Utility function to retrieve settings.py values with defaults"""
return {
"DJANGO_WYSIWYG_MEDIA_URL": getattr(settings, "DJANGO_WYSIWYG_MEDIA_URL", urljoin(settings.STATIC_URL, "ckeditor/")),
"DJANGO_WYSIWYG_FLAVOR": getattr(settings, "DJANGO_WYSIWYG_FLAVOR", "yui"),
... | 1028431d5facd406020892cb5019b26de55f7193 | 3,634,105 |
def einsum_via_matmul(input_tensor, w, num_inner_dims):
"""Implements einsum via matmul and reshape ops.
Args:
input_tensor: float Tensor of shape [<batch_dims>, <inner_dims>].
w: float Tensor of shape [<inner_dims>, <outer_dims>].
num_inner_dims: int. number of dimensions to use for inner pr... | acc672a84661e11444a452393587d0dfc164b636 | 3,634,106 |
def cost(guess, tdoa, array):
""" Calculate the sum of the squares of the loss function of hyperbolic
least squares problem
guess : 1D or 2D row ndarray with one or more guesses coordinates
tdoa : column 2D ndarray with the TDOA from some reference sensor
receptorsPosit... | 27b08a1a6966d5f18974244f4db53db5c6c14fee | 3,634,107 |
def from_literal(tup):
"""Convert from simple literal form to the more uniform typestruct."""
def expand(vals):
return [from_literal(x) for x in vals]
def union(vals):
if not isinstance(vals, tuple):
vals = (vals,)
v = expand(vals)
return frozenset(v)
if not isinstance(tup, tuple):
... | a06d35e27512bfeae030494ca6cad7ebac5c7d2c | 3,634,108 |
def distill_resnet_32_to_15_cifar20x5():
"""Set of hyperparameters."""
hparams = distill_base()
hparams.teacher_model = "resnet"
hparams.teacher_hparams = "resnet_cifar_32"
hparams.student_model = "resnet"
hparams.student_hparams = "resnet_cifar_15"
hparams.optimizer_momentum_nesterov = True
# (base_lr... | 503b49f0e61191eb87516b8c83ca88fbc0313be2 | 3,634,109 |
from datetime import datetime
def timestamp() -> datetime.datetime:
"""
Returns a datetime object representing the current UTC time. The last 3 digits of the microsecond frame are set
to zero.
:return: a UTC timestamp
"""
# Get tz-aware datetime object.
dt = arrow.utcnow().naive
# S... | e1fb7fbe39bef103704af0a7bfece4038506bbdc | 3,634,110 |
def next_fake_batch():
"""
Return random seeds for the generator.
"""
batch = np.random.uniform(
-1.0,
1.0,
size=[FLAGS.batch_size, FLAGS.seed_size])
return batch.astype(np.float32) | 80c4b32fd145430dad06b16fd90273fd9aa944f1 | 3,634,111 |
def print_result(error, real_word):
"""" print_result"""
if error == 5:
print("You lost!")
print("Real word is:", real_word)
else:
print("You won!")
return 0 | 598814ac64ac767c102080a0a82541d3b888843c | 3,634,112 |
def read_cpu_info():
"""Return the CPU model number & number of CPUs."""
try:
with open('/proc/cpuinfo') as f:
models = [line[line.index(':')+2:] for line in f if line.startswith('model name')]
return models[0].strip(), len(models)
except:
log.exception('Failed to read CP... | 68ce0de7a36d01fc18f3be7f182b37735ec5683a | 3,634,113 |
import yaml
def _yaml_parse(s):
"""Uses yaml module to parse s to a Python value.
First tries to parse as an unnamed flag function with at least two
args and, if successful, returns s unmodified. This prevents yaml
from attempting to parse strings like '1:1' which it considers to
be timestamps.
... | 52a788b63ade60bed879b5d0a14e21177902af2e | 3,634,114 |
def mongo_convert(sch):
"""Converts a schema dictionary into a mongo-usable form."""
out = {}
for k in sch.keys():
if k == 'type':
out["bsonType"] = sch[k]
elif isinstance(sch[k], list):
out["minimum"] = sch[k][0]
out["maximum"] = sch[k][1]
elif is... | 0208ceda058042a9f44249a1b724c4b7883afec1 | 3,634,115 |
def files_identical(a, b):
"""Return a tuple (file a == file b, index of first difference)"""
a_bytes = open(a, "rb").read()
b_bytes = open(b, "rb").read()
return bytes_identical(a_bytes, b_bytes) | a8e392f5b2682459525c329d1bd8ab64104628b6 | 3,634,116 |
import math
def discounted_cumulative_gain(rank_list):
"""Calculate the discounted cumulative gain based on the input rank list and return a list."""
discounted_cg = []
discounted_cg.append(rank_list[0])
for i in range(1, len(rank_list)):
d = rank_list[i]/math.log2(i+1)
dcg = d + disco... | eaa5ad6185e2abb239097be5399dffd82d143fd3 | 3,634,117 |
def adapter(js_constructor, base=Adapter):
"""
Allows a class to implement its adapting logic with a `js_args()` method on the class itself.
This just helps reduce the amount of code you have to write.
For example:
@adapter('wagtail.mywidget')
class MyWidget():
...
... | e808a4a8dd50fa61157f45a014ec390cc8ee1370 | 3,634,118 |
import sys
import os
def ancienne_fonction_chemin_absolu(relative_path):
"""
Donne le chemin absolu d'un fichier.
PRE : -
POST : Retourne ''C:\\Users\\sacre\\PycharmProjects\\ProjetProgra\\' + 'relative_path'.
"""
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.ab... | a33db91a2bd72273acc14caea415181297c16318 | 3,634,119 |
import warnings
import inspect
def data(input, name_func=None, doc_func=None, skip_on_empty=False, **legacy):
""" A "brute force" method of parameterizing test cases. Creates new
test cases and injects them into the namespace that the wrapped
function is being defined in. Useful for parameterizing... | 2d38bb642a1e5a020f7c07de8348c5621c8cbccb | 3,634,120 |
def get_form_field_names(form_class):
"""Return the list of field names of a WTForm.
:param form_class: A `Form` subclass
"""
unbound_fields = form_class._unbound_fields
if unbound_fields:
return [f[0] for f in unbound_fields]
field_names = []
# the following logic has been taken fr... | 27c91a1e3c1b71f69d44747955d59cee525aa50e | 3,634,121 |
def gen_empty_structure_data_array(number_of_atoms):
"""
Generate an array data structure to contain structure data.
Parameters
----------
number_of_atoms : int
The number of atoms in the structure.
Determines the size of the axis 0 of the structure array.
Returns
-------
... | 3602483721bd5573cfa9bb605db52511999349ac | 3,634,122 |
from datetime import datetime
def actives_alerts_table(strategy, style='', offset=None, limit=None, col_ofs=None,
group=None, ordering=None, datetime_format='%y-%m-%d %H:%M:%S'):
"""
Returns a table of any active alerts.
"""
COLUMNS = ('Symbol', '#', 'Label', 'TF', 'Created', ... | 729c9e7f30c1c73c4f41cb8ced18820b79639db7 | 3,634,123 |
from django.contrib.auth import logout
def signout(request):
"""Logs out user"""
logout(request)
return redirect('/') | 9b10ffc58f066affc915baf926815c032e041409 | 3,634,124 |
def _get_cached_item(cache_key):
"""Returns an item from memcache if cached
"""
return memcache.get() | 0265025d0599a7ec887c866ce5712d1f89c9832b | 3,634,125 |
def format_dnb_company_investigation(data):
"""
Format DNB company investigation payload to something
DNBCompanyInvestigationSerlizer can parse.
"""
data['dnb_investigation_data'] = {
'telephone_number': data.pop('telephone_number', None),
}
return data | 9c27990bad98b36649b42c20796caabeaae1e21b | 3,634,126 |
def audio_feat(id):
"""
Return audio features of a track.
search_id[0]['insert_feature_here']
id="4nb8OcZG8lpnHi5DmkEnY2" #Sample ID
audio_feat("4nb8OcZG8lpnHi5DmkEnY2")
:param id:
:return:
"""
return sp.audio_features(tracks=id) | 168801f4b0e01bf5fb4d416162bde5bfdd0d592e | 3,634,127 |
import os
def get_results_dir(tomo_path):
"""Return/Create the results directory"""
res_dir = os.path.abspath(tomo_path)+"_results"
common.mkdir_p(res_dir)
return res_dir | f1be2d27e7e0170384f4859db85106baa0f406a0 | 3,634,128 |
def params_v2_biasless(exp_name, convtype='chebyshev5', pooltype='max', nmaps=16,
activation_func='relu', stat_layer=None, input_channels=1,
gc_depth=8, nfilters=64,
const_k=5, var_k=None,
filters=None, batch_norm_output=False,
... | b5db72cd020115283f06d768920b55161a333139 | 3,634,129 |
import io
def get_ccd_pos(filename, radec=None, verbose=True):
"""
Parameters
----------
"""
astrom_file = io.filename_to_guider(filename)
if len(astrom_file)==0:
if verbose:
print("No astrom file found for %s"%filename)
return [np.NaN,np.NaN]
astrom_file = a... | e112e6ccbda8b28d2ac23bba1ab5b23fc7a2aab9 | 3,634,130 |
def mode2(data,v0,v1, dmin=0.0):
""" v0..v1 (both inclusive) are channel selections
threshold on dmin
for odd number of channels, center line in mode2 will be same as mode1
@todo the frequency axis is not properly calibrated here
@todo a full 2D is slow, we only need the 1D version
... | b6d361cacfba244cc906a60ed5f4f5b637451554 | 3,634,131 |
def learning_curve(estimator, X, y, groups=None,
train_sizes=np.linspace(0.1, 1.0, 5), cv=None, scoring=None,
exploit_incremental_learning=False, n_jobs=1,
pre_dispatch="all", verbose=0, shuffle=False,
random_state=None):
"""Learning curve.... | e8109033f2be16494c29c7d8626a3ad23646b9ed | 3,634,132 |
def directed_dfs(digraph, start, end, max_total_dist, max_buildings):
"""
Finds the shortest path from start to end using a directed depth-first
search. The total distance traveled on the path must not
exceed max_total_dist, and the number of buildings on this path must
not exceed max_buildings.
... | 1a88077d9441fc246f3d93194bb1ce53e0e48383 | 3,634,133 |
def zeta(z, x, beta2):
"""
Eq. (6) from Ref[1] (constant term)
Note that 'x' here corresponds to 'chi = x/rho',
and 'z' here corresponds to 'xi = z/2/rho' in the paper.
"""
return 3 * (4* z**2 - beta2 * x**2) / 4 / beta2 / (1+x) | aa623a1876fbb13128132960840ea388dac67e85 | 3,634,134 |
def getCountry(user):
"""
Returns the object the view is displaying.
"""
# get users country from django cosign module
user_countries = TolaUser.objects.all().filter(user__id=user.id).values('countries')
get_countries = Country.objects.all().filter(id__in=user_countries)... | 6d5825cf28729326626585ae566a221b6e90db47 | 3,634,135 |
def calculate_relative_enrichments(results, total_pathways_by_resource):
"""Calculate relative enrichment of pathways (enriched pathways/total pathways).
:param dict results: result enrichment
:param dict total_pathways_by_resource: resource to number of pathways
:rtype: dict
"""
return {
... | 7060e032f2a619929cfcf123cf0946d7965b86de | 3,634,136 |
def _import_config(config_dict, validating=False):
"""Applies a previously exported configuration to the current system.
This method only exists to decouple the import logic from the atomic transaction so that this method can be reused
for validation without making any permanent changes.
:param config... | f891437d68a05a0d98e489ac07fef4dbc77cfd25 | 3,634,137 |
def clean_name(name):
"""Clean a name string
"""
# flip if in last name, first name format
tokens = name.split(',')
if len(tokens) == 2:
first, last = tokens[1], tokens[0]
else:
first, last = name.split(' ')[:2]
# remove punctuation
first_clean = first.strip().capitaliz... | ef5fe3e53ba1134c45c30f4b6342a0641e85f114 | 3,634,138 |
def find_prime(num_bits: int) -> int:
"""Find a prime represented with given number of bits.
Generates random numbers of given size until one of them is deemed prime by
a probabilistic primality check.
Args:
num_bits: size of the prime in terms of bits required for representing it
Return... | 91b09571720fb181d4be135c767c9a9f7ca4c6e0 | 3,634,139 |
import struct
def UnpackS8(buf, offset=0, endian='big'):
""" Unpack an 8-bit signed integer into 1 byte.
Parameters:
buf - Input packed buffer.
offset - Offset in buffer.
endian - Byte order.
Return:
2-tuple of unpacked value, new buffer offset.
"""
try:... | e610b09e5e080634fbcbe3c37b65c8f12988db7e | 3,634,140 |
def estimator(data):
""" Provide the estimate calulations based on that data received """
#Collect required data from data imput
impact = {}
severeImpact = {}
reportedCases = data['reportedCases']
periodType = data['periodType']
timeToElapse = data['timeToElapse']
totalHospitalBeds = data['totalHospital... | 82ad0497914ea038a365bc19357b37bf61af3fab | 3,634,141 |
def diff_align(dfs, groupers):
""" Align groupers to newly-diffed dataframes
For groupby aggregations we keep historical values of the grouper along
with historical values of the dataframes. The dataframes are kept in
historical sync with the ``diff_loc`` and ``diff_iloc`` functions above.
This fu... | 2a92476cd913404b737dc941d51083f64ef70978 | 3,634,142 |
def get_usage_data(
es_client, start_date, end_date, match_terms={}, addl_cols=[], index="path-schedd-*"
):
"""Returns rows of usage data"""
default_cols = [
"Owner",
"ScheddName",
"GlobalJobId",
"RecordTime",
"RemoteWallClockTime",
"RequestCpus",
"Cp... | 665601cab0ac7c12bbde5f702b99ac75bc679872 | 3,634,143 |
def check_email_address_validity(email_address):
"""Given a string, determine if it is a valid email address using Django's validate_email() function."""
try:
validate_email(email_address)
valid_email = True
except ValidationError:
valid_email = False
return valid_email | 809de97c1e87a08e2ebf68b50096fc6d11104c17 | 3,634,144 |
import collections
def _GetHostConfigs(lab_config_pool, hosts_or_clusters):
"""Get host configs for clusters.
Args:
lab_config_pool: a lab config pool
hosts_or_clusters: a list of hosts or clusters.
Returns:
a list of HostConfigs.
"""
if not hosts_or_clusters:
return lab_config_pool.GetHost... | 096ac69e70889ad4a9889caf09ee02457f309e22 | 3,634,145 |
def load_targets_file(input_file):
"""
Takes a string indicating a file name and reads the contents of the file.
Returns a list containing each line of the file.
Precondition: input_file should exist in the file system.
"""
with open(input_file, 'r') as f:
f = f.readlines()
out = [i.replace('\n','').replace('\... | 40d305e244264d6c3249bb9fb914cda3ebcda711 | 3,634,146 |
def plot_avg_profile(rad_dict, ylim=[0, None]):
"""
Function for plotting up average profiles including differences
Parameters
----------
rad_dict : dict
Dictionary of objects and variables to process. See example
ylim : list
ylimits to use
Returns
-------
ax : mat... | c79d28b289c3f403c49bc5695edc3b17215cf7f0 | 3,634,147 |
def localized_dt_string(dt, use_tz=None):
"""Convert datetime value to a string, localized for the specified timezone."""
if not dt.tzinfo and not use_tz:
return dt.strftime(DT_NAIVE)
if not dt.tzinfo:
return dt.replace(tzinfo=use_tz).strftime(DT_AWARE)
return dt.astimezone(use_tz).strft... | 6ae8fd12d93c360e9f23ec3e4e5080474dc7ea59 | 3,634,148 |
import getopt
import sys
import pkg_resources
import os
def parse_command_line():
"""Parses the command line
"""
try:
opts, remaining_args = getopt.getopt(sys.argv[1:], "ihvosmdextn",
["input=", "help", "verbose", "version", "output=", "strict",
"dump-missed-files=", "se... | 3d7f6771df17af7a3cb92a6dd83da1fbf5cc6d36 | 3,634,149 |
def dissolve_project_data(project_data):
"""
This functions uses the unionCascaded function to return a dissolved MultiPolygon geometry
from several Single Part Polygon geometries.
"""
multipolygon_geometry = ogr.Geometry(ogr.wkbMultiPolygon)
for item in project_data:
polygon = ogr.Crea... | 1e657087a564e9e134b11bfa382f337c65efa6d2 | 3,634,150 |
import os
def get_visit_exposure_footprints(visit_file='j1000p0210_visits.npy', check_paths=['./', '../RAW'], simplify=1.e-6):
"""
Add exposure-level footprints to the visit dictionary
Parameters
----------
visit_file : str
File produced by `parse_visits` (`visits`, `all_groups`, `inf... | ea687e5dea3909874c5a70d259e198a91f7bf1a2 | 3,634,151 |
def pega_salada_sobremesa_suco(items):
""" Funcao auxiliar que popula os atributos salada, sobremesa e suco do cardapio da refeicao fornecida."""
alimentos = ["salada", "suco", "sobremesa"]
cardapio = {}
for alim in alimentos:
tag = alim.upper() + ":" # tag para procurar o cardapio dos alimento... | 4ccf2907a4e828d1357e16e827ad587e4a50a287 | 3,634,152 |
def readRGBImg(datapath, driver="GTiff"):
"""
Reads image path and returns 3-D numpy matrix of RGB image.
:param datapath: Path/String
Image path that is opened by rasterio.
:param driver: String
GDAL driver for opening the image. Default: 'GTiff'.
:return: rasterio data, Ndarray
... | 9f20ea8ca8c9594ddad570a650e5a496cf87e1ad | 3,634,153 |
def show_hidden_word(secret_word, old_letters_guessed):
"""
:param secret_word:
:param old_letters_guessed:
:return: String of the hidden word except the letters already guessed
"""
new_string = ""
for letter in secret_word:
if letter in old_letters_guessed:
new_string = ... | 2b3618619dcde2875da9dc8600be334e7aaadaad | 3,634,154 |
import logging
import os
def parse_args(args: list) -> dict:
"""
Create a parser for command line attributes and parses them
:param args: the arguments to parse
:return: parsed arguments
"""
parser = SmartArgumentParser(
description="Triggers some bug in listed programs", parents=[argu... | 7e669dc3c9af1fb56b6f78b74393af1b0959e2e2 | 3,634,155 |
import uuid
def get_cas_user(tree):
"""
Callback invoked by the CAS module that ensures that the user signing in via CAS has a valid Django User associated
with them. Primary responsibility is to create a Django User / Participant if none existed, or to associate the CAS
login id with the given User. ... | e30be40d4bd2ebb92bc264f769c853d11aac6bf3 | 3,634,156 |
def get_total_gap(data : np.ndarray) -> float:
"""
Computes the total gap in time units for a given dataset
:param data: datset of the lightcurve
:return: total gap in units of time
"""
values,counts,most_common = get_diff_values_counts_most_common(data)
values[values - most_common < 10**-5... | 9cba80b47c430b38236f9160e6b62a8eb2ba9cab | 3,634,157 |
def print_srt_line(i, elms):
"""Print a subtitle in srt format."""
return "{}\n{} --> {}\n{}\n\n".format(i, format_srt_time(elms[0]),
format_srt_time(float(elms[0]) +
float(elms[1])),
... | cd089bdc06417f3f0915f97272ba7ec0bdc7d153 | 3,634,158 |
def depthwise_separable_conv(inputs,
num_pwc_filters,
width_multiplier,
scope,
downsample=False):
"""Depth-wise separable convolution."""
num_pwc_filters = round(num_pwc_filters * width_multiplier)
... | d6de489b766800957dceba05b1ba76f337974b04 | 3,634,159 |
def filter_packages(packages: list, key: str) -> list:
"""Filter out packages based on the given category."""
return [p for p in packages if p["category"] == key] | 46f11f5a8269eceb9665ae99bdddfef8c62295a2 | 3,634,160 |
def ptlinear(x, W, b=None, b2=None, is_pre_training=False, activation=None):
"""Pre trainable Linear function, or affine transformation.
It accepts two or three arguments: an input minibatch ``x``, a weight
matrix ``W``, and optionally a bias vector ``b``. It computes
:math:`Y = xW^\top + b`.
Args... | 2a3ae59b1c7e5e15506ec251fa336b89ff1e5f48 | 3,634,161 |
def cubic_bezier(pts, t):
"""
:param pts:
:param t:
:return:
"""
p0, p1, p2, p3 = pts
p0 = pylab.array(p0)
p1 = pylab.array(p1)
p2 = pylab.array(p2)
p3 = pylab.array(p3)
return p0 * (1 - t) ** 3 + 3 * t * p1 * (1 - t) ** 2 + \
3 * t ** 2 * (1 - t) * p2 + t ** 3 * p3 | 3239f0afcda78605d3ea2cf3e77bd3ee3827b358 | 3,634,162 |
from typing import List
def _GetServerComponentArgs(config_path: str) -> List[str]:
"""Returns a set of command line arguments for server components.
Args:
config_path: Path to a config path generated by
self_contained_config_writer.
Returns:
An iterable with command line arguments to use.
"""... | 7f768c8eaa6dc47dc2be3da5297cf17550e26896 | 3,634,163 |
import random
import string
def random_string(length=4):
"""Generates a random string based on the length given
Keyword Arguments:
length {int} -- The amount of the characters to generate (default: {4})
Returns:
string
"""
return "".join(
random.choice(string.ascii_upper... | ad9816e22a898e1e7d17d1bc9f0e56265bb09ac6 | 3,634,164 |
def FindBySummaryName(name):
"""
Find the first instance of a virtual machine with the specified name.
"""
vms = GetAll()
for vm in vms:
try:
summary = vm.GetSummary()
config = summary.GetConfig()
if config != None and config.GetName() == name:
return vm
... | 981d8e13b6bdf39302f5a192453bbb1ea1f4e943 | 3,634,165 |
def get_potential_trace_fields(poly,sln=2):
"""Given a minimal polynomial of a trace field, returns a list of minimal polynomials of the potential invariant trace fields."""
pol = pari(poly)
try:
return [str(rec[0].polredabs()) for rec in pol.nfsubfields()[1:] if _knmiss(rec[0].poldegree(),pol.polde... | a952fefdd98f38b0c23d3ca3962b85584daa70be | 3,634,166 |
import os
def get_movielens(path=None, variant="ml-25m"):
"""Gets the movielens dataset for use with merlin-models
This function will return a tuple of train/test merlin.io.Dataset objects for the
movielens dataset. This will download the movielens dataset locally if needed,
and run a ETL pipeline wi... | e59a3fe560264ad43451cdd0e0ef457a25cbfbd6 | 3,634,167 |
def launch():
"""Initialize the module."""
return UERRCMeasurementsWorker(UERRCMeasurements, PRT_UE_RRC_MEASUREMENTS_RESPONSE) | d26a4e28b5e541eaba9543211b477ba3734a5082 | 3,634,168 |
def enlarge_histogram(file = None,filename = None):
"""
Arguments:
file: an image file that is going to be processed
filename: a filename of the file to be processed
Returns:
The same input image but with its histogram enlarged.
"""
if file is None and filename... | 5997647820fb4cee16f0c4e3d6e588859ee2ea77 | 3,634,169 |
def task(n):
"""Return 2 to the n'th power"""
return 2 ** n | 5780e22d4916664d66279d8ad8afed3b176d9adb | 3,634,170 |
import os
def create_splits(dataframe, split_path, n_splits = 10) :
"""
Should i reset index ?
"""
length = int(dataframe.shape[0] / int(n_splits))
for i in range(n_splits) :
frame = dataframe.iloc[i*length:(i+1)*length]
if i == n_splits-1 :
frame = dataframe.iloc[i*len... | fd6c8e31fe271a957028ff7471a1294a84ee62be | 3,634,171 |
def get_relationship(context, user_object):
"""caches the relationship between the logged in user and another user"""
user = context["request"].user
return get_or_set(
f"relationship-{user.id}-{user_object.id}",
get_relationship_name,
user,
user_object,
timeout=259200... | 5c640f51b8319ad918e6c176be4ca5fab143de1c | 3,634,172 |
def _ts_midpoint(x1, d: int):
"""moving midpoint: (ts_max + ts_min) / 2"""
return _ts_max(x1, d) + _ts_min(x1, d) | b8916ea7bb347a828fc504bbd19bf5eeeed57e5c | 3,634,173 |
import numbers
def maybe_delivery_mode(
v, modes=DELIVERY_MODES, default=PERSISTENT_DELIVERY_MODE):
"""Get delivery mode by name (or none if undefined)."""
if v:
return v if isinstance(v, numbers.Integral) else modes[v]
return default | 20221a11f9af378e2b877cf76941f2f05ff2c8da | 3,634,174 |
def load_pairs(path: str) -> list:
"""
Loads the pairs specified in a file in the format of "word1 word2" separated by new line.
:param path: Path to the file containing the pairs.
:return: The list of unique tuples contained in the file, but not their inverse counterpart as opposed to
load_constrai... | 7f98937c14315d00feb32db79c54e6c79fa32e3a | 3,634,175 |
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: the file path to the i... | b85dd2ee866231a0db53bfab8151fdad9e875ff8 | 3,634,176 |
def is_illumina_run(run_dir):
"""
Detects signature files in the run directory (eg RunInfo.xml) to detemine
if it's likely to be an Illumina sequencing run or not.
:param run_dir: The path to the run.
:type run_dir: str
:return: True if it looks like an Illumina run.
:rtype: bool
"""
... | 7069e29c977da3d4f23bf6e3321ec3ebc7b44d9f | 3,634,177 |
import os
def get_data_filepath(filename):
"""Construct filepath for a file in the test/data directory
Args:
filename: name of file
Returns:
full path to file
"""
return os.path.join(os.path.dirname(__file__), 'data', filename) | d3d83cbf83d32b0252658f77b7bbb6fbdb99845f | 3,634,178 |
from datetime import datetime
import requests
def polo_return_chart_data(currency_pair,
start_unix=None,
end_unix=None,
period_unix=14400,
format_dates=True,
to_frame=True):
"""
... | 51f8ecfce81359132ede56ff5b37f106e54183b2 | 3,634,179 |
def ergtoboatspeed(min,sec,ratio,crew,rigging,erg):
""" Calculates boat speed, given an erg split for given crew, boat, erg
"""
res = ergtopower(min,sec,ratio,crew,erg)
pw = res[0]
res = constantwatt(pw,crew,rigging)
return res | d192c0e9edc1ef46468dc4762c22d45320ad36a9 | 3,634,180 |
import argparse
def parse_args(args):
"""Parse command line arguments.
"""
parser = argparse.ArgumentParser(description='Generate Shadow Hashes')
parser.add_argument('-m', '--method', default='SHA512',
choices=shadow.HASH_METHODS,
help='Hashing method to... | a64f037f10d7fad2a0231dd5f7d280bd5e14965a | 3,634,181 |
def interval_range(
start=None, end=None, periods=None, freq=None, name=None, closed="right",
) -> "IntervalIndex":
"""
Returns a fixed frequency IntervalIndex.
Parameters
----------
start : numeric, default None
Left bound for generating intervals.
end : numeric , default None
... | a2873a34780da22c8955278c358f45d0432b1f53 | 3,634,182 |
def get_summary_description(node_def):
"""Given a TensorSummary node_def, retrieve its SummaryDescription.
When a Summary op is instantiated, a SummaryDescription of associated
metadata is stored in its NodeDef. This method retrieves the description.
Args:
node_def: the node_def_pb2.NodeDef of a TensorSum... | 80df9bd63c23aa9f1f92d5d3a1f49dd54c4f0737 | 3,634,183 |
def _einsum_kronecker_product(*trans_mats):
"""Compute a Kronecker product of multiple matrices with :func:`numpy.einsum`.
The reshape is necessary because :func:`numpy.einsum` produces a matrix with as many
dimensions as transition probability matrices. Each dimension has as many values as
rows or col... | 39622c94ea9138b4cb2511922166178998231b2e | 3,634,184 |
def calc_loss_class(true_box_conf, CLASS_SCALE, true_box_class, pred_box_class):
"""
== input ==
true_box_conf : tensor of shape (N batch, N grid h, N grid w, N anchor)
true_box_class : tensor of shape (N batch, N grid h, N grid w, N anchor), containing class index
pred_box_class : tensor of shape ... | 3971cdce266fc0af85f9a3d56e0266ecb31ff0da | 3,634,185 |
def unmixGradProjMatrixNNLS(image, A, tolerance=1e-4, maxiter=100):
"""
Performs NNLS via Gradient Projection of the primal problem.
Terminates when duality gap falls below tolerance
"""
if image.ndim == 2:
(n1, n3) = image.shape
n2 = 1;
elif image.ndim == 3:
(n1, n2, n3)... | ac6bb769e9343f49095166a751fa1c40e2e6ed06 | 3,634,186 |
def seismic():
"""Benchmark Seismic object."""
# coords = [{"x": np.arange(10)}, {"y": np.arange(10)}, {"z": np.arange(100)}]
coords = [("x", np.arange(10)), ("y", np.arange(10)), ("z", np.arange(100))]
cube = segyio.tools.cube("../data/test.segy")
# seis = from_segy("tests/data/test.segy")
retu... | 556aa9407162951756754be9c24c80986e475cb5 | 3,634,187 |
import math
def sterrmean(s, n, N=None):
"""sterrmean(s, n [, N]) -> standard error of the mean.
Return the standard error of the mean, optionally with a correction for
finite population. Arguments given are:
s: the standard deviation of the sample
n: the size of the sample
N (optional): the... | 30ad7b9b184b1a86b8d9bf03ee515b34aab3b368 | 3,634,188 |
def change_device_status(dispatcher, device_name, status):
"""Set the status of a device in Nautobot."""
if menu_item_check(device_name):
prompt_for_device(
"nautobot change-device-status",
"Change Nautobot Device Status",
dispatcher,
offset=menu_offset_va... | 6f8e7d7637fed71b501aa89791c638d80caa1eab | 3,634,189 |
def text_to_vector(sentences):
"""
#使用one-hot方法将文本转为向量, 例如:
Sentence1 不 知道 你 在 说 什么 。
Sentence2 我 就 知道 你 不 知道 。
词表: 不 就 你 什么 我 说 知道 在 。
S1 [1 0 1 1 0 1 1 1 1]
S2 [1 1 1 0 1 0 2 0 1]
即得到分词后的句子之后,先得到词表
每个词对应一个位置,如“不”对应第一个位置,等等
如果s1出现了不一次,就把s1的第一个位置设为1,如果没有出现就是0,
如果出现了两次“不”,那么s1的第一个位置就是2,以此类推
"""
# 先将所... | a065b6f99c0083473b76d20c13a3722326d29587 | 3,634,190 |
from typing import List
from typing import Tuple
import os
import random
import math
def _list_valid_filenames_in_directory(
base_directory:str,
search_class:str,
white_list_formats:List[str],
split:float,
follow_links:bool,
shuffle_index_directory:str
) -> Tuple[str, List[str]]:
"""F... | 96cfc428815cc5d0625c1bc66f92784dcf5c5b11 | 3,634,191 |
import os
def benchmark_memory(nb_registers, element_width, nb_elements, nb_operations, write_op=False):
"""
This method generate the P4 program to benchmark memory consumption
:param nb_registers: the number of registers included in the program
:type nb_registers: int
:param element_width: the s... | e814328510f890cd5f9bb03421f047da0560fd66 | 3,634,192 |
from snntoolbox.utils.utils import binary_sigmoid, binary_tanh, ClampedReLU
def get_custom_activations_dict():
"""
Import all implemented custom activation functions so they can be used when
loading a Keras model.
"""
# Todo: We should be able to load a different activation for each layer.
#... | 5ef380613087020815fcf9642caa6809ef8eaeff | 3,634,193 |
import tqdm
def block_solve_agd(
r_j,
A_j,
a_1_j,
a_2_j,
m,
b_j_init,
t_init=None,
ls_beta=None,
max_iters=None,
rel_tol=1e-6,
verbose=False,
zero_thresh=1e-6,
zero_fill=1e-3,
):
"""Solve the optimization problem for a single block with accelerated
gradient ... | 168be883091592c86f7c2cd38f7d1980abd3f4c5 | 3,634,194 |
import os
def get_jars_location():
"""
Return the location of the JAR files for installed library.
"""
root_dir = os.path.dirname(flexneuart.__file__)
return os.path.join(root_dir, 'resources/jars/') | d4d397c6031079c85954a5a36d699c67e5b2882d | 3,634,195 |
def bin_array_max(arr, bin_size, pad_value=0):
"""
Given a NumPy array, returns a binned version of the array along the last
dimension, where each bin contains the maximum value of its constituent
elements. If the array is not a length that is a multiple of the bin size,
then the given pad will be u... | db16540a8d5e4ac91948dab6a0c94b86398635b5 | 3,634,196 |
def harmony(img, center, angle=None):
"""Harmonize the pattern by exploiting symmetry
If the shape of the pattern is not anymore odd after the rotation has been
performed the pattern is padded with zeros such that its shape is odd.
:param img: pattern
:param center: center coordinates in patte... | e2a2ddab67d28d34210aaf8926595670a0e046d8 | 3,634,197 |
import os
import errno
def getClimateDataForStation(config, outputDir, outFilename, stationID, overwrite=True):
"""Fetch climate timeseries data for a GHCN daily station
@param config A Python ConfigParser (not currently used)
@param outputDir String representing the absolute/relative path of... | 31b8006bce6eb0abaf5f4a4af285130dadd1b291 | 3,634,198 |
def is_following(request, author) -> bool:
"""Checks if this author is in the user's subscriptions"""
if Follow.objects.filter(user=request.user, author=author):
return True
return False | 32a81b0d6482d5fd99d6d1b55e518b59238d87bd | 3,634,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.