content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def rhand (x,y,z,iopt,parmod,exname,inname):
"""
Calculates the components of the right hand side vector in the geomagnetic field
line equation (a subsidiary subroutine for the subroutine step)
:param x,y,z:
:param iopt:
:param parmod:
:param exname: name of the subroutine for the external... | 008912796a0ac5c61de3b1fa5de90edbf8ed1f61 | 30,600 |
def unique_slug_generator_by_email(instance, new_slug=None):
"""
This is for a Django project and it assumes your instance
has a model with a slug field and a title character (char) field.
"""
slug = new_slug if new_slug is not None else slugify(instance.email)
Klass = instance.__class__
qs_... | a1e1ae8b25e67a9a5f1d93164deb4b769afb4588 | 30,601 |
import logging
def register_provider(price_core_min=1):
"""Register Provider"""
mine(1)
web3.eth.defaultAccount = accounts[0]
prices = [price_core_min, price_data_transfer, price_storage, price_cache]
tx = config.ebb.registerProvider(
GPG_FINGERPRINT,
provider_email,
federa... | 9385a0291af2f306075bc2775d53cd67b442d985 | 30,602 |
from typing import Callable
def get_signature_and_params(func: Callable):
"""Get the parameters and signature from a coroutine.
func: Callable
The coroutine from whom the information should be extracted.
Returns
-------
Tuple[List[Union[:class:`str`, :class:`inspect.Parameter`]]]
... | cc53ba8f8cf54d8cf6167b57bc6ecb626605d333 | 30,603 |
def quadratic_formula(polynomial):
"""
input is single-variable polynomial of degree 2
returns zeros
"""
if len(polynomial.term_matrix) == 3:
if polynomial.term_matrix[2][1] == 1:
a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0]
return 0, -b/a
... | 5501abff2fadcd237e3cb0efc4bca615eef455da | 30,604 |
def handle_domain_deletion_commands(client: Client, demisto_args: dict) -> str:
"""
Removes domains from the inbound blacklisted list.
:type client: ``Client``
:param client: Client to use.
:type demisto_args: ``dict``
:param demisto_args: The demisto arguments.
:... | 54f9174a3b8db9820e612cd3782dac4b9af6554e | 30,605 |
def create_l2_lag_interface(name, phys_ports, lacp_mode="passive", mc_lag=False, fallback_enabled=False,
vlan_ids_list=[], desc=None, admin_state="up", **kwargs):
"""
Perform a POST call to create a Port table entry for L2 LAG interface.
:param name: Alphanumeric name of LAG Por... | 7dcce04a7c9dd5d533bcf40bdda94c5fc8ff2951 | 30,606 |
import argparse
def main_args_parser() -> argparse.Namespace:
""" Implements an easy user-friendly command-line interface.
It creates three main subparser (classify, train, eval) and add the appropriated arguments for each subparser.
Returns
-------
args: argparse.Namespace
input argum... | ef2e079e6fd95576d34d3dc6ab3f07aac6dc6aad | 30,607 |
def get_train_image_matrices(folder_name, num_images=4):
"""Gets image matrices for training images.
:param folder_name: String with name of training image folder in
input_data/train_images directory path.
:param num_images: Integer with number of images.
:return: Matrices from training images.... | be75cd1246421b13830931fd6551c94c0bd673f6 | 30,608 |
import torch
def to_chainer_device(device):
"""Create a chainer device from a given torch device.
Args:
device (torch.device): Device to be converted.
Returns:
A ``chainer.device`` object corresponding to the given input.
"""
if not isinstance(device, torch.device):
raise... | d2d1c9ddf50792225260133f1d434e3166b6338b | 30,609 |
def decode_region(code):
""" Returns the region name for the given region code.
For example: decode_region("be") => "Belgium".
"""
for tag, (language, region, iso639, iso3166) in LANGUAGE_REGION.iteritems():
if iso3166 == code.upper():
return region | 5a4467088d8824a8647d9c7ed89381b94ddab096 | 30,610 |
import zipfile
import os
def unzip_whatsapp_file(whatsapp_file):
"""
unzips a whatsapp .zip file and returns the path of the _chat.txt file that was extracted from the zip
Parameters
----------
whatsapp_file: str
path to a .zip file with the exported data from Whatsapp.
Returns
-... | 694aa88575a35fe07fd781b020db17f217fe01a0 | 30,611 |
def neighbourhood_peaks(signal, n=10):
"""Computes the number of peaks from a defined neighbourhood of the signal.
Reference: Christ, M., Braun, N., Neuffer, J. and Kempa-Liehr A.W. (2018). Time Series FeatuRe Extraction on basis
of Scalable Hypothesis tests (tsfresh -- A Python package). Neurocomputing 3... | b684419844a747633d667abab9b6819f61d13d05 | 30,612 |
def check_success(env, policy, act_noise_pct, render=False):
"""Tests whether a given policy solves an environment
Args:
env (metaworld.envs.MujocoEnv): Environment to test
policy (metaworld.policies.policies.Policy): Policy that's supposed to
succeed in env
act_noise_pct (fl... | 260a03bc47c3864894b5d2922a636bd54b8d1253 | 30,613 |
import glob
def import_data(file_regex, index_col_val=None, parse_dates=None,
date_format=None):
"""
takes in a regular expression describing the filepath to
the data files and returns a pandas dataFrame
Usage1:
var_name = import_data.import_data("./hackat... | 411f767bd27cb40d9aaea28feb94da9f29b1f5aa | 30,614 |
def shift_num_right_by(num: int, digits: int) -> int:
"""Shift a number to the right by discarding some digits
We actually use string conversion here since division can provide
wrong results due to precision errors for very big numbers. e.g.:
6150000000000000000000000000000000000000000000000 // 1e27
... | ff29f5fbc53c8cfa5fa4172fd4e6e7c0b8b4e27b | 30,615 |
def index_handler(request):
"""
List latest 6 articles, or post a new article.
"""
if request.method == 'GET':
return get_article_list(request)
elif request.method == 'POST':
return post_article(request) | b64a81c4bde4d83f99663ffb6384ff6cde8a217c | 30,616 |
def getRawOutput(seqs, tmpfile, command, func):
"""
Returns output from a given subprocess command that is run iteratively
on a given sequence list. It writes to a temporary file on the disk that
should be specified. Also, a text processing function can be passed that
takes the command line program'... | 56af903386d395c88a91313ef1f4a46b56688179 | 30,617 |
import sys
def is_windows() -> bool:
"""
Returns True if the current system is Windows. Returns False otherwise.
"""
return sys.platform == "win32" | bb4f78364bd2182b79b7517466eb251731826464 | 30,618 |
import os
import multiprocessing
def hillis_steeles_scan_inclusive_parallel(inp_list):
"""
Takes in a list, performs hillis-steeles inclusive scan parallelly, returns a shared memory array with the results
input: inp_list, 1D list of n elements.
returns: 1D Array, newArr of n elements.
"""
numProcessors = os.cp... | 13ffd70a98c27360d2032a300375f72dfa62eb37 | 30,619 |
import math
import os
def confusion_matrices(prediction, matrix=False, save=False, OutputPath=None, name=None):
"""
This function plot the confusion matrix at every level of the classification tree.
"""
cnf_matrix_level_1 = confusion_matrix(prediction['label_level_1'].values,prediction['... | 35bdc3911244d8cc30b5cc830b13cca0c7339018 | 30,620 |
import numpy
def back_propogation(weights, aa, zz, y1hot, lam=0.0):
"""Perform a back propogation step
Args:
weights (``list`` of numpy.ndarray): weights between each layer
aa (``list`` of numpy.ndarray): activation of nodes for
each layer. The last item in the list is the hypothesis.
... | 2909809699ae3b3fd5ab97b6294391322cf3d8bb | 30,621 |
async def get_reverse_objects_topranked_for_lst(entities):
"""
get pairs that point to the given entity as the primary property
primary properties are those with the highest rank per property
see https://www.wikidata.org/wiki/Help:Ranking
"""
# some lookups just take too long, so we remove them... | 7266b4f29e3c3878abc14c995da7713a8d7121e0 | 30,622 |
import stat
def compute_confidence_interval(data,confidence=0.95):
"""
Function to determine the confidence interval
:param data: input data
:param confidence: confidence level
:return: confidence interval
"""
a = 1.0 * np.array(data)
n = len(a)
se = stat.sem(a... | b7f64935cefdb2f60a7ca7fdc720b3ecddf7e89c | 30,623 |
def adjacent_powerset(iterable):
"""
Returns every combination of elements in an iterable where elements remain ordered and adjacent.
For example, adjacent_powerset('ABCD') returns ['A', 'AB', 'ABC', 'ABCD', 'B', 'BC', 'BCD', 'C', 'CD', 'D']
Args:
iterable: an iterable
Returns:
a li... | 951418b30d541e1dcdd635937ae609d429e3cd70 | 30,624 |
from typing import Iterator
from typing import Counter
import tqdm
def export_ngrams(
docs: Iterator[str], nlp: spacy.language.Language, n: str, patterns=False
) -> Counter:
"""
Extracts n-gram frequencies of a series of documents
Parameters
----------
docs : Iterator[str]
An iterator... | 242d0b3fcb2dffd2d35ae76416dfc7861bdfb916 | 30,625 |
import argparse
def getArguments():
"""
Gets the name of the gameFile.
:return: The arguments provided by the user
"""
parser = argparse.ArgumentParser()
parser.add_argument('gameFile', help='The ini formatted file with the game configuration')
return parser.parse_args() | b8f3d440e3cd2976e946e7745fb06ff86f179f8a | 30,626 |
import torch
def solve2D_system(
pde_system, conditions, xy_min=None, xy_max=None,
single_net=None, nets=None, train_generator=None, shuffle=True, valid_generator=None,
optimizer=None, criterion=None, additional_loss_term=None, batch_size=16,
max_epochs=1000,
monitor=None, retu... | f9763819a3df3477df88dea395c45d7a357c25c7 | 30,627 |
def model_criterion(preds, labels):
"""
Function: Model criterion to train the model
"""
loss = nn.CrossEntropyLoss()
return loss(preds, labels) | c4005131b30c2e5bab03d13ec00fcf96657b4fbb | 30,628 |
def get_dbmapping(syn: Synapse, project_id: str) -> dict:
"""Gets database mapping information
Args:
syn: Synapse connection
project_id: Project id where new data lives
Returns:
{'synid': database mapping syn id,
'df': database mapping pd.DataFrame}
"""
project_ent =... | cee2daf40886a68871b400ae06298eff095a8205 | 30,629 |
def end_position(variant_obj):
"""Calculate end position for a variant."""
alt_bases = len(variant_obj['alternative'])
num_bases = max(len(variant_obj['reference']), alt_bases)
return variant_obj['position'] + (num_bases - 1) | e49110a1102ea2ca53053858597247799065f8e1 | 30,630 |
def cast_to_server(server_params, topic, msg):
"""
Invoke a remote method that does not return anything
"""
return _get_impl().cast_to_server(cfg.CONF, server_params, topic, msg) | 0fb92932dbe6f23cbc230bd2f23891a514bffd7a | 30,631 |
def get_classification_systems():
"""Retrieve all classification systems available in service."""
system = db.session.query(LucClassificationSystem).all()
return ClassificationSystemSchema().dump(system, many=True) | 03ca32de57f319144c1d185a2f5260ffab269a15 | 30,632 |
def read_annotations(filename, tagset, labeled):
""" Read tsv data and return sentences and [word, tag, sentenceID, filename] list """
with open(filename, encoding="utf-8") as f:
sentence = []
sentence.append(["[CLS]", -100, -1, -1, None])
sentences = []
sentenceID=0
for line in f:
if len(line) > 0:
... | bbb210fe631f1e10432ab6c18146d69933fe7187 | 30,633 |
def find_rmse(data_1, data_2, ax=0):
"""
Finds RMSE between data_1 and data_2
Inputs
------
data_1 (np.array)
data_2 (np.array)
ax (int) The axis (or axes) to mean over
Outpts
------
(int) RMSE between data_1 and data_2
"""
return np.sqrt(... | aed7ee0d6fda234f452056a91eb70495343579ac | 30,634 |
def validate_tag_update(update):
"""
Property: ResourceUpdateConstraint.TagUpdateOnProvisionedProduct
"""
valid_tag_update_values = [
"ALLOWED",
"NOT_ALLOWED",
]
if update not in valid_tag_update_values:
raise ValueError("{} is not a valid tag update value".format(update)... | c2abd7af00be52cf8cfecb5790d88a04d3207253 | 30,635 |
def bollinger_band(df: pd.DataFrame, window: int = 20, window_dev: int = 2) -> pd.DataFrame:
"""Implementation of bollinger band."""
df_with_signals = df.copy()
typical_price = (df["close"] + df["low"] + df["high"]) / 3
df_with_signals["typical_price"] = typical_price
std_dev = df_with_signals["typi... | 69fb61a09512967c92fc997134cad67e7659774f | 30,636 |
def close_corner_contour(contour: np.ndarray, shape: tuple) -> np.ndarray:
"""Check if contours are in the corner, and close them if needed.
Contours which cover a corner cannot be closed by joining the first
and last element, because some of the area is missed. This algorithm
adds the corner point to ... | 62564816c5e00131a5ec59242467cee464d6f5ac | 30,637 |
import os
import argparse
def writable_prefix(prefix):
"""
Checks if this prefix is writable and exists.
:param prefix: str - prefix to check
:return: str - prefix
"""
directory = os.path.dirname(prefix)
if not os.path.exists(directory):
error = "Output directory %s does not exist ... | 89fd163c7d3bd9aaca3e26e4b72aef0c98236d8b | 30,638 |
def simulate_spatial_ratiometric_reading(
do, temperature, sealed_patch_do=0, sealed_patch_kwargs={}, unsealed_patch_kwargs={}
):
""" Simulate a "spatial ratiometric" reading using a sealed DO patch as the ratiometric reference
Args:
do: Dissolved Oxygen partial pressure in mmHg in the unsealed pat... | 17bc66583c6d9c8a9c77b6e9e19f3adee2e73617 | 30,639 |
import json
async def create_pool(uri, **kwargs) -> asyncpg.pool.Pool:
"""Creates a connection pool to the specified PostgreSQL server"""
def _encode_jsonb(value):
return b'\x01' + json.dumps(value).encode('utf-8')
def _decode_jsonb(value):
return json.loads(value[1:].decode('utf-8'))
... | e6de8369412a63466ecdc6ccc7ae23889fb2745f | 30,640 |
from .interactive._iplot_state import iplot_state
from ._state_visualization import plot_state as plot
from .interactive._iplot_state import iplot_state
from ._state_visualization import plot_state as plot
def plot_state(rho, method='city', filename=None, options=None, mode=None,
show=False):
"""Pl... | 3266a41986b8c77a966fd5b76fb55e2b330dd05e | 30,641 |
from datetime import datetime
def tick_format(ticktime):
"""
Format the tick date/time
"""
datetime_object = datetime.strptime(ticktime, '%Y-%m-%dT%H:%M:%S.%fZ')
return datetime_object.strftime("%H:%M:%S UTC %A %d %B") | 6fa02f7627bc947646046a47ab7298aad68399d8 | 30,642 |
def add_finite_filter_to_scorer(score_func):
"""Takes a scorer and returns a scorer that ignores NA / infinite elements in y_true.
sklearn scorers (and others) don't handle arrays with 0 length. In that case, return None
:param score_func: function that maps two arrays to a number. E.g. (y_true, y_pred) -... | a6ee3874b12213fa2b5ea385a8343c8ba3e1462b | 30,643 |
import gc
def lsst_fit(lc, grp):
"""Take full mock LC and SDSS cadence to find best_fit params.
Args:
lc: Kali LC object, full mock LC.
grp: HDF5 group storing the MCMC chains.
"""
best_param = [] # store best-fit params
ref_ls = []
task = kali.carma.CARMATask(1, 0, nste... | 44cd48fe3c7d3de50fdab2c007a0f4c947ae3116 | 30,644 |
def getStudioModeStatus():
"""
Indicates if Studio Mode is currently enabled.
"""
return __createJSON("GetStudioModeStatus", {}) | 544ffccc459259b52b395aadb94c0439d824f7b4 | 30,645 |
from typing import Tuple
def calc_long_short_prec(
pred: pd.Series, label: pd.Series, date_col="datetime", quantile: float = 0.2, dropna=False, is_alpha=False
) -> Tuple[pd.Series, pd.Series]:
"""
calculate the precision for long and short operation
:param pred/label: index is **pd.MultiIndex**, ind... | e74c6666922786522f55190d8f4d9125bb86c94d | 30,646 |
def prepare_tuple_argument(arg, n, arg_name, validate_args=False):
"""Helper which processes `Tensor`s to tuples in standard form."""
arg_size = ps.size(arg)
arg_size_ = tf.get_static_value(arg_size)
assertions = []
if arg_size_ is not None:
if arg_size_ not in (1, n):
raise ValueError('The size of ... | 51f94eb8e4eef0b69df443ca71fdc9def3fd55a1 | 30,647 |
import zipfile
def isValidLibreOfficeFile(file_path):
"""
Return true if given file is valid LibreOffice ods file containing
manifest.xml, false otherwise.
"""
try:
with zipfile.ZipFile(file_path, 'a') as open_document:
open_document.open(DOCUMENT_MANIFEST_PATH)
return ... | 3e36bea3c7f3bd72b91cefba94087ea8afc5116e | 30,648 |
def mean_absolute_percentage_error(y_true, y_pred, zeros_strategy='mae'):
"""
Similar to sklearn https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html
with options for behaviour for around zeros
:param y_true:
:param y_pred:
:param zeros_strategy:
:return... | 5720343835378e50399caafeada31685effde5de | 30,649 |
import json
def __get_pretty_body__(headers, body):
"""
Return a pretty printed body using the Content-Type header information
:param headers: Headers for the request/response (dict)
:param body: Body to pretty print (string)
:return: Body pretty printed (string)
"""
if HEADER_CONTENT_TYP... | 4cb173c8c5d8c924b58b0c39f5595e353e514eee | 30,650 |
def bell_sigmoid(ds, a=None, bc=None, d=None, inplace=True):
"""
Apply a fuzzy membership function to data
using bell-shaped sigmoidal function. Requires a
low left inflection (a), a mid-point (bc), and a low
right inflection (d) point to set the bounds in which to
rescale all values to. Value... | 3e0476a4df3d2c63646aedbc4a64e8ee3656bc43 | 30,651 |
import os
import logging
def post_binary(binary, byte_start, byte_data):
"""Accept a binary file or packet.
binary = binary to get the file to write to from
byte_start = offset from beginning of file to begin writing
byte_data = an iterable that contains data
"""
result = True
... | 0af0f540a2c7bd92df3228d38adda0a4548a3ea9 | 30,652 |
def get_composite(name, error=DontCatchError, error_message=None,
identifier=None, component_category='unknown'):
"""
Gets a Composite Singleton
:param:
- `name`: name to register singleton (clients that want same singleton, use same name)
- `error`: exception to catch (``DontC... | 39bfe67a1482c7c157e655c3f1accb308fa211b0 | 30,653 |
def is_list_of_float(value):
"""
Check if an object is a liat of floats
:param value:
:return:
"""
return bool(value) and isinstance(value, list) and all(isinstance(elem, float) for elem in value) | 35ec9531bcddc33166e0f17d3fc59a08341d2d95 | 30,654 |
def get_example_params(example_index):
"""
Gets used variables for almost all visualizations, like the image, model etc.
Args:
example_index (int): Image id to use from examples
returns:
original_image (numpy arr): Original image read from the file
prep_img (numpy_arr): Proce... | 6e2760e4d91d888ce9f1443787b9bfa864fe7118 | 30,655 |
from geometrylab.geometry import Polyline
def bezier_curve(points, nTimes=500, is_poly=False, is_crv=False):
"""
Given a set of control points, return the
bezier curve defined by the control points.
points should be a list of lists, or list of tuples
such as [ [1,1],
... | 0b60554a2b8697c665822ecf408a089b89df7107 | 30,656 |
import functools
def decorator_with_keywords(func=None, **dkws):
# NOTE: ONLY ACCEPTS KW ARGS
"""
A decorator that can handle optional keyword arguments.
When the decorator is called with no optional arguments like this:
@decorator
def function ...
The function is passed as the first a... | 64c4ddd26cc04a43cbf559600652113db81b79ae | 30,657 |
from datetime import datetime
def parse_line(line):
"""
Extract all the data we want from each line.
:param line: A line from our log files.
:return: The data we have extracted.
"""
time = line.split()[0].strip()
response = line.split(' :')
message = response[len(response) - 1].strip... | 72b4362b7628d31996075941be00e4ddcbd5edbc | 30,658 |
def semi_lagrangian(field: GridType,
velocity: Field,
dt: float,
integrator=euler) -> GridType:
"""
Semi-Lagrangian advection with simple backward lookup.
This method samples the `velocity` at the grid points of `field`
to determine the lo... | b265e660100a9855a99e03f3c03cbd4bad0f79c8 | 30,659 |
def pptx_to_bbox(left, top, width, height):
""" Convert matplotlib bounding box format to pptx format
Parameters
----------
left : float
top : float
width : float
height : float
Returns
-------
bottom, left, width, height
"""
return top-height, left, width, height | 3cdc186301d7e6e97ea44923ca6859e2e51f0774 | 30,660 |
from typing import Counter
def reindex(labels):
"""
Given a list of labels, reindex them as integers from 1 to n_labels
Also orders them in nonincreasing order of prevalence
"""
old2new = {}
j = 1
for i, _ in Counter(labels).most_common():
old2new[i] = j
j += 1
old2newf... | c12afd3b6431f10ccc43cce858e71bc504088a6e | 30,661 |
def _validate_vg(module, vg):
"""
Check the current state of volume group.
:param module: Ansible module argument spec.
:param vg: Volume Group name.
:return: True (VG in varyon state) or False (VG in varyoff state) or
None (VG does not exist), message.
"""
lsvg_cmd = module.ge... | c5d68f69243f1ca24140f09c7047269b7012ed6c | 30,662 |
from typing import List
def news_items(news_index_page) -> List[News]:
"""Fixture providing 10 News objects attached to news_index_page
"""
rv = []
for _ in range(0, 10):
p = _create_news_page(f"Test News Page {_}", news_index_page)
rv.append(p)
return rv | e7e8f417cefd713b9d79e6e28b654df9dd0ca0da | 30,663 |
def is_annotated(procedure):
"""Return True if procedure is annotated."""
procedure = annotatable(procedure)
try:
ann = procedure.func_annotations
return ann.are_for(procedure) and bool(ann)
except AttributeError:
return False | 70eccace122462584e3c536fafe272b5397ac659 | 30,664 |
import io
import os
def read_matrix(name):
"""\
Helper function to read a matrix from /ref_matrix. The file extension .txt
is added automatically.
:return: A tuple of bytearrays
"""
matrix = []
with io.open(os.path.join(os.path.dirname(__file__), 'ref_matrix/{0}.txt'.format(name)), 'rt') ... | b1b70818b36957f2684320d3406bc1e877dfd366 | 30,665 |
def _enable_disable_pim_config(tgen, topo, input_dict, router, build=False):
"""
Helper API to enable or disable pim on interfaces
Parameters
----------
* `tgen` : Topogen object
* `topo` : json file data
* `input_dict` : Input dict data, required when configuring from testcase
* `route... | 4408ac212126895ba161f834e7e076a0c14d864f | 30,666 |
from typing import Union
def linear_interpolation_formula(
left: Union[float, np.array],
right: Union[float, np.array],
gamma: Union[float, np.array],
) -> Union[float, np.array]:
"""
Compute the linear interpolation weighted by gamma on each point of two same shape array.
"""
return gamma... | cdcb915f6bfc60db2f3754044ab5b67432d66370 | 30,667 |
def estimate_visib_mask_est(d_test, d_est, visib_gt, delta, visib_mode='bop19'):
"""Estimates a mask of the visible object surface in the estimated pose.
For an explanation of why the visibility mask is calculated differently for
the estimated and the ground-truth pose, see equation (14) and related text in
Ho... | 90f2de0a4e489207e128668510ba8b08a0bd361f | 30,668 |
import itertools
def combine_assertions(input_filename, output_filename):
"""
Take in a tab-separated, sorted "CSV" files, indicated by
`input_filename`, that should be grouped together into assertions.
Output a msgpack stream of assertions the file indicated by
`output_filename`.
The input f... | 87e2e7df2484dcff7f315da91ef39472991c2351 | 30,669 |
import os
def find_testclass(package, program, testclass, file_required=False):
"""Find the relative path of the test-class file"""
name = f'{program.lower()}.clas.testclasses.abap'
for root, _, files in os.walk('.'):
if name in files:
return os.path.join(root, name)[2:]
if file_... | 9da2aeaadb042da868b0c6d6e5069842cc014654 | 30,670 |
def sanitize_mobile_number(number):
"""Add country code and strip leading zeroes from the phone number."""
return "254" + str(number).lstrip("0") | 944e6e5baef92ee7c59249714a9ba3463ff5981f | 30,671 |
def fakebaraxis(ticks, painter=fakebarpainter(),*args, **kwargs):
"""Return a PyX linear axis that can be used to make fake bar plots.
Use "keyticks" to create the ticks expected by this function."""
return axis.linear(
min=-0.75,
max=len(ticks)-0.25,
parter=None,
manualtick... | 99b30a9b76b9da8e4c8e1c937431aa509b47ab16 | 30,672 |
import csv
def get_score_sent_pairs_from_tsv(tsv_filepath, encoding="ISO-8859-1"):
"""expects tokenized sentences in tsv file!"""
with open(tsv_filepath, encoding=encoding) as tsvfile:
reader = csv.reader(tsvfile, delimiter='\t')
score_sent_pairs = [[float(row[0]), row[1]] for row in reader]
return scor... | 44f5c150d40b407b50a93cd0ad968658fd5ef431 | 30,673 |
def test_timings_trie(port, individual_test_timings):
"""Breaks a test name into chunks by directory and puts the test time as a value in the lowest part, e.g.
foo/bar/baz.html: 1ms
foo/bar/baz1.html: 3ms
becomes
foo: {
bar: {
baz.html: 1,
baz1.html: 3
}
... | dfca4a92715063620b3a110df3ea29b2de3bb0b6 | 30,674 |
def prop_end(wf, **kwargs):
"""Set variables needed to properly conclude a propagation run.
Parameters
----------
wf : obj
The current WaveFront class object
Returns
-------
wf.wfarr : numpy ndarray
Wavefront array
sampling : float
Sampling in meters
Oth... | d294939f5e26df7672611ae6b58ac7039e8d22c0 | 30,675 |
def add_others_ta(df, close, fillna=False):
"""Add others analysis features to dataframe.
Args:
df (pandas.core.frame.DataFrame): Dataframe base.
close (str): Name of 'close' column.
fillna(bool): if True, fill nan values.
Returns:
pandas.core.frame.DataFrame: Dataframe wit... | 97185202663cb83ed1dc5f4bd02320b0ce02c4aa | 30,676 |
def _fixture_union(caller_module, name, fixtures, idstyle, scope="function", ids=fixture_alternative_to_str,
unpack_into=None, autouse=False, **kwargs):
"""
Internal implementation for fixture_union
:param caller_module:
:param name:
:param fixtures:
:param idstyle:
:para... | 7063ab888b99cc0aa10890de9f4575f0ce758017 | 30,677 |
def service_class(cls):
"""
A class decorator enabling the instances of the class to be used
as a ``services``-provider in `JSONRpc Objects`_
and `BSONRpc Objects`_.
Use decorators ``request``, ``notification``, ``rpc_request`` and
``rpc_notification`` to expose methods for the RPC peer node.
... | 7c146b1d04415cd494e62fb9ee310364c345c217 | 30,678 |
def lightcurveplain(request, tcs_transient_objects_id):
"""lightcurveplain.
Args:
request:
tcs_transient_objects_id:
"""
transient = get_object_or_404(TcsTransientObjects, pk=tcs_transient_objects_id)
mjdLimit = 55347.0 # Hard wired to 31st May 2010
# 2012-07-18 KWS Changed this... | 0db9b5ccdb5df9c65fab971fe72d5cec6da84676 | 30,679 |
def locate_address(ip_list, ip_attack):
"""
for each line in the file pointer
define the ip ranges and country codes
if the attacking ip is in between the range then return country code
:param ip_list - list of ip address ranges and country code:
:param ip_attack - attacking ip as an int... | 82a8f9ed0cf79a2ba39d21348779687c1f8c19a8 | 30,680 |
import scipy
def invertnd(f, x, *other_vars, kind='linear', vectorized=False):
"""
Invert a multivariate function numerically
Args:
f: Function to invert
x: Domain to invert the function on (range of inverted function)
*other_vars: Domain to invert the function on (parameters of in... | bc2798e382a700755a1d6a5d59743b969d96a02d | 30,681 |
def most_mentioned(msgs, limit=20):
"""Top mentions by '@' references
"""
mentions = {}
for m in msgs:
for at in preproc.extract_ats_from_text(m['text']):
mentions[at] = mentions[at] + 1 if at in mentions else 1
return sorted(mentions.items(),
key=lambda x: x[1]... | 10aa70248d33325d585fb19875a13965f67896b5 | 30,682 |
import string
def is_valid_matlab_field_label(label):
""" Check that passed string is a valid MATLAB field label """
if not label.startswith(tuple(string.ascii_letters)):
return False
VALID_CHARS = set(string.ascii_letters + string.digits + "_")
return set(label).issubset(VALID_CHARS) | ea1358e94f4fc936cb12b9cad5d7285ee39dba55 | 30,683 |
def identity(n, dtype=DEFAULT_FLOAT_DTYPE):
"""
Returns the identity tensor.
Args:
n (int): Number of rows and columns in the output, must be larger than 0.
dtype (Union[mstype.dtype, str], optional): Designated tensor dtype, can
be in format of np.float32, or `float32`. Default... | 7ad0025b5fb5bc02b8f07039b8beb15e8c402c11 | 30,684 |
def _chain_connectivity(edges, chains):
"""Returns chain connectivity treated as clustered entities represented by nodes"""
chain_connectivity = np.empty((len(edges), 2), dtype=np.int64)
starts = defaultdict(list)
for section_index, chain in enumerate(chains):
starts[chain[0][0]].append(section... | 5687b433a1c47a75641442aef1b8cff4c8cb4e17 | 30,685 |
def reading2celsius(self, reading):
""" Converts sensor reading to celsius """
celsius = reading / 50 - 273.15
return celsius | 72e6933002c9725165145451e10bbf98c162b625 | 30,686 |
import sqlite3
def evaluate_csp(website_id, test_weights):
"""
Checks:
no fallback to default:
base-uri
form-action
frame-ancestors
report-to/uri
sandbox
upgrade-insecure-requests
... | a5c24968ad98790eb3361db8310416b977e4adc7 | 30,687 |
def get_analysis_alias_from_metadata(eload_cfg):
"""
Returns analysis alias only if we find a metadata spreadsheet and it has exactly one analysis.
Otherwise provides an error message and raise an error.
"""
metadata_spreadsheet = eload_cfg.query('submission', 'metadata_spreadsheet')
if metadata... | ac3ecc7aa14f37fa2a25f9b7995923013c68a5c3 | 30,688 |
from imcsdk.mometa.bios.BiosProfileManagement import BiosProfileManagement
from imcsdk.mometa.bios.BiosProfileManagement import \
def bios_profile_backup_running(handle, server_id=1, **kwargs):
"""
Backups up the running configuration of various bios tokens to create a
'cisco_backup_profile'.
Will ove... | e1c1a7b498df6af5238914522eae56e666df328f | 30,689 |
def variantCombinations(items):
""" Calculates variant combinations for given list of options. Each item in the items list represents
unique value with it's variants.
:param list items: list of values to be combined
>>> c = variantCombinations([["1.1", "1.2"], ["2.1", "2.2"], ["3.1", "3.2"]])
>>> ... | 72bfdb19db3cf692e4260a5f75d10324e562f20e | 30,690 |
import regex
def bm_regex(regex_string):
"""Compile best multiline regex."""
return regex.compile(regex_string, regex.B | regex.M) | 9c6507708b1d04ef91783bfd04f4949a9dfc6b76 | 30,691 |
def test_enable_8021q_1(monkeypatch):
"""Verify that enable_802q_1 function return exception when 802.1q is not supported by current os.
"""
def mockreturn(command):
return CmdStatus("", "", 0)
# monkeypatch.setattr(CLISSHNetNS, 'exec_command', mockreturn)
lh = GenericLinuxHost(LH_CFG, OPTS... | 4c3261ef788b369d185c4caff0f02a67818c5cc8 | 30,692 |
def qlearning_dataset(env, dataset=None, terminate_on_end=False, **kwargs):
"""
Returns datasets formatted for use by standard Q-learning algorithms,
with observations, actions, next_observations, rewards, and a terminal
flag.
Args:
env: An OfflineEnv object.
dataset: An optional da... | bcc59e159ada77d2b3acaed530f190d3fcf8a706 | 30,693 |
import torch
def build_save_dataset(corpus_type, fields, opt): # corpus_type: train or valid
""" Building and saving the dataset """
assert corpus_type in ["train", "valid"] # Judging whether it is train or valid
if corpus_type == "train":
src_corpus = opt.train_src # 获取... | 85594737b15ff356da3dcb431bab9c648122f57a | 30,694 |
def gaussian_filter(image, sigma):
"""Returns image filtered with a gaussian function of variance sigma**2"""
i, j = np.meshgrid(np.arange(image.shape[0]),
np.arange(image.shape[1]),
indexing='ij')
mu = (int(image.shape[0]/2.0),
int(image.shape[1]/2.... | 18f8d59ebe82fbeb5cc6090c3c01460923cbbf08 | 30,695 |
def get_lattice_points(strand):
"""
格子点の情報を取得
@param ストランドの格子点の対
@return ストランドの格子点の始点と終点
"""
strand_list = eval(strand)
strand_from = strand_list[0]
strand_to = strand_list[1]
return strand_from, strand_to | a69902c15b9d8ce9f518891f4dea55d9aca186cf | 30,696 |
def while_(condition):
"""
A while loop that can be used in a workchain outline.
Use as::
while_(cls.conditional)(
cls.step1,
cls.step2
)
Each step can, of course, also be any valid workchain step e.g. conditional.
:param condition: The workchain method that will retu... | 6594c6da24d6a27d674ddb18713a0e521f0dc2dd | 30,697 |
def new(init=None):
"""Return a new Whirlpool object. An optional string argument
may be provided; if present, this string will be automatically
hashed."""
return Whirlpool(init) | 2d6bc8ce41009d642c78d92b022b44a23f67c496 | 30,698 |
def extract_bcr(tab, rep_col='CDR3_aa'):
""" Extract BCR repertorie for each patient
Args:
tab: data table from TRUST BCR outputs
rep_col: 'CDR3_aa' or 'complete_CDR3_sequences' or a list of keys
Output: a Series vector containing lists of BCR CDR3 sequences
"""
ta... | 998a3cfd6619b2fa3ae791e523f258a5a82e584b | 30,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.