content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def process_domain_assoc(url, domain_map):
"""
Replace domain name with a more fitting tag for that domain.
User defined. Mapping comes from provided config file
Mapping in yml file is as follows:
tag:
- url to map to tag
- ...
A small example domain_assoc.yml is included
"... | 5,333,400 |
def process_auc(gt_list, pred_list):
"""
Process AUC (AUROC) over lists.
:param gt_list: Ground truth list
:type gt_list: np.array
:param pred_list: Predictions list
:type pred_list: np.array
:return: Mean AUC over the lists
:rtype: float
"""
res = []
for i, gt in enumerate(... | 5,333,401 |
def transform(
Y,
transform_type=None,
dtype=np.float32):
""" Transform STFT feature
Args:
Y: STFT
(n_frames, n_bins)-shaped np.complex array
transform_type:
None, "log"
dtype: output data type
np.float32 is expected
Return... | 5,333,402 |
def tol_vif_table(df, n = 5):
"""
:param df: dataframe
:param n: number of pairs to show
:return: table of correlations, tolerances, and VIF
"""
cor = get_top_abs_correlations(df, n)
tol = 1 - cor ** 2
vif = 1 / tol
cor_table = pd.concat([cor, tol, vif], axis=1)
cor_table.column... | 5,333,403 |
def shuffled(iterable):
"""Randomly shuffle a copy of iterable."""
items = list(iterable)
random.shuffle(items)
return items | 5,333,404 |
def get_local_ray_processes(archive: Archive,
processes: Optional[List[Tuple[str, bool]]] = None,
verbose: bool = False):
"""Get the status of all the relevant ray processes.
Args:
archive (Archive): Archive object to add process info files to.
... | 5,333,405 |
def test_rule(rule_d, ipv6=False):
""" Return True if the rule is a well-formed dictionary, False otherwise """
try:
_encode_iptc_rule(rule_d, ipv6=ipv6)
return True
except:
return False | 5,333,406 |
def intersects(hp, sphere):
"""
The closed, upper halfspace intersects the sphere
(i.e. there exists a spatial relation between the two)
"""
return signed_distance(sphere.center, hp) + sphere.radius >= 0.0 | 5,333,407 |
def invert_center_scale(X_cs, X_center, X_scale):
"""
This function inverts whatever centering and scaling was done by
``center_scale`` function:
.. math::
\mathbf{X} = \mathbf{X_{cs}} \\cdot \mathbf{D} + \mathbf{C}
**Example:**
.. code:: python
from PCAfold import center_sc... | 5,333,408 |
def weighted_smoothing(image, diffusion_weight=1e-4, data_weight=1.0,
weight_function_parameters={}):
"""Weighted smoothing of images: smooth regions, preserve sharp edges.
Parameters
----------
image : NumPy array
diffusion_weight : float or NumPy array, optional
The... | 5,333,409 |
def get_random_tablature(tablature : Tablature, constants : Constants):
"""make a copy of the tablature under inspection and generate new random tablatures"""
new_tab = deepcopy(tablature)
for tab_instance, new_tab_instance in zip(tablature.tablature, new_tab.tablature):
if tab_instance.string == 6:... | 5,333,410 |
def _staticfy(value):
"""
Allows to keep backward compatibility with instances of OpenWISP which
were using the previous implementation of OPENWISP_ADMIN_THEME_LINKS
and OPENWISP_ADMIN_THEME_JS which didn't automatically pre-process
those lists of static files with django.templatetags.static.static(... | 5,333,411 |
def add_files(
client: SymphonyClient,
local_directory_path: str,
entity_type: str,
entity_id: str,
category: Optional[str] = None,
) -> None:
"""This function adds all files located in folder to an entity of a given type.
Args:
local_directory_path (str): local system path ... | 5,333,412 |
def compare_rep(topic, replication_factor):
# type: (str, int) -> bool
"""Compare replication-factor in the playbook with the one actually set.
Keyword arguments:
topic -- topicname
replication_factor -- number of replications
Return:
bool -- True if change is needed, else False
"""
... | 5,333,413 |
def verbosity_option_parser() -> ArgumentParser:
"""
Creates a parser suitable to parse the verbosity option in different subparsers
"""
parser = ArgumentParser(add_help=False)
parser.add_argument('--verbosity', dest=VERBOSITY_ARGNAME, type=str.upper,
choices=ALLOWED_VERBOSIT... | 5,333,414 |
def b2b_config(api):
"""Demonstrates creating a back to back configuration of tx and rx
ports, devices and a single flow using those ports as endpoints for
transmit and receive.
"""
config = api.config()
import snappi
config = snappi.Api().config()
config.options.port_options.location_p... | 5,333,415 |
def test_local_training_relative_output_dir(mocker: MockFixture, cli_runner: CliRunner):
"""
Tests issue #208 - Converting relative path to output-dir to absolute,
because Docker requires mount paths to be absolute
:param mocker: mocker fixture
:param cli_runner: Click runner fixture
"""
tr... | 5,333,416 |
def apply_patch(ffrom, fpatch, fto):
"""Apply given normal patch `fpatch` to `ffrom` to create
`fto`. Returns the size of the created to-data.
All arguments are file-like objects.
>>> ffrom = open('foo.mem', 'rb')
>>> fpatch = open('foo.patch', 'rb')
>>> fto = open('foo.new', 'wb')
>>> app... | 5,333,417 |
def fib(n):
"""Return the n'th Fibonacci number."""
if n < 0:
raise ValueError("Fibonacci number are only defined for n >= 0")
return _fib(n) | 5,333,418 |
def gen(n):
"""
Compute the n-th generator polynomial.
That is, compute (x + 2 ** 1) * (x + 2 ** 2) * ... * (x + 2 ** n).
"""
p = Poly([GF(1)])
two = GF(1)
for i in range(1, n + 1):
two *= GF(2)
p *= Poly([two, GF(1)])
return p | 5,333,419 |
def adjust_learning_rate(optimizer, epoch, opt):
""" Sets the learning rate to the initial LR decayed by 10 """
if opt.exp_lr:
""" test
A=np.arange(200);
np.round(np.power(.1, np.power(2., A/80.)-1), 6)[[0,80,120,160]]
test """
last_epoch = 2. ** (float(epoch) / int(opt.l... | 5,333,420 |
def get_prefix(bot, message):
"""A callable Prefix for our bot. This could be edited to allow per server prefixes."""
# Notice how you can use spaces in prefixes. Try to keep them simple though.
prefixes = ['!']
# If we are in a guild, we allow for the user to mention us or use any of the prefixes in ... | 5,333,421 |
def parse_discontinuous_phrase(phrase: str) -> str:
"""
Transform discontinuous phrase into a regular expression. Discontinuity is
interpreted as taking place at any whitespace outside of terms grouped by
parentheses. That is, the whitespace indicates that anything can be in between
the left side an... | 5,333,422 |
def _StartService(service_name):
"""Starts a Windows service with the given name.
Args:
service_name: string The name of the service to be started.
"""
logging.info("Trying to start service %s.", service_name)
try:
win32serviceutil.StartService(service_name)
logging.info("Service '%s' started.", ... | 5,333,423 |
def preprocess(frame):
"""
Preprocess the images before they are sent into the model
"""
#Read the image
bgr_img = frame.astype(np.float32)
#Opencv reads the picture as (N) HWC to get the HW value
orig_shape = bgr_img.shape[:2]
#Normalize the picture
bgr_img = bgr_img / 255.0
#Co... | 5,333,424 |
def draw_roc_curve(y_true, y_score, annot=True, name=None, ax=None):
"""Draws a ROC (Receiver Operating Characteristic) curve using class rankings predicted by a classifier.
Args:
y_true (array-like): True class labels (0: negative; 1: positive)
y_score (array-like): Predicted probability o... | 5,333,425 |
def make_links_absolute(soup, base_url):
"""
Replace relative links with absolute links.
This one modifies the soup object.
"""
assert base_url is not None
#
for tag in soup.findAll('a', href=True):
tag['href'] = urljoin(base_url, tag['href'])
return soup | 5,333,426 |
def newVersion():
"""increments version counter in swhlab/version.py"""
version=None
fname='../swhlab/version.py'
with open(fname) as f:
raw=f.read().split("\n")
for i,line in enumerate(raw):
if line.startswith("__counter__"):
if version is None:
... | 5,333,427 |
def get_predictions(model, dataloader):
"""takes a trained model and validation or test dataloader
and applies the model on the data producing predictions
binary version
"""
model.eval()
all_y_hats = []
all_preds = []
all_true = []
all_attention = []
for batch_id, (data, label... | 5,333,428 |
def _getPymelType(arg, name) :
""" Get the correct Pymel Type for an object that can be a MObject, PyNode or name of an existing Maya object,
if no correct type is found returns DependNode by default.
If the name of an existing object is passed, the name and MObject will be returned
If a va... | 5,333,429 |
def _parse_objective(objective):
"""
Modified from deephyper/nas/run/util.py function compute_objective
"""
if isinstance(objective, str):
negate = (objective[0] == '-')
if negate:
objective = objective[1:]
split_objective = objective.split('__')
kind = split... | 5,333,430 |
def redirect_path_context_processor(request):
"""Procesador para generar el redirect_to para la localización en el selector de idiomas"""
return {'language_select_redirect_to': translate_url(request.path, settings.LANGUAGE_CODE)} | 5,333,431 |
def exc_info_hook(exc_type, value, tb):
"""An exception hook that starts IPdb automatically on error if in interactive mode."""
if hasattr(sys, 'ps1') or not sys.stderr.isatty() or exc_type == KeyboardInterrupt:
# we are in interactive mode, we don't have a tty-like
# device,, or the user trigg... | 5,333,432 |
def RightCenter(cell=None):
"""Take up horizontal and vertical space, and place the cell on the right center of it."""
return FillSpace(cell, "right", "center") | 5,333,433 |
def name_standard(name):
""" return the Standard version of the input word
:param name: the name that should be standard
:return name: the standard form of word
"""
reponse_name = name[0].upper() + name[1:].lower()
return reponse_name | 5,333,434 |
def getChildElementsListWithTagAttribValueMatch(parent, tag, attrib, value):
"""
This method takes a parent element as input and finds all the sub elements (children)
containing specified tag and an attribute with the specified value.
Returns a list of child elements.
Arguments:
parent = paren... | 5,333,435 |
def f_engine (air_volume, energy_MJ):
"""Прямоточный воздушно реактивный двигатель.
Набегающий поток воздуха попадает в нагреватель, где расширяется,
А затем выбрасывается из сопла реактивной струёй.
"""
# Рабочее вещество, это атмосферный воздух:
working_mass = air_volume * AIR_DENSITY
... | 5,333,436 |
def not_numbers():
"""Non-numbers for (i)count."""
return [None, [1, 2], {-3, 4}, (6, 9.7)] | 5,333,437 |
def get_agol_token():
"""requests and returns an ArcGIS Token for the pre-registered application.
Client id and secrets are managed through the ArcGIS Developer's console.
"""
params = {
'client_id': app.config['ESRI_APP_CLIENT_ID'],
'client_secret': app.config['ESRI_APP_CLIENT_SECRET'],... | 5,333,438 |
def native_python_local(ctx, host=False):
"""
Run the native Python knative container locally
"""
if host:
working_dir = FUNC_DIR
env = copy(os.environ)
env.update({
"LOG_LEVEL": "debug",
"FAASM_INVOKE_HOST": "0.0.0.0",
"FAASM_INVOKE_PORT": "80... | 5,333,439 |
def default_validate(social_account):
"""
Функция по-умолчанию для ONESOCIAL_VALIDATE_FUNC. Ничего не делает.
"""
return None | 5,333,440 |
def _validate_prototype(key, prototype, protparents, visited):
"""
Run validation on a prototype, checking for inifinite regress.
"""
assert isinstance(prototype, dict)
if id(prototype) in visited:
raise RuntimeError("%s has infinite nesting of prototypes." % key or prototype)
visited.a... | 5,333,441 |
def test_script_with_debug_enabled(monkeypatch):
"""
Test setting --debug flag
"""
script = Script()
with monkeypatch.context() as context:
validate_script_debug_flag_enabled(
script,
context,
expected_args=DEFAULT_ARGS.copy()
) | 5,333,442 |
def pull_early_late_by_stop(line_number,SWIFTLY_API_KEY, dateRange, timeRange):
"""
Pulls from the Swiftly APIS to get OTP.
Follow the docs: http://dashboard.goswift.ly/vta/api-guide/docs/otp
"""
line_table = pd.read_csv('line_table.csv')
line_table.rename(columns={"DirNum":"direction_id","Direc... | 5,333,443 |
def create_build_job(user, project, config, code_reference):
"""Get or Create a build job based on the params.
If a build job already exists, then we check if the build has already an image created.
If the image does not exists, and the job is already done we force create a new job.
Returns:
t... | 5,333,444 |
def create(ranger_client: RangerClient, config: str):
"""
Creates a new Apache Ranger service repository.
"""
return ranger_client.create_service(json.loads(config)) | 5,333,445 |
def draw_border(img, border, col=255):
"""Draw a border on an image given the border coordinates."""
l, r, t, b = border
cv2.line(img, (l, t), (l, b), col, 2)
cv2.line(img, (l, t), (r, t), col, 2)
cv2.line(img, (l, b), (r, b), col, 2)
cv2.line(img, (r, t), (r, b), col, 2) | 5,333,446 |
def populate_glue_catalogue_from_metadata(table_metadata, db_metadata, check_existence = True):
"""
Take metadata and make requisite calls to AWS API using boto3
"""
database_name = db_metadata["name"]
database_description = ["description"]
table_name = table_metadata["table_name"]
tbl_de... | 5,333,447 |
def group_median_float64(*args, **kwargs): # real signature unknown
""" Only aggregates on axis=0 """
pass | 5,333,448 |
def choose_komoot_tour_live():
"""
Login with user credentials, download tour information,
choose a tour, and download it. Can be passed to
:func:`komoog.gpx.convert_tour_to_gpx_tracks`
afterwards.
"""
tours, session = get_tours_and_session()
for idx in range(len(tours)):
print... | 5,333,449 |
def root():
"""
The root stac page links to each collection (product) catalog
"""
return _stac_response(
dict(
**stac_endpoint_information(),
links=[
dict(
title="Collections",
description="All product collections",
... | 5,333,450 |
def recursive_dict_of_lists(d, helper=None, prev_key=None):
"""
Builds dictionary of lists by recursively traversing a JSON-like
structure.
Arguments:
d (dict): JSON-like dictionary.
prev_key (str): Prefix used to create dictionary keys like: prefix_key.
Passed by recursive ... | 5,333,451 |
def same_shape(shape1, shape2):
"""
Checks if two shapes are the same
Parameters
----------
shape1 : tuple
First shape
shape2 : tuple
Second shape
Returns
-------
flag : bool
True if both shapes are the same (same length and dimensions)
"""
if len(shap... | 5,333,452 |
def get_reference():
"""Get DrugBank references."""
return _get_model(drugbank.Reference) | 5,333,453 |
def consumer(cond):
"""wait for the condition and use the resource"""
logging.debug("Starting consumer thread")
with cond:
cond.wait()
logging.debug("Resource is available to consumer") | 5,333,454 |
def set_parameter_requires_grad(model, feature_extracting):
"""
Set if parameters require grad
If feature_extract = False, the model is fine-tuned and all model parameters are updated.
If feature_extract = True, only the last layer parameters are updated, the others remain fixed.
Args:
model... | 5,333,455 |
def __parse_search_results(collected_results, raise_exception_finally):
"""
Parses locally the results collected from the __mapped_pattern_matching:
- list of ( scores, matched_intervals, unprocessed_interval,
rank_superwindow, <meta info>, <error_info>)
This parsing
- ev... | 5,333,456 |
def decode_matrix_fbs(fbs):
"""
Given an FBS-encoded Matrix, return a Pandas DataFrame the contains the data and indices.
"""
matrix = Matrix.Matrix.GetRootAsMatrix(fbs, 0)
n_rows = matrix.NRows()
n_cols = matrix.NCols()
if n_rows == 0 or n_cols == 0:
return pd.DataFrame()
if m... | 5,333,457 |
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Track states and offer events for sensors."""
component = hass.data[DOMAIN] = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL
)
await component.async_setup(config)
return True | 5,333,458 |
def apply_dof_transformation_to_transpose_hexahedron(
entity_transformations: _Dict[str, _npt.NDArray[_np.float64]], entity_dofs: _Dict[str, _npt.NDArray[_np.int32]],
data: _np.array, cell_info: int
):
"""Apply dof transformations to some transposed data on a hexahedron.
Args:
entity_transforma... | 5,333,459 |
def _all_lists_equal_lenght(values: t.List[t.List[str]]) -> bool:
"""
Tests to see if all the lengths of all the elements are the same
"""
for vn in values:
if len(values[0]) != len(vn):
return False
return True | 5,333,460 |
def receive_excel(send_json, token):
"""
Use the request_id to download the result, you shall see the file
in the same directory.
@param send_json: a json format dict
@param token: your access_token
"""
request_url = 'https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/get_requ... | 5,333,461 |
def test_create_dir_exist_but_file(mock_exists, mock_isfile, mock_makedirs, mock_msg):
"""Test error if path exist but is a file."""
mock_exists.return_value = True
mock_isfile.return_value = True
create_dir(dir_name)
mock_msg.assert_called_once_with(
"red", "Error: path {} exists and is not... | 5,333,462 |
def wind_shear(
shear: str, unit_alt: str = "ft", unit_wind: str = "kt", spoken: bool = False
) -> str:
"""Translate wind shear into a readable string
Ex: Wind shear 2000ft from 140 at 30kt
"""
if not shear or "WS" not in shear or "/" not in shear:
return ""
shear = shear[2:].rstrip(uni... | 5,333,463 |
def get_security_profiles_command(security_profile: str = None):
"""
Get information about profiles.
"""
if security_profile:
xpath = f'{XPATH_RULEBASE}profiles/{security_profile}'
else:
xpath = f'{XPATH_RULEBASE}profiles'
result = get_security_profile(xpath)
if security_pro... | 5,333,464 |
def root_hash(hashes):
"""
Compute the root hash of a merkle tree with the given list of leaf hashes
"""
# the number of hashes must be a power of two
assert len(hashes) & (len(hashes) - 1) == 0
while len(hashes) > 1:
hashes = [sha256(l + r).digest() for l, r in zip(*[iter(hashes)] * 2)]... | 5,333,465 |
def DumpStr(obj, pretty=False, newline=None, **json_dumps_kwargs):
"""Serialize a Python object to a JSON string.
Args:
obj: a Python object to be serialized.
pretty: True to output in human-friendly pretty format.
newline: True to append a newline in the end of result, default to the
previous ar... | 5,333,466 |
def test_packer_binary_file(host):
"""
Tests if packer binary is file type.
"""
assert host.file(PACKAGE_BINARY).is_file | 5,333,467 |
def snake_case(s: str):
"""
Transform into a lower case string with underscores between words.
Parameters
----------
s : str
Original string to transform.
Returns
-------
Transformed string.
"""
return _change_case(s, '_', str.lower) | 5,333,468 |
def multiple_workers_thread(worker_fn, queue_capacity_input=1000, queue_capacity_output=1000, n_worker=3):
"""
:param worker_fn: lambda (tid, queue): pass
:param queue_capacity:
:param n_worker:
:return:
"""
threads = []
queue_input = Queue.Queue(queue_capacity_input)
queue_output = ... | 5,333,469 |
def reorder(list_1: List[Any]) -> List[Any]:
"""This function takes a list and returns it in sorted order"""
new_list: list = []
for ele in list_1:
new_list.append(ele)
temp = new_list.index(ele)
while temp > 0:
if new_list[temp - 1] > new_list[temp]:
... | 5,333,470 |
def is_extended_markdown(view):
"""True if the view contains 'Markdown Extended'
syntax'ed text.
"""
return view.settings().get("syntax").endswith(
"Markdown Extended.sublime-syntax") | 5,333,471 |
def _generate_graph(rule_dict: Dict[int, List[PartRule]], upper_bound: int) -> Any:
"""
Create a new graph from the VRG at random
Returns None if the nodes in generated graph exceeds upper_bound
:return: newly generated graph
"""
node_counter = 1
new_g = LightMultiGraph()
new_g.add_node... | 5,333,472 |
def match_command_to_alias(command, aliases, match_multiple=False):
"""
Match the text against an action and return the action reference.
"""
results = []
for alias in aliases:
formats = list_format_strings_from_aliases([alias], match_multiple)
for format_ in formats:
tr... | 5,333,473 |
def dan_acf(x, axis=0, fast=False):
"""
DFM's acf function
Estimate the autocorrelation function of a time series using the FFT.
:param x:
The time series. If multidimensional, set the time axis using the
``axis`` keyword argument and the function will be computed for every
other... | 5,333,474 |
def set_selenium_local_session(proxy_address,
proxy_port,
proxy_username,
proxy_password,
proxy_chrome_extension,
headless_browser,
us... | 5,333,475 |
def match():
"""Show a timer of the match length and an upload button"""
player_west = request.form['player_west']
player_east = request.form['player_east']
start_time = dt.datetime.now().strftime('%Y%m%d%H%M')
# generate filename to save video to
filename = '{}_vs_{}_{}.h264'.format(playe... | 5,333,476 |
def timeit_helper():
"""Part A: Obtain some profiling measurements using timeit."""
# YOUR CODE GOES HERE
pass | 5,333,477 |
def sync_db(domain, username, restore_as=None):
"""Call Formplayer API to force a sync for a user."""
user = check_user_access(domain, username, allow_enterprise=True)
if restore_as:
check_user_access(domain, restore_as)
use_livequery = FORMPLAYER_USE_LIVEQUERY.enabled(domain)
data = {
... | 5,333,478 |
def start_end_epoch(graph):
"""
Start epoch of graph.
:return: (start epoch, end epoch).
"""
start = 0
end = 0
for e in graph.edges_iter():
for _, p in graph[e[0]][e[1]].items():
end = max(end, p['etime_epoch_secs'])
if start == 0:
start = p['s... | 5,333,479 |
def test_loop(predefined_ll_short):
"""Test before and after loop created on list."""
a = predefined_ll_short
assert a.has_loop() is False
a.head._next._next._next._next = predefined_ll_short.head
assert a.has_loop() is True | 5,333,480 |
def get_all_metadata_from_users():
"""
Collects all unique tracks available in the database and retrieves their metadata.
Intended to be used with the data from the first experiment.
:return:
"""
track_set = set()
tracks = {}
for user in SessionUser.objects:
user_tracks = user.g... | 5,333,481 |
def distance_metric(seg_A, seg_B, dx):
"""
Measure the distance errors between the contours of two segmentations.
The manual contours are drawn on 2D slices.
We calculate contour to contour distance for each slice.
"""
table_md = []
table_hd = []
X, Y, Z = seg_A.shape
... | 5,333,482 |
def tomographic_redshift_bin(z_s, version=default_version):
"""DES analyses work in pre-defined tomographic redshift bins. This
function returns the photometric redshift bin as a function of photometric
redshift.
Parameters
----------
z_s : numpy array
Photometric redshifts.
version... | 5,333,483 |
def is_point_in_rect(point, rect):
"""Checks whether is coordinate point inside the rectangle or not.
Rectangle is defined by bounding box.
:type point: list
:param point: testing coordinate point
:type rect: list
:param rect: bounding box
:rtype: boolean
:return: boolean check result
"""
x0, y0,... | 5,333,484 |
def chinese_theorem_inv(modulo_list):
"""
Returns (x, n1*...*nk) such as
x mod mk = ak for all k, with
modulo_list = [(a1, n1), ..., (ak, nk)]
n1, ..., nk most be coprime 2 by 2.
"""
a, n = modulo_list[0]
for a2, n2 in modulo_list[1:]:
u, v = bezout(n, n2)
a, n = a*v*n2+a... | 5,333,485 |
def write_dict_to_csv(filename, data):
"""Write a dictionary to a CSV file with the key as the first column."""
with open(filename, 'w') as csvfile:
writer = csv.writer(csvfile)
keys = sorted(data.keys())
for key in keys:
value = data[key]
row = [str(key)] + [str(... | 5,333,486 |
def clean():
"""
Clean test files
"""
if "output" not in os.listdir():
os.mkdir("output")
for f in os.listdir("./output"):
if os.path.isfile("./output/"+f):
os.remove("./output/"+f)
if "tmp" not in os.listdir():
os.mkdir("tmp")
for f in os.listdir("./tmp")... | 5,333,487 |
def compute_segment_cores(split_lines_of_utt):
"""
This function returns a list of pairs (start-index, end-index) representing
the cores of segments (so if a pair is (s, e), then the core of a segment
would span (s, s+1, ... e-1).
The argument 'split_lines_of_utt' is list of lines from a ctm-edits ... | 5,333,488 |
def local_neighborhood_nodes_for_element(index, feature_radius_pixels):
"""
local_neighborhood_nodes_for_element returns the indices of nodes which are in the local neighborhood of an
element. Note that the nodes and elements in a mesh have distinct coordinates: elements exist in the centroids
of cubes ... | 5,333,489 |
def _classification(dataset='iris',k_range=[1,31],dist_metric='l1'):
"""
knn on classificaiton dataset
Inputs:
dataset: (str) name of dataset
k: (list) k[0]:lower bound of number of nearest neighbours; k[1]:upper bound of number of nearest neighbours
dist_metric: (str) 'l1' or 'l2'
... | 5,333,490 |
def parse_pgpass(hostname='scidb2.nersc.gov', username='desidev_admin'):
"""Read a ``~/.pgpass`` file.
Parameters
----------
hostname : :class:`str`, optional
Database hostname.
username : :class:`str`, optional
Database username.
Returns
-------
:class:`str`
A ... | 5,333,491 |
def make_move(board, max_rows, max_cols, col, player):
"""Put player's piece in column COL of the board, if it is a valid move.
Return a tuple of two values:
1. If the move is valid, make_move returns the index of the row the
piece is placed in. Otherwise, it returns -1.
2. The updat... | 5,333,492 |
def convert_timestamp(ts):
"""Converts the timestamp to a format suitable for Billing.
Examples of a good timestamp for startTime, endTime, and eventTime:
'2016-05-20T00:00:00Z'
Note the trailing 'Z'. Python does not add the 'Z' so we tack it on
ourselves.
"""
return ts.isoformat() + 'Z... | 5,333,493 |
def object_id(obj, clazz=None):
"""Turn a given object into an ID that can be stored in with
the notification."""
clazz = clazz or type(obj)
if isinstance(obj, clazz):
obj = obj.id
elif is_mapping(obj):
obj = obj.get('id')
return obj | 5,333,494 |
def get_email_from_request(request):
"""
Get 'Authorization' from request header,
and parse the email address using cpg-util
"""
auth_header = request.headers.get('Authorization')
if auth_header is None:
raise web.HTTPUnauthorized(reason='Missing authorization header')
try:
... | 5,333,495 |
def test_install_file(tmp_path):
"""
test spm.pkgfiles.local
"""
assert (
spm.install_file(
"apache",
formula_tar=MagicMock(),
member=MockTar(),
formula_def={"name": "apache"},
conn={"formula_path": str(tmp_path / "test")},
)
... | 5,333,496 |
def retweet_fav_post(api):
"""
Retweets tweets with #motivation or #inspiration
@param api - api object created from config
"""
try:
for tweet in tweepy.Cursor(api.search,q=hashtag).items(1):
if not tweet.favorited and not tweet.retweeted:
try:
... | 5,333,497 |
def play(url, offset, text, card_data, response_builder):
"""Function to play audio.
Using the function to begin playing audio when:
- Play Audio Intent is invoked.
- Resuming audio when stopped / paused.
- Next / Previous commands issues.
https://developer.amazon.com/docs/custom-s... | 5,333,498 |
def all_flags_match_bombs(cells: List[List[Dict]]) -> bool:
"""
Checks whether all flags are placed correctly
and there are no flags over regular cells (not bombs)
:param cells: array of array of cells dicts
:return: True if all flags are placed correctly
"""
for row in cells:
for c... | 5,333,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.