content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def transformation(job_title):
"""
Transform a job title in a unisex job title
Here are examples of main transformations :
- Chauffeur / Chauffeuse de machines agricoles --->>> Chauffeur de machines agricoles
- Débardeur / Débardeuse --->>> Débardeur
- Arboriste grimpeur / grimpeuse --->>> Arbor... | f8580e9a64070ba96cfd540a58327f904c311f9b | 3,609,100 |
from typing import Optional
from typing import Any
def _handle_tileset(tileset: Optional[tcod.tileset.Tileset]) -> Any:
"""Get the TCOD_Tileset pointer from a Tileset or return a NULL pointer."""
return tileset._tileset_p if tileset else ffi.NULL | 2fb133ae732e824c340a4a42a718c0b24409e54f | 3,609,101 |
import gzip
import bz2
def open_zipped(infile, mode='r'):
""" Return file handle of file regardless of zipped or not
Text mode enforced for compatibility with python2 """
mode = mode[0] + 't'
p2mode = mode
if hasattr(infile, 'write'):
return infile
if isinstance(infile, str):
... | 0c6444e844ea27a30830584834e8cbc4926c1972 | 3,609,102 |
from typing import Dict
def user_kid_injection(jwt_json: Dict, injection: str) -> str:
"""
Print for kid injection method.
Parameters
----------
jwt_json: Dict
your jwt json (use encode_to_json.Check Doc).
injection: str
your injection
Returns
----------
str
... | 71e7c09002b425ab3e3017d33ef9daac8036c86d | 3,609,103 |
def render_text_block(el, ns=None):
"""
Created for EcoSpold2. Take all the children of an objectified element and render them as a text block. Implement
variable substitution (!!!)
:param el: Element with tags including 'text' and 'variable'
:param ns: [None] namespace
:return:
"""
vs ... | 696dcc4386384b6865b81c14047c001d5f6fc780 | 3,609,104 |
import time
import requests
import json
def macro_china_cpi_monthly():
"""
中国月度CPI数据, 数据区间从19960201-至今
https://datacenter.jin10.com/reportType/dc_chinese_cpi_mom
:return: pandas.Series
"""
t = time.time()
res = requests.get(
JS_CHINA_CPI_MONTHLY_URL.format(
str(int(roun... | a74ead1750e66c660e8dfbc28f168db5f8fe2829 | 3,609,105 |
def get_integer(prompt):
"""Gets an integer from the user."""
myInteger = input(prompt)
while not is_integer(myInteger):
print("Integers only please.")
myInteger = input(prompt)
myInteger = int(myInteger)
return myInteger | 63fcff9f7be72d1c9bc38f8885680677f3288ef0 | 3,609,106 |
def all_pairwise_distances(x, y=None, squared=False, approx=False):
"""
Fast pairwise L2 squared distances between two sets of d-dimensional vectors
Args:
x (Tensor): an Nxd matrix
y (Tensor, default=None): an optional Mxd matirx
squared (bool, default=False): if True returns square... | d31cdd5fcb6071626c989271209f839b89b97a33 | 3,609,107 |
def _random_zoom(x, scale=0.1, imshape=(256,256), **kwargs):
"""
Randomly zoom in on the image- augmented image will be between
[scale] and 100% of original area.
Based on the random crop function in the SimCLR repo:
https://github.com/google-research/simclr/blob/7fd0c80092a650c5318ce08fd3... | 51f541f6e8def5325fdf0fa518113da3f1c65340 | 3,609,108 |
def common_keys(dictionary_list):
""" Identify keys common to a set of dictionaries.
Arguments:
dictionary_list (list of dict): dictionaries to analyze
Returns:
(list): sorted list of common keys
"""
# find intersection of key sets
common_key_set = None
for current_diction... | 0cb0d2b1c0c033cb64636b1822501ec860d9449d | 3,609,109 |
def gaus(x, a, x0, sigma, c):
"""
Gaussian function.
:param x:
:param a: constant
:param x0: constant
:param sigma: RMS width
:param c: gaussian function offset
:return:
"""
return a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)) + c | b715e8464134f95324e1931f473bca90d173a16b | 3,609,110 |
import random
def coin_flip():
"""Randomly return 'heads' or 'tails'."""
if random.randint(0,1) == 0:
return "heads"
else:
return "tails" | c46afd1e6f6b899448501043400d1a7570aecabe | 3,609,111 |
def part_one(data):
"""Part one"""
nodes = read_nodes(data)
for name, _, _ in nodes:
count = data.count(name)
if count == 1:
return name
return None | 27368c64e486d0d61458db950961484cde75a953 | 3,609,112 |
from typing import Type
def get_tree_model() -> Type['TreeBase']:
"""Returns the Tree model, set for the project."""
return get_model_class('MODEL_TREE') | 992ce792ad2fa0e0826bab1a1d8dab0287f53c3d | 3,609,113 |
def wigner_d_parallel(m1,m2,theta,l,ncpu=None,l_use_bessel=1.e4):
"""
Compute wigner matrix in parallel.
"""
if ncpu is None:
ncpu=cpu_count()
p=Pool(ncpu)
d_mat=np.array(p.map(partial(wigner_d,m1,m2,theta,l_use_bessel=l_use_bessel),l))
p.close()
p.join()
return d_mat[:,:,0].... | 25e5a4839fabd0a6da4c141a80f3d2d38c34bbc6 | 3,609,114 |
def check_rule_permission(rule_id, permission):
""" Check the respective rule breaking the respective permission.
Args:
rule_id (str):
ruleNumber which should match 1 of the rules present in rule_ids for auto-remediation.
permission (list):
The permis... | 9862f71f0564f1f38443086dac39366a792dac35 | 3,609,115 |
import os
def readESO6Trajectory(trajectoryFile): ### DONE
"""
Reading trajectory eS06 file
trajectory [list]
initTime [s]
endTime [s]
"""
trajectory=[]
for line in open(trajectoryFile): trajectory.append(line.split())
firstLine=os.popen('head -1 '+trajectoryFile).read().split()
endLine=os.popen('tail -1 ... | feab61c30bd330abb2b8e3f59fb4950a6298e8f2 | 3,609,116 |
def flags_to_faces(flags, vert_tags):
"""
flags is a dict where the
key face tag + vert tag
value (face tag, vert tag, tag of next CCW vert in the face)
vert_tags
key vert tag
value index of vert
returns a list of faces, where each face is
given as a list of vert indices in CCW... | ac410a6f8e76dbefdb7e70ad64d1cefd7c224925 | 3,609,117 |
def generate_cell_type_cell_sets(df, cl_obo_file):
"""
Generate a tree of cell sets
for hierarchical cell type annotations.
"""
tree = init_cell_sets_tree()
# Load the cell ontology DAG
graph, id_to_name, name_to_id = load_cl_obo_graph(cl_obo_file)
ancestors_and_sets = []
for cell... | 6829acec52469a253afd2c9e71ddbff1803e49db | 3,609,118 |
import os
import json
def paginate(entries_to_post):
"""
This expects a list of dicts, and returns a list of lists of dicts,
where the maximum length of each list of dicts, under JSONification,
is less than max_chars
"""
max_chars = int(os.environ.get("PAGE_MAX_CHARS")) if os.environ.get("PA... | af62a55f250406c36880acdf66ced47ad2013104 | 3,609,119 |
def selectPersonsWhoAreRadiologists():
"""
Helper method to select all persons who are radiologists.
:return: A list of persons who are radiologists.
"""
return db.session.query(models.Person).join(models.User).filter(models.User.user_class == 'r').all() | 762d1a0749db5e94ad6a83f8f6ec742e701bdd68 | 3,609,120 |
def init_flat_save_grid(
dataset,
grid_shape,
times,
time_units,
projection,
x_min,
x_max,
y_min,
y_max,
units,
):
"""
Prepare a netCDF4 dataset for saving a concentration grid. This
preparation involves creating the appropriate dimensions, variables, and
attribut... | 3dd3b7e7ed2e63c1a9f529d72ecdb073552daf6b | 3,609,121 |
import os
def load_training_df(dataset_path: str) -> pd.DataFrame:
""" Load data from training set in Deep Fashion 2 into DataFrame """
#training_dir = os.path.join(dataset_path, 'train')
training_dir = dataset_path
images_dir = os.path.join(training_dir, 'image')
images_df = _load_images_df(image... | dd6895a060f8884d9c6467564419288a4b605ea6 | 3,609,122 |
import argparse
def get_args():
"""Parse sys.argv"""
parser = argparse.ArgumentParser()
parser.add_argument('-i','--input-dir', required=True,
help='The input directory containing the phylip files.')
args = parser.parse_args()
return args | 4fd4d48e3dbbb0d777c87ec3f5956422d6493c6f | 3,609,123 |
import uuid
def Upload(
id="dash-uploader",
text="Drag and Drop Here to upload!",
text_completed="Uploaded: ",
cancel_button=True,
pause_button=False,
filetypes=None,
max_file_size=1024,
chunk_size=1,
default_style=None,
upload_id=None,
max_files=1,
):
"""
du.Upload... | 3aeb6eef053aa8da72b1f86e6039eba0e524dc2e | 3,609,124 |
from re import T
def adagrad(loss, all_params, learning_rate=1.0, epsilon=1e-6):
"""
epsilon is not included in the typical formula,
See "Notes on AdaGrad" by Chris Dyer for more info.
"""
all_grads = theano.grad(loss, all_params)
all_accumulators = [theano.shared(np.zeros(param.get_value().sh... | cdcc1c9df10c5a4e0f43f7c623cf05c6a3dbb59a | 3,609,125 |
def _get_or_build_subword_text_encoder(tmp_dir, vocab_filepath, target_size):
"""Builds a SubwordTextEncoder based on the corpus.
Args:
tmp_dir: directory containing dataset.
vocab_filepath: path to store (or load) vocab.
target_size: an optional integer.
Returns:
a SubwordTextEncoder.
"""
i... | 9be9bfbba4a54577c6254d0b6aae4a25438e5881 | 3,609,126 |
import ast
def _ast_tree_to_dict(tree, only_self_params=False, lineno=False):
"""Parses ast trees to dict.
:param tree: ast.Tree
:param only_self_params: get only self params from class __init__ function
:param lineno: add params line number (needed for update)
:return:
"""
result = {}
... | 1dd15f69530385f1c35656d2092444297f3da06e | 3,609,127 |
import logging
import argparse
import bisect
def main():
"""Finds the commit SHA where an error was initally introduced."""
logging.getLogger().setLevel(logging.INFO)
utils.chdir_to_root()
parser = argparse.ArgumentParser(
description='git bisection for finding introduction of bugs')
parser.add_argum... | 271d483d32ecd8eb036517b0eebeb6a9e6883c71 | 3,609,128 |
def create_apps(
blockchain_services,
endpoint_discovery_services,
raiden_udp_ports,
transport_class,
verbosity,
reveal_timeout,
settle_timeout,
database_paths,
retry_interval,
retries_before_backoff,
throttle_capacity,
thro... | e89fab033fc55a0e1b06a9af2fb97a28fe7ee5db | 3,609,129 |
def sqnxt23_w3d2(**kwargs):
"""
0.75-SqNxt-23 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'... | 26febe9c0b738958573315848d0bcc95be776ad3 | 3,609,130 |
import requests
def spotlight(text):
"""To implement the DBpedia Spotlight API:
"""
headers = {
'Accept': 'application/json',
}
#e.g. text = "What is a car?" "enitenziagite" #"President Obama"
data = {
"text":text ,
'confidence': '0.35'
}
response = requests.post('http:... | dcf47994ae343cba9102d26e3cb86954e6f6c213 | 3,609,131 |
def NullBBox():
"""
Returns a BBox object with all NaN entries.
This represents a Null BB box;
BB merged with it will return BB.
Nothing is inside it.
"""
arr = np.array(((np.nan, np.nan), (np.nan, np.nan)), np.float64)
return np.ndarray.__new__(BBox, shape=arr.shape, dtype=arr.dtype,... | 418858f556b93567901af93fe5651a5928f9eba3 | 3,609,132 |
def fallback_to_gcc(args):
"""Check whether if we should fall back to GCC."""
if not invoked_as_gcc():
return False
return any(arg in GCC_ONLY_ARGS for arg in args[1:]) | 3a5cae2b8ee8d49b409578c013e0c9ee6a26634a | 3,609,133 |
def wms_in_extent(vector, extent_geom, buffer=0.1):
""" checks if vector layer within extent """
bounds = wms_bbox(vector)
bbox_vector = (bounds[0], bounds[2], bounds[1], bounds[3])
extent_buff = extent_geom.Buffer(buffer)
bbox_extent = extent_buff.GetEnvelope()
return bbox1_in_bbox2(bbox_vector... | 3e740e535c5be4bffa275fd78816934d66c33e93 | 3,609,134 |
def nans(axes=None, dims=None, shape=None):
""" Initialize an empty array filled with NaNs. See empty for doc.
>>> nans(dims=('time','items'), shape=(2, 3))
dimarray: 0 non-null elements (6 null)
0 / time (2): 0 to 1
1 / items (3): 0 to 2
array([[nan, nan, nan],
[nan, nan, nan]])
... | 2916274b6c5e86dbb464e41d6891dc4fd688592e | 3,609,135 |
def maximize(
criterion,
params,
algorithm,
criterion_kwargs=None,
constraints=None,
general_options=None,
algo_options=None,
gradient_options=None,
logging=DEFAULT_DATABASE_NAME,
log_options=None,
dashboard=False,
db_options=None,
):
"""Maximize *criterion* using *al... | 8a98fb39a849e72336858ff392a4faab0db7a7ab | 3,609,136 |
def hog_feature(image, multichannel=True):
""" Extract HOG feature descriptors from the image.
Args:
image (numpy array): Array of image pixels.
multichannel (bool): True for RGB image, else False.
Returns:
(numpy array): Feature descriptors.
"""
hog_feature_var = hog(ima... | a7ca9656dc378339f99d12620b10c5acbc836503 | 3,609,137 |
import io
def return_object():
""" Retrieve object data from the Fink database
"""
if 'output-format' in request.json:
output_format = request.json['output-format']
else:
output_format = 'json'
# Check all required args are here
required_args = [i['name'] for i in args_objects... | 41ea00f46fb5325ab584231852d08b8be7799e16 | 3,609,138 |
def detect_anomalies_cons(residuals, threshold, summary=True):
"""
Compares residuals to a constant threshold to identify anomalies. Can use set threshold level or threshold
determined by set_cons_threshold function.
Arguments:
residuals: series of model residuals.
threshold: constant th... | 4c37ca93ab8cbde85b57cb94b44ac1e234809be6 | 3,609,139 |
import redis
def connect_redis(dsn):
"""
Return the redis connection
:param dsn: The dsn url
:return: Redis
"""
return redis.StrictRedis.from_url(url=dsn) | 0b17418c36cd9a6eb5c0b4ea40a40762c1e41259 | 3,609,140 |
def _instance_to_allocations_dict(instance):
"""Given an `objects.Instance` object, return a dict, keyed by resource
class of the amount used by the instance.
:param instance: `objects.Instance` object to translate
"""
# NOTE(danms): Boot-from-volume instances consume no local disk
is_bfv = com... | 6b32e2912489e4192e42d00da00aa627101a1827 | 3,609,141 |
def _tag_depth(path, depth=None):
"""Add depth tag to path."""
# All paths must start at the root
if not path or path[0] != '/':
raise ValueError("Path must start with /!")
if depth is None:
depth = path.count('/')
return "{}{}".format(depth, path).encode('utf-8') | 6746ce97ac2569e2775cbdc13510263df0860deb | 3,609,142 |
def init_effects(context):
"""
Initialise common effects
:returns: effect configuration
"""
surface_manager = context.surface_manager
config = []
config.append(('cure minor wounds',
{'type': Heal,
'duration': 20,
'frequency': 5,
... | b8c7eb1c27f51e3c33f1d2c429ad9665e49b0435 | 3,609,143 |
from typing import Dict
from typing import Any
async def provider() -> Dict[str, Any]:
"""Define a basic example data provider function."""
async with Browser() as browser:
await browser.goto("https://httpbin.org/html")
content = await browser.content()
# response = await client.get("h... | f76c2e806ea9e89d078f6cd6d97a07304b9c9a05 | 3,609,144 |
def get_runtime_map(runtimes, module, tags=()):
"""Return a mapping of module and its derivatives that satisfy
a specified set of runtimes"""
result = {}
modruntimes = get_compatible_runtimes(module, tags=tags,
include_ancestors=True)
runtimes_full = []
... | 492e0d52a127791d2b73697cc1c0332018b89808 | 3,609,145 |
def calc_sl_price(contract_price, sl_percent):
"""Returns price that is sl_percent below the contract price"""
return round(contract_price * (1 - sl_percent), 2) | 487690208c81dcc708b526630929f1ba424b0c0f | 3,609,146 |
def Vortex(df, n):
"""
Vortex Indicator
"""
i = 0
TR = [0]
while i < len(df) - 1: # df.index[-1]:
Range = max(df.get_value(i + 1, 'High'), df.get_value(i, 'Close')) - min(df.get_value(i + 1, 'Low'), df.get_value(i, 'Close'))
TR.append(Range)
i = i + 1
i = 0
VM = ... | 6749c92bb0579a5e817f7faf07bd90c6e3264225 | 3,609,147 |
def qutip_gate(gate_name: str):
"""Generates the Pauli gate from a name
Parameters:
-----------
gate_name: string representing the gate, e.g. 'X' for sigmax() etc.
"""
if gate_name == 'X':
return sigmax()
elif gate_name == 'Y':
return sigmay()
elif gate_name == 'Z':
... | 331cb1a3ca71376d9e589d4c3f9b310699fcc62b | 3,609,148 |
def cspline(r,L,extra=False):
"""
CSPLINE Compactly supported spline function and derivatives.
f = cspline(R,L) is the compactly supported spline function
with length scale parameter L evaluated at R.
The length scale L is defined here as L = sqrt(-1/f''(0)).
f,df,ddf = cspline(R,L... | 05da8170d92f39bf8e553fdf30f059980a7db402 | 3,609,149 |
import logging
def _publish_project_details(project, config, batch_id, published_projects):
"""Publish project data to pubsub topic.
Args:
project: obj, projects_lib._Project object.
config: obj, config_utils._Config object.
batch_id: random number.
published_projects: set, to... | c17058066b124322f195082f4ea97d5fb61421bc | 3,609,150 |
def complete_key(ctx, param, incomplete):
"""
Autocompletion for keys.
"""
database = ctx.parent.params.get("database")
if database:
data = load_database(database)
else:
data = []
data = bib_entries(data)
return [x["key"] for x in data if x["key"].startswith(incomplete.lo... | 3026e34c8fb50daf4f65af50b94e66a1b7946bfa | 3,609,151 |
import argparse
def get_args():
"""
Command line arguments parser.
"""
ap = argparse.ArgumentParser(
prog='preprocess_treegrafter.py', description="TreeGrafter data preprocessor",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
ap.add_argument(
'-d', '--data', req... | a7dca54566eada19d55c456737d95d15f023e44f | 3,609,152 |
import requests
import json
import time
def get_report(scan_id, headers):
"""
Will get all vulnerabilities for the scan
"""
url = f"https://cloud.tenable.com/was/v2/scans/{scan_id}/report"
headers["Content-Type"] = "application/json"
response = requests.request("GET", url, headers=heade... | 12412233f7ebff4e0e5ba19a1c66fb7c835a8115 | 3,609,153 |
def softmax(input, use_cudnn=False, name=None, axis=-1):
"""
This operator implements the softmax layer. The calculation process is as follows:
1. The dimension :attr:`axis` of the ``input`` will be permuted to the last.
2. Then the input tensor will be logically flattened to a 2-D matrix. The matrix's... | e3bcde3a0919230742e00c2ec5d09a930774724f | 3,609,154 |
def binaryStat(augboost_m, X_test, y_test, y_pred):
"""
calculate stats for binary classification
:param augboost_m: AugBoost classifier
:param X_test: test data
:param y_test: test classification
:param y_pred: predicted classification using augboost_m
:return: accuracy, TPR, FPR, precision... | 972013447b57c9f4c1764af5aece0924c8e737dd | 3,609,155 |
def get_loaders(
train_batch_size,
val_batch_size,
train_set,
val_set,
num_stages=1,
num_workers=8,
train_shuffle=True,
val_shuffle=False,
train_pin_memory=False,
val_pin_memory=False,
train_drop_last=False,
val_drop_last=False,
):
"""Create train and val loaders"""
... | 99fbe395275de8319b681b790de4869571cf6abc | 3,609,156 |
def mysigmoid(mylist:list)->list:
"""
This function converted each element of the input list to its sigmoid form
# Input:
mylist: list, This is the input list where sigmoid operation is performed
# Returns:
list: It returns the transformed list
# Functionality:
The input ... | 67a1707a8a4878114278cbe93e1f604a338ba84f | 3,609,157 |
def _loadmat_internal(fn):
"""
Helper function to load matlab data
Parameters
----------
fn: basestring
Filename of Matlab .mat file
Returns
-------
mat: dict
Data in fn
Notes
-----
Data is loaded with mat_dtype=True so that e.g. data stored in float
(i... | 06c883658f2079541859a1cd48720673f66733c1 | 3,609,158 |
import json
def get_snapshot_time_points_table(results: PyDssResults, job_info: JobInfo):
"""Return the snapshot time points determined by each job."""
snapshot_time_points_table = []
data = json.loads(results.read_file(f"Exports/snapshot_time_points.json"))
row = {"name": job_info.name}
for time_... | 36d7235fca1eae74f937fa47319ea533c3f2832b | 3,609,159 |
import hashlib
def verifyhash_password_hashlib(password: str, hash: str) -> bool:
"""check if password is correct using hashlib
Args:
password (str): user password
hash (str): user password encrypted
Returns:
bool: True if correct password else False
"""
return hashlib.md... | a3ca663abc33777df4f33d0483ba598cef8c5c3b | 3,609,160 |
import random
def uniform_coords(lim):
"""
Generates uniformly distributed random coordinates in the 2D square, (0,lim)^2.
Parameters
----------
lim : int, float
Upper bound of coordinate value in both the x and y directions.
Returns
-------
tuple
2D coordinates.
... | 408c7344f782eb8ddafe7933d2bd5cc09badc6d8 | 3,609,161 |
def docalculations(set1, set2, tempdir, pairwisecorr, activeds):
"""compute canonical correlations and return results dictionary
tempdir is where to write the temporary sav files
printcorr is whether or not to print correlations
activeds is the name of the active dataset"""
# In order to c... | 8b916c5768b1d90906dd17e969d1be6ddf0a8e10 | 3,609,162 |
def get_utility_command_kill_signal(name):
"""
Return the proper kill signal used to stop the utility command.
:param name: name of utility command (string).
:return: kill signal
"""
# note that the NetworkMonitor does not require killing (to be confirmed)
sig = SIGUSR1 if name == 'MemoryM... | 026c83ab42386d378fca4eb6a9c90136594e8317 | 3,609,163 |
def get_files_recursive_by_id(root_entry):
"""
Walk the tree starting from a specified root node, collecting
all of the files that hang from those entries.
"""
results = {'.': root_entry}
# Get the files
for file1 in get_all_files(root_entry['id']):
results[file1['title']] = file1
... | 1e96dc55b8cee839206ffa771c06bb381675b5e3 | 3,609,164 |
from typing import Optional
def get_api_release(api_id: Optional[str] = None,
release_id: Optional[str] = None,
resource_group_name: Optional[str] = None,
service_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) ->... | bf47e293454cb722452e54df6a0a10407983276b | 3,609,165 |
def run(inp, opt, cfg):
"""
calculate svv from arterial waveform
:param art: arterial waveform
:return: max, min, upper envelope, lower envelope, respiratory rate, ppv
"""
data = arr.interp_undefined(inp['art1']['vals'])
srate = inp['art1']['srate']
data = arr.resample_hz(data, srate, 1... | 8d4bcffb29e8ae54dc96a4873f43b7cb40163438 | 3,609,166 |
def build_drive_aggregator(
rotation: str = "hadamard",
concatenate: bool = True,
zeroing: bool = True,
clipping: bool = True,
weighted: bool = True) -> tff.aggregators.AggregationFactory:
"""Creates an aggregation factory for comparing to DRIVE.
Args:
rotation: A string to specify what rot... | 006f63b97b8cb0886c41f3e4fa8491f35c896c22 | 3,609,167 |
def get_node_info(host, port, serviceNodeId):
"""GET (serviceNodeId) get_node_info"""
method = 'get_node_info'
params = { 'serviceNodeId' : serviceNodeId }
return _check(https.client.jsonrpc_get(host, port, '/', method, params=params)) | 8983dd514a7c2705bc7ab272488ced7b7e1ff1e3 | 3,609,168 |
def collect_certificate_data_from_file(certname, pem_file):
"""
Collect certificate data
Input: certname, pem_file
Returns: (certname, expiration_date, annotation_data, mode_metadata)
expiration_date will be None if data missing or error
annotation_data will be set to defaults
... | 9b4c10cdf3b16ed27995d28c0c3f09bb2e84c3bf | 3,609,169 |
def sample_evergreen_configuration():
"""Return sample evergreen configuration"""
return get_sample_yaml("evergreen_config.yml") | 2c3b0b9135ced2c9e1e220d95c5aa512e2780189 | 3,609,170 |
import copy
def add_target_info(data, tables, targets):
"""
>>> d = [{'data': [{'table': 'products'}]}]
>>> tables = {'products': {'target': 'products'}}
>>> targets = [{ 'name': 'products', 'type': 'foo' }]
>>> result = add_target_info(d, tables, targets)
>>> result == [{'data': [{'table': '... | 88dbf6234aaca34e68e27644a7cc444952ec8ab2 | 3,609,171 |
import logging
def fetch_json2xx_async(url, content='', method='GET', credentials=None, headers=None, multipart=False,
ua='', timeout=50, returnhandler=lambda x: x, caching=None):
"""Like `fetch_async()` but returnhandler is called with decoded jsondata."""
def decodingreturnhandler(status, rhead... | 77059e823967cbd61333ce1336c168de7a8807c9 | 3,609,172 |
def find_outlier_samples(X, toobig1, toobig2=[]):
"""Find outlier trials using an absolute threshold."""
n_samples, n_chans, n_trials = theshapeof(X)
X = unfold(X)
# apply absolute threshold
weights = np.ones((n_trials * n_samples, n_chans))
if toobig1 is not None:
weights[np.where(abs... | 256d11d815a81577d44d2f9c192d030d466c4967 | 3,609,173 |
def new_roc_bound_w_pi( # pylint: disable=invalid-name
bc2: float, fpr: np.ndarray, pi: float
) -> np.ndarray:
"""Calculates our new ROC upper bound for parameter pi.
Args:
bc2: Bhattacharyya coefficient squared.
fpr: False positive rates.
pi: Prior for H1 (i.e., weight for FNR).
... | 6e3a2f2de6571e70cc46b09e934eccdf869867ba | 3,609,174 |
def check_match(filename, contents):
"""Check if contents contains any matching entries"""
ret = False
for reg in REGEX_LIST:
match = reg.search(contents)
if match:
suppressed = False
for supp in SUPPRESSION_LIST:
idx = match.start()
supp_match = supp.match(contents[idx:])
if supp_match:
s... | c9c83080ffc069478eabad2516099bcb84ddfa86 | 3,609,175 |
import time
import os
def plot(graph, legend=True, labels=False,
major=True, filename='', save=True):
"""If major=True, plot the major component, else plot the entire graph"""
# print('Start plotting the network ....')
tic = time.time()
plt.ioff()
plt.clf()
if major:
g... | 7d36f996662bf95030f66ca0aadb2bd4bf4be207 | 3,609,176 |
import click
def check(context: click.Context) -> int:
"""
Runs a one-time type check of a Python project.
"""
return _run_check_command(context.obj["arguments"]) | c38b5fe726955da1170810a26eb865a09d6b55ea | 3,609,177 |
def riscale_coordination(coordinates, x, y, z):
"""
Robert:
I do not understand why you would want this quantity.
"""
coordinatesCM = []
for i in range(len(coordinates)):
coordinatesCM.append(
[str(coordinates[i][0]), coordinates[i][1]-x,
coordinates[i][2]-y,... | cee155c66b857f9bee6a2e6975f3797de40dfdcc | 3,609,178 |
def get_bonds(input_group):
"""Utility function to get indices (in pairs) of the bonds."""
out_list = []
for i in range(len(input_group.bond_order_list)):
out_list.append((input_group.bond_atom_list[i * 2], input_group.bond_atom_list[i * 2 + 1],))
return out_list | 4f39d9d588a1d3e919fcd5e369cd72c6dbac3442 | 3,609,179 |
def create_iterator(pattern, batch_size, sequence_length, vocab_size, repeat=False):
"""
Parameters
----------
pattern : string
glob pattern with files to read
batch_size : integer
batch size for input
sequence_length : integer
unroll size for rnn
vocab_size : inte... | 768de90de0b9d1645e8d8a1f84c4e3108ee96766 | 3,609,180 |
async def get_location_by_id(request: Request, id: int, source: Sources = "jhu", timelines: bool = True):
"""
Getting specific location by id.
"""
location = await request.state.source.get(id)
return {"location": location.serialize(timelines)} | faad65c82551b4f6d190a66429350e6508392d3b | 3,609,181 |
from typing import List
def bio_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIO tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Il... | 9413d826ace0e8a7e90bf6f166bf6547165cb36c | 3,609,182 |
from typing import OrderedDict
def file_list_table_format(result):
"""Format file list as a table."""
table = []
for item in result:
row = OrderedDict()
row['Name'] = item['name']
row['Type'] = item['fileType']
row['Size'] = '' if item['fileType'] == 'directory' else str(it... | 87c90c96f4d580ea8aae26be218fca15c491ae0a | 3,609,183 |
def scsi_out(d, cdb, data):
"""Send a low-level SCSI packet with outgoing data."""
return d.scsi_out(pad_cdb(cdb), data) | 3e98c79216712c07a284151148def53ad9991c53 | 3,609,184 |
def read_data(file, delimiter="\n"):
"""Read the data from a file and return a list"""
with open(file, 'rt', encoding="utf-8") as f:
data = f.read()
return data.split(delimiter) | e0854a2f7ac2190f3b296725b36da0bb4ad14ce3 | 3,609,185 |
import argparse
def create_args_parser():
""" process command line arguments and perform sanity checks """
parser = argparse.ArgumentParser(description="Run the same command across a number of "
"AWS accounts and/or regions.",
... | 9d5f15e23480bc82074c598be571ee62edc10e10 | 3,609,186 |
def deubiquitinase():
"""Curate deubiquitinases."""
return _render_func(
get_dub_statements,
title="Deubiquitinase Curator",
description=f"""\
The deubiquitinase curator identifies INDRA statements using INDRA
CoGEx whose subjects are human deubiquitinase genes an... | b41bf1fb83c1bb16e1ca863ca65b01608ef39799 | 3,609,187 |
def mark(name=None) -> Node:
"""
Mark is a pseudonym of identity. The idea is to mark (associate a name) internal placeholders
(from the graph point of view).
:param name: The identifier of the identity node
:return:
"""
return Identity(name) | 9be9ed3e8f3b2009bc672a43d5a7c177c57b1611 | 3,609,188 |
def create_maf_record_from_vcf(sample_id, center_name, sequence_source, vcf_data, is_germline_data, matched_normal_sample_id, tumor_sample_data_col):
"""
Creates MAF record from VCF data.
"""
# init maf record
maf_data = init_maf_record()
# set easy to resolve values
maf_data["Tumor_Sam... | 07cec878d8f7d76226f9ffa4e779171323c057dc | 3,609,189 |
def disable_by_type(token, _type, disable=False, customerid=None):
""" Toggle a check so it is enabled or disabled.
Accepts an API token, the checkid of the check to be toggled,
whether it's enabled/disabled (disable by default), and the
customerid if the check is a part of a subaccount
:type toke... | c8bf31b5a4e44f6f0593aefc891416d10a1f2678 | 3,609,190 |
def delete_reports_endpoint():
"""A Flask route which accepts a list of report filenames and then deletes them
from the reports path.
This endpoint should be json and the body should be in
the format {"data":"filenames":["file1.xlsx","file2.xlsx", ...]}
This is a POST request but is a destructive ac... | 8f448ca529472c3bcef33cb656e7d3eebb8b643d | 3,609,191 |
async def deep_into(url, _list, get):
"""Test for getting references. Used for raw scan."""
try:
resp = await get(url)
new_resp = resp
if "uri" in new_resp:
new_resp["uri"] = remove_all_ip_occurs(resp["uri"])
if "id" in new_resp and new_resp["id"] == "/gateway/uuid":
... | d5cb6d4169c5653b5db6f132783bc6039de4756e | 3,609,192 |
def get_param_server_cache():
"""
Get a handle on the client-wide parameter server cache
"""
global _param_server_cache
if _param_server_cache is None:
_param_server_cache = ParamServerCache()
return _param_server_cache | 3c5b0547c263aefaebead7a63ac2ff4722bae9ca | 3,609,193 |
def sanitize (s):
"""
Removes HTML tags, replaces HTML entities and unescapes the text so that
only human generated content remains.
"""
s = preserve_quotes(s)
s = preserve_code(s)
s = replace_newlines(s)
s = remove_meta(s)
return unescape(s) | 5cf30686177ca2110a6170783f1694a51d2c8ec4 | 3,609,194 |
def get_auth_id_from_user_id(user_id):
"""Returns the auth ID associated with the given user ID.
Args:
user_id: str. The auth ID.
Returns:
str|None. The user ID associated with the given auth ID, or None if no
association exists.
"""
return platform_auth_services.get_auth_i... | b4d47ea370c81f1668f57642aa7fb43f08e9c31a | 3,609,195 |
def make_property(name, bit, size=1, type=bool, var="flags"):
"""Helper function for make_struct which defines properties based on
bit fields. This is called automatically for "flags" when passing a
list of flags to make_struct, but can also be added to init_exec to
handle flags in other variables if n... | c891e7bf87f3842fb6e0e1577f26b8906feadd86 | 3,609,196 |
def get_southwest_ray(bitboard: np.uint64, from_square: int) -> np.uint64:
"""
Returns a bitboard of southwest sliding piece attacked squares on an otherwise empty board
:param bitboard: The bitboard representing the southwest ray sliding attacks from `square`
:param from_square: The square from a south... | 546a2df681cec125890349e82d75c47c668b27b1 | 3,609,197 |
from .inspection import PACKAGE_NAME
import copy
def sanitize_deps(deps_dict):
"""
Helper function that takes the output of `notebook_path_to_dependencies`
or `simple_import_search` and turns normalizes the import names to be
synonymous with their conda/pip names
Parameters
----------
dep... | fbef4c20e73ef67a7ed2159757cd77bf5cd62ad0 | 3,609,198 |
def register():
"""Register a user: produce form and handle form submission."""
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
user = User.register(username, password)
db.session.add(user)
db.session.commit()
... | 1f3a0ee30d816b70adf7dc69c638b5c8f3a8b841 | 3,609,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.