content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def graph_mutation_diff(source_graph, dest_graph):
"""
Generates the set of operations (ADD, DEL) needed to go from `source_graph` to
`dest_graph`.
"""
source_graph_edges = break_knowledge_graph(source_graph)
dest_graph_edges = break_knowledge_graph(dest_graph)
diff_edges = source_graph_edge... | f2d8caff213f91c5af64bfcf2f2679f16fce6b4e | 3,609,070 |
def load_dataset(dataset='mnist', flatten=False):
"""Keras, derin öğrenme ve makine öğrenmesi çalışmalarında sıkça kullanılan bazı verisetlerini kendi içinde barındırmaktadır.
Bu verisetlerini ilk yüklemeye çalıştığınızda keras internetten otomatik olarak indirecek ve önbelleğe alaaktır.
Bu yüzden kodun çal... | 91303ece070da6569594ea6021bfe3cca7855557 | 3,609,071 |
def non_stratified_matching(control, treatment):
"""Find index of KNN-neighbor of control sample for treatment group.
:returns nn_index: knn index, M1 X M2 matrix. M1 is number of treatment, M2
is number of control.
Conponent function of :func:`psm`.
"""
exam_input(control, treatment)
t... | 4365a2fa12720914f8e4a668f0ccac16bf0e2306 | 3,609,072 |
def normal_upper_bound(probability, mu=0.0, sigma=1.0):
"""returns the z for which P(Z <= z) = probability"""
return inverse_normal_cdf(probability, mu, sigma) | 1814536206554e4f9a547ef43ffff7f8b98e197b | 3,609,073 |
import unicodedata
import re
def slugify(value):
"""
Normalizes string, removes non-alpha characters,
and converts spaces to hyphens.
"""
# assume that strings are ascii
if isinstance(value, str):
value = value.decode('ascii')
value = unicodedata.normalize('NFKD', value).encode('as... | 37ed557de0ab93d8bbdb356b2e5ec66895083c4e | 3,609,075 |
def common_to_alphabetical_key(common_key):
"""Convert a common key to an alphabetical key.
Convert a key ordered by most common letter to a key ordered by most common
letter at indices determined by the English alphabet, i.e. the most common letter
will be at index 4, second most common at index 18, a... | a22795797031e2b88827fd07f5da5f1f8e429c65 | 3,609,077 |
def vfunc(probability, prediction, threshold):
"""Simple function for thresholding predictions.
Args:
probability: The probability of the minority class
prediction: The class prediction of the classifier
threshold: Probability threshold above which the minor... | 3ae085dabee7432a543f68b35a274bd613b7f07f | 3,609,078 |
def dijkstra(mazeMap, start):
""" ͏ ͏ ͏ ͏ ͏ ͏ ͏͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏͏ ͏ ͏ ͏ ͏͏ ͏ ͏ ͏͏ ͏ ͏ ͏͏ ͏ ͏ ͏͏ ͏ ͏͏ ͏ ͏ ͏ ͏͏͏͏ ͏͏ ͏͏͏͏ ͏ ͏ ͏͏ ͏ ͏ ͏͏ ͏ ͏͏ ͏ ͏ ͏͏͏͏ ͏͏ ͏͏͏͏ ͏ ͏
Return t... | b6c2634dc2b115a244e1601ccf58258d8189f017 | 3,609,079 |
def check_custom_parameters_against_defaults(assay_type, custom_config_parameters, json=False):
"""
Converts and evaluates set of custom parameters against default config. If json, maps parameters and
populates background (default) parameters for non-specified parameters.
NB: requires that default conf... | 7ae2ee3ac79f78b49377a4875f1f9ca2a4a9cc44 | 3,609,081 |
def broadcast_ts(ts, params_len, new_columns):
"""Broadcast time series `ts` to match the length of `new_columns` through tiling."""
if checks.is_series(ts) or len(new_columns) > ts.shape[1]:
return ts.vbt.wrap(reshape_fns.tile(ts.values, params_len, axis=1), columns=new_columns)
else:
retur... | 7a6635eb7ec9992221397d0050b2b529b5683dc8 | 3,609,082 |
import requests
def get_room_id(room_name):
"""
This function will find the Webex Teams room id based on the {room_name}
Call to Webex - /rooms
:param room_name: The Webex Teams room name
:return: the Webex Teams room Id
"""
room_id = None
url = WEBEX_URL + '/rooms' + '?max=1000'
h... | 2e33edf94313fdef63c7d92021ee48b73492b7bc | 3,609,083 |
def pysiphash(uint64):
"""Convert SipHash24 output to Py_hash_t
"""
assert 0 <= uint64 < (1 << 64)
# simple unsigned to signed int64
if uint64 > (1 << 63) - 1:
int64 = uint64 - (1 << 64)
else:
int64 = uint64
# mangle uint64 to uint32
uint32 = (uint64 ^ uint64 >> 32) & 0xf... | a0a4bb7703aef9a95146c519aa1ace751bcf532e | 3,609,084 |
from typing import List
def _parse_lammps_log(file_in) -> List[float]:
"""Parse a LAMMPS log file for energy components."""
tag = False
with open(file_in) as fi:
for line in fi.readlines():
if tag:
data = [float(val) for val in line.split()]
tag = False
... | a5bb037a4482053d12b84ea6570ee80ec314f516 | 3,609,085 |
def get_authenticator():
"""Get authenticator instance."""
return current_authenticator | a131faaac547b35eb2f488c226a7290a99aaee3e | 3,609,086 |
import select
from operator import and_
async def gen_invitation(request: AthenianWebRequest, id: int) -> web.Response:
"""Generate a new regular member invitation URL."""
async with request.sdb.connection() as sdb_conn:
await get_user_account_status(request.uid, id, sdb_conn, request.cache)
e... | b66ef01723e23d2080645349e6fbc1decdc62b76 | 3,609,087 |
def histc(x: np.ndarray, bins: np.ndarray) -> np.ndarray:
"""
MATLAB `histc` equivalent function.
Args:
x: Input array
bins: Array of bins. It has to be 1-dimensional and monotonic
Rrturns
Counts the number of values in x that are within each specified bin range
"""
... | 7ec584c3dc62220008aaf7603ee9256feda7370a | 3,609,088 |
import random
import string
def get_unique_key(str_len: int) -> str:
"""Returns a random string of length str_len.
Args:
str_len (int): Length of string.
Returns:
str: Random string
"""
return "".join([random.choice(string.ascii_lowercase) for _ in range(str_len)]) | de8a7743ac5b802e3fe5687e4305ec14e26987a8 | 3,609,089 |
import tqdm
def load_word_vector(vector_path, word2id, dim=300):
"""
Read pretrained vectors
Make lookup table with vocabulary
Load vector at lookup table
"""
vocab_size = len(word2id)
lookup_table = np.random.normal(size=[vocab_size, dim])
if 'glove' in str(vector_path):
n_to... | 49cf4e437ea2a5354399b27454d0281b44fc702f | 3,609,090 |
def get_rr_cholesky(N, Fmat, psd):
"""
Use the Smola and Vishwanathan method to obtain the lower-triangular
Cholesky decomposition L of a matrix C = N + FF^{T} = LL^{T}.
This is a fast version of lowRankUpdate_slow, assuming that N is diagonal.
@param N: Vector with the elements of the diagon... | 0c5b506d5c47d202a5bd3f2bc87a7ffa885c71bd | 3,609,091 |
def greet_user():
"""Greets users and asks for their name"""
font= Figlet(font='standard',justify='center')
print(font.renderText("Welcome to Flat_Me !"))
name_prompt= {
'type':'input',
'name':'user_name',
'message':'Before we begin, let\'s start with something easy: What is your... | 13c4e24b507e4ab59005610b1eb0a20dc330bb34 | 3,609,092 |
import string
import random
def randomStringDigits(stringLength=11):
"""Generate a random string of letters and digits """
lettersAndDigits = string.ascii_letters + string.digits
return ''.join(random.choice(lettersAndDigits) for i in range(stringLength)) | e41bc2879d1ab75a61df25139df90b7ef5ee756b | 3,609,093 |
def get_quota_message(user):
"""
get quota warning, grace period, or enforcement message to email users and display
when the user logins in and display on user profile page
:param user: The User instance
:return: quota message string
"""
if not QuotaMessage.objects.exists():
QuotaMes... | 3ee6c7384777e4f1696e937bb38bbecb74f19b95 | 3,609,095 |
def find_augmenting_path(path, adjacency, n_rooms):
"""
Find an angmenting path if possible by a breadth-first serach, update the
residual capacity matrix,and return the flow increment.
If there is no augmenting path, return and IndexError Exception.
"""
parents = [-1] * n_rooms
parents[0]... | a4d3b1d9d222f43a9560de2a2a3d10e9c1b80058 | 3,609,096 |
def roll_2d6_plus6(count=6):
"""
Roll 2d6+6 and assign as required
"""
stats = list()
for _ in repeat(None, count):
stat = best_rolls(num_rolls=2, top=2, discard_ones=False, base=6) + 6
stats.append(stat)
stats.sort(reverse=True)
return stats | 305ce25b741a61062027c1d328e42838e85b3f3d | 3,609,097 |
import copy
def mk_gnfa(Nin):
"""Input : Nin, an NFA.
Output: G, a GNFA, with at-most one transition from any
state p to a state q.??true any more?? Note that we have created
an NFA (G+NFA), and so one state can have a transition
to A SET OF STATES !!
Met... | 0f978570d66fda16dd056a99b2b72b876b84448a | 3,609,098 |
from typing import OrderedDict
def sort_by_key(value, reverse=False):
"""
sorts a dictionary by its keys.
:param dict value: dict to be sorted.
:param bool reverse: sort by descending order.
defaults to False if not provided.
:rtype: OrderedDict
"""
result = so... | df200eaf2810e04281e8f8379ded09f21ed6df74 | 3,609,099 |
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 |
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 |
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 |
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 |
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 |
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 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 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 |
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 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.