content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def PIsA (inTL):
""" Tells if the input really is a Python Obit TableList
returns true or false (1,0)
inTL = Python TableList to test
"""
################################################################
# Checks
if not isinstance(inTL, TableList):
return False
#
return Obit... | e119d79895f5f36405d26a5125308249845df25a | 56,200 |
def _GetStepLogViewUrl(build, full_step_name, log_name, partial_match=False):
"""Gets view url of the requested log.
Args:
build (buildbucket_proto.build_pb2.Build proto): Information about a build.
full_step_name (str): Full name of the step.
log_name (str): Type of the log.
partial_match (bool): ... | 7e240e0414c8d83620d701d348d3386cb5054226 | 56,201 |
def downgrade(emap, factor, op=np.mean):
"""Returns enmap "emap" downgraded by the given integer factor
(may be a list for each direction, or just a number) by averaging
inside pixels."""
fact = np.full(2, 1, dtype=int)
fact[:] = factor
tshape = emap.shape[-2:]//fact*fact
res = op(np.reshape(emap[...,:tshape[0],... | 6f4cb34441b371436ebe94b9ce9afb71c19614bf | 56,202 |
import os
import shutil
def delete(path, regex=None, recurse=False, test=False):
"""Deletes the file or directory at `path`. If `path` is a directory and
`regex` is provided, matching files will be deleted; `recurse` controls
whether subdirectories are recursed. A list of deleted items is returned.
If... | f63540d60db2b2e8df66b6189605fe1d479d2346 | 56,203 |
def test_config_file_fails_missing_database(monkeypatch, presence, config):
"""Check if test fails with missing database configuration."""
def mock_file_config(self):
return {'algorithm': 'asha'}
monkeypatch.setattr(presence.builder, "fetch_file_config", mock_file_config)
status, msg = presenc... | dd96df036a9e07d5ee207310e21c490e027f7e53 | 56,204 |
import itertools
def pairwise(iterable):
"""
Iterate pairwise through an iterable.
pairwise([1,2,3,4]) -> (1,2),(2,3),(3,4)
"""
val, nextVal = itertools.tee(iterable)
next(nextVal, None)
return zip(val, nextVal) | 495fedbaf2046d66bd791dc78dea8525761e01b1 | 56,205 |
import numpy
def lamb2(v,r):
"""Approximate the Lambert W function.
Approximate the Lambert W function from its upper and lower bounds.
The result replicates the triple point of the (idealized) system
exactly, because lamb2(0,r) = 1.
:arg float v: Modified argument of the function. Must ... | 358907f75de539d3da88935b0d470f72310c3b57 | 56,206 |
def interleave(l1, l2):
"""
Return an interleaving of lists l1 and l2.
If l2 is not a list, broadcast its value.
"""
if isinstance(l2, list):
l2_list = l2
else:
l2_list = [l2] * len(l1)
return list(it.chain.from_iterable(it.zip_longest(l1, l2_list))) | 5101be177cbfcbf8f769ceaacd7ad022bd8625c5 | 56,207 |
from typing import Tuple
from typing import Optional
def collide(left: int, right: int) -> Tuple[Optional[int]]:
"""Return the result of a collision
Returns
tuple of (negative, positive) remaining after collision
"""
small, big = sorted((left, right))
if abs(small) > big:
return (... | 4d75def5df0315f8b8adabb13fef49adf48fbf2d | 56,208 |
import re
import os
def plot_calrep_results_difference_comparison(calrep_model, results_model, **options):
"""Plots a calrep file and a results file on the same axis. Input is a calrep table from the sparameter
function calrep and a
results file, with options. """
defaults = {"display_legend": False,
... | 4b61b8af5bb4ac888f955fb5d91d888ea6e15d5b | 56,209 |
def choose(aliases, exprs, mapper, mingain):
"""
Analyze the detected aliases and, after applying a cost model to rule out
the aliases with a bad memory/flops trade-off, inject them into the original
expressions.
"""
aliases = AliasList(aliases)
# `score < m` => discarded
# `score > M` ... | 8028318ec907c69504e721eaffc023a4a857f3bf | 56,210 |
from pathlib import Path
from typing import Any
import os
import subprocess
def exec_file_on_target(
target: TestTarget,
filepath: Path,
timeout: int,
args: list[str] = [],
extra_files: list[Path] = [],
**kwargs: Any,
):
"""Executes a file on the test target.
The file is uploaded to t... | 35012825ce5cfcffa1d9fd4bcb4e65ad09c2a900 | 56,211 |
import random
def name() -> str:
"""(TBI) Generates name, unique every time."""
while True:
new_name = "S"
while(new_name[-1] != "E"):
new_name += random.choice(name_next_chars[new_name[-1 - memory:]])
if((new_name not in names) and (len(new_name) > 3)):
break
names.append(new_name)
return new_name[1:... | 2ae4a65732f1c8d40899811d22ce5ad41e83256c | 56,212 |
def check_if_author_relevant(author_id, query):
"""
Check whether the author is relevant to the search query based on their tags.
Parameters:
author_id (string or int)
query (string): The search query used to retrieve this particular author
Returns:
boolean based on the presence of... | 23603688813f39a4d422e9c8ac049e9372042f60 | 56,213 |
def apply_perspective_transform(img):
"""
This function takes in a binary threshold image and retuned a warped bird eyes view of the image
"""
img_size = (img.shape[1], img.shape[0])
# # source points
src = np.float32([[699,462],[1084,img_size[1]],[227,img_size[1]],[585,462]])
# 4 destinat... | 9bca1a2d08b8a875d8f67e0d37700b555c243d74 | 56,214 |
def create_mating_pool(population, fitnesses, norm=True):
"""
Generate a mating pool
This will create a new population proportional to the fitnesses
of the original population. The pool will the be used as the basis
for generating the next generation.
Parameters
----------
population :... | 1ea329c334ffa54527aacf8fba7a33b55c927eb1 | 56,215 |
def active_filesets(filesets):
"""Active filesets are displayed in the listing"""
return filesets.filter(Fileset.deleted.isnot(True)) | fa39a2ff62623828fabf076acd4049dc8062f136 | 56,216 |
import os
def path_components(path):
"""Find all directories that make up a full path."""
components = [path]
current = path
while current and current != '/':
current, _ = os.path.split(current)
components.append(current)
return components | c36e15bc75735a60a254a0e203a2fc142497423b | 56,217 |
from sys import prefix
def staff():
""" RESTful CRUD controller """
tablename = "%s_%s" % (prefix, resourcename)
table = db[tablename]
# Pre-processor
def prep(r):
# No point in downloading large dropdowns which we hide, so provide a smaller represent
# the update forms are not ... | 1ae4faa0e1cf55fc53890b81bbd6392d24462461 | 56,218 |
from typing import List
def _align_mortgages(periods_a: List[int],
periods_b: List[int],
fees_a: List[int],
fees_b: List[int]) -> (List[int], List[int]):
""" Align periods and fees of two mortgages and compute the exact fee for each period.
:para... | 01c30c3b010c94a5d03c0936377c3551cdb3e5ef | 56,219 |
def two_point(rng, population, fitness, new_individuals, N):
"""Add `N` individuals based on the crossovering two randomly selected individuals by a middle point.
If there are no new individuals, then they crossovering occurs between the individuals in the previous generation.
Parameters
----------
... | a0e149b319391ddc2e6e975954e381bccdc728cf | 56,220 |
import json
def rating(ticker):
"""
Description
----
Gives information about the rating of a company which includes i.a. the company
rating and recommendation as well as ratings based on a variety of ratios.
Input
----
ticker (string)
The company ticker (for example: "... | afd26bc4db16e9f6f6d03217a26ab223f8687ab5 | 56,221 |
import traceback
def testrangepartition(MyAssignment, ratingstablename, n, openconnection, partitionstartindex, ACTUAL_ROWS_IN_INPUT_FILE):
"""
Tests the range partition function for Completness, Disjointness and Reconstruction
:param ratingstablename: Argument for function to be tested
:param n: Argu... | c4d4f945c0f51180964114bda178a2e9bf245281 | 56,222 |
def bpow(a, f):
"""Broken power law. This model assumes that there is a break in the power
spectrum at some given frequency.
Parameters
----------
a : ndarray[3]
* a[0] : the natural logarithm of the normalization constant
* a[1] : the power law index at frequencies lower than t... | 1d42e9ab0c22ba9dbdd0190c09ea7b191ae5d66c | 56,223 |
def sample_dataframe(df, parameters=None):
"""
Sample a dataframe on a given number of cases
Parameters
--------------
df
Dataframe
parameters
Parameters of the algorithm, including:
- Parameters.CASE_ID_KEY
- Parameters.CASE_ID_TO_RETAIN
Returns
-------... | e7e8f203339d671f3e363572a813f4658e189d35 | 56,224 |
import uuid
def modes(valid_types):
"""Decorate a function to cast inputs/outputs to different precision.
>>> snt.Linear.__call__ = snt.mixed_precision.modes(
... [tf.float32, tf.float16])(snt.Linear.__call__)
>>> mod = snt.Linear(10)
>>> snt.mixed_precision.enable(tf.float16)
>>> y... | bb5af7bd036e8e26ab191fbbe493d569bcb9331d | 56,225 |
import os
import copy
def run_calc(
atoms: Atoms, store_dir: str = None, scratch_dir: str = None, gzip: bool = False
) -> float:
"""
Run a calculation in a scratch directory and copy the results back to the
original directory. This can be useful if file I/O is slow in the working
directory, so lon... | 530d0e5b13e0c4f23925dd908f2d1bd26966f7de | 56,226 |
def synmodel(spec,params,alinefile=None,mlinefile=None,verbose=False,normalize=True):
"""
Synthetic spectrum model.
Parameters
----------
spec : Spec1D object or str
The observed Spec1D spectrum to match or the name of a spectrum file.
params : dict
Dictionary of initial value... | 39a12bdd20d89a6a29b878fc399029a595b40a3e | 56,227 |
def make_row(path1, path2, dt1, dt2, diff_man, diff_euc):
"""Make a list containing all row info.
For Hive and RPi number, just add the two columns later.
header = [...]
"""
# # Get interval duration
# td = (dt2 - dt1)
# dur = td.total_seconds()
# dt_center = dt1 + (td / 2)
# Shor... | 21159e7d109b4019f632c2644354c97f8416a80f | 56,228 |
from pathlib import Path
def elec_demands_dirpath(tmp_path: Path) -> Path:
"""Create a temporary directory of dummy data called 'SM_electricity'.
Args:
tmp_path (Path): see https://docs.pytest.org/en/stable/tmpdir.html
Returns:
Path: Path to a temporary directory of dummy data called 'SM... | 19cd13a7bfd61f211fd900caa43c9355c26ac500 | 56,229 |
import os
from datetime import datetime
def send():
""" Sends notifications via Flask-Mail. """
try:
data = request.get_json()
if data['authkey'] != os.environ.get('MAIL_AUTHKEY'):
return "Ooops. Wrong `authkey`."
msg = Message(data['subject'],
sender=os.enviro... | 6b5f1b0e1d11ae4429d1e8f82c02412f5666eee9 | 56,230 |
def get_operation_subfuncs(entry_info, callgraph):
"""
get reachable functions of each operation
entry_funcs_file: operation entry functions list
callgraph: callgraph of the application, networkx.classes.multidigraph.MultiDiGraph type
"""
OperationNames = list(entry_info.keys())
# callgraph ... | 8fa5bc77dd8ab378d61345d2f9377ed5ffba51c2 | 56,231 |
import re
def StringHits(s: str, ks: [str], excluding=None, regexformat=r"[a-zA-Z0-9]*{}[a-zA-Z0-9]*"):
"""
find tokens in which there is at least one of <ks>
:param excluding: a list of keywords that should not appear in the tokens
"""
ms = []
excluding = [ex.lower() for ex in excluding]
... | 36948be94cf210767ccdeb7a93b80df3a5b5db97 | 56,232 |
def calculate_ms_ssim(predictions, gt_labels, max_val):
"""
ms-ssim calculation
Parameters
----------
predictions : ndarray
the reconstructed results
gt_labels : ndarray
the ground truth
max_val : float
the value range
"""
tf_predictions = tf.placeholder(t... | 671ea748fd2c0c62a145bf3a98231dcf3f807830 | 56,233 |
def rescale(nums, scales, budget=None):
"""
Rescale nums with scales to budget. Budget defaults to sum(nums)
Ex:
nums = [10, 20]
scale = [2, 1]
budget = 30
will return [15, 15]
"""
raw = np.multiply(nums, scales)
if np.sum(raw) == 0:
raise ValueError("Rescaling denominat... | 33f030390f96c04220b25f201138554d9dcf97fb | 56,234 |
from typing import Iterable
from typing import Set
def BCH_words_of_order(n: int,
alphabet: Iterable[BCH_Symbol],
disallowed_end: Set[BCH_Symbol] = set()) \
-> Iterable[BCH_Word]:
"""Generate all possible combinations of symbols in alphabet of length n.
R... | 3a815165fd4bd1d4c99603b55bd3def8193ee6da | 56,235 |
def uCSIsAegeanNumbers(code):
"""Check whether the character is part of AegeanNumbers UCS
Block """
ret = libxml2mod.xmlUCSIsAegeanNumbers(code)
return ret | e2e62a6ce992bc6f38990bdb1f3adf52f78871f8 | 56,236 |
def prettify(elem):
"""
Return a pretty-printed XML string for the Element.
"""
rough_string = ET.tostring(elem, encoding="utf-8", method='xml')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | 314db4eba6628be37cac6a239767962a3e677767 | 56,237 |
import resource
def GetVPNServiceClass():
"""Gets the VPNService class.
Args:
Returns:
Implementation class
"""
return resource.GetResourceClass(VPNService) | 614092185f37e10367901848e88363d294f0b7cd | 56,238 |
def get_nn_gp_kernel(kernel_type, nn_type, gp_cts_hps, gp_dscr_hps, tp_comp,
kernel_options):
""" Constructs and returns the kernel hyperparams. """
# pylint: disable=unused-argument
kernel_hyperparams = {}
gp_cts_hps = gp_cts_hps[:] # create a copy of the list
# Extract GP hyper-paramete... | 9d5f6d71f25901bc0a5ac8cba93956981fa1220f | 56,239 |
from typing import Optional
def get_sobol(
search_space: SearchSpace,
seed: Optional[int] = None,
deduplicate: bool = False,
init_position: int = 0,
scramble: bool = True,
) -> RandomModelBridge:
"""Instantiates a Sobol sequence quasi-random generator.
Args:
search_space: Sobol ge... | f5f36fb20c7b8e39ebc8c0de6e5b47b267e1f939 | 56,240 |
def compute_distance(x0,y0,x1,y1):
"""takes two location vectors computes there distance from each element
in the first location to the elements in the second returning the element
from location one that is closet to location 2.
This is done using a kdtree algorithm."""
# Create point arrays
x... | 780101198af3401bbe29634b151c8279ecac5b4e | 56,241 |
def load_model(weights, device):
""" load model and it's weights """
model = YoloV2Net()
if weights:
load_weights(model, weights)
#model.load_state_dict(torch.load(weights))
return model.to(device) | 5b966fff88e1bc2bfb07f68303f5723733dc2fa6 | 56,242 |
def supported_territory_codes():
""" Return a set of recognized territory codes.
"""
return supported_country_codes().union(supported_subdivision_codes()) | 3cbe9fe8070658f8884f309cfeb4d0777b70c0dc | 56,243 |
from typing import Match
def from_paper(match: Match) -> Players:
"""Creates the players information from a Paper server match.
https://github.com/conqp/mcipc/issues/13#issuecomment-726145034
"""
online, max_, names = match.groups()
players = players_from_paper_names(names)
return Players(int... | a4c53b8e0f55ae6342f13f19053b586bd993ea65 | 56,244 |
def get_target_name(label):
"""
Try to extract the target_name from a given PDS label.
Parameters
----------
label : Object
Any type of pds object that can be indexed
Returns
-------
target_name : str
The defined target_name from the label. If this is None a target name... | 7aae704d4590fb44bfb650481a65af870c7c6570 | 56,245 |
def constant_fold(trace, expression):
"""Replace an expression with a constant if possible"""
try:
return Constant(
trace,
expression.value(),
expression.type_(),
expression.signed()
)
except AttributeError:
trace.error("Not a valid exp... | b5a2e0e08a598f8be8d9d6098f474de3ca0f5b7b | 56,246 |
def confirm_update(bot, update, user_data):
"""Handler for a message that begins with Edit, Cancel or Remove.
Confirm what the user want to do when an already tagged sticker was sent.
"""
if update.message.text == "Edit":
update.message.reply_text("Cool, send me the new tags to your sticker\n... | b42accb2e1c4587f1c5e24a66e2d29858f5e816d | 56,247 |
def _get_str_from_bin(src: bytearray) -> str:
"""Join data in list to the string.
:param src: source to process
:type src: bytearray
:return: decoded string
:rtype: str
"""
return src.rstrip().decode(encoding="utf-8", errors="backslashreplace") | a51d562ea06ff80d3a7f7c10622eb599cd9a1e83 | 56,248 |
def most_likely_distance2(atom1, atom2, box):
"""
Same as most_likely_distance, but distance^2 is computed (faster).
:param atom1: pmx.model.Atom
:param atom2: pmx.model.Atom
:param box: a tuple
:return: most likely distance from atom1 to atom2 w.r.t. box
"""
return closest_distance2(ato... | b3bcb4ec3f323843f29a5150f656f6f71ec809cc | 56,249 |
def mean_cost_div_value_and_grad(X, Y):
"""Compute the mean-cost divergence value *and* gradient w.r.t. X.
The cost is assumed to be the squared Euclidean one.
Args:
X: time series, numpy array of shape (size_X, num_dim).
Y: time series, numpy array of shape (size_Y, num_dim).
gamma: regularization ... | 111e386fea7331c4c53765c754a35873d1eb3406 | 56,250 |
from typing import Optional
def get_certificate(name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCertificateResult:
"""
Get information on a certificate. This data source provides the name, type, state,
domains, expiry date, and the sha1 fingerpri... | be8cc3ea0a00b4bed4f001d7a0eaf9a6f7476a7b | 56,251 |
def frame_filter_highpass(array, mode, median_size=5, kernel_size=5,
fwhm_size=5, btw_cutoff=0.2, btw_order=2,
hann_cutoff=5, psf=None, conv_mode='conv',
mask=None):
"""
High-pass filtering of input frame depending on parameter ``mode... | 41a8f965d1f37b7d648ebdd8e2a387343e994553 | 56,252 |
import os
def version_consistency(self):
"""Pipeline and container version number consistency.
.. note:: This test only runs when the ``--release`` flag is set for ``nf-core lint``,
or ``$GITHUB_REF`` is equal to ``master``.
This lint fetches the pipeline version number from three possible... | df037cedc3ca5a95488560d294fcf1b19eb49999 | 56,253 |
def kth_diag_indices(array, diag_k):
"""Return a tuple of indices for retrieving the k'th diagonal
of matrix a.
:param array: Input matrix.
:type array: :class:`numpy array <numpy.ndarray>`
:param int diag_k: Diagonal to index. 0 is the centre, 1 is the first \
diagonal below the centre... | 0e81dea00f4931f541a2f339ef3425fd1c46010a | 56,254 |
def unique(obj):
"""
Unique with order
"""
temp = set()
return [x for x in obj if x not in temp and not temp.add(x)] | 2d4fc7a5ba39f1fcc84ccebc1f8604c8ca972e8c | 56,255 |
def str_word_count(s: str) -> int:
"""
This function returns word count using RegexpTokenizer
"""
if s:
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(s)
return len(tokens)
else:
return 0 | 0e2d598008ae8dd1c84cea5d05a8bbd1d5b38da9 | 56,256 |
def identity(x):
"""identity: return the argument"""
return x | 12201cf98d8984c1ade07f2048b770c9bad66c8b | 56,257 |
def is_main_process():
"""
Check whether the current process is the main process.
Returns:
bool: Whether the current process is the main process.
"""
return get_rank() == 0 | 968ae6ca845be6df40b396ca93266047a6b062ae | 56,258 |
def aggregate(namespace, user_project, consortium, drs_file_path=None, terra_output_path=None):
"""Run a series of reconciliations."""
def counts_factory():
return {'expected_sample_count': 0, 'actual_sample_count': 0, 'problems': []}
accessions = defaultdict(counts_factory)
assert drs_file_path... | ebda81fa50dd5be83a7e59b88115afe420978d7a | 56,259 |
from datetime import datetime
def get_bookmarks_backup_filename(date=None):
"""Return the default bookmarks filename as it is exported by Firefox at specific date."""
if date is None:
date = datetime.datetime.today()
return 'bookmarks-{year:0>4}-{month:0>2}-{day:0>2}.json'.format(
year=dat... | a09ee7d9dda2cdb15b4c2916bc19d1ceff32e396 | 56,260 |
from datetime import datetime
def get_sandbox_data(request, code):
""" If the proxy is in sandbox_mode, return sandbox data if it's there else 404 for robot, EDR request for others"""
if SANDBOX_MODE:
res = None
if request.authenticated_role == 'robots':
res = get_sandbox_details(r... | 658e9bfa5384f1e572d39eba8e39557eaffd4405 | 56,261 |
def metabase_data_db_name() -> str:
"""The name (in Metabase) of the database that Metabase reads from"""
return 'MyCompany DWH' | 391551068308d842c35e80a8e196f3854259e143 | 56,262 |
def doy_to_datetime(doy, year, zero_based=False):
"""convert a decimal day of year (e.g., 34.58275) to a datetime.
Day is one-based unless zero_based param is True"""
origin = '{}-01-01'.format(year)
o = pd.Timestamp(origin)
if not zero_based:
adjusted_doy = doy - 1
return pd.to_datetime... | 95f4d0d02d80c20e8099b08b2d2d56770685e4ae | 56,263 |
def smiley():
"""Return smiley page of for app."""
if current_app.smiley:
table = current_app.smiley.db.tables.smiley.head(n=10000).to_html()
else:
table = ''
return render_template('smiley.html', table=table) | 527367ebbf113016b7955d2e2da013bf665f911e | 56,264 |
def _h1_chebyshev_sum_ ( h1 , N , **kwargs ) :
"""Make a histogram representation in terms of Chebyshev polynomials
>>> histo = ...
>>> fsum = histo.chebyshev_sum ( 4 )
>>> print fsum
>>> x = ...
>>> print 'FUN(%s) = %s ' % ( x , fsum ( x ) )
"""
##
xmin = max ( kwargs.get( 'xmin... | 02f56aa730639e6474734e312e0000398a39a74d | 56,265 |
from typing import List
from typing import Any
def flatten_list(x: List[Any]) -> List[Any]:
"""
Converts a list of lists into a flat list.
Args:
x: list of lists
Returns:
flat list
As per
http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-o... | b600cce1dc88869c60c80019f3be9ea5245cdda7 | 56,266 |
import copy
def cmap_powerlaw_adjust(cmap, a):
"""
Returns a new colormap based on the one given
but adjusted via power-law, `newcmap = oldcmap**a`.
:param cmap: colormap instance (e.g., cm.jet)
:param a: power
"""
if a < 0.:
return cmap
cdict = copy.copy(cmap._segmentdata)
... | cfbafb772e867c88e35693a5b009b1f6cfbd3c95 | 56,267 |
def buff_eval(params):
"""Builds and evaluates BUFF energy of model in parallelization
Parameters
----------
params: list
Tuple containing the specification to be built, the sequence,
and the parameters for model building.
Returns
-------
model.bude_score: float
BUF... | 84ba0e9632cbcd5052a790fc805493f79c33cad2 | 56,268 |
def st100(x: np.ndarray) -> float:
"""Styblinksitang function with noise 100."""
return _styblinksitang(x, 100) | 650c07b0e60d7cde6d86dc432e5d19dad7ba5521 | 56,269 |
def normalize_year(input_month, input_year=None):
""" This routine is used when we only have month parameters (text planner / stop schedule lookup) and the
year is implied...
RULES:
return last year if we're w/in a few months of the new year, today is in the months of Jan-March and the se... | 1d53f51d092b96f8ac9267c8fc4d9b90c1cebe4f | 56,270 |
def rank_targets(sample_frame, ref_targets, ref_sample):
"""Uses the geNorm algorithm to determine the most stably expressed
genes from amongst ref_targets in your sample.
See Vandesompele et al.'s 2002 Genome Biology paper for information about
the algorithm: http://dx.doi.org/10.1186/gb-2002-3-7-rese... | befab1b5434b9f584a7d7a931a81e51c25f6cfed | 56,271 |
import random
def sample_dims(
min_num_layers: int = 1,
max_num_layers: int = 5,
upper: int = 256,
q: int = 16,
) -> Function:
"""
Create a sampler for hidden dimensions.
:param min_num_layers:
The minimum number of hidden layers.
:param max_num_layers:
The maximum num... | 42c6c16402618ee3d593f764624e923e47ca6d6a | 56,272 |
def get_containerbox_list(context, slug, num=0, template_name=None):
""" returns a list of sub-lists of the containerbox specific containers,
the size of the sub lists is treated with a parameter num """
request = context['request']
cachekey = "ContainerBoxList-{}-{}-{}".format(
slug,
... | 4be68fcc35e6d72629dcfaadabd6d6cbe05b140e | 56,273 |
import argparse
import os
def parse_args():
"""Training Options for Depth Prediction Experiments"""
parser = argparse.ArgumentParser(description='MXNet Gluon Monodepth2 Demo')
# model and dataset
parser.add_argument('--model_zoo', type=str,
choices=['monodepth2_resnet18_kitti_... | 3fbf77a2b56f9b0a8e7d9c8165a2d20101464ab8 | 56,274 |
from typing import Counter
def recompute_interest_by_batch(queryset=None, verbose=False):
"""
Using `verbose` reports potential discrepancies between old and recomputed interest values.
It requires 2 extra queries for each import batch, so it should be used with caution.
"""
with cache_based_lock(... | a9f573791d953126ab868b8db44a5fef0b466b93 | 56,275 |
from typing import Optional
from datetime import datetime
def tomorrow(tz: Optional[tzinfo]=None) -> datetime:
"""get datetime of tomorrow"""
return today(tz) + timedelta(days=1) | 396a07456142463d0c707a74728a766ca470b926 | 56,276 |
def get_accessable_systems(ships, systems):
"""
Determine which systems are currently accessable
"""
accessable = []
for ship in ships:
if ship[const.LOCATION] not in accessable:
accessable.append(ship[const.LOCATION])
for system in systems:
if system[const.NAME] not ... | 26ffc740879d6f324489883b153aaf4b184329ba | 56,277 |
import math
def set_engine_state(engine: Engine, aggregation_epochs: int, aggregation_iters: int):
"""
This function is used to set the engine's state parameters according to
the aggregation ways (iteration based or epoch based).
Args:
engine: the engine that to be processed.
aggregat... | 41b65b6fc6cff5d1b7269f25309977bf1f672906 | 56,278 |
def _get_const_info(const_index, const_list):
"""Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
"""
argval = const_index
if const_list is not ... | e495685a5d742f014cbe14cda23e2cc97ba2761d | 56,279 |
def config_list():
"""
List all config items.
:return:
"""
# Pull all the config items
items = Config.query.all()
# Return the broken down objects
return success_response({"config": [item.data for item in items]}) | 7cdc3a986a54b103fc6a591ffef532c6d500bcab | 56,280 |
def inv_linear_augTikho_chol_dense(
Tn=None,
TTn=None,
Tyn=None,
R=None,
yn=None,
sol0=None,
nchan=None,
nbs=None,
mu0=None,
conv_crit=None,
a0bis=None,
b0=None,
a1bis=None,
b1=None,
d=None,
conv_reg=True,
verb=None,
verb2head=None,
**kwdargs,
... | 2bd511443e5695c824bdec5abdc3bf58ce428a3e | 56,281 |
def return_gaia_Ag():
"""set the Hipparcos computation
if truly obsessed see https://www.cosmos.esa.int/documents/532822/552851/vol1_all.pdf
though this has higher precision!!
"""
return np.array([[-0.0548755604162154,+0.4941094278755837,-0.8676661490190047],
[-0.8734370902348... | 5d8071120fcc8a429a31f049dab1cd8a009bc7fb | 56,282 |
def find_repeated_adjectives(lyrics):
"""Creates a list of all repeating adjectives from the lyrics.
Args:
lyrics: A string containing the lyrics of a song.
Returns:
A list of all adjectives found more than once in the lyrics.
"""
adjectives = adjectives_sorted(lyrics)
repeated... | 4dbef0fb9afa7571c054b60a7774345f42e8153d | 56,283 |
def set_attr(conninfo, credentials, mode, owner, group, modification_time,
change_time, size=None, creation_time=None, extended_attrs=None,
path=None, id_=None, if_match=None):
"""
Sets all file attributes on the specified file system object.
!!! This function is deprecated in favor of set_f... | b69f958abbf1f6ba6430f2b62a3527737f050a24 | 56,284 |
import logging
import subprocess
def get_stash_info(directory: str):
"""Return stash info under `directory`."""
logging.debug('Checking GIT stashes under "%s"', directory)
return subprocess.run(
'git stash list'.split(), cwd=directory,
capture_output=True, text=True, check=False
).stdo... | f31418e25b03442bf5533cf05c2852c823dbcfeb | 56,285 |
def DBK(graph, LIMIT, solver_function):
"""
INPUT:
- "graph" must be a Networkx Undirected Graph
- "LIMIT" is an integer describing the largest size of graph which solver_func can solve; all subgraph sizes solved will be less than or equal to LIMIT
- "solver_function" takes a Networkx Graph, and outputs a list ... | 4b9f5c104bf55fff1728ce5ff2686c191be0898e | 56,286 |
def _character_name(code):
"""Returns the printable name of a character."""
return unicode_data.name(unichr(code), '<Unassigned>') | f2b598198013ac65dbe80deb8e42e3e65bb9dde5 | 56,287 |
def readmask(name) :
""" Read a single FERRE mask file
"""
f=open(name)
data=[]
for line in f :
data.append(float(line))
return np.array(data) | a55641126abf57812d6db3d3236fddd4af194b92 | 56,288 |
import os
def generate_lando_files(name, docroot, cache):
"""
Generate Lando files in the docroot
"""
services = ""
tooling = ""
if cache == "redis":
services = """ cache:
app_mount: disabled
type: redis:5
"""
tooling = """ redis-cli:
service: cache
"""
elif c... | ab95e77c41f4e00ad588ffd19ffdec9b0f95c1c0 | 56,289 |
def _featuresmanager_parsing_creation(feats_info):
"""FeaturesManager instantiation from features information. This function
transforms features information into a FeaturesManager object.
Parameters
----------
feats_info: np.ndarray, list, tuple, pst.BaseFeatures, pst.FeaturesManager
The fe... | 6dc00d2df0edd3536385e5aef5f5114492775623 | 56,290 |
def __from_probmap_to_labels(probmap, threshold):
"""Thresholds an intensity map and find connected components.
Args:
probmap (np.array): The original array with probabilities.
threshold (int/float): threshold
Returns:
regions:
res: numpy array in which each disconnected re... | f8bd59815d86a0d246d02a5728a8c02364fecc9c | 56,291 |
def checkout():
"""
This function represents a /checkout API endpoint.
"""
return Response(status_code=200,
body={"result": "Success"},
headers=RESPONSE_HEADERS) | 1f9921bff1ecb10e50541e50b25ee947fc331b84 | 56,292 |
def send_trial(parameters: dict) -> int:
"""
Send a new trial. Executed on tuner end.
Return a ID that is the unique identifier for this trial.
"""
return get_advisor().send_trial(parameters) | 919eee4a644a0ec15172e724c4367b1864596545 | 56,293 |
import json
import logging
def gen_json_data(op_desc):
"""Generating test data for composite json"""
desc = json.loads(op_desc)
input_for_mod = []
input_dict = {}
input_order = {}
inplace_assign_dict = {}
output_indexes = []
expect = []
with_inplace_assign = False
if isinstance... | 1c894be57fe3a44365ec5200ba1fedc4a1dc5ba7 | 56,294 |
def _create_binary_operator(operator_func, description, list_kword=None):
"""Creates and returns a BinaryOperator class based on the given
operator_func function, which is assumed to be a function taking two
arguments (lvalue, rvalue) and returning a boolean value.
"""
class _BinaryOperatorImpl(_Bi... | 1a5691b018df8e7b9f296b33d0187e327819befe | 56,295 |
async def get_commit_oneline_message(*, github_access_token, repo_url, commit_hash):
"""
Get the git commit message plus a piece of the hash for display purposes
Args:
github_access_token (str): The access token
repo_url (str): The URL for the git repo of the project
commit_hash (st... | 56de60b5477c2707e5fafeb29eccb56727e44c0b | 56,296 |
def return_subset_number(pedigree):
"""
Find out how many founders there are in the given file.
"""
founder = 0
with open(pedigree, 'r') as filein:
for lines in filein:
line = lines.rstrip().split()
if line[2] == "0" and line[3] == "0": founder += 1
return foun... | 090661dfbc367fe3974fe2dfa2069f97dd70ee75 | 56,297 |
def waveoauth(func):
"""Decorator used to specify that a handler requires wave authentication."""
@wraps(func)
def inner(request, *args, **kwargs):
result = _oauth_helper(request)
if result is not None:
return result
return func(request, *args, **kwargs)
return inner | b8936965c60410856ee436b159a098044fcd5fc8 | 56,298 |
def tool_no_apply(cols):
"""Gets the tool number from the PMC signal
Explanation
===========
Same explanation as in the cut_signal_apply function
"""
pmc = cols[0]
if (pmc - 64) > 0:
return int(pmc - 64)
else:
return int(pmc) | 8d094cabdab58bd009d9019de8896c772e5fc72a | 56,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.