content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def concatenate_weather_files(dir_path):
"""Concatenate all .nc files found in the directory set by path."""
# import all the files as datasets
fnames = get_weather_files(dir_path)
ds_list = []
for f in fnames:
with xr.open_dataset(f, engine='netcdf4') as ds:
ds_list.append(ds)
... | 5,342,300 |
def homepage(module=None, *match, **attr):
"""
Shortcut for module homepage menu items using the MM layout,
retrieves the module's nice name.
@param module: the module's prefix (controller)
@param match: additional prefixes
@param attr: attributes for the navigation item
... | 5,342,301 |
def task_created_upon_camera_create(camera):
"""task_created_upon_camera_create
Args:
camera (Camera): a Camera instance
"""
assert CameraTask.objects.exists() | 5,342,302 |
def handle_fallthrough(event, path, query):
"""
Handles the fallthrough cases where no redirects were matched
"""
# If no fallthough response provider, 302 the whole website to the HOST that
# was input
if variables.FALLTHROUGH == None:
return redirect('//' + variables.HOST + path + quer... | 5,342,303 |
def vowel_space_area(F1a, F1i, F1u, F2a, F2i, F2u):
"""
Return vowel space area
Args:
F1a: (float) the 1. formant frequency of the vowel /a [Hz]
F1i: (float) the 1. formant frequency of the vowel /i [Hz]
F1u: (float) the 1. formant frequency of the vowel /u [Hz]
F2a: (float)... | 5,342,304 |
def get_hosted_zone(domain):
"""Return a domain's hosted zone."""
return api.get(f"/api/domain/{domain['_id']}/records/") | 5,342,305 |
def call_subprocess(command, action, module):
"""Call a command, redirect output given current logging level."""
output = []
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, b""):
output.append(line)
... | 5,342,306 |
def align_spikes(spike_data, spt_dict, sp_win, type="max", resample=1,
contact=0, remove=True):
"""Aligns spike waves and returns corrected spike times
Parameters
----------
spike_data : dict
spt_dict : dict
sp_win : list of int
type : {'max', 'min'}, optional
resamp... | 5,342,307 |
def rgb2hsi(rgb: np.ndarray,
*,
axis: int=None) -> np.ndarray:
"""
Convert RGB to Hue Saturation Intensity
:param rgb:
:param axis:
:return:
"""
if axis is None:
axis = get_matching_axis(rgb.shape, 3)
big_m, little_m, chroma = _compute_chroma(rgb, ... | 5,342,308 |
def p_cmdexpr_rtorder(p):
"""cmdexpr : RTORDER
| RTORDER arglist
| RTORDER MACRO""" | 5,342,309 |
def set(d=False, t=False):
"""
Enable logging types (debug, trace)
"""
assert(type(d) is bool)
assert(type(t) is bool)
global _debug_on, _trace_on
_debug_on = d
_trace_on = t | 5,342,310 |
def get_movie_brief_actor(actor, soup):
"""
Getting brief data from individual movie webpage (for actor dictionary)
"""
headers=['actor','title','year','rating','vote','genre_list','budget','opening','gross_usa',\
'gross_cw','runtime','director','writer','star','distributor']
... | 5,342,311 |
def mul(a: TensorableType, b: TensorableType) -> Tensor:
"""Returns the product of input tensor_objects with their local gradients"""
a = enforceTensor(a)
b = enforceTensor(b)
output = Tensor(a.data * b.data, requires_grad=(a.requires_grad or b.requires_grad))
output.save_for_backward([a, b])
... | 5,342,312 |
def _validate_asset_icons(icon_manager: 'IconManager') -> None:
"""
Loops through icons in the user's data directory and deletes those that are malformed.
"""
icons_directory = icon_manager.icons_dir
for icon_entry in icons_directory.iterdir():
if icon_entry.is_file():
icon_file_... | 5,342,313 |
def safe_extract_zip(
in_path: Union[str, Path],
out_path: Union[str, Path],
*,
only_prefix: Iterable[str] = (),
ignore_prefix: Iterable[str] = ('..', '/'),
callback: Callable[[str, Any], None] = null_callback,
callback_description: str = 'Extracting zip files'
):
"""Safely extract a zip... | 5,342,314 |
def split_multi(vds: 'VariantDataset', *, filter_changed_loci: bool = False) -> 'VariantDataset':
"""Split the multiallelic variants in a :class:`.VariantDataset`.
Parameters
----------
vds : :class:`.VariantDataset`
Dataset in VariantDataset representation.
filter_changed_loci : :obj:`bool... | 5,342,315 |
def zeros(shape, dtype=K.floatx()):
"""Return all-zeros tensor of given shape and type."""
# As of Keras version 1.1.0, Keras zeros() requires integer values
# in shape (e.g. calling np.zeros() with the Theano backend) and
# thus can't be called with tensor values. This version avoids the
# issue by... | 5,342,316 |
def nrc_emo_lex(headlines, bodies):
"""
Counts Number of words in a text associated with 8 different emotions.
Uses EmoLex lexicon: http://saifmohammad.com/WebPages/lexicons.html#EmoLex
"""
lexicon_path = "%s/../data/lexicons/emoLex/" % (path.dirname(path.dirname(path.abspath(__file__))))
word... | 5,342,317 |
def accretion_cylinder(mbh, mdot, r):
"""rschw, omega, facc, teff, zscale = accretion_cylinder(mbh, mdot, r)"""
GM = cgs_graw * mbh * sol_mass
rschw = 2 * GM / cgs_c**2
omega = sqrt( GM / (r * rschw)**3 )
facc = 3 * GM * (mdot * mdot_edd(mbh)) / (8 * pi * (r * rschw)**3) \
* (1 - ... | 5,342,318 |
def plot_gt_freqs(fp):
"""
Draws a scatterplot of the empirical frequencies of the counted species
versus their Simple Good Turing smoothed values, in rank order. Depends on
pylab and matplotlib.
"""
MLE = MLENGram(1, filter_punctuation=False, filter_stopwords=False)
MLE.train(fp, encoding="... | 5,342,319 |
def test_rectify_latest_version():
"""Test the function rectify_latest_version."""
lst = [
{
"package": "io.vertx:vertx-web",
"actual_latest_version": "3.7.9"
}
]
resp = rectify_latest_version(lst, "maven")
assert resp == "Success" | 5,342,320 |
def bidirectional(*args, **kwargs): # real signature unknown
"""
Returns the bidirectional class assigned to the character chr as string.
If no such value is defined, an empty string is returned.
"""
pass | 5,342,321 |
def cost_function_wrapper(theta, cost_function_parameters):
"""Wrapper for the Cost Function"""
cost_function_parameters['theta'] = theta
return cost_function(cost_function_parameters) | 5,342,322 |
def make_img_tile(imgs, path, epoch, aspect_ratio=1.0,
tile_shape=None, border=1, border_color=0):
"""
"""
if imgs.ndim != 3 and imgs.ndim != 4:
raise ValueError('imgs has wrong number of dimensions.')
n_imgs = imgs.shape[0]
tile_shape = None
# Grid shape
img_shape = np.array(imgs.shape[1:3])
... | 5,342,323 |
def test_flags_init_app_production():
"""Ensure that extension can be initialized."""
app = Flask(__name__)
app.env = 'production'
app.config['LD_SDK_KEY'] = 'https://no.flag/avail'
with app.app_context():
flags = Flags()
flags.init_app(app)
assert app.extensions['featureflags'] | 5,342,324 |
def dummy_plugin_distribution(dummy_plugin_distribution_name, save_sys_path):
"""Add a dummy plugin distribution to the current working_set."""
dist = pkg_resources.Distribution(
project_name=dummy_plugin_distribution_name,
metadata=DummyEntryPointMetadata(
f"""
[lektor.p... | 5,342,325 |
def powerup_drift(ship: monospace.Ship):
"""Make all the bullets shifty."""
for blaster in ship.blasters:
blaster.bullet_type = monospace.DriftingShipBullet | 5,342,326 |
def write_f_songplay_df(spark, f_songplay_df, output_data_path):
"""
Write a song play fact dataframe to an S3 path.
Parameters:
spark (SparkSession): The spark session.
f_songplay_df (DataFrame): The song play fact dataframe.
output_data_path (str): The base S3 bucket URL.
Returns:
... | 5,342,327 |
def set_array_significant_figures(sig_figs):
"""Summary.
Parameters
----------
sig_figs
optional int, number of significant figures to be shown when printing
"""
_assert_array_significant_figures_formatting(sig_figs)
global array_significant_figures_stack
array_significant_figu... | 5,342,328 |
def parse_temperature_item(item):
"""Parse item for time and temperature
:param item: Definition, eg. '17.0 > 07:00'
:returns: dict with temperature and minutes"""
temp_time_tupel = item.split(">")
temperature = float(temp_time_tupel[0].strip())
minutes_from_midnight = calculate_minutes_from_mi... | 5,342,329 |
def add_file_to_dataset_view(user_data, cache):
"""Add the uploaded file to cloned repository."""
ctx = DatasetAddRequest().load(request.json)
user = cache.ensure_user(user_data)
project = cache.get_project(user, ctx['project_id'])
if not ctx['commit_message']:
ctx['commit_message'] = 'serv... | 5,342,330 |
def get_available_adapters() -> dict:
"""Get information on all available adapters
Returns:
(dict) Where keys are adapter names and values are descriptions
"""
return _output_plugin_info(ExtensionManager(namespace='materialsio.adapter')) | 5,342,331 |
def _must_find_n(session, obj_outer, cls_inner, name_inner):
"""Searches the database for a "namespaced" object, such as a nic on a node.
Raises NotFoundError if there is none. Otherwise returns the object.
Arguments:
session - a SQLAlchemy session to use.
obj_outer - the "owner" object
cls_... | 5,342,332 |
def list_providers():
"""
Get list of names of all supported cloud providers
:rtype: list
"""
return [cls.provider_name() for cls in BaseHandler.__subclasses__()] | 5,342,333 |
def GetRPCProxy(address=None, port=None, url=GOOFY_RPC_URL):
"""Gets an instance (for client side) to access the goofy server.
Args:
address: Address of the server to be connected.
port: Port of the server to be connected.
url: Target URL for the RPC server. Default to Goofy RPC.
"""
address = addr... | 5,342,334 |
def getparser():
"""
Use argparse to add arguments from the command line
Parameters
----------
createlapserates : int
Switch for processing lapse rates (default = 0 (no))
createtempstd : int
Switch for processing hourly temp data into monthly standard deviation (default = 0 ... | 5,342,335 |
def dict_hash_table_100_buckets():
"""Test for hash table with 100 buckets, dictionary."""
ht = HashTable(100, naive_hash)
for word in dictionary_words:
ht.set(word, word)
return ht | 5,342,336 |
def write_fv_schemes(case):
"""Sets fv_schemes"""
fv_schemes = {
'ddtSchemes' : {'default' : 'Euler'},
'gradSchemes' : {'default' : 'Gauss linear'},
'divSchemes' : {'default' : 'none', 'div(tauMC)' : 'Gauss linear'},
'laplacianSchemes' : {'default' : 'Gauss linear corrected'},
'interpolationSchemes' : {'d... | 5,342,337 |
def white(N):
"""
White noise.
:param N: Amount of samples.
White noise has a constant power density. It's narrowband spectrum is therefore flat.
The power in white noise will increase by a factor of two for each octave band,
and therefore increases with 3 dB per octave.
"""
r... | 5,342,338 |
def annotate_search_plugin_restriction(results, file_path, channel):
"""
Annotate validation results to restrict uploads of OpenSearch plugins
https://github.com/mozilla/addons-server/issues/12462
Once this has settled for a while we may want to merge this with
`annotate_legacy_addon_restrictions`... | 5,342,339 |
def plot_XWSigma(qa_dict,outfile):
"""
Plot XWSigma
Args:
qa_dict: qa dictionary from countpix qa
outfile : file of the plot
"""
camera=qa_dict["CAMERA"]
expid=qa_dict["EXPID"]
pa=qa_dict["PANAME"]
xsigma=qa_dict["METRICS"]["XWSIGMA_FIB"][0]
wsigma=qa_dict... | 5,342,340 |
def lgamma(x) -> float:
"""
Return the natural logarithm of the gamma function of ``x``.
"""
... | 5,342,341 |
def read_HiCPro(bedfile, matfile):
"""
Fast loading of the .matrix and .bed files derived from HiC-Pro
Parameters
----------
bedfile : str,
path to the .bed file which contains fragments info
matfile : str,
path to the .matrix file which contains contact counts
Ret... | 5,342,342 |
def get_objective_by_task(target, task):
"""Returns an objective and a set of metrics for a specific task."""
if task == 'classification':
if target.nunique() == 2:
objective = 'binary'
else:
objective = 'multi'
elif task == 'regression':
objective = 'regressi... | 5,342,343 |
def websocket_recv_nb():
"""Receive data from websocket (non-blocking).
:return: The received data
:rtype: str
""" | 5,342,344 |
def pileupGenes(GenePositions,filename,pad=500000,doBalance=False,
TPM=0,CTCFWapldKO=False,TPMlargerthan=True,
minlength=0,maxlength=5000000,OE=None, useTTS=False):
"""
This function piles up Hi-C contact maps around genes, centered on TSSs or TTSs.
Inputs
------
Gene... | 5,342,345 |
def model_cnn_2layer(in_ch, in_dim, width, linear_size=128):
"""
CNN, small 2-layer (default kernel size is 4 by 4)
Parameter:
in_ch: input image channel, 1 for MNIST and 3 for CIFAR
in_dim: input dimension, 28 for MNIST and 32 for CIFAR
width: width multiplier
"""
model = nn... | 5,342,346 |
def snack_raw_formants_tcl(wav_fn, frame_shift, window_size, pre_emphasis, lpc_order, tcl_shell_cmd):
"""Implement snack_formants() by calling Snack through Tcl shell
tcl_shell_cmd is the name of the command to invoke the Tcl shell.
Note this method can only be used if Tcl is installed.
The vectors r... | 5,342,347 |
def _run_eval(annot_dir, output_dir, eval_tracking=False, eval_pose=True):
"""
Runs the evaluation, and returns the "total mAP" and "total MOTA"
"""
from datasets.posetrack.poseval.py import evaluate_simple
(apAll, _, _), mota = evaluate_simple.evaluate(
annot_dir, output_dir, eval_pose, eva... | 5,342,348 |
def reserve_api():
"""Helper function for making API requests to the /reserve API endpoints
:returns: a function that can be called to make a request to /reserve
"""
def execute_reserve_api_request(method, endpoint, **kwargs):
master_api_client = master_api()
return master_api_client(me... | 5,342,349 |
def extract_user_id(source_open_url):
"""
extract the user id from given user's id
:param source_open_url: "sslocal://profile?refer=video&uid=6115075278" example
:return:
"""
if source_open_url[10:17] != 'profile':
return None
try:
res = re.search("\d+$", source_open_url).gr... | 5,342,350 |
def prolog_rule(line):
"""Specify prolog equivalent"""
def specify(rule):
"""Apply restrictions to rule"""
rule.prolog.insert(0, line)
return rule
return specify | 5,342,351 |
def simple_interest(p, r, t):
"""
calculate SIMPLE INTEREST ----
:param p:
:param r:
:param t:
:return:
"""
SI = (p * r * t) / 100
print("simple interest is: ", SI) | 5,342,352 |
def load_GloVe_model(path):
"""
It is a function to load GloVe model
:param path: model path
:return: model array
"""
print("Load GloVe Model.")
with open(path, 'r') as f:
content = f.readlines()
model = {}
for line in content:
splitLine = line.split()
word = ... | 5,342,353 |
def quadratic_program() -> MPQP_Program:
"""a simple mplp to test the dimensional correctness of its functions"""
A = numpy.array(
[[1, 1, 0, 0], [0, 0, 1, 1], [-1, 0, -1, 0], [0, -1, 0, -1], [-1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0],
[0, 0, 0, -1]])
b = numpy.array([350, 600, 0, 0, 0, 0,... | 5,342,354 |
def load_img(str_img):
"""
"""
str_b64 = None
if os.path.exists(str_img) and is_path_img(str_img):
with open(str_img, 'rb') as f:
content = f.read()
content_b64 = base64.b64encode(content)
str_b64 = content_b64.decode('utf-8')
elif str_img.startswith('ht... | 5,342,355 |
def snr(flux, axis=0):
""" Calculates the S/N ratio of a spectra.
Translated from the IDL routine der_snr.pro """
signal = np.nanmedian(flux, axis=axis)
noise = 1.482602 / np.sqrt(6.) * np.nanmedian(np.abs(2.*flux - \
np.roll(flux, 2, axis=axis) - np.roll(flux, -2, axis=axis)), \
... | 5,342,356 |
def subtract_images(img_input, img_output, img_height, img_width):
"""Subtract input and output image and compute difference image and ela image"""
input_data = img_input.T
output_data = img_output.T
if len(input_data) != len(output_data):
raise Exception("Input and Output image have different s... | 5,342,357 |
def k4a_playback_get_track_name(playback_handle, track_index, track_name, track_name_size):
"""
K4ARECORD_EXPORT k4a_buffer_result_t k4a_playback_get_track_name(k4a_playback_t playback_handle,
size_t track_index,
char *track_name,
size_t *track_name_size);
"""
_k4a_... | 5,342,358 |
def stripLeadingCharacters(charQueue, numChars):
"""
Takes in the queue representation of the text and strips the leading numChars characters.
Args:
charQueue: The text in a Queue object.
numChars: The number of characters to remove.
Returns:
None
"""
for i in xrange(nu... | 5,342,359 |
def recommend_lowercase_d(data: pd.Series, **kwargs) -> int:
"""Returns the recommended value of differencing order 'd' to use
Parameters
----------
data : pd.Series
The data for which the differencing order needs to be calculated
*kwargs: Keyword arguments that can be passed to the differ... | 5,342,360 |
def get_player_current_games_to_move(username: str) -> Dict:
"""Public method that returns an array of Daily Chess games
where it is the player's turn to act
Parameters:
username -- username of the player
"""
r = _internal.do_get_request(f"/player/{username}/games/to-move")
return json... | 5,342,361 |
def get_rb_data_attribute(xmldict, attr):
"""Get Attribute `attr` from dict `xmldict`
Parameters
----------
xmldict : dict
Blob Description Dictionary
attr : str
Attribute key
Returns
-------
sattr : int
Attribute Values
"""
try:
sattr = int(xml... | 5,342,362 |
def dopythonphot(image, xc, yc, aparcsec=0.4, system='AB', ext=None,
psfimage=None, psfradpix=3, recenter=False, imfilename=None,
ntestpositions=100, snthresh=0.0, zeropoint=None,
filtername=None, exptime=None, pixscale=None,
skyannarcsec=[6.0, 12.0], ... | 5,342,363 |
def zip_dir(source_dir, archive_file, fnmatch_list=None):
"""Creates an archive of the given directory and stores it in the given
archive_file which may be a filename as well. By default, this function
will look for a .cfignore file and exclude any matching entries from the
archive.
"""
if fnmat... | 5,342,364 |
def tls_params(mqtt_config):
"""Return the TLS configuration parameters from a :class:`.MQTTConfig`
object.
Args:
mqtt_config (:class:`.MQTTConfig`): The MQTT connection settings.
Returns:
dict: A dict {'ca_certs': ca_certs, 'certfile': certfile,
'keyfile': keyfile} with the TL... | 5,342,365 |
def is_admin():
"""Check if current user is an admin."""
try:
return flask.g.admin
except AttributeError:
return False | 5,342,366 |
def statistic():
""" RESTful CRUD Controller """
return crud_controller() | 5,342,367 |
def parse_args():
""" Parses command line arguments.
:return: argparse parser with parsed command line args
"""
parser = argparse.ArgumentParser(description='Godot AI Bridge (GAB) - DEMO Environment Action Client')
parser.add_argument('--id', type=int, required=False, default=DEFAULT_AGENT,
... | 5,342,368 |
async def test_async_edit_development_config(
aresponses, readarr_client: ReadarrClient
) -> None:
"""Test editing development config."""
aresponses.add(
"127.0.0.1:8787",
f"/api/{READARR_API}/config/development",
"PUT",
aresponses.Response(
status=202,
... | 5,342,369 |
def test_all():
"""function test_all
Args:
Returns:
"""
test1() | 5,342,370 |
def segment_range_to_fragment_range(segment_start, segment_end, segment_size,
fragment_size):
"""
Takes a byterange spanning some segments and converts that into a
byterange spanning the corresponding fragments within their fragment
archives.
Handles prefix, suff... | 5,342,371 |
def update_dict(d, u):
""" Recursively update dict d with values from dict u.
Args:
d: Dict to be updated
u: Dict with values to use for update
Returns: Updated dict
"""
for k, v in u.items():
if isinstance(v, collections.Mapping):
default = v.copy()
... | 5,342,372 |
def test_third_party_overwrite_build_file():
""" this test emulates the work of a developer contributing recipes to ConanCenter, and
replacing the original build script with your one one.
The export_sources is actually copying CMakeLists.txt into the "src" folder, but the
'download' will overwrite it, ... | 5,342,373 |
def get_dataset(args, tokenizer, evaluate=False):
"""Convert the text file into the GPT-2 TextDataset format.
Args:
tokenizer: The GPT-2 tokenizer object.
evaluate: Whether to evalute on the dataset.
"""
file_path = args.eval_data_file if evaluate else args.train_data_file
if args.l... | 5,342,374 |
def test_function_decorators():
"""Function Decorators."""
# Function decorators are simply wrappers to existing functions. Putting the ideas mentioned
# above together, we can build a decorator. In this example let's consider a function that
# wraps the string output of another function by p tags.
... | 5,342,375 |
def log_to_stderr(log_level='INFO', force=False):
"""
Shortcut allowing to display logs from workers.
:param log_level: Set the logging level of this logger.
:param force: Add handler even there are other handlers already.
"""
if not log.handlers or force:
mp.log_to_stderr()
log.set... | 5,342,376 |
def make_loci_field( loci ):
""" make string representation of contig loci """
codes = [L.code for L in loci]
return c_delim2.join( codes ) | 5,342,377 |
def compute_wilderness_impact1(ground_truth_all, prediction_all, video_list, known_classes, tiou_thresholds=np.linspace(0.5, 0.95, 10)):
""" Compute wilderness impact for each video (WI=Po/Pc < 1)
"""
wi = np.zeros((len(tiou_thresholds), len(known_classes)))
# # Initialize true positive and false posit... | 5,342,378 |
def write_data_header(ping, status):
""" write output log file header
:param status: p1125 information
:return: success <True/False>
"""
try:
with open(os.path.join(CSV_FILE_PATH, filename), "w+") as f:
f.write("# This file is auto-generated by p1125_example_mahrs_csv.py\n".form... | 5,342,379 |
def register_config_validator(type, validator_class):
"""
Register a config value validator.
Args:
type: The value type.
validator_class: The validator class type.
"""
_config_validators_registry[type] = validator_class | 5,342,380 |
def clear_flags(header, flags=None):
"""Utility function for management of flag related metadata."""
bitmask = BitmaskWrapper(header['flags'])
if flags is not None:
_verify_flags(flags)
bitmask.clear([flag-1 for flag in flags])
else:
bitmask.clear() | 5,342,381 |
def require_client(func):
"""
Decorator for class methods that require a client either through keyword
argument, or through the object's client attribute.
Returns:
A wrapped version of the function. The object client attrobute will
be passed in as the client keyword if None is provided.... | 5,342,382 |
def untar(inpath: PathOrStr, outdir: PathOrStr) -> None:
"""
Unpack tarfile.
Parameters
----------
inpath
Path to tarfile
outdir
Desired output directory
"""
logging.info(f"Untarring {inpath} to {outdir}")
with tarfile.open(inpath) as archive:
members = arch... | 5,342,383 |
async def on_shard_ready(shard_id : int) -> None:
"""When a shard starts print out that the shard has started.
Args:
shard_id (int): The ID of the shard that has started. (Starts from 0).
"""
print(f"{Style.BRIGHT}{Fore.CYAN}[SHARD-STARTED]{Fore.WHITE} Shard {Fore.YELLOW}{shard_id}{Fore.WHITE}... | 5,342,384 |
def test_set_params_regressor():
"""Test set_params method of Regressor class."""
regressor = Regressor()
regressor.set_params(strategy="LightGBM")
assert regressor._Regressor__strategy == "LightGBM"
regressor.set_params(strategy="RandomForest")
assert regressor._Regressor__strategy == "RandomFo... | 5,342,385 |
def plot_dislikes_vs_videos():
"""
Plots a graph by looking at the data stored in the files, and then saves the graph in Assets/Graphs as png.
None -> None
"""
video_dislikes = fio.read.get_dislikes()
for i in range(len(video_dislikes)):
if video_dislikes[i ] is None :
video_dislikes[i] = 0.0
for i in ran... | 5,342,386 |
def db_session():
"""FastAPI dependency genarator for create database session."""
db: Session = _mk_orm_session()
try:
yield db
finally:
db.close() | 5,342,387 |
def extract_subwindows_image(image, scoremap, mask, input_window_size, output_window_size, mode, mean_radius,
flatten=True, dataset_augmentation=False, random_state=42, sw_extr_stride=None,
sw_extr_ratio=None, sw_extr_score_thres=None, sw_extr_npi=None):
"""... | 5,342,388 |
def format_template(string, tokens=None, encode=None):
"""Create an encoding from given string template."""
if tokens is None:
tokens = {}
format_values = {"config": config,
"tokens": tokens}
result = string.format(**format_values)
if encode == "base64":
result ... | 5,342,389 |
def make_mosaic(band='fuv', ra_ctr=None, dec_ctr=None, size_deg=None, index=None, name=None, pgcname=None, model_bg=True, weight_ims=True, convert_mjysr=True, desired_pix_scale=GALEX_PIX_AS, imtype='intbgsub', wttype='rrhr', window=False):
"""
Create noise of a galaxy in a single GALEX band.
Parameters
... | 5,342,390 |
def exists_case_sensitive(path: str) -> bool:
"""Returns if the given path exists and also matches the case on Windows.
When finding files that can be imported, it is important for the cases to match because while
file os.path.exists("module.py") and os.path.exists("MODULE.py") both return True on Windows,... | 5,342,391 |
def make_datastore_api(client):
"""Create an instance of the GAPIC Datastore API.
:type client: :class:`~google.cloud.datastore.client.Client`
:param client: The client that holds configuration details.
:rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`
:returns: A datastore API insta... | 5,342,392 |
def _mul_certain(left, right):
"""Multiplies two values, where one is certain and the other is uncertain,
and returns the result."""
if _is_number(left):
return Uncertain(
value=right.value * left,
delta=right.delta,
)
return Uncertain(
value=lef... | 5,342,393 |
def felica_RequestSystemCode(): # -> (int, List[int]):
"""
Sends FeliCa Request System Code command
:returns: (status, systemCodeList)
status 1: Success, < 0: error
systemCodeList System Code list (Array length should longer than 16)
"""
cmd = bytearra... | 5,342,394 |
def test_dev_bump_pipeline_version(datafiles, tmp_path):
"""Test that making a release works with a dev name and a leading v"""
# Get a workflow and configs
test_pipeline_dir = os.path.join(tmp_path, "nf-core-testpipeline")
create_obj = nf_core.create.PipelineCreate(
"testpipeline", "This is a t... | 5,342,395 |
def get_regularizer(
regularizer_type: str, l_reg_factor_weight: float
) -> Optional[Callable[[tf.Tensor], Optional[tf.Tensor]]]:
"""Gets a regularizer of a given type and scale.
Args:
regularizer_type: One of types.RegularizationType
l_reg_factor_weight: Scale for regularization.
Returns:
A fun... | 5,342,396 |
def app_eliminar():
"""
Eliminar datos a través de formulario
"""
helper.menu()
# Seccion eliminar
output.span(output.put_markdown("## Sección Eliminar"))
output.put_markdown(f"Eliminar una fila")
form_delete = input.input_group("Eliminar Datos", [
input.input(label="ID", type=in... | 5,342,397 |
def metadata():
"""Returns shared metadata instance with naming convention."""
naming_convention = {
'ix': 'ix_%(column_0_label)s',
'uq': 'uq_%(table_name)s_%(column_0_name)s',
'ck': 'ck_%(table_name)s_%(constraint_name)s',
'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_ta... | 5,342,398 |
def date_rss(dte=None):
"""Dtate au format RSS """
ctime = time if dte is None else time.mktime(dte.timetuple())
return ctime.strftime('%a, %d %b %Y %H:%M:%S %z') | 5,342,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.