content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import itk
def get_label_object_attributes(dataset, progress_callback=None):
"""Compute shape attributes of integer-labeled objects in a dataset. Returns
an ITK shape label map. An optional progress_callback function can be passed
in. This callback is expected to take one argument, a floating-point number... | bcf7e813492c94d132bd716f482c36709e540240 | 3,615,500 |
from aiida.orm import StructureData
def generate_structure():
"""Return a ``StructureData`` representing either bulk silicon or a water molecule."""
def _generate_structure(structure_id="Si"):
"""Return a ``StructureData`` representing bulk silicon or a snapshot of a single water molecule dynamics.
... | 7fc610d9dcb36e56953c98fcd4e067c6db33fd5b | 3,615,501 |
def get_lat_bin(lat, nbins=NBINS):
""" get latitude bin """
if lat < LATLIM[0]:
return 0
if lat > LATLIM[1]:
return nbins
return int((lat-LATLIM[0]) * nbins / (LATLIM[1]-LATLIM[0])) | cc6f67f0c9afb209416caa43b101c5a5174bfd43 | 3,615,502 |
def get_aff_trafo(xy0=None, xy1=None, theta=0, por=(0, 0), ax=None, patch=None):
"""
:param xy0: current position of the object, if not provided patch.get_xy() is used
:param xy1: desired position of the object
:param theta: rotation in degrees
:param por: point of rotation relative to the objects ... | 958249e940bf21cc10c68d2e2b7142d0fee62e15 | 3,615,503 |
from typing import Dict
from typing import Any
from typing import cast
def get_sig_alg(sig: key.Signature) -> Dict[str, Any]:
"""
Create `SignedDigestAlgorithm` structure.
"""
if sig.meta.algorithm == key.AsymmetricAlgorithm.RSA:
return get_sig_alg_rsa(cast(rsa.RsaSignature, sig))
if sig.... | 02a244ff0a8c67027a29c827e4101598a19fa455 | 3,615,504 |
import os
import json
def read_manifest_file():
"""Reads the manifest file"""
manifest_file = os.path.join(settings.STATIC_ROOT, "mix-manifest.json")
with(open(manifest_file)) as manifest:
return json.load(manifest) | 6a08c93e92112831526f8910f150be5a396dc720 | 3,615,505 |
def descendants(node, lst=None):
"""Return a list of all the descendants beneath a node"""
if lst is None:
lst = []
for child in node.children:
lst.append(child)
descendants(child, lst=lst)
return lst | 5fe6fb9d9fbfd63bbeb161fdbe1d0e54d20edf9e | 3,615,506 |
import os
def read(path, onlyHeader=False):
"""reads any Type 1 font file, returns raw data"""
_, ext = os.path.splitext(path)
ext = ext.lower()
creator, typ = getMacCreatorAndType(path)
if typ == 'LWFN':
return readLWFN(path, onlyHeader), 'LWFN'
if ext == '.pfb':
return readPFB(path, onlyHeader), 'PFB'
el... | e50b35c0db4408e6fbefb8284128c8df20caff53 | 3,615,507 |
def read_uncompressed_dataset(file):
""" Get a file path and return the uncompressed dataset"""
try:
return pd.read_pickle(file)
except:
try:
return pd.read_csv(file)
except:
print("%s cannot be read" % file)
return | 61accb9fa81e59b4b1324c40b567a5ce4e718fa6 | 3,615,508 |
def _run_reformulator_eval(questions, annotations, reformulator_instance,
environment_fn, batch_size):
"""Runs eval with just the reformulator, using greedy decoding."""
f1s = []
for (questions_batch, annotations_batch) in batch(questions, annotations,
... | 0ba54ac97a0f33bf7a0c77c968036c01d946ea3e | 3,615,509 |
def _get_single_node_name_from_collection(meta_graph_def, collection_key):
"""Obtain a node name that is the single element of a collection."""
if collection_key not in meta_graph_def.collection_def:
return None
collection = meta_graph_def.collection_def[collection_key]
if not collection.node_list.value:
... | 160ddf3f178f69fe31cfa8301516395f46ee6740 | 3,615,510 |
def test_create_plots_create_matrix_deletion_raw_count():
"""
"""
#ref_seq, total_dels, total_ins, cov = crispr_count_indels._count_indels("15_dels_ladder_for_matrix.fasta")
ref_seq, ref_seq_id = count_indels._get_ref_seq("15_dels_ladder_for_matrix.fasta")
cov = count_indels._get_coverage("15_d... | 473d86545ff3669279e7e5aed65b0fe920eef48c | 3,615,511 |
def wire_mutual_inductance(wire_i, wire_j, ref):
# di0: float, dj0: float, dij: float, rw0: float):
"""Inductance between wire i and wire j, with reference wire 0.
Uses widely separated assumption, di0/rw > 4
"""
if type(ref) == Wire:
rw0 = ref.radius
di0 = wire_i.distance_to(ref)
... | 484027eca8864a4d66e78988d4f2580fbf12644b | 3,615,512 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Faster R-CNN demo')
parser.add_argument('jsonFile',
help='detections json file')
parser.add_argument('-o', dest='resFile', type=str,
default='dum... | 3e270f034e9b4352dc6bc3254808a8b719655dd6 | 3,615,513 |
import os
def extract_sapcar_file(sapcar_exe, sar_file, **kwargs):
"""
Execute SAPCAR command to decompress a SAP CAR or SAR archive files.
If user and password are provided it will be executed with this user.
Args:
sapcar_exe(str): Path to the SAPCAR executable
sar_file (str): Path t... | 3e80a08c2d8ecb6d7b55fda073e80de30454eb4f | 3,615,514 |
from typing import Any
from typing import Tuple
def parl_to_kaldi_test_pairs(request: Any) -> Tuple[str, str]:
"""Return an embedded statement from the above list using given index."""
index: int = request.param
return parl_to_kaldi_pairs[index] | 5b830e2daf852358bafe2caf365438a3cd1301d0 | 3,615,515 |
def global_pairwise_align_protein(seq1, seq2, gap_open_penalty=11,
gap_extend_penalty=1,
substitution_matrix=None,
penalize_terminal_gaps=False):
"""Globally align pair of protein seqs or alignments with Needleman-... | b2494fb60f5735eae0aa9d1eda0185884f905d92 | 3,615,516 |
import requests
def client(api_client):
"""Returns HttpClient instance with retrying feature skipped."""
api_client = api_client(disable_retry_status_list={503, 404})
# This won't work with Httpx but will save us about 10 mins for this test alone
api_client.session = requests.Session()
return api_... | 615756a81fd243d4d7495bafca4538e19775f7b4 | 3,615,517 |
def create_elem_dict(row):
"""
Create new element dictionary from row with metadata common to all
nodes/ways/relations.
"""
elem = {
'id': row.id,
'version': row.version,
'userId': row.user_id,
'userName': row.user_name,
'timestamp': row.timestamp,
'ta... | d97b712cd4b0bc6e79f5aa09f212491d715f1c69 | 3,615,518 |
from typing import Dict
from typing import Any
from typing import Tuple
from typing import Optional
def source_ip_and_reverse_dns(
message: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]:
"""
Extract the source IP and reverse DNS information from a canary request.
"""
reverse_dns, sour... | df2a9b6c4a177073fc019e88c33234f4d6124ccb | 3,615,519 |
import typing
def spark_flatMap(func: typing.Callable[[pyspark.rdd.RDD], pyspark.rdd.RDD]=default_function(1)):
"""Spark's flatMap
:param Callable func: The function to apply.
:input RDD data: The RDD to convert.
:output RDD result: The resulting RDD.
"""
def inner(data: pyspark.rdd.RDD) -> R... | 9f7d6fa9a18d844f6e0d140063ab0dc5684217a6 | 3,615,520 |
def fCO2_to_CO2(fCO2, Ks):
"""
Calculate CO2 from fCO2
"""
return fCO2 * Ks.K0 | 2b71b46147291e7fffb99d51d0acb59ea4cd0c69 | 3,615,521 |
def highlight_min(dsty, bg_color="#ffd700", axis=0, df_slice=None):
"""FIXME! briefly describe function
:param dsty:
:param bg_color:
:param axis: 0=index,1=column, None=all elements
:returns:
:rtype:
"""
res = dsty.highlight_min(color=bg_color, axis=axis, subset=df_slice)
retu... | 5e9be25203ae89df6039c7dec4354a5f28af9027 | 3,615,522 |
def summary_stats(tile_summary):
"""
Obtain various stats about the slide tiles.
Args:
tile_summary: TileSummary object.
Returns:
Various stats about the slide tiles as a string.
"""
return "Original Dimensions: %dx%d\n" % (tile_summary.orig_w, tile_summary.orig_h) + \
"Original Tile Siz... | 8e36e9b10ec721cd567eccb54c9afecad13f2eea | 3,615,523 |
def soundnet5_model_params(model_filename=None, num_classes=None, scope='SoundNet'):
"""
Load model parameters from Torch file.
"""
def retrieve_if_not_none(local_net, layer_num, var_name): return None if local_net is None else \
local_net['modules'][layer_num][var_name]
def transpose_if_n... | 305e06bbadb67b9beab060c1763e68423c64b393 | 3,615,524 |
def landsat457_cloud_mask_func(img):
"""Apply basic ACCA cloud mask to a daily Landsat 4, 5, or 7 image"""
cloud_mask = ee.Algorithms.Landsat.simpleCloudScore(img).\
select(['cloud']).lt(ee.Image.constant(50))
return img.mask(cloud_mask.mask(cloud_mask)) | 50b01ef70f41be0788952c5e0ca2a55c8b6ccff5 | 3,615,525 |
def check_if_in_team(api, team_id, person):
""" Checks if a person is in a given team
:param api: CiscoSparkAPI instance to query Spark with.
:param team_id: The ID of the team to check for
:param person: The person to check against the team
"""
team_memberships = api.team_memberships.list(te... | b20a5ee41485b2dd397c7dd23407ef95d0f34e4a | 3,615,526 |
def handle_public_events(iterable):
"""Report private repositories being made public, and new releases."""
lines = []
unused = iterable
# Private -> Public Transitions
events, unused = partition_type('PublicEvent', unused)
for event in events:
tmpl = 'made {} public'
lines.appen... | 7608bbf011729c2bf78a9c5a62e5061760aa50ae | 3,615,527 |
def generate_sub_tetrahedrons(a, b, c, d):
"""
Generate sub-tetrahedrons.
Returns tuple of tetrahedrons.
ARGUMENTS: a, b, c, d - vertices of tetrahedron
"""
sub_tetra = []
sub_tetra.append((a, midpoint(a, b), midpoint(a, c), midpoint(a, d)))
sub_tetra.append((midpoint(a, b), b, midpoin... | 9f4a379092d62162109da199589393f2a02ccab1 | 3,615,528 |
def ExtractMemoryDumpIds(trace_builder):
"""Get a list with the ids of 'GlobalMemoryDump' events found in a trace.
Args:
trace_builder: A TraceDataBuilder object; trace data is extracted from it
and the builder itself is cleaned up.
"""
event_ids = _SerializeAndProcessTrace(
trace_builder, _GET... | 4a102b4d897fceeb63a493bc5799e22f7d0f044c | 3,615,529 |
from azure.mgmt.keyvault import KeyVaultManagementClient
import re
def get_vm_format_secret(secrets, certificate_store=None):
"""
Format secrets to be used in `az vm create --secrets`
:param dict secrets: array of secrets to be formatted
:param str certificate_store: certificate store the secret will ... | 5f97ae86c07250864012f869bd718fb3513b6a8e | 3,615,530 |
import builtins
def instance(type_cls, cls):
""" Decorator for creating a typeclass instance.
Examples:
>>> from abc import ABC, abstractmethod
>>> from pycats import typeclass, instance
>>>
>>> @typeclass
... class Functor(ABC):
...
... @abstractme... | acd655661d2106e18004f7c22f6c8395287a20d4 | 3,615,531 |
def get_inputs(seq_len: int) -> tensorflow.Tensor:
"""Get input layers.
See: https://arxiv.org/pdf/1810.04805.pdf
Args
seq_len: Length of the sequence or None.
"""
names = ['Token', 'Segment']
# , 'Masked']
return [
keras.layers.Input(
shape=(None,),
... | 3742ff634a7b46e17e19d509ea20dcac79660060 | 3,615,532 |
def replace_self_attention_layer_with_sparse_self_attention_layer(
config,
layers,
# SparsityConfig parameters needs to be set accordingly
sparsity_config=SparsityConfig(num_heads=4)):
"""This function replaces the self attention layers in attention layer with sparse self attention.
For sparsity... | 381b7c876a90ff2d6f135db4fd92ba3b4114aa94 | 3,615,533 |
def mape(y_true: pd.Series, y_pred: pd.Series) -> float:
"""Compute Mean Absolute Percentage Error (MAPE)
Args:
y_true (pd.Series): actual values
y_pred (pd.Series): predict values
Returns:
float: mape value
"""
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100 | a1959cd422db225ec0ddd77fc47ca55c78a686d9 | 3,615,534 |
def list_mutations(context):
"""
:type context: Context
"""
assert context.mutation_id == ALL
mutate(context)
return context.performed_mutation_ids | a78ba96202c910df057d86dac13cc549b6951e06 | 3,615,535 |
import random
def split_data(x_all, y_all, test_percent=0.01):
"""
split the data to train set and test set
:param x_all: all the x : (count,n_features)
:param y_all: all the y : (count,1)
:param percent: the percent of the test set [0,1]
:return: (x_train, y_train), (x_test, y_test)
"""
... | 1403a237a4594ecbc213b89c54f22533b77301ba | 3,615,536 |
from typing import Optional
import json
async def make_keyboard_from_json(query: str, message: Message) -> Optional[Message]:
"""
Запрос в конструктор из json формата
:param query: JSON запрос
:param message: Объект сообщения пользователя
"""
try:
data = json.loads(query)
retur... | 7f4b9fd01776b486c450e8515ae38e8854530202 | 3,615,537 |
def group_per_category(bkgs):
"""
Groups a flat list of datasets into sublists with the same category
E.g. [ ttjet, ttjet, ttjet, qcd, qcd ] --> [ [ttjet, ttjet, ttjet], [qcd, qcd] ]
"""
cats = list(set(bkg.get_category() for bkg in bkgs))
cats.sort()
return [ [ b for b in bkgs if b.get_cate... | c331456b1b3066f667c94e6ed7d00c8421ec2160 | 3,615,538 |
def subtract_params(param_list_left: list, param_list_right: list):
"""Subtract two lists of parameters
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays
"""
return [x - y for x, y in zip(param_list_left, param_list_right)] | f8563cae337af0e30621428103afa10bde614e93 | 3,615,539 |
def rebin_or(newbins, oldbins, oldvalues):
"""Deprecated as of 2015-02-15. Use rebin instead."""
return rebin(newbins, oldbins, oldvalues, method='or') | d58c3334f2789c1d01f618e78ff5a519a9c88c4d | 3,615,540 |
import sys
def get_groups_of_molec(molec, groups:dict, df_in, ind:int):
"""Function to that looks for a variety of functional groups, defined in "groups"
within a specific molecule. Will add this data into the dataframe, df at index, ind.
Inputs:
-------
molec - An RDKit mo... | 81bc3349bbdf54c355ba8fe1af5c2cecb090eb87 | 3,615,541 |
from typing import List
def mkrefpath(r:DRef, items:List[str]=[])->RefPath:
""" Construct a [RefPath](#pylightnix.types.RefPath) out of a reference `ref`
and a path within the stage's realization """
assert_valid_dref(r)
return [str(r)]+items | 04a1b10478d71d0751898d69e521119549102d62 | 3,615,542 |
import re
def resize(url, width):
"""
Return a url to a resized version of the given image at the url -- only
works for files hosted on your MEDIA_ROOT --- CACHE THIS HEAVILY
"""
width = int(width)
regex = get_media_url_regex()
# check to see if the url is one we can handle, othe... | 0ddaed81e450d00e4c76682c4c059b1155f0e975 | 3,615,543 |
async def me(
request: Request,
scopedTo: ScopedTo = ScopedTo(
[UserScope.admin, UserScope.auditor, UserScope.guardian, UserScope.voter]
),
) -> UserInfo:
"""
Get user info for the current logged in user.
"""
token_data = scopedTo(request)
if token_data.username is None:
... | a4ff28f2eccaf36383894e9af103d67c752aa7c1 | 3,615,544 |
def crop_center(image):
"""Returns a cropped square image."""
shape = image.shape
new_shape = min(shape[1], shape[2])
offset_y = max(shape[1] - shape[2], 0) // 2
offset_x = max(shape[2] - shape[1], 0) // 2
image = tf.image.crop_to_bounding_box(
image, offset_y, offset_x, new_shape, new_s... | bf069a5388ec40f8c07671cf514bb88442674cbd | 3,615,545 |
def load_video(video_data, *, config=VideoLoaderConfig()):
"""Load a video into the database"""
video_id = video_data.pop("video_id")
platform = video_data.pop("platform")
topics_data = video_data.pop("topics", None)
offered_bys_data = video_data.pop("offered_by", None)
with transaction.atomic(... | 93d18d2d8bb067e85747641478555d21d1fe2148 | 3,615,546 |
from typing import Union
async def is_float(obj: Union[Message, CallbackQuery]) -> bool:
"""
Checks if message text can be converted to float
:return: True if so
"""
obj = await _to_message(obj)
return obj.text and obj.text.isnumeric() | 55fe1160431027f0c9546023ad5760455e3c632b | 3,615,547 |
def _context_license_spdx(context, value):
"""convert a given known spdx license to another one"""
# more values can be taken from from https://github.com/hughsie/\
# appstream-glib/blob/master/libappstream-builder/asb-package-rpm.c#L76
mapping = {
"Apache-1.1": "ASL 1.1",
"Apache-2.0... | 3ad3b91bf7db36a9be3751877e248ed481d1be71 | 3,615,548 |
def html_header():
"""
Global & common html header. SHould be used everywhere
Returns:
--------
out: str
"""
return """
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/finkstyle.css">
<title>Mon programme test</title>
</head>
<body>
... | 7d4a7571be9a269927ec29a0d38daa950f1404b6 | 3,615,549 |
import subprocess
import threading
import signal
def executeCommand(command, cwd=None, env=None, input=None, timeout=0):
"""
Execute command ``command`` (list of arguments or string)
with
* working directory ``cwd`` (str), use None to use the current
working directory
* e... | ea213b7db603c83a77d79e9bc9971e987a8db542 | 3,615,550 |
def build_repository_type_select_field( trans, repository=None, name='repository_type' ):
"""Called from the Tool Shed to generate the current list of supported repository types."""
if repository:
selected_type = str( repository.type )
else:
selected_type = None
repository_type_select_fi... | eb0cc6085814d0d5390e842efe0f75c9694ee82c | 3,615,551 |
import os
import wrf
def wrf_cloudtemp(data_pstag, data_tstag, data_qstag, data_cloudstag, data_zstag, data_mapfc, data_icestag):
"""Function to compute ``ctt`` using wrf-python.
Args:
data_pstag (Xarray data array): Total pressure (P0+PB) (3d).
data_tstag (Xarray data array): Temper... | fadb87ed23da9afe51e2926c442fcecbfb118560 | 3,615,552 |
def get_boolean_value(file_location, section, key):
"""
Searches an INI Configuration file for a section & key and returns it as a string.
:param file_location: The file to get a key value from
:param section: The section to find the key value
:param key: The key that can contain a value to retriev... | 1c419a320e715f056310a6f6aac54b73f5d073da | 3,615,553 |
def net_connections(kind='inet'):
"""Return system-wide connections as a list of
(fd, family, type, laddr, raddr, status, pid) namedtuples.
In case of limited privileges 'fd' and 'pid' may be set to -1
and None respectively.
The 'kind' parameter filters for connections that fit the
following cri... | 75403d79b2964e868aa9fddaec7e8b1e655d87b1 | 3,615,554 |
def db_check():
"""
Performs a basic check on the database by performing a select query on a simple table
:return: True or False according to successful retrieval
"""
try:
HealthCheck.objects.get(health_check_field=True)
return HealthStatus.OK
except Exception as e:
captu... | 6a096621a9e6def7754a773ba13ad6af83894f48 | 3,615,555 |
import csv
def get_report(readings_file):
"""
Prepares a report and returns it as a string.
Report includes starting and ending readings,
amount consumed and cost of each utility,
as well as the total, how much if any was paid,
and the amount outstanding.
"""
with open(readings_file) ... | 1a460f3deed40c0ce32d80dcaa893c5297281b9b | 3,615,556 |
from typing import Dict
from typing import Tuple
from typing import List
def parse_template(template: WorkflowTemplate, arguments: Dict) -> Tuple[List[ContainerStep], Dict, List[str]]:
"""Parse a serial workflow template to extract workflow steps and output
files.
The expected schema of the workflow spec... | 89ae23f7e01f6c7802770c814a06339ed2e13eb8 | 3,615,557 |
def int_df_two_segments(int_df_one_segment) -> pd.DataFrame:
"""Generate dataframe with simple targets for lags check."""
df_1 = int_df_one_segment.reset_index()
df_2 = int_df_one_segment.reset_index()
df_1["segment"] = "segment_1"
df_2["segment"] = "segment_2"
df = pd.concat([df_1, df_2], ign... | 043d47a175a194692e66ff546eed73861741d7c7 | 3,615,558 |
import re
def get_user_agent(request):
"""
Checks if the given user agent string matches one of the valid user
agents.
"""
name = request.META.get('HTTP_USER_AGENT', None)
if not name:
return False
for platform, regex in settings.USER_AGENTS.iteritems():
if re.compile(regex... | c893000db1be1051c7ca74898b4f98d8ad47e9a1 | 3,615,559 |
def indent(element, level=0):
""" Indents an XML root object from ElementTree.
Parameters
----------
element : ElementTree.Element
The XML root object to manipulate and indent.
level : int, optional
I guess at which level of indentation it should start. Can be
ignored and u... | 1f0049077d567308aa8f4e8018846b1dd57f957e | 3,615,560 |
import torch
def train_collate_fn(batch):
"""
# collate_fn这个函数的输入就是一个list,list的长度是一个batch size,list中的每个元素都是__getitem__得到的结果
"""
imgs, pids, _, _, = zip(*batch)
pids = torch.tensor(pids, dtype=torch.int64)
return torch.stack(imgs, dim=0), pids | 81f653acbf9c9643289416b70dcba08e002d2613 | 3,615,561 |
def level_4(f):
"""
Decorate routes to require level 4 previleges (Super Admin).
IMPORTANT: Place this decorator in after @login_required
Documentation here:
http://flask.pocoo.org/docs/1.0/patterns/viewdecorators/
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if session... | 0f44dfeae69b4b40998870ae96bd6f5c3a4708de | 3,615,562 |
def distance_to_border(logicarray, maxdist=65535):
"""
Returns the eucledian distance to the border of a binary logical array.
Positive distances mean distance to the next negative (false) pixel, negative distance
the distance to the next positive (true) pixel.
:logicarray a binary array
:maxdis... | f622720a616ba2a5193ecc3673c19938457fce57 | 3,615,563 |
def encrypt_string(enabled, string, config):
# type: (bool, str, dict) -> str
"""Encrypt a string
:param bool enabled: if encryption is enabled
:param str string: string to encrypt
:param dict config: configuration dict
:rtype: str
:return: encrypted string if enabled
"""
if enabled:... | df00b8ece08491ecbd0aecaedaabf43ea4850379 | 3,615,564 |
def split_data(X, y, problem_type, problem_configuration=None, test_size=.2, random_seed=0):
"""Splits data into train and test sets.
Arguments:
X (ww.DataTable, pd.DataFrame or np.ndarray): data of shape [n_samples, n_features]
y (ww.DataColumn, pd.Series, or np.ndarray): target data of length... | 37807727fae7cb6e8f1a57265b0a167f610f1e01 | 3,615,565 |
def eval_mode(cfg):
"""Runs the evaluation-only loop."""
if cfg.VIS_TEST:
assert cfg.USE_WANDB is True, "Visualizations use Wandb, therefore, it must be enabled"
trainer = CSDTrainerManager(cfg)
trainer.resume_or_load(resume=False)
res = trainer.test(cfg, trainer._trainer.model)
if com... | 1f03fdb7b4c641b07f5dc946fc9cba1daf9b54c6 | 3,615,566 |
import requests
def get_invites_for_account(account, timeout=5):
"""
Gets a users invites for any gsr groups.
Return invites along with details about the gsr group (color, name, group id)
"""
x_authorization = request.headers.get("X-Authorization")
authorization = request.headers.get("Authori... | ee1c4f9b18ec490627185e7b4956473250731ddf | 3,615,567 |
def handle_orphan_edges(edge_img, sobel_sig, bpm=None, flux_valid=True, buffer=0, copy=False):
"""
In the case of single left/right traces and multiple matching
traces, pick the most significant matching trace and remove the
others.
If *no* left and/or right edge is present, this will add one using... | 7e58ae718a4cfa3fe1ff87f470010c2a33b5e45e | 3,615,568 |
from datetime import datetime
async def format_tweak_page(ctx, entries, current_page, all_pages):
"""Formats the page for the tweak embed.
Parameters
----------
entries : List[dict]
"The list of dictionaries for each tweak"
all_pages : list
"All entries that we will eventually ite... | 86268ada306ecb0d6dcc4e63b7390e5cb0e74456 | 3,615,569 |
def _parse_opts():
"""Parse the command line options.
:param list argv: List of arguments to process. If not provided then will
use optparse default
:return: options,args where options is the list of specified options that
were parsed and args is whatever arguments are left after parsing al... | b76d44484c8c5af7aa93039f2aa4d689c8ae36bf | 3,615,570 |
def encode2(valeur,base):
""" float*int -->String avec 16 décimales
hypothèse : base maxi = 16
"""
chaine=""
for n in range (1,17) :
valeur=valeur*base
calcul = int(valeur)
if (calcul)>9:
if calcul==10:
bit='A'
if calcul==11:
... | a4f9a96a7f53f17ec9cc57a54df3db3ec7c9aac7 | 3,615,571 |
import re
def get_stacktrace(gdb_output):
"""Returns the stacktrace and the exit signal """
if not "#0" in gdb_output:
error("gdb output error")
stacktrace = Stacktrace()
# Get the exit Signal from the gdb-output
exit_signal = re.search(_exit_signal_re, gdb_output)
if exit_signal:
... | 0e9c32e793dda756451309b78f4308096df3eee7 | 3,615,572 |
def index():
"""
Basic index route.
"""
return {"msg": "Hi! This is an API by Mariia Sizova"} | 211f24da5736e57216f160db39af0590f8eb2c4f | 3,615,573 |
import torch
def pretty_size(size):
"""
Pretty prints a torch.Size object
By user machinethink: https://forums.fast.ai/t/gpu-memory-not-being-freed-after-training-is-over/10265/7
"""
assert(isinstance(size, torch.Size))
return " × ".join(map(str, size)) | 006ae05ce22653bfe58a5791aa5912de7283d9ca | 3,615,574 |
from re import T
from typing import Literal
def merge_rest_docs(
prnt_doc: T.Optional[str] = None,
child_doc: T.Optional[str] = None,
method: T.Union[Literal["merge"], Literal["replace"]] = "replace",
) -> str:
"""See custom_inherit.style_store.reST for details."""
prnt_sections = parse_rest_doc(p... | 9489df9890807fd87807cc71d4b63a53c76f80ef | 3,615,575 |
def get_recipe_intent_handler(request):
"""
You can insert arbitrary business logic code here
"""
return alexa.create_response(message="Hello stranger!") | 373568260c72903d2266a807bf12af58f110a6fb | 3,615,576 |
import re
def path_splitter(s, _d_match=re.compile(r"\.\d").match):
"""
Split a string into its path components.
Assumes a string is a path or is path-like.
Parameters
----------
s : str | pathlib.Path
Returns
-------
split : tuple
The path split by directory components ... | 531c94f1b05f840f07944a748983787fc8dff8bf | 3,615,577 |
from typing import Tuple
def convert_time(time: str, ampm: str) -> Tuple[int, int]:
"""Convert time given "HH:MM" to 24h format.
Args:
time (str): a time like "12:00" without ampm
ampm (str): either "am" or "pm"
Returns:
Tuple[int, int]: (hour, minute) in 24h time format
"""... | b1bd57ea92e82ba629e3ad2733f173dfcc805e9e | 3,615,578 |
def proportional_allocation_by_location_and_activity(df, sectorcolumn):
"""
Creates a proportional allocation within each aggregated sector within a location
:param df: df with sector columns
:param sectorcolumn: str, sector column for which to create allocation ratios
:return: df, with 'FlowAmountR... | f8cd293f04ae00703318437f4c4936a883f29e33 | 3,615,579 |
def Cov_bb_Das(Cb, α, A, β, B, γ, C, τ, D):
"""Compute analytic errorbars.
A, B, C, D correspond to frequencies,
α, β, γ, τ correspond to seasons
"""
N = 0.0
term0 = 2 * Cb**2 / nu_b
term1 = 0.0
term2 = 0.0
for i in range(n_d[0]):
for j in range(n_d[1]):
for k in... | cb2f608aab167728941050885c2322047f780caf | 3,615,580 |
def join_(table, on_str, **kwargs):
"""
join_(table='items', on_str='items.id=topic_item.item_id', status=1)
"""
join_str = ' JOIN `' + table + '` on ' + on_str
re_str, values = _rebuild_argv(kwargs, table=table)
return join_str, re_str, values | 8f054d9e1567d2bbea1a7f08acbd0f322755534a | 3,615,581 |
def optimize_glm(x, y, distri):
"""Apply Bayesian Optimization to select enet parameters."""
def function(alpha, reg_lambda):
return glm_train(alpha=alpha, reg_lambda=reg_lambda, x=x, y=y, distri=distri)
optimizer = BayesianOptimization(
f=function,
pbounds={"alpha": (1e-6, 1), "reg... | 1323eed2e2beba65194c32db96cb1d8d993b0c2e | 3,615,582 |
import random
import string
import os
def upload_webcam(request):
"""
Generate a random name for the photo and save it to disk, then crop it and extract information
"""
name = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10)) + ".png"
path = os.path.join(settings.ME... | f971ff01019e282a0890fc80e506e8cb89ffabe6 | 3,615,583 |
def project_duals(dual_vars, dual_types):
"""Projects dual variables to satisfy dual constraints."""
make_pos = lambda v: None if v is None else jnp.maximum(v, 0)
_project = lambda v, t: make_pos(v) if t == DualVarTypes.INEQUALITY else v
return jax.tree_multimap(_project, dual_vars, dual_types) | 14b4782d2cdda2998d18eca38ae3602b7b8f3744 | 3,615,584 |
def column_equality(series, col1, col2, comparison='equal', pos_return_val=1, neg_return_val=0):
"""
Apply to a dataframe row to return a binary feature depending on equality or inequality
E.g. df.apply(lambda s: column_match(s, 'day_of_week', 'day_of_sale'), axis=1) to for matching the two.
Result is ... | 9ec71f5fd3af4a8d89b4cd58a255065ec8352eb2 | 3,615,585 |
def destroy_sns_event(app_name, env, region):
""" Destroys all Lambda SNS subscription
Returns:
boolean: True if subscription destroyed successfully
"""
session = boto3.Session(profile_name=env, region_name=region)
sns_client = session.client('sns')
lambda_subscriptions = get_sns_subsc... | 8f0e611c2db71dcc1595679d66d7d2c122edab1b | 3,615,586 |
def SS_workflow(scope="function"):
"""SS_workflow.
Simple workflow including StartToStart dependency.
"""
task1 = BaseTask("task1")
task2 = BaseTask("task2")
task3 = BaseTask("task3")
task2.append_input_task(task1, task_dependency_mode=BaseTaskDependency.SS)
task3.append_input_task(task... | 14e130ae5fbdd8dd5d514d56aac27e9c297ba200 | 3,615,587 |
def removeStopwords(text):
"""Se eliminan palabras que carecen de significado
Args:
text: Texto del que se desea eliminar las palabras sin significado.
"""
stopw = nltk.corpus.stopwords.words('spanish')
stopw = stopw + ["juguete", "juguetes", "edad", "máxima", "recomendada", "incluye... | ed2ffe85765c6bbdc99ba5de78d789c25181caf9 | 3,615,588 |
import shutil
def delete_directory(path):
"""
Deletes a ticket attachments directory from disk
"""
path = '{}/{}'.format(settings.MEDIA_ROOT, path)
try:
shutil.rmtree(path)
return path
except:
logger.error('Error removing folder{}'.format(path))
return False | 2525a6a58dc01a2d8d958b8d506c7f387b22c5cc | 3,615,589 |
import math
def get_tile_from_lon_lat(lon: float, lat: float, zoom: int) -> tuple[int, int]:
"""
Turns a lon/lat measurement into a Slippy map tile at a given zoom.
"""
# Clamps lon, lat to proper mercator projection values
lat = min(lat, 85.0511)
lat = max(lat, -85.0511)
lon = min(lon, 1... | cdd542c8a362d54dccb8760278b22a17f5df57f9 | 3,615,590 |
def simpson_integral(f, a, b):
"""辛普森求积公式
"""
return (b - a) * (f(a) + 4 * f((a + b) / 2) + f(b)) / 6 | 572e7af1137ed0f7b6be12f2869a0aa5ba123f85 | 3,615,591 |
def api_subscribe_pull_request(repo, requestid, username=None, namespace=None):
"""
Subscribe to an pull-request
----------------------------
Allows someone to subscribe to or unsubscribe from the notifications
related to a pull-request.
::
POST /api/0/<repo>/pull-request/<request id>/... | f7a5cac4ae7c2b84ebd5da2e702356ef58da4ca3 | 3,615,592 |
def _group_lst(lst, n):
"""Split the lst into sublists of len n."""
return (lst[i : i + n] for i in range(0, len(lst), n)) | c609b16940718d128d62bae7c9e0d94c16207080 | 3,615,593 |
def get_cincinnati_channels(major, minor):
"""
:param major: Major for release
:param minor: Minor version for release.
:return: Returns the Cincinnati graph channels associated with a release
in promotion order (e.g. candidate -> stable)
"""
major = int(major)
minor = int(minor... | e57ad8d26ea0a397e8c3f9edc99174f78b506564 | 3,615,594 |
def translate_batch(exe,
src_words,
encoder,
enc_in_names,
enc_out_names,
decoder,
dec_in_names,
dec_out_names,
beam_size,
max_length,
... | 0cbb5c68b4289530c161e7aaa44c0c68d11518f4 | 3,615,595 |
from typing import Optional
from typing import Tuple
def load_audio(
file: str, sr: Optional[int], verbose=True, **kwargs
) -> Tuple[Tensor, AudioMetaData]:
"""Loads an audio file using torchaudio.
Args:
file (str): Path to an audio file.
sr (int): Optionally resample audio to specified t... | 9db58f1805120a3a24013d0625665fa90710b3d0 | 3,615,596 |
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return MetaConv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) | 6d02696846d31cf8dc14d03ed08c7375c7642849 | 3,615,597 |
def get_value(seq, index):
"""Get the value of a nested sequence using index.
"""
if index == ():
return seq
if isinstance(seq, Storage):
return seq[index]
assert isinstance(seq, (tuple, list)), type(seq)
value = seq
for i in index:
value = value[i]
return value | bd923ed372efb99fdbe80d7a443c62a9c9df6d84 | 3,615,598 |
import logging
import time
def indices_client():
"""Returns an Elasticsearch indices client that is responsive
to the environment variable ELASTICSEARCH_ENDPOINT"""
es_connected = False
while not es_connected:
try:
ES = Elasticsearch(
hosts=[HOSTNAME]
)
... | 22a625170dc42523c5747ce5f76da198d0a3a74a | 3,615,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.