content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_location(url):
"""
Parse latitude and longitude from a Google Maps URL.
URL is in the form:
https://maps.google.com/maps/ms?...&ll=9.029795,-83.299043&...
Sometimes there is a weird ll query param like this:
https://maps.google.com/maps/ms?...&ll=9.029795, -83.299043,255&..... | 5,311,200 |
def test_singleton_get_instance_preserves_state():
""" Changes to the Controller singleton should be preserved across calls to get_instance() """
settings = """
[system]
DEBUG = True
DEFAULT_LANGUAGE = en
[display]
BACKGROUND_COLOR = #000
TEXT_COLOR = orange
"""
config = configparser.ConfigParser()
co... | 5,311,201 |
def conv2d_zeros(name,
x,
width,
filter_size=[3, 3],
stride=[1, 1],
pad="SAME",
logscale_factor=3,
skip=1,
edge_bias=True):
"""Conv2dZeros is just a normal Conv2d layer with zero i... | 5,311,202 |
def deepcopy(value):
"""
The default copy.deepcopy seems to copy all objects and some are not
`copy-able`.
We only need to make sure the provided data is a copy per key, object does
not need to be copied.
"""
if not isinstance(value, (dict, list, tuple)):
return value
if isins... | 5,311,203 |
def delete_fragment_cache(model, request=None, **kwargs):
"""
Drops a fragment cache.
"""
key = make_fragment_key(model, request=None, **kwargs)
cache.delete(key) | 5,311,204 |
def split_delimited_symbol(symbol):
"""
Takes in a symbol that may be delimited and splits it in to a company
symbol and share class symbol. Also returns the fuzzy symbol, which is the
symbol without any fuzzy characters at all.
Parameters
----------
symbol : str
The possibly-delimi... | 5,311,205 |
def gravatar(email, size=48):
"""hacked from djangosnippets.org, but basically given an email address
render an img tag with the hashed up bits needed for leetness
omgwtfstillreading
"""
url = "http://www.gravatar.com/avatar.php?%s" % urllib.urlencode({
'gravatar_id': hashlib.md5(email).hex... | 5,311,206 |
def carli(
p0: np.array,
p1: np.array,
) -> float:
"""
Carli bilateral index, using price information.
.. math::
\\text{Carli} = \\frac{\\sum_{i=1}^{n} p_i}{\\sum_{i=1}^{n} p_0}
:param p0: Base price vector.
:param p1: Current price vector.
"""
return np.mean(p1 / p0) | 5,311,207 |
def format_outcome_results(outcome_results):
"""
Cleans up formatting of outcome_results DataFrame
:param outcome_results: outcome_results DataFrame
:return: Reformatted outcomes DataFrame
"""
new_col_names = {"links.learning_outcome": "outcome_id"}
outcome_results = outcome_results.rename(c... | 5,311,208 |
def infer(batch, model, lite, framework):
"""
Perform inference on supplied image batch.
Args:
batch: ndarray
Stack of preprocessed images
model: deep learning model
Initialized EfficientPose model to utilize (RT, I, II, III, IV, RT_Lite, I_Lite or II_Lite)
... | 5,311,209 |
def get_package_data(package):
"""
Return all files under the root package, that are not in a
package themselves.
"""
walk = [(dirpath.replace(package + os.sep, "", 1), filenames)
for dirpath, dirnames, filenames in os.walk(package)
if not os.path.exists(os.path.join(dirpath,... | 5,311,210 |
def xrdb(xrdb_file=None):
"""Merge the colors into the X db so new terminals use them."""
xrdb_file = xrdb_file or os.path.join(CACHE_DIR, "colors.Xresources")
if shutil.which("xrdb") and OS != "Darwin":
subprocess.Popen(["xrdb", "-merge", xrdb_file],
stdout=subprocess.DEVN... | 5,311,211 |
def delete_saved_search(search_name, owner):
"""Deletes an existing saved search. This is used when overwriting a saved search."""
try:
voyager_server = sys.argv[2].split('=')[1].split('solr')[0][:-1]
get_url = "{0}/api/rest/display/ssearch/export".format(voyager_server)
get_response = r... | 5,311,212 |
def AddUpdateMapFlags(parser, flag_name, long_name=None, key_type=None,
value_type=None):
"""Add flags for updating values of a map-of-atomic-values property.
Args:
parser: The argument parser
flag_name: The name for the property to be used in flag names
long_name: The name for th... | 5,311,213 |
def get_edges(t, p):
"""
Gets the edges (segments) that contain point p as their right
endpoint or in the interior
"""
lr = []
lc = []
for s in AVLTree(t):
if s.rp == p:
lr.append(s)
elif s.lp == p and s.status == INTERIOR:
lc.append(s)
elif si... | 5,311,214 |
def register_derived_unit(symbol, singular_name, base_unit, multiple=1, plural_name=None):
"""Registers a unit based on another unit.
i.e. it should be a measure of the same quantity."""
return register_unit(symbol, singular_name, base_unit.quantities,
base_unit.quantity_vector, mul... | 5,311,215 |
def soup(
url: str, *args, session: Optional[requests.Session] = None, **kwargs
) -> bs4.BeautifulSoup:
"""Get a url as a BeautifulSoup.
Args:
url: The url to get a soup from.
*args: Passed to session.get().
session: The session to use to download the soup.
Defaults to N... | 5,311,216 |
def _get_max_width():
"""Hamta information om total skarmbredd och -hojd
"""
from win32api import GetSystemMetrics
#Hamta information om total skarmbredd over alla anslutna skarmar
width = GetSystemMetrics(78)
#Hamta information om total skarmhojd over alla anslutna skarmar
height = GetSyste... | 5,311,217 |
def blog_queue(ch, method, props, body):
"""
declare the queue of direct exchange, flask-rabbitmq will bind automatically by key.
:param ch:
:param method:
:param props:
:param body:
:return:
"""
print("simple queue => {}".format(body))
ch.basic_ack(delivery_tag=method.delivery_t... | 5,311,218 |
def preprocess_stack_parallel(hier_graph_dict:dict,circuit_name,G):
"""
Preprocess the input graph by reducing parallel caps, series resistance, identify stacking, adding parallel transistors.
Parameters
----------
hier_graph_dict : dict
dictionary of all circuit in spice file
circuit_n... | 5,311,219 |
def main(argv):
"""
Main method that unfortunately is way too complicated.
"""
eqsFile, plotFile = parseProgramArgs(argv)
plotMonod() | 5,311,220 |
def test_that_client_id_is_created(unauth_client):
"""Test that the client id is created and properly formatted."""
assert unauth_client.client_id == 'test app; ver 0.0; Python SDK; 18.5; test machine;' | 5,311,221 |
def list_table_names():
"""List known table names from configuration, without namespace."""
return get_config().yaml['schemas'].keys() | 5,311,222 |
def execute_quantum_request(backend, quantum_request):
"""
Takes a quantum request and execute the content,
returns the messages for Alice and Bob.
"""
method = quantum_request["method"]
A_basis = quantum_request["A_basis"]
B_basis = quantum_request["B_basis"]
if method == "BB84":
... | 5,311,223 |
def test_linkify():
"""Optional Linkify flag controls linkification."""
# Linkify is also responsible for adding `nofollow` on all links
assert markdown(linkify_text) == linkify_html
assert markdown(linkify_text, linkify=True) == linkify_html
assert markdown(linkify_text, linkify=False) == nolinkify... | 5,311,224 |
def test_cmd_read_button():
"""Test that the CMD_READ_BUTTON."""
assert type(CMD_READ_BUTTON) is ReadCommand
assert CMD_READ_BUTTON.code == 8
assert CMD_READ_BUTTON.data_len == 4 | 5,311,225 |
def get_ResidualDemand(demand_sector):
"""loader function for parameter ResidualDemand
"""
return get_demand_sector_parameter("ResidualDemand",
demand_sector) | 5,311,226 |
def test_no_browsing_context(session, create_window):
"""
1. If the current top-level browsing context is no longer open,
return error with error code no such window.
"""
session.window_handle = create_window()
session.close()
response = get_window_rect(session)
assert_error(response, "... | 5,311,227 |
def parse_bar_separated_phrase(bar_separated_phrase):
"""
Parses a vertical bar separated phrase into a Phrase object.
The expect format is that used by e.g. the LCC:
Aber|KON es|PPER gibt|VVFIN keine|PIAT Garantie|NN
:param bar_separated_phrase:
:return:
"""
assert isinstance(bar... | 5,311,228 |
def preprocess(filename):
"""
Preprocesses the file at the specified name and returns only
the branching (conditional) lines in the dump, defined to have
(in the format specified for the offline dump versions):
1) Reads the flags register (that is, conditionRegister == 'R'), and
2) Is either tak... | 5,311,229 |
def load_paste_app(filename, appname):
"""Builds a wsgi app from a paste config, None if app not configured."""
filename = os.path.abspath(filename)
app = None
try:
app = deploy.loadapp("config:%s" % filename, name=appname)
except LookupError:
pass
return app | 5,311,230 |
def Hunter_Lab_to_XYZ(
Lab: ArrayLike,
XYZ_n: ArrayLike = TVS_ILLUMINANTS_HUNTERLAB[
"CIE 1931 2 Degree Standard Observer"
]["D65"].XYZ_n,
K_ab: ArrayLike = TVS_ILLUMINANTS_HUNTERLAB[
"CIE 1931 2 Degree Standard Observer"
]["D65"].K_ab,
) -> NDArray:
"""
Converts from *Hunter... | 5,311,231 |
def post_multipart(host, selector, fields, files):
"""
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return the server's re... | 5,311,232 |
def vfolder():
"""Set of vfolder operations""" | 5,311,233 |
def total_jurisdiction_columns_helper(df):
"""calculation to include private facility numbers"""
df["PVINF_Temp"] = df["PVINF"].apply(convert_nan_for_calculation)
df["PVOTHF_Temp"] = df["PVOTHF"].apply(convert_nan_for_calculation)
df["PVINM_Temp"] = df["PVINM"].apply(convert_nan_for_calculation)
df[... | 5,311,234 |
def client():
"""Static link to MongoDB connection."""
return AsyncIOMotorClient(URI) | 5,311,235 |
def mask_ring_median(values_array, positions_array, alpha): # pragma: no cover
"""Find outlier pixels in a single ring via a single pass with the median.
Parameters
----------
values_array : ndarray
The ring values
positions_array : ndarray
The positions of the values
alpha: fl... | 5,311,236 |
def _p_qrs_tconst(pattern, pwave):
"""
Temporal constraints of the P Wave wrt the corresponding QRS complex
"""
BASIC_TCONST(pattern, pwave)
obseq = pattern.obs_seq
idx = pattern.get_step(pwave)
tnet = pattern.last_tnet
# Beat start
tnet.set_equal(pwave.start, pattern.hypothesis.star... | 5,311,237 |
def drop_tables(engine, clobber=False):
"""Drops all tables from a SQLite database.
Creates an sa.schema.MetaData object reflecting the structure of the
database that the passed in ``engine`` refers to, and uses that schema to
drop all existing tables.
Todo:
Treat DB connection as a contex... | 5,311,238 |
def load_main_index(out_dir: Path=OUTPUT_DIR, warn: bool=True) -> List[Link]:
"""parse and load existing index with any new links from import_path merged in"""
from core.models import Snapshot
try:
return Snapshot.objects.all()
except (KeyboardInterrupt, SystemExit):
raise SystemExit(0) | 5,311,239 |
def upstream(env=env):
"""Get 'upstream' URL for the git repository."""
remotes = remotes('fetch')
# Try the remote tracking value for this branch
try:
upstream = subprocess.check_output(
['git', 'rev-parse', '--symbolic-full-name', '@{u}'], env=env,
).decode('utf-8').strip(... | 5,311,240 |
def ref_model_and_multivariate_training_data(training_data_covar_complex):
"""
defines a multivariate GP model and the data it is defined by
:return: covars
:return: train_X, train_Y (training data, from custom_models_simple_training_data_4elements above)
:return: model_obj (model object, SingleTask... | 5,311,241 |
def delete_dir_banner_file_after_model_deletion(sender, **kwargs):
"""
Delete the model file after the Directory has been deleted.
"""
directory = kwargs['instance']
if (
directory.banner_file is not None and len(directory.existing_banner_file.name) > 0 and
os.path.exists(directory.... | 5,311,242 |
async def test_calling_httpx(
unused_tcp_port: int, calculator_server_creator
) -> None:
"""Test the httpx client."""
serv = calculator_server_creator(AioRequest)
app = create_aiohttp_app(serv)
runner = AppRunner(app)
await runner.setup()
site = TCPSite(runner, port=unused_tcp_port)
awa... | 5,311,243 |
def get_all_movies(request):
"""
List of all movies names
"""
try:
name = request.GET.get('name', None)
offset = request.GET.get('offset', 0)
limit = request.GET.get('limit', 10)
movies_list = []
count = 0
if not name:
movies_list = Movie.objects.filter().order_by('-date_created')[offset:limit]
... | 5,311,244 |
def is_email_or_url(string: str) -> bool:
"""Checks if string is either an email or url.
"""
out = False
try:
URL_VALIDATOR(string)
out = True
except ValidationError:
pass
try:
URL_VALIDATOR(string)
out = True
except ValidationError:
pass
... | 5,311,245 |
def get_synthetic_preds(synthetic_data_func, n=1000, estimators={}):
"""Generate predictions for synthetic data using specified function (single simulation)
Args:
synthetic_data_func (function): synthetic data generation function
n (int, optional): number of samples
estimators (dict of ... | 5,311,246 |
def arrays_from_dataset(dataset):
"""Converts a tf.data.Dataset to nested np.ndarrays."""
return tf.nest.map_structure(
lambda tensor: np.asarray(tensor), # pylint: disable=unnecessary-lambda
tensors_from_dataset(dataset)) | 5,311,247 |
def ldns_buffer_status_ok(*args):
"""LDNS buffer."""
return _ldns.ldns_buffer_status_ok(*args) | 5,311,248 |
def parse_args() -> argparse.Namespace:
"""Parse command line arguments
:return: argparse.Namespace
"""
parser = argparse.ArgumentParser()
parser.add_argument('--log', dest='log', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
default='ERROR', help='Set the loggi... | 5,311,249 |
def test_binary_combinator_sub(f, ff):
"""Sub combinator should always intersperse '-' in the elements."""
assert str(comb.Sub(f, ff)) == "{0} - {1}".format(str(f), str(ff)) | 5,311,250 |
def upsample(img, scale, border='reflect'):
"""Bicubical upsample via **CONV2D**. Using PIL's kernel.
Args:
img: a tf tensor of 2/3/4-D.
scale: must be integer >= 2.
border: padding mode. Recommend to 'REFLECT'.
"""
device = img.device
kernels, s = _weights_upsample(scale)
kernels = [k.astype('... | 5,311,251 |
def first_round_phase(tableau, phase_stabilizer, phase_destabilizer):
"""This phase round adds a diagonal matrix D to the Z stabilizer matrix such that Z + D = M*M' for some
invertible M"""
num_qubits = int(len(tableau[0, :]) / 2)
x_destab = tableau[0:num_qubits, 0:num_qubits]
z_destab = tableau[0:n... | 5,311,252 |
async def read_address2account(address: PyAddress, cur: Cursor):
"""read account by address or raise exception"""
user = await read_address2userid(address, cur)
if user is None:
raise BlockChainError('Not found account {}'.format(address))
return await read_account_info(user, cur) | 5,311,253 |
def _get_ntddi(osvi):
"""
Determines the current operating system.
This function allows you to quickly tell apart major OS differences.
For more detailed information call L{kernel32.GetVersionEx} instead.
@note:
Wine reports itself as Windows XP 32 bits
(even if the Linux host is 64 ... | 5,311,254 |
def mel_dropout(mel: tf.Tensor, drop_prob: int = 0.05) -> tf.Tensor:
""" mel drop out
Args:
mel (tf.Tensor): [freq, time] float32, float32
drop_prob (int, optional): keep prob. Defaults to 0.05.
Returns:
tf.Tensor: [freq, time] float32, float32
"""
return tf.nn.dropout(mel, rate=1 - drop_prob) | 5,311,255 |
def getPortableIpRangeServices(config):
""" Reads config values related to portable ip and fills up
services accordingly"""
services = {}
attributeError = False
if config.portableIpRange.startip:
services["startip"] = config.portableIpRange.startip
else:
attributeError = True
... | 5,311,256 |
def function_timer(func):
"""This is a timer decorator when defining a function if you want that function to
be timed then add `@function_timer` before the `def` statement and it'll time the
function
Arguments:
func {function} -- it takes a function for this decorator to work
Returns:
... | 5,311,257 |
def load_graph(filename):
"""Unpersists graph from file as default graph."""
with tf.gfile.FastGFile(filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='') | 5,311,258 |
def print_defaults(type):
""" Print default configurations that can be used as a template.
:param type: If "list" is used as the TYPE, the list of supported
types will be printed.
"""
pass | 5,311,259 |
def provision_web_packages():
"""
Installs required software packages on a newly provisioned web instance.
"""
packages = ('libjpeg-dev nginx supervisor xclip zip libmysqlclient-dev uwsgi-plugin-python')
provision_packages(packages) | 5,311,260 |
def breadcrumbs(category):
"""
Renders a category tree path using a customizable delimiter.
Usage::
{% breadcrumbs <category> %}
Example::
{% breadcrumbs category %}
"""
return {'ancestors': category.get_ancestors()} | 5,311,261 |
def resnext34(**kwargs):
"""Constructs a ResNeXt-34 model.
"""
model = ResNeXt(BasicBlockX, [3, 4, 6, 3], **kwargs).cuda()
name = "resnext34"
return model, name | 5,311,262 |
def parse_coords(lines: Iterable[str]) -> Iterator[tuple[Coord, Coord]]:
"""
>>> lines = ["795,887 -> 541,887"]
>>> list(parse_coords(lines))
[(Coord(x=795, y=887), Coord(x=541, y=887))]
"""
for line in lines:
result = cast(parse.Result, line_format.parse(line))
yield Coord(resul... | 5,311,263 |
def _draw_latex_header(table, drop_columns):
"""Draw the Latex header.
- Applies header border if appropriate.
Example Output:
\hline
Name & Age & Nickname \\
\hline
"""
out = ""
if table._has_border():
out += _indent_text("\\hline\n", 3)
# Drop header colu... | 5,311,264 |
def register():
"""Register a new user, and send them a confirmation email."""
form = RegistrationForm()
if form.validate_on_submit():
user = User(
first_name=form.first_name.data,
last_name=form.last_name.data,
email=form.email.data,
confirmed=True,
... | 5,311,265 |
def combine_results_dicts(results_summaries: List[dict]) -> dict:
"""For a list of dictionaries, each with keys 0..n-1,
combine into a single dictionary with keys 0..ntot-1"""
combined_summary = {}
n_overall = 0
for d in results_summaries:
n_this = len(d)
for i in range(n_this):
... | 5,311,266 |
def test_calculate_score_empty(empty_repo):
"""
Test calculate_actvitiy if no data is available
"""
assert calculate_score(empty_repo) == 0 | 5,311,267 |
def svc_get_objects_in_collection(database, collection):
"""
Get objects from a collection.
These forms of query strings are supported
* No query string implies all objects in a collection are returned
* A query string with a single "query_string" parameter results in the value of this parameter bei... | 5,311,268 |
def save_trks(filename, lineages, raw, tracked):
"""Deprecated
Copied from deepcell_tracking.utils, version 0.3.1. Author Van Valen Lab.
Modification: changed trks to trk to fit caliban labeler.
Saves raw, tracked, and lineage data into one trk_file.
Args:
filename (str): full path to the ... | 5,311,269 |
def conv_model(features, labels, mode):
"""2-layer convolution model."""
# Reshape feature to 4d tensor with 2nd and 3rd dimensions being
# image width and height final dimension being the number of color channels.
feature = tf.reshape(features[X_FEATURE], [-1, 28, 28, 1])
# First conv layer will compute 32 ... | 5,311,270 |
def MapColoringCSP(colors, neighbors):
"""Make a CSP for the problem of coloring a map with different colors
for any two adjacent regions. Arguments are a list of colors, and a
dict of {region: [neighbor,...]} entries. This dict may also be
specified as a string of the form defined by parse_neighbors.""... | 5,311,271 |
def direction_resend_n3(limit):
"""
Вернуть:
Направления, в к-рых все исследования подтверждены, и подтверждены после определенной даты
в SQL:
"""
with connection.cursor() as cursor:
cursor.execute(
"""
SELECT id FROM public.directions_napravleniya
WHERE ... | 5,311,272 |
def StringToId(peg_positions):
""" input a list of strings representing peg positions
returns the game bitfield as integer number
"""
my_string = [''] * 36
cur_pos = 0
cur_bitfield = 0
for row in ['A', 'B', 'C', 'D', 'E', 'F']:
for col in ['1', '2', '3', '4', '5', '... | 5,311,273 |
def hide(obj):
"""Convert object to hidden task.
"""
converted_object = convert(obj, Hidden=True)
return converted_object | 5,311,274 |
def copy_model_files(controlfile, dirname):
"""Create subdirectory and copy relevant model files to it,
then change working directory to subdirectory"""
os.makedirs(dirname, exist_ok=True)
# Copy needed files from the working directory into the sub-directory
for file in ['model', 'payoff', 'opt... | 5,311,275 |
def summary(filename=None):
"""Print a summary table for all timers or write CSV to filename."""
Timer.summary(filename) | 5,311,276 |
def trim_prediction(
data,
prediction_days,
history_days=CREST_RANGE
):
"""trim predicted dataframe into shape for results
Args:
data (:obj:`pandas.DataFrame`): data reported
history_days (int): number of days BACK to report
prediction_days (int): number of days ... | 5,311,277 |
def series_simple_math(
ser: pd.Series, function: str, number: int
) -> pd.core.series.Series:
"""Write some simple math helper functions for series.
Take the given series, perfrom the required operation and
return the new series.
For example. Give the series:
0 0
1 1
... | 5,311,278 |
def _gl_matrix(array):
"""
Convert a sane numpy transformation matrix (row major, (4,4))
to an stupid GLfloat transformation matrix (column major, (16,))
"""
a = np.array(array).T.reshape(-1)
return (gl.GLfloat * len(a))(*a) | 5,311,279 |
def create_vshieldr_controller(vmm_domp, provider, vcenter_domain, controller, host_or_ip, **args):
"""Create vShield Controller"""
args = args['optional_args'] if 'optional_args' in args.keys() else args
vmm_ctrlrp = CtrlrP(vmm_domp, controller,
hostOrIp=host_or_ip,
... | 5,311,280 |
def get_all_by_type_and_status(
*, db_session, service_type: str, is_active: bool
) -> List[Optional[Service]]:
"""Gets services by type and status."""
return (
db_session.query(Service)
.filter(Service.type == service_type)
.filter(Service.is_active.is_(is_active))
.all()
... | 5,311,281 |
def wkt_to_proj4(wkt):
"""Converts a well-known text string to a pyproj.Proj object"""
srs = osgeo.osr.SpatialReference()
srs.ImportFromWkt(wkt)
return pyproj.Proj(str(srs.ExportToProj4())) | 5,311,282 |
def runtime_expand1(bindings, filename, tree):
"""Macro-expand an AST value `tree` at run time, once. Run-time part of `expand1r`.
`bindings` and `filename` are as in `mcpyrate.core.BaseMacroExpander`.
Convenient for experimenting with quoted code in the REPL.
"""
expander = MacroExpander(bindings... | 5,311,283 |
def elasticnet(exprDF, lMirUser = None, lGeneUser = None, n_core = 2):
"""
Function to calculate the ElasticNet correlation coefficient
of each pair of miRNA-mRNA, return a matrix of correlation coefficients
with columns are miRNAs and rows are mRNAs.
Args:
exprDF df Concat Dataframe ... | 5,311,284 |
def test_delete_course(mocker):
"""
Tests that delete_course calls the delete tasks for the course and its content files
"""
patched_delete_task = mocker.patch("search.task_helpers.delete_document")
course = CourseFactory.create()
course_es_id = gen_course_id(course.platform, course.course_id)
... | 5,311,285 |
def get_batch_unpack(args): # arguments dictionary
""" Pass through function for unpacking get_batch arguments.
Args:
args: Arguments dictionary
Returns:
Return value of get_batch.
"""
# unpack args values and call get_batch
return get_batch(tensors=args['tensors'],
... | 5,311,286 |
def options():
"""
The options page provides an initial means to the user
to navigate to the required service.
""" | 5,311,287 |
async def test_setup_course_hook_calls_normalize_strings(
auth_state_dict,
setup_course_environ,
setup_course_hook_environ,
make_mock_request_handler,
make_http_response,
mock_nbhelper,
):
"""
Does the setup_course_hook return normalized strings for the username and the course_id?
""... | 5,311,288 |
def MakeDirs(path):
"""Make directories without raising errors when they already exist."""
if not os.path.exists(path):
os.makedirs(path) | 5,311,289 |
def simple_unlimited_args(one, two='hi', *args):
"""Expected simple_unlimited_args __doc__"""
return "simple_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args))) | 5,311,290 |
def _random_subset(seq, m, rng):
"""
Return m unique elements from seq.
This differs from random.sample which can return repeated
elements if seq holds repeated elements.
Taken from networkx.generators.random_graphs
"""
targets = set()
while len(targets) < m:
x = rng.choice(seq... | 5,311,291 |
def rnn_forward(x, nb_units, nb_layers, rnn_type, name, drop_rate=0., i=0, activation='tanh', return_sequences=False):
"""Multi-RNN layers.
Parameters
----------
nb_units: int, the dimensionality of the output space for
recurrent neural network.
nb_layers: int, the number of the layers for ... | 5,311,292 |
def write_file(filename, content):
"""Write a file to disk."""
dirname = os.path.dirname(filename)
if not os.path.isdir(dirname):
os.makedirs(dirname)
with open(filename, 'wb') as f:
f.write(content.encode('utf-8')) | 5,311,293 |
def test_column_type_instantiation():
"""If a bloop.Type subclass is provided, Column calls __init__ with no args"""
# noinspection PyAbstractClass
class MyType(Type):
def __init__(self, *args, **kwargs):
assert not args
assert not kwargs
super().__init__()
c... | 5,311,294 |
def lambda_handler(*kwargs):
""" Lambda handler for usercount
:param event: Lambda event
:param context: Lambda context
"""
print kwargs[0].get('account')
function_name = kwargs[1].function_name
account = kwargs[0].get('account')
results = get_user_count(function_name, account)
body ... | 5,311,295 |
def test_vis_mask_alpha_0() -> None:
"""
By setting alpha to zero, we do not modify the RGB image.
"""
rgb_img = np.zeros((2,3,3), dtype=np.uint8)
rgb_img[:,:,0] = np.array([[100,100,100],[200,200,200]], dtype=np.uint8)
mask_img = np.array([[0,1,0],[1,1,1]], dtype=np.uint8)
col = np.array([60,0,0], dtype=np.uint... | 5,311,296 |
def test_affinity_vs_matlab():
"""Test that the affinity calculation matches the matlab result"""
matlab = io.loadmat(TEST_DATA)
D = np.sqrt(matlab['S']) # matlab outputs squared distances
A_matlab = matlab['A']
radius = matlab['rad'][0]
# check dense affinity computation
A_dense = comput... | 5,311,297 |
def notebook_is_active() -> bool:
"""Return if script is executing in a IPython notebook (e.g. Jupyter notebook)"""
for x in sys.modules:
if x.lower() == 'ipykernel':
return True
return False | 5,311,298 |
def test_create_item_auction():
"""
Testing to create an auction item.
This is an item with postal code.
This item uses open_days instead of list_time and closing_time.
"""
data = {
'category_id': category_id,
'condition': 'weak',
'delivery_methods': ['pickup', 'shipment'... | 5,311,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.