content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def removelink(inp, nick='', db=None):
""".removelink <search terms> -- Remove a bad link from the database. e.g., .removelink shaq"""
if nick in administrators:
result = remove_link(db, urllib.quote_plus(inp))
if result is True:
return "Removed " + inp + " successfully."
el... | 53,000 |
def test_some_mobile_attck_actors_have_generated_datasets_properties(attck_fixture):
"""All MITRE Mobile ATT&CK Techniques should have techniques
Args:
attck_fixture ([type]): our default MITRE Mobile ATT&CK JSON fixture
"""
country_count = 0
operations_count = 0
attribution_links_count... | 53,001 |
def embed(sagas):
"""
The data is embedded into numerical data (vectors to represent characters) that we can use to train our RNN.
:param sagas: Training data
:return: Tensor containing the input data in embeded form, array of unique character in the input.
"""
# All unique characters in our sa... | 53,002 |
def create_data(step: 'projects.ProjectStep') -> STEP_DATA:
"""
Creates the data object that stores the step information in the notebook
results JavaScript file.
:param step:
Project step for which to create the data
:return:
Step data tuple containing scaffold data structure for th... | 53,003 |
def byte_string_dtypes(endianness="?", min_len=0, max_len=16):
# type: (str, int, int) -> st.SearchStrategy[np.dtype]
"""Return a strategy for generating bytestring dtypes, of various lengths
and byteorder."""
order_check("len", 0, min_len, max_len)
return dtype_factory("S", list(range(min_len, max_... | 53,004 |
def get_company():
"""
Gets company for contact entered
"""
company = input("Please input a company\n")
while True:
if company == "":
print("Please input a company please")
else:
break
return company | 53,005 |
def plot_results(
model_names: tuple,
model_data: tuple,
y_limits: tuple,
metric_name: str,
output_filename: str,
supplemental_plot_info: list = [],
title: str = "(Social) bias metric evaluation",
colors: tuple = ("red", "blue"),
plot_individual_ru... | 53,006 |
def set(request):
"""Set new CTL value to a encoder/decoder"""
def inner(func, obj, value):
result_code = func(obj, request, value)
if result_code is not opuslib.api.constants.OK:
raise opuslib.exceptions.OpusError(result_code)
return inner | 53,007 |
async def progress(current, total, message, start, type_of_ps, file_name=None):
"""Progress Bar For Showing Progress While Uploading / Downloading File - Normal"""
now = time.time()
diff = now - start
if round(diff % 10.00) == 0 or current == total:
percentage = current * 100 / total
spe... | 53,008 |
def getInstalledPackageVersion(pkgid):
"""
Checks a package id against the receipts to
determine if a package is already installed.
Returns the version string of the installed pkg
if it exists, or an empty string if it does not
"""
# First check (Leopard and later) package database
proc... | 53,009 |
def is_gif(url):
"""Checks if the url contains a gif (not implemented yet)"""
content_type = requests.head(url).headers['Content-Type']
pass | 53,010 |
def read_mapping(mapf, verbose=False):
"""
Read the mapping from metagenomes to nodes in the tree
:param mapf: the mapping file
:param verbose: more output
:return:
"""
mapping = {}
with open(mapf, 'r') as f:
for l in f:
p = l.strip().split("\t")
if p[1] ... | 53,011 |
def test_if_not():
"""Test that 1 if (not) statement works."""
test = [
'target_value',
[
IfStatement(**{
'condition': 'not',
'target': 'not_target',
'then': 'value2',
}),
],
]
assert apply_if_statements(*tes... | 53,012 |
def CFLAGS(d_flags, r_flags):
"""
set the global compile options for c files,
this influences the all of c files in module
Args:
d_flags : debug mode preprocess flags
r_flags : release mode preprocess flags
"""
if sys.argv[0] == 'PLANISH':
return
env = Environment.GetCu... | 53,013 |
def tfr_gen(func, op_defs):
"""Parse a function and emit the TFR functions."""
mlir_code, _ = TfrGen(op_defs).transform(func, None)
assert tfr.verify(mlir_code), 'mlir code not verified: {}'.format(mlir_code)
return mlir_code | 53,014 |
def FindMissingEmail(arg_list):
"""menu.FindMissingEmail
INPUTS:
- directory -- list containing the MemberHub directory families
- map_d -- dictionary mapping teacher names to hub IDs
OUTPUTS:
Prints to standard output statistics about families with and without
email addresses, and give ... | 53,015 |
def preprocess_image(image:'np.ndarray', input_shape:Tuple=(79,95,79), normalized=True) -> 'torch.Tensor':
"""Resize, normalize between 0-1 and convert to uint8
Args:
image('np.ndarray'):
input_shape(Tuple, optional): (Default value = (79,95,79))
normalized: (Default value = True)
Retur... | 53,016 |
def convert_to_static(dyfunc):
"""
Converts dygraph function into static function.
"""
# Get AST from dygraph function
raw_code = inspect.getsource(dyfunc)
code = textwrap.dedent(raw_code)
root = gast.parse(code)
# Transform AST
dygraph_to_static = DygraphToStaticAst()
root_wrap... | 53,017 |
def call_contig_methylation(completed_contigs, call_methylation_kwargs):
""" Wrapper to initialize methylation calling
Arguments:
completed_contigs (multiprocessing.manager.list): List of contigs with completed methylation calls
call_methylation_kwargs (dict): dict of argument for CallMethylatio... | 53,018 |
def add_minutes(sourcedate, min_, debug=False):
"""
Incremental increase of datetime by given minutes
"""
sourcedate += datetime.timedelta(minutes=float(min_))
return sourcedate | 53,019 |
def poly_kernel(X, Y=None, gamma=1.0, coef0=0.0, degree=3):
"""
Compute the poly kernel between X and Y:
K(x, y) = (scale*dot(x, y^T) + shift)**degree
for each pair of rows x in X and y in Y.
Parameters
----------
X : ndarray of shape (n_samples_X, n_features)
Y : nda... | 53,020 |
def filter_process(session, file, action, wkt, **kwargs):
"""Wrapper function for the filtering process.
Arguments:
session (dict): Dictionary with session information.
file (str): The full path of the source file.
action (str): The filtering operation.
wkt (str): Well-Known Tex... | 53,021 |
def diapos():
"""Construits les fichiers HTML des diapositives."""
cwd = os.getcwd()
for folder in DIAPOS_DIRS:
try:
os.chdir(folder)
except (FileNotFoundError, NotADirectoryError):
os.chdir(cwd)
continue
# Déterminer le nom du fichier source.
... | 53,022 |
def help_text():
"""
Retreive human-readable description of all added craftable items
:return: description of all added craftable items
:rtype: str
"""
ret = []
for name in craftables:
items, item = craftables[name]
item_names = utils.list_to_english([str(x) for x in items])... | 53,023 |
def _load_image(path):
"""
Reads image image from the given path and returns an numpy array.
"""
image = np.load(path)
assert image.dtype == np.uint8
assert image.shape == (64, 64, 3)
return image | 53,024 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Add sensors for passed config_entry in HA."""
session = async_get_clientsession(hass)
data = ToonBoilerStatusData(
session, config.get(CONF_HOST), config.get(CONF_API_KEY)
)
await data.async_update()
... | 53,025 |
def nb(model, ref):
"""
Normalzied bias.
model = nuemrical solution of shape M by N
ref = analytical solution or observation of shape M by N
returns nb
"""
e = model - ref
mean_e = nanmean(e)
mean_abs_ref = nanmean(abs(ref))
nb = mean_e / mean_abs_ref
return nb | 53,026 |
def test_list_name_max_length_4_nistxml_sv_iv_list_name_max_length_5_1(mode, save_output, output_format):
"""
Type list/Name is restricted by facet maxLength with value 10.
"""
assert_bindings(
schema="nistData/list/Name/Schema+Instance/NISTSchema-SV-IV-list-Name-maxLength-5.xsd",
instan... | 53,027 |
def annotate_heatmap(im, data=None, valfmt="{x:.2f}", textcolors=["black", "white"], threshold=None, **textkw):
"""
A function to annotate a heatmap.
Parameters
----------
im
The AxesImage to be labeled.
data
Data used to annotate. If None, the image's data is used. Optional.
... | 53,028 |
def sigmoid(x):
"""
Sigmoid activation function
@param x: input array
@return:
out: output array
"""
return 1 / (1 + np.exp(-x)) | 53,029 |
def _flagword(obj):
"""Internal use only"""
#create the flags word for an objective
_f = B_DISC #everything's discoverable
if obj.neg:
_f |= B_NEG
if obj.synch:
_f |= B_SYNCH
if obj.dry:
_f |= B_DRY
return _f | 53,030 |
def create_model(conditioning_dim, flags):
"""Define model, and initialize classifiers."""
model = VAEBasic(flags.height, flags.width, latent_dim=flags.latent_dim, conditioning_dim=conditioning_dim,
start_filters=flags.start_filters, name='VAE')
return model | 53,031 |
def palette(name):
"""Palette decorator"""
def wrapper(cls):
palette_providers[name] = cls
return cls
return wrapper | 53,032 |
def remove_one_path(path_graph, dest=None, preserv_cov=False):
"""
Removes one path from the path set in a way that
the vertices covered by the set of paths does not
decrease.
"""
complete = False
ix = 0
if dest is None:
dest = max(list(path_graph.keys())) + 1
while not compl... | 53,033 |
def spec_builtin(obj):
""" Describe a builtin function """
# Built-in functions cannot be inspected by
# inspect.getargspec. We have to try and parse
# the __doc__ attribute of the function.
docstr = obj.__doc__
args = ''
if not docstr:
if isinstance(obj,types.BuiltinFunctionType):
... | 53,034 |
def get_nb_skl_base_estimators(obj, fitted=True):
"""
Returns the number of :epkg:`scikit-learn` *BaseEstimator*
including in a pipeline. The function assumes the pipeline
is not recursive.
@param obj object to walk through
@param fitted count the number of fitted object
... | 53,035 |
def interval_velocity_time(vp, pars):
"""
Output the interval velocity in time
@params:
vp (numpy.ndarray) : A 1D array containing the Vp profile in depth
pars (ModelParameter): Parameters used to generate the model
@returns:
vint (numpy.ndarray) : The interval velocity in time
"""
... | 53,036 |
async def ensure_room_power_levels(
room_id: str, client: AsyncClient, config: Config, members: List,
):
"""
Ensure room has correct power levels.
"""
logger.debug(f"Ensuring power levels: {room_id}")
state, users = await get_room_power_levels(client, room_id)
member_ids = {member.user_i... | 53,037 |
def read_analysis_settings(analysis_settings_fp, il_files_exist=False,
ri_files_exist=False):
"""Read the analysis settings file"""
# Load analysis_settings file
try:
# Load as a json
with io.open(analysis_settings_fp, 'r', encoding='utf-8') as f:
ana... | 53,038 |
def get_ca_bundle_path(settings):
"""
Return the path to the merged system and user ca bundles
:param settings:
A dict to look in for the `debug` key
:return:
The filesystem path to the merged ca bundle path
"""
ensure_ca_bundle_dir()
system_ca_bundle_path = get_system_ca... | 53,039 |
def encode_current(value: Any) -> bytes:
"""Encode current value to raw (2 bytes) payload"""
return int.to_bytes(int(value * 10), length=2, byteorder="big", signed=True) | 53,040 |
def assessments_view():
"""The clutter-free list of all Person's Assessments"""
return flask.render_template("assessments_view/index.haml") | 53,041 |
def check_search_bbox(session_id, bbox):
""" Checks whether a bounding box exists for this search and writes the bounding box geometry into the session
Args:
session_id: Which session shall be written to
bbox: The bounding box as comma separated string
Returns:
nothing
"""
... | 53,042 |
def run_charm_authorize(token):
"""Authorize charm to perfom certain actions.
Run vault charm action to authorize the charm to perform a limited
set of calls against the vault API.
:param token: Token to authorize action against vault.
:type token: str
:returns: Action object
:rtype: juju.... | 53,043 |
def get_price_from_substr(istr, original_str):
"""Extracts the float value (e.g. 7.5) and the channel_name from a string like this: "channel_name; unit; 7.5".
Args:
istr (str): a string like this: "bitcoin; eur; 7.5"
original_str (str): at the very first stage of parcing, before this func is ca... | 53,044 |
def ethclient(ctx, host, port):
"""pyethclient is collection of commands allowing the interaction with a
running pyethereum instance.
"""
config = read_config()
if not host:
host = config.get('api', 'listen_host')
if not port:
port = int(config.get('api', 'listen_port'))
path... | 53,045 |
def date_range(start: Literal["2000"], periods: int, freq: Literal["M"]):
"""
usage.statsmodels: 11
"""
... | 53,046 |
def main(args: Dict[str, Any]) -> None:
"""
Main function
:param args: Command Line Arguments
"""
logger.info("Script to train a siamese neural network model")
logger.info(f"Using batch size: {args['batch_size']}")
siamese_model = select_model(args['model'],
... | 53,047 |
def get_odds_labels(nfunc, adfam=False):
"""Labels used for odds in results_df."""
if adfam:
col_names = [r'$P(T={},N={})$'.format(1, i + 1)
for i in range(nfunc)]
col_names += [r'$P(T={},N={})$'.format(2, i + 1)
for i in range(nfunc)]
col_names... | 53,048 |
def subsetphaseheads(repo, subset):
"""Finds the phase heads for a subset of a history
Returns a list indexed by phase number where each item is a list of phase
head nodes.
"""
cl = repo.changelog
headsbyphase = {i: [] for i in allphases}
# No need to keep track of secret phase; any heads ... | 53,049 |
def queue_next_on_off_event():
"""Consult schedule_dict and set the next datetime that we should send an on or off command"""
now = datetime.datetime.now() # Right now
next_event_datetime = None
next_action = None
for day in scheduleList:
sched = day["schedule"]
for item in sched:... | 53,050 |
def mimic_3_demo(encoded: bool = False, mudata: bool = False) -> Union[MuData, List[AnnData]]: # pragma: no cover
"""Loads the MIMIC-III demo dataset
Args:
encoded: Whether to return an already encoded object
mudata: Whether to return a MuData object. Returns a Dictionary of file names to AnnD... | 53,051 |
def add_package(path, packages):
"""
Check the path and if it exists extract the packages runtime dependencies.
:param Path path: The resource file containing the runtime dependencies
:param dict packages: A mapping from package names to the sets of runtime
dependencies to add to
"""
cont... | 53,052 |
def isNeXusFile(filename):
"""Is `filename` is a NeXus HDF5 file?"""
if not os.path.exists(filename):
return None
f = h5py.File(filename, "r")
if isHdf5FileObject(f):
for item in f:
if isNeXusGroup(f[item], "NXentry"):
f.close()
return True
... | 53,053 |
def get_validation_context(self):
"""
Retrieves the validation context.
:rtype: String
:return: The validation context.
"""
return self.validation_context | 53,054 |
def parse_version_folder(base_dir: str, version_folder_name: str,
csv_paths: list, crd_dict: Dict[str, Tuple[str, str]]):
"""
Parse the version folder of the bundle and collect information of CSV and CRDs
in the bundle
:param base_dir: Path of the base directory where the versi... | 53,055 |
def _iprompt(repo, mynode, orig, fcd, fco, fca, toolconf):
"""Asks the user which of the local or the other version to keep as
the merged version."""
ui = repo.ui
fd = fcd.path()
if ui.promptchoice(_(" no tool found to merge %s\n"
"keep (l)ocal or take (o)ther?"
... | 53,056 |
def floating_ip_bulk_destroy(context, ips):
"""Destroy a lot of floating ips from the values dictionary."""
return IMPL.floating_ip_bulk_destroy(context, ips) | 53,057 |
async def update_grstn_phonebook(message, nats_handler, shared_storage, logger):
"""
Callback used to update the internal knowledge of which ground stations are in range. Receives broadcasts from orbit service that contain the new ground phonebooks.
Updates the ground phonebook if it is different, and sets ... | 53,058 |
def prepare_save_data(ts, conf):
"""
Given a time stepper configuration, return a list of time steps when the
state should be saved.
"""
try:
save_steps = conf.options.save_steps
except:
save_steps = -1
if save_steps == -1:
save_steps = ts.n_step
is_save = nm.li... | 53,059 |
def _validate_options(existing: dict) -> None:
""" """
expected_keys = ["team", "suite", "version"]
has_handshake = not existing.get("offline")
if has_handshake and any(x in existing for x in ["api_key", "api_url"]):
expected_keys.extend(["api_key", "api_url"])
key_status = {k: k in existing... | 53,060 |
def _add_attr(caller, attr_string, **kwargs):
"""
Add new attribute, parsing input.
Args:
caller (Object): Caller of menu.
attr_string (str): Input from user
attr is entered on these forms
attr = value
attr;category = value
attr;ca... | 53,061 |
async def async_auth():
"""AsyncAuth fixture."""
with patch("pyatmo.auth.AbstractAsyncAuth", AsyncMock()) as auth:
yield auth | 53,062 |
def route_multiple(world, robots, mode="random", number_of_runs=1):
"""
Routes the world demand and matches it with the robots like in the route method but multiple times to evaluate
quantities such as mean, etc. Particularly useful for the random method.
Parameters
----------
world: W... | 53,063 |
def disk_total_write():
"""
Returns the total amount of data written for the startup disk in a readeable format (> string)
"""
return get_scaled_size(psutil.disk_io_counters().write_bytes) | 53,064 |
def identify_principle_axis(C, sI_N=100):
"""
Using 2nd-order cumulant identify principle axis of correlation in 2D.
`sI_N` denotes window over which to look for maximum correlation
"""
if C.dims == ("x", "y"):
Nx, Ny = C.shape
else:
Ny, Nx = C.shape
x_ = C.coords["x"]
y... | 53,065 |
def check_modules():
"""
Checks if the required modules are installed and if not, installs them via pip
:return: none
"""
# Modules list
modules = ("tkinter", "netmiko", "pxssh")
for m in modules:
try:
__import__(m)
except ModuleNotFoundError:
os.syste... | 53,066 |
def help(args: list[str] = [], device: Device = None):
"""
help
输出本段消息
"""
print(
'usage: arknights-mower command [command args] [--config filepath] [--debug]')
print(
'commands (prefix abbreviation accepted):')
for cmd in global_cmds:
if cmd.__doc__:
... | 53,067 |
def _jupyter_nbextension_paths():
"""Called by Jupyter Notebook Server to detect if it is a valid nbextension and
to install the widget
Returns
=======
section: The section of the Jupyter Notebook Server to change.
Must be 'notebook' for widget extensions
src: Source directory name to c... | 53,068 |
def ssl_valid_time_remaining(hostname: str) -> datetime.timedelta:
"""Get the number of days left in a cert's lifetime."""
expires = ssl_expiry_datetime(hostname)
return expires - datetime.datetime.utcnow() | 53,069 |
def absolute_import_try(space, modulename, baselevel, fromlist_w):
""" Only look up sys.modules, not actually try to load anything
"""
w_path = None
last_dot = 0
if '.' not in modulename:
w_mod = check_sys_modules_w(space, modulename)
first = w_mod
if fromlist_w is not None a... | 53,070 |
def get_engine():
"""Return engine singleton"""
global _engine
if _engine is None:
_engine = create_engine(_connection_string)
return _engine | 53,071 |
def CreateTestAdUnit(client, server, version):
"""Create a test ad unit.
Args:
client: DfpClient used for service creation.
server: str the API server.
version: str the API version.
Returns:
The ID of the ad unit.
"""
inventory_service = client.GetService('InventoryService', server, version)... | 53,072 |
def _cache_deserialize(func):
"""Simple caching decorator"""
def cache_decorator(self, *args, **kwargs):
if self._deserialization_done:
return self._deserialization_result
self._deserialization_result = func(self, *args, **kwargs)
self._deserialization_done = ... | 53,073 |
def FindDescriptors(validator_pb2, msg_desc_by_name, enum_desc_by_name):
"""Finds the message and enum descriptors in the file.
This method finds the message and enum descriptors from a file descriptor;
it will visit the top-level messages, and within those the enums.
Args:
validator_pb2: The proto2 Pytho... | 53,074 |
def correct_directory_path(directory_path):
"""
Attempts to convert the directory path to a proper one by removing
any double slashes next to one another.
Args:
directory_path:
String of a potential directory path.
Returns:
Returns the fixed path.
"""
l... | 53,075 |
async def releaseStorageClient(app):
""" release the client storage connection
(Used for cleanup on application exit)
"""
client = _getStorageClient(app)
await client.releaseClient()
if "storage_client" in app:
del app["storage_client"] | 53,076 |
async def test_intent_request_with_slots_but_no_value(alexa_client):
"""Test a request with slots but no value."""
data = {
"version": "1.0",
"session": {
"new": False,
"sessionId": SESSION_ID,
"application": {"applicationId": APPLICATION_ID},
"att... | 53,077 |
def fused_laplacian_pyramid(gauss_pyramid_mod1, gauss_pyramid_mod2, lap_pyramid_mod1, lap_pyramid_mod2):
"""
A funtion that builds a fused Laplacian pyramid of two modalities of the same image
:param gauss_pyramid_mod1: The Gaussian pyramid of modality 1, a list of grayscale images, the first one in highes... | 53,078 |
def send_js(path):
"""
Serve static JS files
"""
return flask.send_from_directory(os.path.join(static_folder, "js"), path) | 53,079 |
def ascend(x):
"""True if vector x is monotonically ascendent, false otherwise
Recommended usage:
if not ascend(x): sort(x)
"""
return alltrue(greater_equal(x[1:],x[0:-1])) | 53,080 |
def existing_channels_handler_by_importance(client: object, importance: int):
"""
This function retrieves channels from DB by importance and updates their indexing status
:param client: Telegram client
:param importance: The target importance of the channels to be retrieved from DB
:return: -
""... | 53,081 |
def read_cdf_forecast_group(forecast_id):
"""Read CDF Group Forecast metadata.
Parameters
----------
forecast_id: String
UUID of the forecast to retrieve.
Returns
-------
dict
The CDF Forecast's metadata or None if the Forecast
does not exist.
"""
forecast =... | 53,082 |
def integrate(t_0: TimeSpan,
x_0: Matrix,
h: TimeSpan,
dynamics_func: Callable[[TimeSpan, Matrix], Matrix]
) -> Tuple[TimeSpan, Matrix, TimeSpan]:
""" Function utilizes a 4th-order Runge-Kutta integration scheme to integrate
the input state vector from... | 53,083 |
def increase(value):
"""Test template tag that returns an increased value."""
return value + 1 | 53,084 |
def get_processor():
"""Docstring.
Returns:
TYPE: Description
"""
try:
info = cpuinfo.get_cpu_info()
data = {
"bits": get_value(info, 'bits'),
"count": get_value(info, 'count'),
"brand": get_value(info, 'brand'),
"hz_advertised": g... | 53,085 |
def get_module_registry_dependencies(
pkg_names, registry_key='calmjs.module', working_set=None):
"""
For the given packages 'pkg_names' and the registry identified by
'registry_key', resolve the exported location for just the package.
"""
working_set = working_set or default_working_set
... | 53,086 |
def get_contour(rad,thresh):
"""
Find the edge in the input radiograph.
Parameters:
rad (numpy.ndarray): Radiograph of a sharp edge sample
thresh (float): The value at which a iso-valued contour (contour is the edge) is drawn
Returns:
numpy.ndarray: Coordinates along the longes... | 53,087 |
def _mp_message_dialog(
monkeypatch: MonkeyPatch,
method: str = "warning",
return_value: QMessageBox.StandardButton | None = None,
mock_class: Type[QMessageBox] = QMessageBox,
) -> CallList:
"""Mock a QMessageDialog and return a list with the call's arguments."""
return _mp_call(monkeypatch, moc... | 53,088 |
def dominant_wavelength(xy, xy_n, cmfs=None, inverse=False):
"""
Returns the *dominant wavelength* :math:`\\lambda_d` for given colour
stimulus :math:`xy` and the related :math:`xy_wl` first and :math:`xy_{cw}`
second intersection coordinates with the spectral locus.
In the eventuality where the :m... | 53,089 |
def getIconAsQPixmap(name: str, scale: int = None) -> QtGui.QPixmap:
"""Retrive a icon image as a QPixmap
:param name: the icon filename
:type name: str
:param scale: the desired size to apply to the icon (squared size), defaults to None
:type scale: int, optional
:return: the icon as a QPixmap
:rtype: QtGui.QP... | 53,090 |
def plot_obs(ax, metrics, data, color=OBS_GREY, zorder=1):
"""
Plot obs range as error bars.
:param axes ax: ``matplotlib.axes`` to plot data in
:param list metrics: List of metrics to plot in order
:param dict data: Metrics dictionary
:param str color: Colour to plot error bars
:param int ... | 53,091 |
def _requires(filename):
"""Determine a project's various dependencies from requirements files."""
try:
with open(os.path.join(REPODIR, 'requirements', filename)) as f:
return f.read().splitlines()
except FileNotFoundError:
pass
return None | 53,092 |
def replace_local_links(content, site):
"""Replaces a local link with the same link on an external blog. Originally crated because of `gatsby-plugin-catch-links`. Where
a link like ``[Blog Link](/blog/article-1)`` would get transformed into ``[Blog Link](https://haseebmajid.dev/blog/article-1)``.
So in case... | 53,093 |
def test_cli():
"""test sner server cli/main flask wrapper"""
with pytest.raises(SystemExit) as pytest_wrapped_e:
with patch.object(sys, 'argv', ['dummy']):
with patch.object(os, 'environ', {}):
cli()
assert pytest_wrapped_e.type == SystemExit
assert pytest_wrapped_e... | 53,094 |
def validate_arguments(selected_args: params.SelectedAnalysisOptions, validate_extra_args_func: Any = None) -> Tuple[params.SelectedAnalysisOptions, Dict[str, Any]]:
""" Validate arguments passed to the analysis task. Converts str and float types to enumerations.
Note:
If the selections are not specifi... | 53,095 |
def post_processing(results, bar_boxes, cluster_idx):
"""Post process identified barcode regions, combine overlapping or adjacent areas."""
combined = combine_overlapping_areas(results, cluster_idx)
filtered = []
for rect in combined:
# Barcode should be a horizontal series of bars, not a a ver... | 53,096 |
def kl_with_logits(p_logits, q_logits, scope=None,
loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES):
"""Helper function to compute kl-divergence KL(p || q)
"""
with tf.name_scope(scope, "kl_divergence") as name:
p = tf.nn.softmax(p_logits)
p_log = tf.nn.log_softmax(p_logits)
q_lo... | 53,097 |
def _total_exposure_op(habitat_arr, *num_denom_list):
"""Calculate the exposure score for a habitat layer from all stressors.
Add up all the numerators and denominators respectively, then divide
the total numerator by the total denominator on habitat pixels, to get
the final exposure or consequenc... | 53,098 |
def builtin_break(self, context, looping=False):
"""Break out of a number of loops."""
a = context.pop()
if not isinstance(a, BNum):
raise BTypeError(self, a)
av = int(a.simplify().value)
ctx = context
while av > 0 and ctx:
ctx.broken = True
if ctx.looping:
ctx.looping = False
av -= 1
ctx = ctx.pare... | 53,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.