content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def list_groups(UserPoolId=None, Limit=None, NextToken=None):
"""
Lists the groups associated with a user pool.
Requires developer credentials.
See also: AWS API Documentation
:example: response = client.list_groups(
UserPoolId='string',
Limit=123,
NextToken='string... | 5,298,400 |
def next_task():
"""
To fetch data at this endpoint:
$ curl -X GET localhost:8080/api/v0.1/task
"""
db = pybackend.database.Database(
project=app.config['cloud']['project'],
**app.config['cloud']['database'])
random_uri = random.choice(list(db.uris(kind='audio')))
audio_url... | 5,298,401 |
def get_last_ideas(json_data, d=1):
"""
Returns last ideas.
@param: json_data - List of ideas in JSON format.
@param: d - History length in days.
"""
selected_items = []
for item in json_data:
date = format_string_to_date(item['created'])
if date > datetime.datetime.now() - d... | 5,298,402 |
def _build_histogram_root_no_hessian(n_bins, binned_feature, all_gradients):
"""Special case for the root node
The root node has to find the split among all the samples from the
training set. binned_feature and all_gradients already have a consistent
ordering.
Hessians are not updated (used when h... | 5,298,403 |
def _handleBulletWidth(bulletText, style, maxWidths):
"""
work out bullet width and adjust maxWidths[0] if neccessary
"""
if bulletText:
if isinstance(bulletText, basestring):
bulletWidth = stringWidth(bulletText, style.bulletFontName, style.bulletFontSize)
else:
... | 5,298,404 |
def is_pipeline(item: Any) -> bool:
"""Returns whether 'item' is a pipeline."""
return isinstance(item, (MutableSequence, Tuple, Set)
and all(isinstance(i, Hashable) for i in item)) | 5,298,405 |
def cluster_state_circuit(bits):
"""Return a cluster state on the qubits in `bits`."""
circuit = cirq.Circuit()
circuit.append(cirq.H.on_each(bits))
for this_bit, next_bit in zip(bits, bits[1:] + [bits[0]]):
circuit.append(cirq.CZ(this_bit, next_bit))
return circuit | 5,298,406 |
def once(wrapped):
"""
Decorates a function that takes no arguments, ensuring it's only called once & that the result
is memoized. This function is greenlet safe.
"""
wrapped._once_called = False
wrapped._once_retval = None
lock = RLock()
@functools.wraps(wrapped)
def wrapper():
... | 5,298,407 |
def get_exposed_members(obj, only_exposed=True, as_lists=False, use_cache=True):
"""
Return public and exposed members of the given object's class.
You can also provide a class directly.
Private members are ignored no matter what (names starting with underscore).
If only_exposed is True, only m... | 5,298,408 |
def start_server():
"""Starts the webserver"""
webhook_port = "tcp:{}".format(config.webhook_port)
endpoints.serverFromString(reactor, webhook_port).listen(server.Site(Handler()))
log_message("Listening for requests on port: {}".format(config.webhook_port))
try:
reactor.run()
except Keyb... | 5,298,409 |
def remove_group_project(repo, groupid, username=None, namespace=None):
"""Remove the specified group from the project."""
if not pagure_config.get("ENABLE_USER_MNGT", True):
flask.abort(
404,
description="User management is not allowed in this "
"pagure instance",
... | 5,298,410 |
def get_residue_sequence_poly_seq(cf, align_seq=True, verbose=False):
"""
used to work with load_struct_from_pdbfile, now uses load_pdbfile output
:param structure:
:return:
"""
# residue_sequence = list(np.array([[residue.resname.capitalize(), int(residue.id[1])] for residue in
# ... | 5,298,411 |
def _demo_head_inputs(input_shape=(1, 512, 8, 8)):
"""Create a superset of inputs needed to run test or train batches.
Args:
input_shape (tuple):
input batch dimensions
"""
(N, C, H, W) = input_shape
rng = np.random.RandomState(0)
features = rng.rand(*input_shape)
tra... | 5,298,412 |
def load_ckp(checkpoint_fpath,model):
"""
checkpoint_path: path to save checkpoint
model: model that we want to load checkpoint parameters into
optimizer: optimizer we defined in previous training
"""
# load check point
# checkpoint = torch.load(checkpoint_fpath)
checkpoint = torc... | 5,298,413 |
def get_config_string(config):
"""
Use the given config to extract one string for the output.
:param config: a dictionary of configs from a Build object
:return: string representation
"""
configs = {}
for key, entry in config.items():
abbrev = entry.get('abbreviation')
value ... | 5,298,414 |
def wrap_rethink_generator_errors(f, *args, **kwargs):
"""
:param f:
:param args:
:param kwargs:
:return:
"""
try:
for data in f(*args, **kwargs):
yield data
except (r.errors.ReqlOpFailedError,
r.errors.ReqlError,
r.errors.ReqlDriverError) as ... | 5,298,415 |
def _api_shutdown(name, output, kwargs):
""" API: accepts output """
sabnzbd.shutdown_program()
return report(output) | 5,298,416 |
def test_run_shortcut_groups_str(mock_pipe, monkeypatch):
"""Run shortcut with str groups converting to list."""
shortcuts = {'arb pipe': {
'pipeline_name': 'sc pipe',
'groups': 'sc g'
}}
monkeypatch.setattr('pypyr.config.config.shortcuts', shortcuts)
out = run(pipeline_name='arb pi... | 5,298,417 |
def help_command(ctx, config_dump=False):
"""Print some information on the system environment."""
def banner(title):
"Helper"
click.echo('')
click.secho('~~~ {} ~~~'.format(title), fg='green', bg='black', bold=True)
if config_dump:
ctx.obj.cfg.dump()
sys.exit(0)
... | 5,298,418 |
def combine_loss_components(critic_loss_val, actor_loss_val, entropy_val,
actor_loss_weight, entropy_bonus):
"""Combine the components in the combined AWR loss."""
return critic_loss_val + (actor_loss_val * actor_loss_weight) - (
entropy_val * entropy_bonus) | 5,298,419 |
def train(train_loader, model, criterion, optimizer, epoch):
"""
Performs one epoch's training.
:param train_loader: DataLoader for training data
:param model: model
:param criterion: cross entropy loss layer
:param optimizer: optimizer
:param epoch: epoch number
"""
model.train() ... | 5,298,420 |
def country_filter() -> str:
""" find selected country to gather news from from config.json """
with open('config.json') as config_file:
data = json.load(config_file)
logging.info('Countries for news briefing located')
return data['news_briefing'][0]['country'] | 5,298,421 |
def get_env_agent_current(env = Depends(get_env)) -> str:
"""Returns name of currently expected agent."""
return env.agent_selection | 5,298,422 |
def exponential_backoff(attempt_num):
"""Returns an exponential backoff value in seconds."""
assert attempt_num >= 0
if random.random() < _PROBABILITY_OF_QUICK_COMEBACK:
# Randomly ask the bot to return quickly.
return 1.0
# If the user provided a max then use it, otherwise use default 60s.
max_wait ... | 5,298,423 |
def watchdog(timeout: int | float, function: Callable, *args, **kwargs) -> Any:
"""Time-limited execution for python function. TimeoutError raised if not finished during defined time.
Args:
timeout (int | float): Max time execution in seconds.
function (Callable): Function that will be evaluate... | 5,298,424 |
def ridgeline(ax, data, overlap=0, fill=True, fill_color="b", n_points=150):
"""
Adapted from https://glowingpython.blogspot.com/2020/03/ridgeline-plots-in-pure-matplotlib.html
"""
if overlap > 1 or overlap < 0:
raise ValueError('overlap must be in [0 1]')
xx = np.linspace(np.min(np.concaten... | 5,298,425 |
def make_notebook(template_file_name, tutorial_file_name=None, solution_file_name=None):
"""
Master function to create requested notebooks
"""
if tutorial_file_name is None and solution_file_name is None:
print "Nothing to do"
return
with open(template_file_name) as f:
... | 5,298,426 |
def test_AlignmentRecords_update(alignment_env):
""" Tests if a alignment record can be updated without breaking
hierarchial relations.
# C1: Check that specified record was dynamically created
# C2: Check that specified record has a composite key
# C3: Check that specified record was archived... | 5,298,427 |
def _stop_container(container):
"""
Force remove a container
"""
try:
logger.info(f'Stopping container {container.id}')
container.remove(force=True)
except:
pass
finally:
return True | 5,298,428 |
def _wmd(embedding_1, embedding_2, word_freq_1, word_freq_2, constraint_matrix=None):
"""
Calculate the Word mover´s Distance
parameters
---------
- embedding_1 : np.array (distinct words x embedding dimensions) -> embedding of the first article
- embedding_2 : np.a... | 5,298,429 |
def converter():
"""Bits to Target"""
bits = int(request.form['bits'], 16)
response = bits_to_target(bits)
return jsonify(response), 200 | 5,298,430 |
def _coerce_exceptions(function):
"""
Decorator that causes exceptions thrown by the decorated function
to be coerced into generic exceptions from the hadoop.fs.exceptions
module.
"""
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as e:
e.msg = force... | 5,298,431 |
def read_train_valid(filname):
"""
读取训练或者验证文件
:param filname: 训练集/验证集的文件名字
:return:
返回训练集的文本和标签
其中文本是一个list, 标签是一个list(每个元素为int)
返回示例:['我很开心', '你不是真正的快乐', '一切都是假的], [1, 0, 0]
"""
pass | 5,298,432 |
def decode_der(cert_der):
"""Decode cert DER string to Certificate object.
Args:
cert_der : Certificate as a DER encoded string
Returns:
cryptography.Certificate()
"""
return cryptography.x509.load_der_x509_certificate(
data=cert_der, backend=cryptography.hazmat.backends.defau... | 5,298,433 |
def find_threshold_by_precision(precisions, thresholds, p_cutoff):
"""This function finds the lowest index that guarantess a precision
of at leat p_cutoff."""
return thresholds[np.argmax(precisions >= p_cutoff)] | 5,298,434 |
def compare_vectors(phi, index1, index2):
"""
A function which compares the directions of two vectors given by polar co-ordinates.
The two vectors are identified as being in the same (or opposite) directions for x and y.
The returned array indicates which one of 4 possible alignments the two vecto... | 5,298,435 |
def test_runner_enabled_and_configuration_template_failure(monkeypatch):
"""
Test configured runner catches service configuration exception correctly
Trying to substitute a missing value into valid JSON template should be caught
"""
monkeypatch.setenv('DISCORD_ENABLE', 'True')
monkeypatch.seten... | 5,298,436 |
def cmplx(a,b,*vars):
"""
See VSIP specification for Information
Convert Convert real, imaginary (a,b) into complex
Usage:
cmplx(a,b,c)
where
a and b are views of type vview_f or vview_d
c is a compliant view of type cvview_f or cvview_d
OR:
c = cmplx(a,b)
... | 5,298,437 |
def pull(remote_path, local_path=None):
"""Download a file from the device.
Arguments:
remote_path(str): Path or directory of the file on the device.
local_path(str): Path to save the file to.
Uses the file's name by default.
Return:
The contents of the file.
Examp... | 5,298,438 |
def build_vtk_colormap(colormap, vtk_colormap=None) :
""" Build either a ``vtkLookupTable`` or a ``vtkColorTransferFunctionWithAlpha``
from the given colormap. The colormap is specified as a
custom table -- which must respect the formats of the dictionaries
defined in :func:`build_lookup... | 5,298,439 |
def _get_message_from_model(message_model):
"""Converts the FeedbackMessageModel to a FeedbackMessage.
Args:
message_model: FeedbackMessageModel. The FeedbackMessageModel to be
converted.
Returns:
FeedbackMessage. The resulting FeedbackMessage domain object.
"""
return ... | 5,298,440 |
def includeme(config):
""" Setup the dealer. """
settings = dict(DEFAULTS)
settings.update(dict(
(key.split('.', 1)[1], value)
for key, value in config.registry.settings.items()
if key.startswith('dealer.')
))
config.registry.settings['dealer'] = settings
config.registry.... | 5,298,441 |
def get_survey_ids():
"""
categoryIdを元に、予約データのsurveyIdを取得する
"""
command = []
command.append('aws')
command.append('dynamodb')
command.append('scan')
command.append('--table-name')
command.append(table_name_survey_results)
command.append('--profile')
command.append(... | 5,298,442 |
def list_tracker_issue_field_value(tracker_id: str, field: str, project=None):
"""
GET /api/tracker/{tracker_id}/issue_field/{issue_field_id}
:param tracker_id:
:param field:
:param project:
:return:
"""
try:
return {
'title': 'Succeed to list Issue Field Value from t... | 5,298,443 |
def isogenies_5_1728(E):
"""
Returns a list of 5-isogenies with domain ``E`` when the j-invariant is
1728.
OUTPUT:
(list) 5-isogenies with codomain E. In general these are
normalised; but if `-1` is a square then there are two
endomorphisms of degree `5`, for which the codomain is the sam... | 5,298,444 |
def _setup_ip_forwarding():
"""
Ensure that IP forwarding is enabled.
:return: None
"""
# Enable IP forwarding since all compute hosts are vRouters.
# IPv4 forwarding should be enabled already by docker.
try:
with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:
f.write("... | 5,298,445 |
def save_report_file(report_file_name, animals_list: List[Animal], output_format='excel'):
"""
Saves report file in CSV with needed data.
:param report_file_name:
:param animals_list:
:param output_format:
:return:
"""
now = datetime.now()
dt_of_fetching_data = now.strftime('%Y-%m-... | 5,298,446 |
def _parse_link(link: str) -> Any:
"""Parse rapid upload link
Format 1: cs3l://<content_md5>#<slice_md5>#<content_crc3>#<content_length>#<filename>
Format 2: <content_md5>#<slice_md5>#<content_length>#<filename>
Format 3: bdpan://{base64(<filename>|<content_length>|<content_md5>|<slice_md5>)}
Form... | 5,298,447 |
def change_zone_to_coordinates(changing_data, which=None):
"""
Change zone data into coordinate.
Get data with zone data and add coordinate data into original data. Last modified: 2019-11-24T22:19:49+0900
Args:
changing_data (DataFrame): Mandatory. The DataFrame which contains zone data.
... | 5,298,448 |
async def test_is_new_course_initiates_rolling_update(
setup_course_environ,
setup_course_hook_environ,
make_auth_state_dict,
make_http_response,
make_mock_request_handler,
mock_nbhelper,
):
"""
If the course is a new setup does it initiate a rolling update?
"""
local_authenticat... | 5,298,449 |
def create_unwarp_workflow(name="unwarp", fieldmap_pe=("y", "y-")):
"""Unwarp functional timeseries using reverse phase-blipped images."""
inputnode = Node(IdentityInterface(["timeseries", "fieldmap"]), "inputs")
# Calculate the shift field
# Note that setting readout_times to 1 will give a fine
# ... | 5,298,450 |
def test_list_unsigned_long_enumeration_4_nistxml_sv_iv_list_unsigned_long_enumeration_5_2(mode, save_output, output_format):
"""
Type list/unsignedLong is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/unsignedLong/Schema+Instance/NISTSchema-SV-IV-list-unsignedLong-... | 5,298,451 |
def main(dt=None):
"""Encodes the sample data-set.
Returns path to where sample data file was saved.
"""
if dt is None:
dt = datetime.datetime.now()
filepath = os.path.abspath(os.path.join(os.path.dirname(__file__), "..",
"sample.unk"))
encode_data(filepath, create_data(), ... | 5,298,452 |
def ramping_trajectory():
"""
Calculates the pearson coefficient for multiple durations.
Returns
-------
ramping_p : array
An array of log-odds for each duration.
"""
raise NotImplementedError | 5,298,453 |
def leadterm(e, x):
"""
Compute the leading term of the series.
Returns
=======
tuple
The leading term `c_0 w^{e_0}` of the series of `e` in terms
of the most rapidly varying subexpression `w` in form of
the pair ``(c0, e0)`` of Expr.
Examples
========
>>> lea... | 5,298,454 |
def write_recal_bam(data, region=None, out_file=None):
"""Step 2 of GATK recalibration -- use covariates to re-write output file.
"""
config = data["config"]
if out_file is None:
out_file = "%s-gatkrecal.bam" % os.path.splitext(data["work_bam"])[0]
logger.info("Writing recalibrated BAM for %... | 5,298,455 |
def _cleanup():
"""
Calls APTCleanUp
"""
if (_lib is not None):
_lib.APTCleanUp() | 5,298,456 |
def delete_group_resource_permissions_view(request):
"""
Delete a permission from a specific resource for a group.
"""
group = ar.get_group_matchdict_checked(request)
resource = ar.get_resource_matchdict_checked(request)
permission = ar.get_permission_multiformat_body_checked(request, resource)
... | 5,298,457 |
def get_bins(data):
"""Return bin edges for all unique values in data. """
bins = np.unique(data)
return np.append(bins[~np.isnan(bins)], max(bins) + 1) | 5,298,458 |
def filter_in_out_by_column_values (column, values, data, in_out):
"""Include rows only for given values in specified column.
column - column name.
values - list of acceptable values.
"""
if in_out == 'in':
data = data.loc[data[column].isin (values)]
else:
data = data.loc... | 5,298,459 |
def obj_gemfix_obj():
""" Improve cosmic ray and bad pixel correction.
Print raw and corrected files for comparison. """
print('# GEMFIX #')
# Remove pre-existing processed files.
if os.path.exists('gemgs{}'.format(obj_sci_name[0])):
os.remove('gemgs{}'.format(obj_sci_name[0]))
if ... | 5,298,460 |
def download_content_gui(**args):
"""
function to fetch links and download them
"""
global row
if not args ['directory']:
args ['directory'] = args ['query'].replace(' ', '-')
root1 = Frame(root)
t1 = threading.Thread(target = search_function, args = (root1,
args['query'], args['website'], args['fil... | 5,298,461 |
def parse_example_proto(example_serialized):
"""Parses an Example proto containing a training example of an image.
The output of the build_image_data.py image preprocessing script is a dataset
containing serialized Example protocol buffers. Each Example proto contains
the following fields:
ima... | 5,298,462 |
def test_handle_recipe_basic():
"""
handle_recipe takes a base url and some utf-8 encoded
content that is a recipe. It returns a list of urls.
"""
urls = handle_recipe('http://example.com/', """
tiddler: monkey/pirate.tiddler
recipe: special/thing.recipe
""")
assert urls == ['http://example.com/... | 5,298,463 |
def intersection(set_1, set_2):
"""realisation of two sets intersection(simple set generator inside)"""
return {i for i in set_1 if i in set_2} | 5,298,464 |
def simulated_quantize_compute(attrs, inputs, out_type):
"""Compiler for simulated_quantize."""
assert len(inputs) == 5
assert attrs.sign
assert attrs.rounding == "round"
axis = attrs.axis
data, in_scale, out_scale, clip_min, clip_max = inputs
data = my_print(data, '\n\n********************... | 5,298,465 |
def dy(series, n=1):
"""Difference over n years"""
return (series-series.shift(n*series.index.freq.periodicity)) | 5,298,466 |
def scale_node(node, x, y, z, **kwargs):
"""
Scales node
:param node: str
:param x: float
:param y: float
:param z: float
:param kwargs:
"""
raise NotImplementedError() | 5,298,467 |
def main():
"""Main entry point for execution."""
opt_parser = argparse.ArgumentParser(
description='A tool for parsing fsconfig config files and producing' +
'digestable outputs.')
subparser = opt_parser.add_subparsers(help='generators')
gens = generator.get()
# for each gen, ins... | 5,298,468 |
def inad(V1,V2):
""" Inertial advective wind
<div class=jython>
INAD ( V1, V2 ) = [ DOT ( V1, GRAD (u2) ),
DOT ( V1, GRAD (v2) ) ]
</div>
"""
return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2)))) | 5,298,469 |
def get_node_log(request, biz_cc_id, node_id):
"""
@summary: 查看某个节点的日志
@param request:
@param biz_cc_id:
@param node_id
@return:
"""
task_id = request.GET.get('instance_id')
history_id = request.GET.get('history_id')
try:
task = TaskFlowInstance.objects.get(pk=task_id, b... | 5,298,470 |
def _app_options(self, url, headers=None, status=None, expect_errors=False):
"""
To be injected into TestApp if it doesn't have an options method available
"""
req = TestRequest.blank(path=url, method='OPTIONS', headers=headers, environ=self.extra_environ)
return self.do_request(req, status, expect_... | 5,298,471 |
def iter_with_final(it: Iterable[E]) -> Iterable[Tuple[E, bool]]:
"""
Change given iterator to new one yielding additional *final* flag.
>>> list(iter_with_final(iter([1, 2, 3])))
[(1, False), (2, False), (3, True)]
>>> list(iter_with_final(iter([42])))
[(42, True)]
>>> list(iter_with_fin... | 5,298,472 |
def display_page(my_title):
"""Creates the custom content of a page.
args:
- my_title: string with the title for the page.
"""
page_header(my_title)
with st.beta_expander("Line chart"):
with st.echo():
data = [1,2,3,2,1,2,3,2,1]
st.line_chart(data)
... | 5,298,473 |
def remlplen_herrmann(fp,fs,dp,ds):
"""
Determine the length of the low pass filter with passband frequency
fp, stopband frequency fs, passband ripple dp, and stopband ripple ds.
fp and fs must be normalized with respect to the sampling frequency.
Note that the filter order is one less than the filt... | 5,298,474 |
def _log_github_milestone_error(milestone):
"""
Log a GitHub milestone error
"""
separator = "\n"
string_buffer = (
"Failed to close GitHub milestone:",
"Title: {0}.".format(milestone.title),
"Number: {0}.".format(milestone.number),
"State: {0}.".format(milestone.sta... | 5,298,475 |
def CreateBooleanIntersection1(curveA, curveB, tolerance, multiple=False):
"""
Calculates the boolean intersection of two closed, planar curves.
Note, curves must be co-planar.
Args:
curveA (Curve): The first closed, planar curve.
curveB (Curve): The second closed, planar curve.
Re... | 5,298,476 |
def pointer_scope(func):
"""The FDB format has a lot of pointers to structures, so this decorator automatically reads the pointer, seeks to the pointer position, calls the function, and seeks back."""
def wrapper(self, *args, **kwargs):
pointer = kwargs.get("pointer")
if pointer == None:
pointer = self._read_... | 5,298,477 |
def create_example_gpt(example: Example, tokenizer: Tokenizer) -> Example:
""" Create example for GPT-[1,2]
Substitute mask with <pad>, and store where the token was placed. During
repr. collection, we'll need it.
Example:
>>> x = 'Most apples are [MASK].'
... tokenizer = transformers.AutoTo... | 5,298,478 |
def should_smooth_series(tag: Enum) -> bool:
"""
:param tag:
:return:
"""
if tag is TrainingScalars.training_loss:
return True
elif tag is TrainingScalars.validation_loss:
return True
return False | 5,298,479 |
def do_storage_show(client, args):
""" Show details of a storage """
storage = client.storages.get(args.id)
utils.print_dict(storage) | 5,298,480 |
def load_all_plugins(module_path: Set[str],
plugin_dir: Set[str]) -> Set[Plugin]:
"""
:说明:
导入指定列表中的插件以及指定目录下多个插件,以 ``_`` 开头的插件不会被导入!
:参数:
- ``module_path: Set[str]``: 指定插件集合
- ``plugin_dir: Set[str]``: 指定插件路径集合
:返回:
- ``Set[Plugin]``
"""
def _lo... | 5,298,481 |
def lineno():
"""Returns the current line number in our program."""
return str( inspect.currentframe().f_back.f_lineno ) | 5,298,482 |
def test_numpy_functions_indices():
"""
Check numpy functions that return indices.
"""
values = [np.array([-4, 3, -2, 1, 0]), np.ones((3, 3)), np.array([17])]
units = [volt, second, siemens, mV, kHz]
# numpy functions
keep_dim_funcs = [np.argmin, np.argmax, np.argsort, np.nonzero]
for ... | 5,298,483 |
def positive_rates(df, score_col, label_col, thresholds):
"""Compute false positive and true positive rates."""
tpr = []
fpr = []
for threshold in thresholds:
confusion = confusion_matrix_counts(df, score_col, label_col, threshold)
if (
confusion["tp"] + confusion["fn"] == 0
... | 5,298,484 |
def get_phrases():
""" Returns a phrases dictionary of the form <callback>:<list of phrases> """
return _config_object["phrases"] | 5,298,485 |
def graham_scan(points: np.ndarray) -> np.ndarray:
"""Find vertices of convex hull around points.
Args:
points: (x, y) coordinates of points.
Returns:
hull: points that are vertices on convex hull.
"""
primary, remaining_points = extract_primary(points)
sorted_points = sort_for... | 5,298,486 |
def waitfor(css_selector, text=None, classes=None):
"""
Decorator for specifying elements (selected by a CSS-style selector) to
explicitly wait for before taking a screenshot. If text is set, wait for the
element to contain that text before taking the screenshot. If classes is
present, wait until th... | 5,298,487 |
def parse_arguments():
""" Parse arguments passed to the script """
parser = argparse.ArgumentParser(description='File uploader to Firebase Storage.')
parser.add_argument('config', help='Path of Firebase configuration file.')
parser.add_argument('--filetoken', dest='filetoken', default=None,
... | 5,298,488 |
def grandac(e, a, r, f_e):
"""Returns integrand for probability density of orbital radius where
semi-major axis is a constant
Args:
e (float):
Value of eccentricity
a (float):
Value of semi-major axis (AU)
r (float):
Value of orbital radius (A... | 5,298,489 |
def get_default_path(name):
"""this function takes a an import name
and returns the path full bash of the library
if the library is in stdlib"""
name_ = name
if isinstance(name, (DottedName, Symbol)):
name_ = str(name)
if name_ in pyccel_external_lib.keys():
name = pyccel_external... | 5,298,490 |
def test_1_uut2(executed_tests, test_result, uut, uut2):
"""
test 1 with two uut
"""
executed_tests.append(1)
assert test_result | 5,298,491 |
def get_requested_countries(countries, country_names):
"""
gets requested countries for visualization and info
:param countries: list of all available countries for research
:param country_names: list
:return: (list, str)
"""
print(country_names)
# gather the requested informat... | 5,298,492 |
def AUTO_TECHSUPPORT_GLOBAL_since(db, since):
""" Only collect the logs & core-dumps generated since the time provided.
A default value of '2 days ago' is used if this value is not set explicitly or a non-valid string is provided """
table = "AUTO_TECHSUPPORT"
key = "GLOBAL"
data = {
"s... | 5,298,493 |
def start():
"""Create and run view_book_list window"""
root = Toplevel()
book_list_window = BookListWindow(root)
root.title('View book')
root.resizable(width=False, height=False)
root.mainloop() | 5,298,494 |
def retrieve_plain(monitor, object_string):
"""Retrieves the request object as-is (doesn't apply any modification). This
is valid only for objects which are single values (items from a tensor)
:param monitor: either a training or evaluation monitor
:param object_string: string to identify the object to... | 5,298,495 |
def unique_id(context: Any) -> str:
"""
Returns a new unique string that can be used as an id="" attribute in HTML.
Usage:
{% with new_id=request|unique_id %}
<label for="input:{{ new_id }}"> I am labelling a far-away input </label>
...
<input id="input:{{ new_id }}">
{... | 5,298,496 |
def get_contrast_in_df(df, img, img_name, contrast_type, grating_mask, white_mask, black_mask,
metadata, x0, y0, angle, contrast_prefix=''):
"""helper function that handles inserting the contrast into the df
"""
if contrast_type == 'fourier':
grating_1d = utils.extract_1d_grat... | 5,298,497 |
def eprint(*args, **kwargs):
"""Print to stderr
"""
print(*args, file=sys.stderr, **kwargs) | 5,298,498 |
def cash(ttl=60, key=None, ver=CURRENT_VERSION_ID, pre="", off=False):
"""
Copyright (C) 2009 twitter.com/rcb
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
rest... | 5,298,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.