content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def file_exists(file):
"""Check if a file exists."""
if not os.path.exists(file):
return False
try:
open(file).close()
except IOError:
return False
return True | 5,289,300 |
def save_polygon_data_format(naptan_polygon,
area_name,
naptan_column):
"""[summary] saves naptan polygon data, into a variety of formats for later
usage by other analytical tools.
Args:
naptan_polygon ([type]): [description]
area_na... | 5,289,301 |
def run_step(context):
"""Echo input to output. Input context['echoMe'].
Args:
context: dictionary-like. context is mandatory.
context must contain key 'echoMe'
context['echoMe'] will echo the value to logger.
This logger could well be stdout.
Whe... | 5,289,302 |
def fit_all_random(X_matr, rand_X_matr, Y_matr, rows, lag, fit_method, save_prefix=None, save_XY=True, verbose=False,
has_reps=False, bootstrap=False, seed=None, only_array=False, **kwargs):
"""
X_matr: m x T (x r) of X's
rand_X_matr: m x T ( x r) of X's. Same as X_matr except each row (within e... | 5,289,303 |
async def async_unlock(hass, entity_id=None, code=None):
"""Lock all or specified locks."""
data = {}
if code:
data[ATTR_CODE] = code
if entity_id:
data[ATTR_ENTITY_ID] = entity_id
await hass.services.async_call(DOMAIN, SERVICE_UNLOCK, data, blocking=True) | 5,289,304 |
def test_warn(fn):
"""Checks if calling train functions outside of session raises warning."""
with pytest.warns(UserWarning) as record:
fn()
assert fn.__name__ in record[0].message.args[0]
reset_log_once_with_str(fn.__name__) | 5,289,305 |
def check_bad_bbox(data, test_op, invalid_bbox_type, expected_error):
"""
:param data: de object detection pipeline
:param test_op: Augmentation Op to test on image
:param invalid_bbox_type: type of bad box
:param expected_error: error expected to get due to bad box
:return: None
"""
de... | 5,289,306 |
def check_patch_in_bounds(x, y, X_dim, Y_dim):
""" Usage: TrueFalse = check_patch_in_bounds(x, y, X_dim, Y_dim)
determine if the box is within the image
Args:
x: a tuple, list or array (x_start, x_end)
y: a tuple, list or array (y_start, Y_end)
... | 5,289,307 |
def _tiger_line_url(geometry, year):
"""
Return URL (or URLs) of zip file(s) containing shape files
for a given census geography
:param geometry: name of census geometry to download
:param year: year of geometry to download
:return: List of URLs
"""
base = "https://www2.census.gov/geo/t... | 5,289,308 |
def get_coordinate_transformation(source_sr, target_sr):
"""This function takes a source and target spatial reference and creates
a coordinate transformation from source to target, and one from target
to source.
source_sr - A spatial reference
target_sr - A spatial reference
... | 5,289,309 |
def d_customer_orders():
"""
Real Name: b'D Customer Orders'
Original Eqn: b'W Indicated Orders'
Units: b''
Limits: (None, None)
Type: component
b''
"""
return w_indicated_orders() | 5,289,310 |
def test_package_version() -> None:
"""Test that we can read the package version."""
assert __version__ is not None | 5,289,311 |
def build_reservations_ical_file(reservations):
"""
Return iCalendar file containing given reservations
"""
cal = Calendar()
cal['X-WR-CALNAME'] = vText('RESPA')
cal['name'] = vText('RESPA')
for reservation in reservations:
event = Event()
event['uid'] = 'respa_reservation_{... | 5,289,312 |
def domain(request) -> str:
"""Return AWS domain"""
return request.config.getoption("--domain") or "amazonaws.com" | 5,289,313 |
def sha2_384(data: bytes) -> hashes.MessageDigest:
"""
Convenience function to hash a message.
"""
return CryptographyHash.hash(hashes.sha2_384(), data) | 5,289,314 |
def build_corpus(group):
"""
Function to apply to a category subset. Returns a list of LabeledSentences to train doc2vec.
"""
return group.apply(lambda row: LabeledSentence(row.clean_comment, [row.sentence_tag]), axis=1).values | 5,289,315 |
def get_substitutions_from_config(config):
"""
Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error will be thrown.
... | 5,289,316 |
def signature(text):
"""
This helper method normalizes text and takes the SHA1 hash of it,
returning the base64 encoded result. The normalization method includes
the removal of punctuation and white space as well as making the case
completely lowercase. These signatures will help us discover textual... | 5,289,317 |
def index_finance_daily(ids, **kw):
"""
Bug 748015
Takes a list of Contribution ids and uses its addon and date fields to
index stats for that day.
Contribution stats by addon-date unique pair. Uses a nested
dictionary to not index duplicate contribution with same addon/date
pairs. For each... | 5,289,318 |
def no_stderr():
"""
There is no standard error
"""
with app.app_context():
return jsonify({'error':'stderr does not exist'}), 400 | 5,289,319 |
def compute_colors_for_labels(labels):
"""
Simple function that adds fixed colors depending on the class
"""
palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
colors = labels[:, None] *palette # self.palette
colors = (colors % 255).numpy().astype("uint8")
return color... | 5,289,320 |
def set_instance_from_metadata(esh_driver, core_instance):
"""
NOT BEING USED ANYMORE.. DEPRECATED..
"""
# Fixes Dep. loop - Do not remove
from api.serializers import InstanceSerializer
# Breakout for drivers (Eucalyptus) that don't support metadata
if not hasattr(esh_driver._connection, 'ex... | 5,289,321 |
def read_table(data, coerce_type, transpose=False):
"""
Reads in data from a simple table and forces it to be a particular type
This is a helper function that allows data to be easily constained in a
simple script
::return: a dictionary of with the keys being a tuple of the strings
in the fi... | 5,289,322 |
def load_def_omni(tint, cfg, data_path):
"""Loads Density Energy Flux spectrum
Parameters
----------
tint : list of str
Time interval
cfg : dict
Hash table from configuration file.
Returns
-------
"""
ic = np.arange(1, 5)
suf = "fpi_{}_{}".format(cfg["data_r... | 5,289,323 |
def usage():
""" print program usage """
print("Usage: %s <spec.table> <file.cpp>" % sys.argv[0]) | 5,289,324 |
def test_constant():
""" Test a tesorflow session """
sess = tf.Session()
first = tf.constant(4)
second = tf.constant(5)
return sess.run(first * second) | 5,289,325 |
def robots():
"""Robot Crawler txt for search engines."""
if current_app.config['STATIC_ROUTES'].get('robots', None):
response = make_response(
render_template(
template_path(current_app.config['STATIC_ROUTES']['robots'])
)
)
response.headers['Cont... | 5,289,326 |
def parameter_parser():
"""
A method to parse up command line parameters. By default it trains on the PubMed dataset.
The default hyperparameters give a good quality representation without grid search.
"""
parser = argparse.ArgumentParser(description = "Run .")
parser.add_argument("--edge-path... | 5,289,327 |
def RunScriptForAllFiles(scriptF, fNm, Is_Cluster=False, Inpts=None):
"""
Run a script in all files in in some list (fNm)
?? Update to run on selected/all files within the library? (so, get rid of fNm input?) ??
TO DO: allow substitutions at particular lines of the script file? This would allow different script be... | 5,289,328 |
def cat_arg_and_value(arg_name, value):
"""Concatenate a command line argument and its value
This function returns ``arg_name`` and ``value
concatenated in the best possible way for a command
line execution, namely:
- if arg_name starts with `--` (e.g. `--arg`):
`arg_name=value` is returned (... | 5,289,329 |
def configure_oob_ip_intf(if_name, startup_file):
"""
configure the OOB interfaces with vpn instance: "mgmt" -> needed if in-band mgmt interfaces
overlaps with the OOB interface (will be removed at day 2)
:param if_name: corresponding interfaces of the index ID as str()
:param startup_file: startup... | 5,289,330 |
def is_expired_dds_response(response):
"""
Check status_code of the response for the two values denoting expired URLs
:param response: requests.Response
:return: bool: True when the response is expired status
"""
return response.status_code == SWIFT_EXPIRED_STATUS_CODE or response.status_code ==... | 5,289,331 |
def make_backup_file(fname):
"""
Ensure an existing file L{fname} will not be overwritten by moving it out
of the way.
@param fname: Filename to move out of the way.
@type fname: C{str}
"""
if fname == '/dev/null': # No need to make a backup of /dev/null
return
bak_name = fna... | 5,289,332 |
def write_session(prev_sessions, sessions, start_time, end_time, session_path, logger=structlog.get_logger()):
"""
Rewrite json file with new data
:param prev_sessions: old sessions
:param sessions: new sessions
:param time: timestamp of processed flows
:param session_path: path to json file
... | 5,289,333 |
def test_create_PatchClamp(data_pool):
"""Test that we can create a PatchClamp object manually."""
pc = data_pool.get_patch_clamp()
assert isinstance(pc, PatchClamp) | 5,289,334 |
def remove_formatting(input: str) -> str:
"""Remove color information from string."""
return input.replace(bcolors.ENDC, "")\
.replace(bcolors.OKGREEN, "")\
.replace(bcolors.OKBLUE, "") | 5,289,335 |
def update_event(request, event_id):
"""Event update view.
If the request type is POST, update the event and redirect the user to the
events detail page. Otherwise, display the event creation form.
Arguments:
request - Django object containing request information.
event_id (int) - ID of Event ... | 5,289,336 |
def poly_linear_constraints(p, d):
"""
Given p = [p1, ..., pm] in k[t]^m and d in k[t], return
q = [q1, ..., qm] in k[t]^m and a matrix M with entries in k such
that Sum(ci*pi, (i, 1, m)), for c1, ..., cm in k, is divisible
by d if and only if (c1, ..., cm) is a solution of Mx = 0, in
which case... | 5,289,337 |
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
step_unit = 1000.0 # 1024?
results=[]
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
results.append("%3.2f %s" % (num, x))
num /= step_unit
return results | 5,289,338 |
def add_lo_ipaddr(nflink, ip_addr, prefix_len):
"""Add an ipv4 address to loopback interface.
Add an ipv4 address to loopback provided that it does not already exist.
Args:
nflink: a pyroute2.IPRoute() object/NFLINK connection
ip_addr (str): IP address
prefix_len (int): prefix leng... | 5,289,339 |
def force_json_in():
"""A version of jsontools.json_in that forces all requests to be interpreted as JSON."""
request = cherrypy.serving.request
if not request.headers.get('Content-Length', ''):
raise cherrypy.HTTPError(411)
if cherrypy.request.method in ('POST', 'PUT'):
body = request.... | 5,289,340 |
def comment_is_liked(comment_entity, liker):
"""Returns true if a given user (liker) has liked a given comment"""
likes_query = CommentLike.all()
likes_query.filter('liker =', liker)
likes_query.filter('comment =', comment_entity)
return likes_query.count() > 0 | 5,289,341 |
def GetRenderView(connection=None):
"""Return the render view in use. If more than one render view is in
use, return the first one."""
if not connection:
connection = ActiveConnection
render_module = None
for aProxy in ProxyManager().NewConnectionIterator(connection):
if aProxy.IsA... | 5,289,342 |
def disable_source(
config_map: Optional[ConfigMapDisableSource] = None,
) -> DisableSource:
"""
Points at a thing that can control whether something is disabled
Args:
config_map: This DisableSource is controlled by a ConfigMap
"""
pass | 5,289,343 |
def get_fuzzer_name(fuzzer_config_filename: str) -> str:
"""Get the fuzzer specified in fuzzer_config_filename"""
fuzzer_config = yaml_utils.read(get_fuzzer_configs_dir() /
fuzzer_config_filename)
# Multiple configurations of the same fuzzer are differentiated by their
... | 5,289,344 |
def colorize_mask(mask, color_map=None):
"""
Attaches a color palette to a PIL image. So long as the image is saved as a PNG, it will render visibly using the
provided color map.
:param mask: PIL image whose values are only 0 to 4 inclusive
:param color_map: np.ndarray or list of 3-tuples with 5 row... | 5,289,345 |
def test_pass_filter_and_match_filename(flake8dir):
"""Verify that no violations are raised when a file passes the filter and matches the desired filename."""
# Setup
flake8dir.make_setup_cfg(config)
flake8dir.make_file('test_File-10.py', 'import sys')
# Test
result = flake8dir.run_flake8(extr... | 5,289,346 |
def langs():
"""
Get list of both src and target languages
"""
html = requests.get(settings.site_url).content
crawl_soup = bs4.BeautifulSoup(html, 'html.parser')
langs = []
lang_id = 0
tags = crawl_soup.find('select').find_all('option')
for tag in tags:
name = tag['value']
... | 5,289,347 |
def watch_directory(path, magic_string, extension):
"""
Controller function.
Scans files in target directory, calls functions to monitor new and removed
files, calls function to look for "magic text" if target files have been
updated. Updates local memory's reference to last known line where
"m... | 5,289,348 |
def _remove_source_from_views(source_group):
"""
Remove a source group from all views.
"""
for view in commands.viewNodes():
view_inputs = commands.nodeConnections(view)[0]
if source_group in view_inputs:
view_inputs.remove(source_group)
commands.setNodeInputs(vie... | 5,289,349 |
def do_equalization(fileIn, fileOut):
"""
Эквализация (выравнивание) сигнала.
Параметры:
fileIn - имя входного файла. Тип - str.
fileOut - имя выходного файла. Тип - str.
"""
data = pd.read_csv(fileIn, index_col=0, dtype=np.double)
ep = {}
for key in data.keys():... | 5,289,350 |
def dummy_pipeline_measurements_vaex() -> vaex.dataframe.DataFrame:
"""
A dummy pipeline measurements dataframe, as a vaex dataframe.
Loaded from the test data directory.
Returns:
The dummy pipeline measurements vaex dataframe.
"""
filepath = TEST_DATA_DIR / 'test_measurements_vaex.csv... | 5,289,351 |
def _extract_messages(full_file, results, key, args):
"""
This extracts error and warning messages from the sting buffer full_file.
"""
err_warn_patterns = [("%s_errors" % key, r"^Error: .*"),
("%s_errors" % key, r"^ERROR: .*"),
("%s_errors" % key, r"^.*... | 5,289,352 |
def publisher(handler):
""" Decorator that will publish messages to SNS Topics. This decorator looks for a 'messages'
key in the result of the wrapper decorator. It expects result['messages'] to be a dict where
key is Topic Name or ARN and value is the message to be sent. It will publish each message to
... | 5,289,353 |
def unwrap_obj(obj):
""" Gets the actual object from a decorated or wrapped function
@obj: (#object) the object to unwrap
"""
try:
obj = obj.fget
except (AttributeError, TypeError):
pass
try:
# Cached properties
if obj.func.__doc__ == obj.__doc__:
... | 5,289,354 |
def get_user(user_id) -> dict:
"""
Used only in record_to_dict and user_setting.
"""
user = (
db.session.query(Users.username, Users.name, Users.classnum, Users.email)
.filter_by(id=user_id)
.first()
)
return {
"username": user.username,
"name": user.name,... | 5,289,355 |
def isolines(location, **kwargs):
"""
:param location: an address string, or a shapely geometry
the source location
:param graph: NetworkX graph
:param edges: geopandas GeoDataFrame
:param edge_idcol: string
id attribute/column name of the graph/edges GeoDataFrame (default is 'id')
:para... | 5,289,356 |
def delete_item(bucketlist_id, item_id):
"""
Deletes a bucketlist item
:param bucketlist_id:
:param item_id:
:return:
"""
item = get_item(bucketlist_id, item_id)
if not item or not get_bucketlist(bucketlist_id):
return jsonify({
'message': 'Bucketlist item not found.... | 5,289,357 |
def predict_on_atom_efs(param):
"""Predict the local energy, forces, and partial stresses and predictive
variances of a chemical environment."""
structure, atom, gp = param
chemenv = AtomicEnvironment(structure, atom, gp.cutoffs)
return gp.predict_efs(chemenv) | 5,289,358 |
def import_data(jsonfile):
"""Load JSON, parse it into Datastore Entity object."""
with open(jsonfile, "r") as infile:
result = json.load(infile)
for item in result:
entity = item["entity"]
kind = entity["key"]["path"][0]["kind"]
key = DATASTORE_CLIENT.key(kind)
entr... | 5,289,359 |
def get_export_info(archive_name):
"""
Given a file or directory, extract it and return information that will be used in
an export printout: the basename of the file, the name stripped of its extension, and
our best guess (based on Slack's current naming convention) of the name of the
workspace that... | 5,289,360 |
def call_var42127803hap(bamfile, cnvtag, base_db):
"""
Call haplotype with regard to g.42127803C>T and g.42127941G>A
"""
diff_haplotype = False
if cnvtag == "cn2":
haplotype_per_read = get_haplotypes_from_bam_single_region(
bamfile, base_db, range(len(base_db.dsnp1))
)
... | 5,289,361 |
def enforce_rbc(pos, vel, box_vector, dt) -> None:
"""
Numba'd function to enforce reflecting boundary conditions.
Parameters
----------
pos: numpy.ndarray
Particles' positions.
vel : numpy.ndarray
Particles' velocities.
box_vector: numpy.ndarray
Box Dimensions.
... | 5,289,362 |
def closest_match(num,num_list):
"""
Finds the closest number to num in num_list.
:num: (float) a number
:num_list: (array of floats)
:returns: (float) the number in num_list closest to num
"""
diffs = np.abs(np.subtract(num,num_list))
return num_list[np.argmin(diffs)] | 5,289,363 |
def get_workspace(repo_context):
"""
Construct the workspace url from the given repo context
:param repo_context: Repo context from context.py
:return: Workspace url for known VCS or None
"""
if not repo_context["repositoryUri"]:
return None
revision = repo_context.get("revisionId",... | 5,289,364 |
def get_wavelet(wavelet_name, dtype=tf.float32):
"""
Get a wavelet based on the wavelets name.
Args:
wavelet_name (str): Name of the wavelet ('haar', 'db1', 'db2', 'db3' or 'db4').
Returns:
A wavelet object. If the wavelet name is not recognized, it returns None.
"""
wname = wa... | 5,289,365 |
def argToBoolean(value):
"""
Boolean-ish arguments that are passed through demisto.args() could be type bool or type string.
This command removes the guesswork and returns a value of type bool, regardless of the input value's type.
It will also return True for 'yes' and False for 'no'.
... | 5,289,366 |
def doscmd(cmd):
"""Execute a command."""
if flag_echo:
sys.stderr.write("executing: " + cmd + "\n")
if flag_dryrun:
return
return u.doscmd(cmd, True) | 5,289,367 |
def initialize_table(
nrows=0,
name: Optional[str] = None,
subj: Optional[str] = None,
set: Optional[str] = None,
path: Optional[str] = None,
) -> Document:
"""Initializes a docx file containing the Science Bowl header row.
Parameters
----------
nrows : int, optional
Number ... | 5,289,368 |
def plotlify_scatter_js(xy=None, x=None, y=None, xtag=None, ytag=None, description=""):
"""
Update the plot data in plotly format.
:param xy: x and y in a single structure.
:param description: The description of the plotly plot.
:param plot_type: The type of the plotly plot.
:return: A dictiona... | 5,289,369 |
def get_sequence_context_to_array_index_table(motif_size: int) \
-> Tuple[Dict[str, int], Dict[str, int]]:
""" Return dicts mapping sequence contexts to counter array indices
Parameters
----------
motif_size: int
size of motifs (e.g. 3 or 5 bp)
Returns
-------
Dict[str, str... | 5,289,370 |
def resizeAndCenterCubes(cubelist, over):
"""
Resize and center a cube based on the size of the biggest cube.
Based on https://stackoverflow.com/a/35751427/6571817
"""
# TODO(nat): DANGER: This does not update the relevant x and y keywords.
# That would be a good thing to implement.
# TODO(... | 5,289,371 |
def copy(source, destination):
"""
Copy files.
"""
shutil.copy(source, destination) | 5,289,372 |
def make_cover_image(im):
"""
Make a cover image.
That is, resize an image to be smaller than :py:data:`COVER_SIZE` if
necessary.
Parameters:
im: A sanpera ``Image``.
Returns:
*im*, if the image is smaller than :py:data:`COVER_SIZE`. Otherwise, a
new ``Image`` resized ... | 5,289,373 |
def uniqueCruiseIdentifier_exists(cruise_id):
""" Verify cruise identifier provided does not exist. Boolean result True if exists, else False.
"""
try:
try:
# If uframe returns a value, then cruise exists, otherwise it does not.
#value = uframe_get_cruise_by_subsite(cruise_id... | 5,289,374 |
async def info_bot(msg):
"""
Отправляет сообщеие в ЛС, удаляет сообщение с командой.
:param msg: сообщение
:return: сообщение в ЛС написавшему команду
"""
user = msg.message.author
await user.send(f'Привет, {user.id}\n'
f'я тут главый смотрящий Бот!:)\n'
... | 5,289,375 |
def plot_cmc(rank=None, tdr=None, similarityMatrix=None, truthMatrix=None, label=None, title=None, outfile=None, logscale=True, logy=False, figure=None, style=None, fontsize=None, xlabel='Rank', ylabel='Correct Retrieval Rate', legendSwap=False, errorbars=None, miny=0.0, color=None):
"""Generate cumulative match ch... | 5,289,376 |
def init_loguru(
fmt: str = "{time:YYYY-MM-DDTHH:mm:ss.SSS!UTC-3}Z {name} {level}: {message}",
level: Union[str, int] = "DEBUG",
enqueue: bool = False,
stream_on: bool = True,
file_on: bool = True,
file_fmt: Optional[str] = None,
# file_path: PathType = Path(__file__).absolute().parent / "lo... | 5,289,377 |
def operator(openshift):
"""Return operator pod object."""
def select_operator(apiobject):
return apiobject.get_label("app") == "apicast" and apiobject.get_label("control-plane") == "controller-manager"
project_name = settings["threescale"]["gateway"]["OperatorApicast"]['openshift']['project_name'... | 5,289,378 |
def addsuffixtodesc():
""" ==============
command: addsuffixtodesc
usage: work.py addsuffixtodesc mystr file1.cup
like addsuffixtoname but the string mystr is appended to the 'description' field of each waypoint in file1
the result is stored in the file file1_withsuffix.cup
this can be useful to labe... | 5,289,379 |
def retrieve_article(article, output_filename, clobber=False):
"""Download the journal article (preferred) or pre-print version
of the article provided, and save the PDF to disk.
Inputs
------
article : `Article` object
The article to retrieve.
output_filename : str
The filenam... | 5,289,380 |
def envelops(reg, target_reg):
"""Given a region and another target region, returns whether the region
is enveloped within the target region."""
return (target_reg.start <= reg.start < target_reg.end) \
and (target_reg.start <= reg.end < target_reg.end) | 5,289,381 |
def stats(request):
"""Show usage stats"""
if settings.WASCH_USE_LEGACY:
users_count = len(Users.select(Users.login).execute())
machines_count = len(
Waschmaschinen.select(Waschmaschinen.id).execute())
appointents_count = len(Termine.select(Termine.user).execute())
else:
... | 5,289,382 |
def _writeHorizAdvX(glyph, attrib):
"""
>>> from defcon import Glyph
>>> attrib = {}
>>> glyph = Glyph()
>>> glyph.width = 100
>>> _writeHorizAdvX(glyph, attrib)
>>> attrib
{'horiz-adv-x': '100'}
"""
assert glyph.width >= 0
attrib["horiz-adv-x"] = valueToString(glyph.width) | 5,289,383 |
def get_ror_inflows(aggregation_level: str, timestamps: pd.DatetimeIndex = None) -> pd.DataFrame:
"""Returns ROR inflows (per unit of installed power capacity) per NUTS or country in which it exists"""
return get_hydro_inflows(aggregation_level, 'ror', timestamps) | 5,289,384 |
def tfidf(s: pd.Series, max_features=None, min_df=1, max_df=1.0,) -> pd.DataFrame:
"""
Represent a text-based Pandas Series using TF-IDF.
Rows of the returned DataFrame represent documents whereas columns are
terms. The value in the cell document-term is the tfidf-value of the
term in this document... | 5,289,385 |
def get_EI(dim, sigmas, Ampl, nE, nI, alpha, **kwargs):
""" wrapper function for connectivity matrix
input:
dim: dimensionality, 1 or 2
sigmas: list or float of standard deviation of connectivity
Ampl: list or float of standard deviation of connectivity
nE: size of excitatory units
nI: size of inhibitory units... | 5,289,386 |
def download_celeba(data_path):
"""
Download and extract database
:param data_path:
"""
print("downloading celeba dataset")
database_name = 'celeba'
extract_path = data_path
save_path = f'{database_name}.zip'
if not os.path.exists(save_path):
with DLProgress(unit='B', unit_s... | 5,289,387 |
def include_filter(
include: MutableMapping[Any, Any],
target: MutableMapping[Any, Any]) -> MutableMapping[Any, Any]:
"""Filters target by tree structure in include.
Args:
include: Dict of keys from target to include. An empty dict matches all
values.
target: Target dict to apply filter to.
... | 5,289,388 |
def _local_pca(pca, args):
"""Create the local PCA object
"""
local_pca = PCA(pca, api=args.retrieve_api_)
kwargs = {}
if args.max_components:
kwargs.update({"max_components": args.max_components})
if args.variance_threshold:
kwargs.update({"variance_threshold": args.variance_th... | 5,289,389 |
def create_app(config_name):
"""
Creates Flask instance & initialize
Came from 'Use Application Factory' : http://slides.skien.cc/flask-hacks-and-best-practices/#7
:rtype: Flask
"""
app_ = Flask(__name__)
app_.config.from_pyfile(config_name)
cors.init_app(app_)
jwt.init_app(app_)
... | 5,289,390 |
def cv(model):
"""
A function to perform cross-validation on a model.
"""
(x_train, y_train), _ = get_metadata()
cv_score = cross_validate(model, x_train, y_train, cv=5,
scoring="neg_mean_squared_error", return_estimator=True,
retu... | 5,289,391 |
def formatContextChecks(cg, contextList, onFail):
"""Using the code generator 'cg', emit code to call 'onFail' if
any of the context objects in 'contextList' fails a check call."""
for context in contextList:
cg.format("""
if ({0}_ctx == NULL)
{1}
""", con... | 5,289,392 |
def analyze_data(fitsfn, observables_dir="", affine2d=None,
psf_offset_find_rotation = (0.0,0.0),
psf_offset_ff = None,
rotsearch_d=None,
set_pistons=None):
"""
returns: affine2d (measured or input),
... | 5,289,393 |
def _get_pb_likelihood(likelihood):
"""Convert protobuf Likelihood integer value to Likelihood enum.
:type likelihood: int
:param likelihood: Protobuf integer representing ``Likelihood``.
:rtype: :class:`~google.cloud.vision.likelihood.Likelihood`
:returns: Enum ``Likelihood`` converted from proto... | 5,289,394 |
def eval_loss(original, latent, decoder, loss_func=bce_loss):
"""
Example of a native Keras / Tensorflow function to be used with
pca_tests
"""
return loss_func(original, decoder.predict(latent)).numpy() | 5,289,395 |
def test_basic_in_cluster_migration(in_cluster_app, testdata):
"""Test a basic in-cluster migration."""
recipe_id = 'my_recipe'
in_cluster_app.config['SEARCH_INDEX_PREFIX'] = 'new-'
old_suffix = current_search.current_suffix
current_search._current_suffix = '-new'
records_mapping_file, mapping_f... | 5,289,396 |
def _CheckImageName(image_name):
"""Checks for a valid GCE image name."""
name_message = ('Name must start with a lowercase letter followed by up to '
'63 lowercase letters, numbers, or hyphens, and cannot end '
'with a hyphen.')
name_ok = True
valid_chars = string.digits + s... | 5,289,397 |
def test_item_recommend():
"""Test that KNN-item will recommend reasonable items."""
recommender = KNNRecommender(user_based=True)
utils.test_recommend_simple(recommender) | 5,289,398 |
def service_create(request, name, port, protocol):
"""Create service."""
params = {"name": name,
"port": port,
"protocol": protocol}
iotronicclient(request).service.create(**params) | 5,289,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.