content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Callable
from typing import Tuple
from typing import Mapping
from typing import Union
from typing import Sequence
def _find_all_tree(tree: dict,
func: Callable,
args: Tuple,
kwargs: Mapping
) -> Union[Sequence[dict], None]:... | e06917b6e2bd773570e84dd42928cd044393cfd0 | 66,900 |
def loginview(request):
"""Login view."""
email = request.POST.get('email')
context = basecontext(request, 'login')
result, user = None, None
if email is not None:
password = request.POST.get('password')
user = authenticate(username=email, password=password)
if user is No... | 1ef6686af4564adbf1526adcd1f9e04d29a97925 | 66,901 |
import os
def absolute_path(dir_path):
"""Return absolute path"""
return os.path.abspath(os.path.expanduser(os.path.expandvars(dir_path))) | b2f1f0f8acb1e0854a95542564aceac1d0ea2e0b | 66,902 |
def prompt(message, validator=lambda x: True, input_to_option=lambda x: x, default_value=None, options_to_print=None):
"""
Prompt the user a message with optionally some options.
:param message: the message to show to the user
:param validator: a function that predicates if the input is correct
:pa... | 3dcb9ab47330dfb0ea52b8c9704d22b02b245174 | 66,903 |
import tokenize
import jinja2
import math
def result_sort_key(tokens):
"""
The sort key function for the search results
Input:
response_item: the tuple of (code, snippet)
output:
sortable value, the greatest first
"""
def similarity(tokens, snippet):
target_tokens = lem... | 3846a3163f14d22a60bfb39adf1fbf33333162c0 | 66,904 |
import sys
def wrap_exception_as_string():
"""
return exception as string to be rethrown
"""
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
msg = "%s.%s" % (exceptionType.__module__, exceptionType.__name__)
exception_value = str(exceptionValue)
if len(exception_value):
... | 649509e1fd93f17aaeada650dab69259e804085d | 66,905 |
def create_colors_per_class_instance(detected_objects):
"""
Based on the detected classes assign the same color to each class ID and return a list of tuples for
the display_instances function
:param detected_objects:
:return: list of tuples containing the color
:rtype: list
"""
# TODO:... | 0a1212e3b997e22e1bc9a098cddb42a32fb159ab | 66,906 |
def MockAsyncServerResponseException( exception ):
"""Return a fake future object that is complete, but raises an exception.
Suitable for mocking a response future within a client request. For example:
with MockVimBuffers( [ current_buffer ], [ current_buffer ], ( 1, 1 ) ) as v:
mock_response = MockAsyncServ... | 7ca4cb5f180fb39db4c8c59354fe4829d6948fc0 | 66,907 |
def mesh_hook(mesh, mode):
"""
Generate the block mesh.
"""
if mode == 'read':
mesh = gen_block_mesh(dims, shape, 0.5 * nm.array(dims),
name='user_block', verbose=False)
return mesh
elif mode == 'write':
pass | c7c61dbf7125650daff1e205920d77f05adf07a7 | 66,908 |
def prettyPercent(numerator, denominator, format="%5.2f"):
"""output a percent value or "na" if not defined"""
try:
x = format % (100.0 * numerator / denominator)
except (ValueError, ZeroDivisionError):
x = "na"
return x | c9c201731c89deb1b86d066ccaba1049bd401757 | 66,909 |
import os
def get_pressure_to_altitude_func():
"""Get function converting air pressure [Pa] to altitude [m].
Returns
-------
callable
Function that converts air pressure to altitude.
"""
base_dir = os.path.dirname(os.path.abspath(__file__))
source_file = os.path.join(base_dir, 'u... | 9d462e8a6194b91cb8c6d7b6394fa1e14b012d6c | 66,910 |
def _documents_word_count(
documents: tp.List[str], label: str, ignore_case: tp.Optional[bool] = True
) -> pd.DataFrame:
"""Counts words in multiple :obj:`documents` of a given :obj:`label`.
Parameters:
documents: The list of documents to count words in.
label: The label of the documents.
... | 6a01b18646c2d7ce7498b8194ccbcaab6e02a80b | 66,911 |
def simple_mlp(inputs, layer_sizes, activation, dense=tf.layers.dense):
"""
Apply a simple multi-layer perceptron model to the
batch of inputs.
Args:
inputs: the batch of inputs. This may have any shape
with at least two dimensions, provided all the
sizes are known ahead of time b... | 5cf9dd14c5d8b887c32d609cd610c0e48ee2ef90 | 66,912 |
def get_video_service() -> VideoService:
"""
Function that creates a VideoService object using the
credentials set in config.json
Returns:
A VideoService object
"""
token_manager: TokenManager = get_token_manager()
video_service: VideoService = VideoService(
config=token_m... | 6e56d43f4f636c1c5d0408c8a98e810275708657 | 66,913 |
def wiki_return_validate(x):
"""Validates input for wiki_return() function."""
if x in yes:
mainmenu()
elif x in no:
wikichat()
else:
return False | 65ed24e3ea316e174b8bcad96911ecbbc98f864a | 66,914 |
import functools
import urllib
def admin(method):
"""Decorate with this method to restrict to site admins."""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.current_user:
if self.request.method == "GET":
url = self.get_login_url()
... | 77d1cfcf1398b263d050d323fef38b9285c9dd2c | 66,915 |
from typing import Iterable
def _prepare_input_img(imgs, test_pipeline: Iterable[dict]):
"""Inference image(s) with the detector.
Args:
imgs (str/ndarray or list[str/ndarray] or tuple[str/ndarray]):
Either image files or loaded images.
test_pipeline (Iterable[dict]): Test pipline ... | 35daee38f23ec4a66e22c89f4b88e4892dd30192 | 66,916 |
def ida_star_search(
start_node,
expand_fn,
goal_fn,
heuristic_fn=None,
hash_fn=None,
iter_lim=None,
return_path=False,
):
"""
IDA* search.
Returns the tuple (cost, target_node) if return_path is set to False.
Otherwise, returns the target node, the costs of nodes expanded b... | f17d968b4ab3b72b1f264460d4ec109192eae6b5 | 66,917 |
def sample_indexed_reads(
run_folder: model.RunFolder,
num_reads: int = 10_000,
lower_thresh: float = 0.01) -> [model.SampleIndexedReadsStats]:
"""Sample indexed reads.
Will sample ``num_reads`` reads from each lane, ignoring everything that
is below ``lower_thres * num_reads``.
... | 75a81b51d0f29574bbc2d972bfbfe90d54591aac | 66,918 |
def align_by_pelvis(joints):
"""
Assumes joints is N x 14 x 3 in LSP order.
Then hips are: [3, 2]
Takes mid point of these points, then subtracts it.
"""
with tf.name_scope("align_by_pelvis", [joints]):
left_id = 3
right_id = 2
pelvis = (joints[:, left_id, :] + joints[:, ... | 3c49323e54a18fc2742be55ce99adbb430651b67 | 66,919 |
from typing import Dict
def get_kraus_matrices_from_ibm_noise_model(noise_model: NoiseModel) -> Dict:
"""Gets the kraus operators from a pre defined noise model
Args:
noise_model: Noise model for circuit
Return
dict_of_kraus_operators(dict): A dictionary labelled by keys which are the ba... | 191608a15fcfbbb9c7c1dd5a3c9a6a22b7007758 | 66,920 |
def cut_and_pad_seq_list(seq_list, max_len, pad, auto=False):
"""
"""
if auto == True:
max_len = min(max(len(seq) for seq in seq_list), max_len)
x = []
for seq in seq_list:
x.append(cut_and_pad_seq(seq, max_len, pad))
return x | 4bf24462279387f7d0d49fd9c243c5019914634d | 66,921 |
import re
def get_pull_no(ref):
"""
Get pull request from a git given ref
>>> get_pull_no('refs/pull/12345/head')
12345
>>> get_pull_no('refs/pull/6789/merge')
6789
"""
match = re.search('refs/pull/([0-9]+)/', ref)
if match:
return int(match[1])
raise ValueError("Unable... | dbd4ca5f241c735976f992765c1e8b507dab53a0 | 66,922 |
def sentence_to_avg(sentence, word_to_vec_map):
"""
Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word
and averages its value into a single vector encoding the meaning of the sentence.
Arguments:
sentence -- string, one training example f... | 78eefbeea5cbbcfbf59d03f785228c38d6196cdc | 66,923 |
def find_nodes(root, query):
""" Interprets json as tree and finds all nodes with given string. """
if not isinstance(root, dict):
return []
rv = []
for key, value in root.items():
if key == query:
rv.append(value)
continue
if not isinstance(value, list... | 2aab02bfe372461e9c2541133abab7c8cbb5d80d | 66,924 |
def find_rel_prop(s_coords, o_coords):
"""OK [65]
Returns the normalized difference of the subject and object coordinates.
The normalization is the semantic relation between the two coordinates.
Calls list_substract with the two coordinate lists and normalizes the
result.
Example: for s_coords =... | b52631ea0fd10d2a7c88065e0b795b9918ed1e12 | 66,925 |
import pudb
def build_range_image_from_point_cloud_np(points_frame,
num_points,
inclination,
range_image_size,
extrinsic=None,
... | 6dc85ed623121895a38d11484f033158b5cdba4b | 66,926 |
def get_scan_group(sdm, band="a", **dyna_kwargs):
"""
Parameters
----------
sdm : sdmpy.SDM
band : str
**dyna_kwargs
Arguments passed to `DynamicSpectrum`
"""
assert band in SCANS_BY_BAND
return [
DynamicSpectrum(sdm.scan(scan_id), **dyna_kwargs)
for s... | 2810f337e98eeec8fe891144b2a4f66430b4bb42 | 66,927 |
def decompress(data):
"""Decompression of data
Parameters
----------
data : string
(from xml) data string containing compressed data.
"""
zlib = util.import_optional('zlib')
return zlib.decompress(data) | c729cb37584d4c91cc2092259dff8ab35ed3f28a | 66,928 |
def provenanceRule(scModel, edgeTuples):
"""
:param scModel:
:param edgeTuples:
:return:
@type scModel: ImageProjectModel
"""
bases = set()
for node in scModel.getNodeNames():
nodedata = scModel.getGraph().get_node(node)
if nodedata['nodetype'] == 'final':
bas... | 71ba40734e6ffd60f5b69c1ce927403f0b42aefa | 66,929 |
def interval_to_json(interval: Interval):
"""
The function converts an object of Interval to a json string.
:param interval: An Interval object.
:type interval: ibmpairs.query.Interval
:rtype: str
"""
return Interval.to_json(interval) | d168a80364ac8834036b1cbb47b68f8400a2ac44 | 66,930 |
def calculate_distance(sample, centroid, method='euclidean', p=None):
"""
距离度量
----
method:
1. 欧氏距离 euclidean
2. 闵可夫斯基距离 minkowski
3. 曼哈顿距离 cityblock
4. 切比雪夫距离 chebyshev
5. 余弦相似度 cosine
6. 汉明距离 hamming
7. 兰氏距离 canberra
8. 马氏距离 mahalanobis
... | a74149adfc685b53e7a5e044949ad453e58b3ab3 | 66,931 |
import os
def section_name(name, n, prefix='py-{pid}'.format(pid=os.getpid())):
"""Join arguments to get a Travis section name, e.g. 'py-123.section.0'"""
return '.'.join(filter(bool, [prefix, name, str(n)])) | 413b812bc746c0b5621ee9d2f94ebaad9ce64179 | 66,932 |
def symgauss_sigmoid(xarr, **kwargs):
"""symgauss test function"""
n_dim = xarr.shape[-1]
a = 0.1
pref = pow(1.0 / a / np.sqrt(np.pi), n_dim)
coef = np.sum(np.arange(1, 101))
# Tensorflow variable will be casted down by numpy
# you can directly access their numpy representation with .numpy()... | 554cb2bdb039a0c29a9f45064cfbd8c10fe8a896 | 66,933 |
def boxes_area(boxes):
"""
calculating the area of the input bounding boxes
:param boxes: the list of bounding boxes in the form [x0, y0, x1, y1, conf(optional)]
:return: the area calculated for each bounding box in the list
"""
w = (boxes[:, 2] - boxes[:, 0] + 1)
h = (boxes[:, 3] - boxes[:,... | cee56ca4eb64d24d5354bbe671deb9cc46c8f931 | 66,934 |
def oscillating_sinspace(amplitude, period, base_value, num_steps, delta_time):
"""This function returns a 1D array of values that are calculated by inputting a
vector of linearly spaced time steps into a sine function.
:param amplitude: float
This is the amplitude of the value fluctuation.
:pa... | 904069e1efaab27cd22f0b7a3e2013edf5aad165 | 66,935 |
import uuid
def get_anno_base(motivation):
"""Return the base for a new Web Annotation."""
ts_now = get_xsd_datetime()
github_repo = app.config.get('GITHUB_REPO')
return {
"@context": "http://www.w3.org/ns/anno.jsonld",
"id": str(uuid.uuid4()),
"type": "Annotation",
"mo... | 4abdd5dad5ee7c83aef476fba5f4e972c4fb4e5d | 66,936 |
from typing import List
from typing import Dict
from typing import Set
async def collect_subfields(
execution_context: "ExecutionContext",
return_type: "GraphQLOutputType",
field_nodes: List["FieldNode"],
) -> Dict[str, List["FieldNode"]]:
"""
Collects the fields of each field nodes.
:param ex... | 0988986b56dc80125fe78766887e677c8ccd0a73 | 66,937 |
from datetime import datetime
import socket
import ssl
import pytz
def cert_validate_date(hostname, port = 443)->datetime:
"""
Validate the certificate expiration date
"""
with socket.create_connection((hostname, port)) as sock:
context = ssl.create_default_context()
with context.wrap_... | 4aadf152b960043ad2cd6c3232719977a39c6a44 | 66,938 |
def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim):
"""
Build part of the neural network
:param cell: RNN cell
:param rnn_size: Size of rnns
:param input_data: Input data
:param vocab_size: Vocabulary size
:param embed_dim: Number of embedding dimensions
:return: Tuple (Logi... | ab79a3967f4072391920f36ffbe4b53b2aecd00a | 66,939 |
def tokenize(text):
"""
tokenize the input text
Parameters:
text (string): input text
Returns:
List: tokenized text
"""
tokens = word_tokenize(text)
lemmatizer = WordNetLemmatizer()
clean_tokens = []
for tok in tokens:
clean_tok = lemmatizer.lemmatize(tok).... | f3cd58350b3b4abefa4c8d2e8b9e17e2f4ae0afa | 66,940 |
def mollification_smoothing (rawspectrum, struct_el, number_of_mollifications):
""" Molifier kernel here is defined as in the work of Koch et al.:
JRS 2017, DOI 10.1002/jrs.5010
The structure element is in pixels, not in cm-1!
struct_el should be odd integer >= 3
"""
mollifier_kernel... | fb439bba98b8d02fced6a53ebff3f86404f161ed | 66,941 |
import itertools
from datetime import datetime
import uuid
import os
def volume_matching(
gpmfile: str,
grfile: str,
grfile2: str = None,
gr_offset: float = 0,
gr_beamwidth: float = 1,
gr_rmax: float = None,
gr_refl_threshold: float = 10,
radar_band: str = "C",
refl_name: str = "co... | c21b6232decddc1d0c03c67208a1599f8e2d39be | 66,942 |
def get_category_weights_from_csb(classes, scores, bboxes, raw):
"""
Count the number of pixels of each class in classes weighted by their scores/probabilities.
Args:
classes: list of categories
scores: list of probabilities [0,1] for each category
bboxes: list of 4 tuples for each c... | 57fd5575f31679153a0c5944dc8d40ae41f22e96 | 66,943 |
def _mlflow_conda_env(path, additional_conda_deps=None, additional_pip_deps=None):
"""
Create conda environment file. Contains default dependency on current python version.
:param path: local filesystem path where the conda env file is to be created.
:param additional_conda_deps: List of additional cond... | 2784ec6c15afc03d17795af6d56e022125308ebf | 66,944 |
def allclose(A, B, rtol=1e-5, atol=1e-8):
"""Use np.allclose to compare, but relative tolerance is relative to
the smallest element compared
"""
return np.allclose(np.maximum(A, B), np.minimum(A, B), rtol, atol) | e3df3ba3bbe37271f9fced5b51c052b3d4189256 | 66,945 |
def testGuildInvTaille(ID):
"""Verifie si ton coffre de guilde est plein """
inv = DB.valueAt(ID, "Coffre", "DB/guildesDB")
tailletot = 0
for c in objetOutil:
for x in inv:
if c.nom == str(x):
if inv[x] > 0:
tailletot += c.poids*int(inv[x])
fo... | 309fa0d2d3741b53d1e92293397832ab6807f240 | 66,946 |
from scipy.optimize import minimize_scalar
def fit_delay(fun, ts, ys, T=2*np.pi, bounds = (-3.14, 3.14), method = 'bounded', debug = False, info = '', **kwargs):
""" Fit a set of points to a given function just by displacing it in the horizontal axis
"""
def D(ys, ts, delay):
""" Sum of all square... | e08ff83350efffb45cadf0c1b3fc5df7d1ce8347 | 66,947 |
import logging
import json
def get_mycroft_message(command: str, json_dir=MYCROFT_JSON_DIR) -> dict:
"""Retrives and loads the correct json file for the command given"""
json_file = f"{json_dir}/{command}.json"
logging.debug(f"json_file: {json_file}")
with open(f"{json_file}", "rb") as fh:
mes... | a63860495804d38f6321d333f623448061a82e80 | 66,948 |
import logging
def _calculate_plot_variables(cp_profile, selected_variables):
"""
Helper function to calculate valid subset of variables to be plotted
"""
if not selected_variables:
return cp_profile.selected_variables
if not set(selected_variables).issubset(set(cp_profile.selected_variabl... | 73e6a499173fb5c8bd5c957c60eac66a176dd566 | 66,949 |
import os
def load_coil_like(path):
"""
Load COIL-20(COIL-100) dataset.
Returns:
X, y -- data points and labels
"""
for _, _, f in os.walk(path):
fs = f
break
p = LargePool(fs, CoilLoader, (path,))
res = p.run()
X = []
y = []
for r in res:
X.appen... | 4d0de4b13ea038ec08fed6de1ba394fede0300b4 | 66,950 |
def genamons(p):
"""
for multiprocessing
"""
obj = ParentMol(p.string, iat=p.iat, i3d=p.i3d, k=p.k, k2=p.k2, stereo=p.stereo, \
isotope=p.isotope, scale_vdw=p.scale_vdw, opr=p.opr, fixGeom=p.fixGeom, \
nocrowd=p.nocrowd, icc4Rsp3out=p.icc4Rsp3out, ioc=p.ioc, ioc... | 2c9bced16108eb51dc8449c81359fc6db6db7a87 | 66,951 |
def cradmin_render_breadcrumb_item_list(context, include_context=True,
location=None,
**kwargs):
"""
Render breadcrumbs from the ``cradmin_breadcrumb_item_list`` template context
variable.
If ``cradmin_breadcrumb_item_list`... | 0e1ccbff76b0779a2cf9efc50b168e244a8535b6 | 66,952 |
import sklearn.preprocessing
def create_one_hot_encoder(length):
"""
Create an sklearn OneHotEncoder for encoding peptides.
Parameters
----------
length : int
the expected length of the peptides to be encoded
Returns
-------
sklearn.preprocessing.OneHotEncoder
the cre... | d0ad4837257e988d33e84595bb438f1b0cd4156b | 66,953 |
def get_queue_config():
"""记录queue的基本信息
{'title':'sys_cron-0', #可选
'tags':(['sys_cron']), #可选
} #可选
"""
prefix = 'ztq:config:queue:'
return get_dict(prefix) | 117ec095b7c2084944e53e69d03f81c7d59ae0f3 | 66,954 |
def get_runs(limit=40000, compress_attributes=True, **kwargs):
"""
Gets all runs that match the filter given in
:param compress_attributes: Gets the attributes inside rr_attributes:* and the ones in the DatasetTripletCache (The lumisections insdie the run/dataset) and spreads them over the run object
:... | c90e1d30418ef9d44083931129b58081abbf3c8f | 66,955 |
def git_unstash_all():
"""Function that unstashes all changes in repo.
Returns
-------
out : str
Output string from stdout if success, stderr if failure
err : int
Error code if failure, 0 otherwise.
"""
command = 'git stash pop'
name = 'git_unstash_all'
return handle... | c5c804baaf394740dc33f85b53c278ec613f4c70 | 66,956 |
import math
def total_sample_splits_categorical(no_of_values):
"""
Compute total number of sample splits that can generated by categoricals.
Parameters
----------
no_of_values : Int.
Returns
-------
no_of_splits: Int.
"""
no_of_splits = 0
for i in range(1, no_of_values):... | 705a565998c5cde4a37370e6787aa0f07d973987 | 66,957 |
import random
def edit_derivation_note(deriv_id: str, new_note: str, path_to_db: str) -> str:
"""
Args:
deriv_id: numeric identifier of the derivation
path_to_db: filename of the SQL database containing
a JSON entry that returns a nested dictionary
Returns:
Raises... | 677783f33ff328d0d3e5e3f13c21b07ff1c7980b | 66,958 |
def isnointeger(number):
""" This method decides if a given floating point number is an integer or not --
so only 0s after the decimal point.
For example 1.0 is an integer 1.0002 is not."""
return number % 1 != 0 | 446c844a9807a6ffba0608c88ceb43f437b4d57c | 66,959 |
def normalize_commit(commit, **kwargs):
"""
This takes commits either in the JSON format provided by a GitHub
webhook, or the object format provided by github3.py, and returns a
normalized Python dict.
"""
if isinstance(commit, dict):
# If GitHub webhook payload:
sender = kwargs.... | 7728c9d9f42929fce8193580ef374d1e55e4df7f | 66,960 |
def get_polygon(annotation):
"""
Extracts a polygon from an annotation
Parameters
----------
- annotation : Kili annotation
"""
try:
return annotation['boundingPoly'][0]['normalizedVertices']
except KeyError:
return None | 4dc22e186db271469ff5070df2b7238f684766ac | 66,961 |
def disassemble(chip: Processor, location: str, pc: int) -> bool:
"""
Control the dissassembly of a previously assembled program.
Parameters
----------
chip : Processor, mandatory
The instance of the processor containing the registers, accumulator etc
location : str, mandatory
... | 79b3ed4ee34e5bfc1eef2f889f26c003bff654d6 | 66,962 |
def _merge_validator(def_validators, ref_validators):
""" merge def_validators with ref_validators.
Args:
def_validators (list):
ref_validators (list):
Returns:
list: merged validators
Examples:
>>> def_validators = [{'eq': ['v1', 200]}, {"check": "s2", "expect": 16, "... | 79d257efcfcc717a7737b269a59835515b14924b | 66,963 |
def get_dev(coord, snap):
"""
Compute a coordinate's deviation from the nearest multiple of snap.
Keyword arguments:
coord: the coordinate to check
snap: base value from which to compute deviation
"""
orig = dec.Decimal(coord)
rounded = (orig / snap).quantize(1, dec.ROUND_HALF_... | f9ddb16e5597cf557c71a341e69e22b09ad07ccd | 66,964 |
from typing import Iterable
def succ_deep(node: ANFNode) -> Iterable[ANFNode]:
"""Follow node.incoming and graph references.
A node's successors are its `incoming` set, or the return node of a graph
when a graph Constant is encountered.
"""
if node.is_constant_graph():
return [node.value.... | 20e415548e89f3f88c823bdae77215915468d89b | 66,965 |
from datetime import datetime
def get_date(timestr=None):
"""
Always parses the time to be in the UTC time zone; or returns
the current date (with UTC timezone specified)
:param: timestr
:type: str or None
:return: datetime object with tzinfo=tzutc()
"""
if timestr is None:
r... | cebf74b3e1ba72cb0d6201319ebc871ac2f01d25 | 66,966 |
import os
def documents_path():
"""On windows, returns the path to My Documents. On OSX, returns the user's Documents folder. For anything else, returns the user's home directory."""
if is_windows:
path = winpaths.get_my_documents()
elif is_mac:
path = os.path.join(os.path.expanduser("~"),... | 0de60bcb8f3a49cf206823684a66718e585f17b6 | 66,967 |
def arrays_to_strings(measure_def):
"""To facilitate readability via newlines, we express some JSON
strings as arrays, but store them as strings.
Returns the json with such fields converted to strings.
"""
fields_to_convert = [
"title",
"description",
"why_it_matters",
... | 212a6211d55ed3745d8772180a5e285771145a05 | 66,968 |
from typing import List
import re
def filtered_lineage_group_to_allele_table(
filtered_lgs: List[pd.DataFrame],
) -> pd.DataFrame:
"""Produces the final allele table as a DataFrame to be used for
reconstruction.
Takes a list of alignment DataFrames annotated with lineage groups and
forms a final ... | 7f03b663bc467592702743d1ea2eec2df657c4cd | 66,969 |
def reaction_temperature(mu, velocity):
"""
Calculates reaction temperature
:param mu: reduced mass of reactants
:param velocity: relative velocity of reactants
:return: reaction temperature
"""
top = mu * velocity ** 2
bot = 2 * _u.k
output = top / bot
return output | 1dd9839b1c272adb99a5d086dcaffed7ba39fb32 | 66,970 |
async def cdoTopScorer(msg : Message,**kwargs):
"""
Shows the topscorer for a given competition
:param kwargs:
:return:
"""
return await basicStatsFun(msg,getTopScorers,False,**kwargs) | b171eb5cb6662eef6c410d565a80f2eeb13b2fd8 | 66,971 |
def train_op(
*,
gcs_bucket,
pose_estimation_gcs_path,
log_dir,
docker_image,
epochs,
memory_limit,
num_gpu,
gpu_type,
checkpoint_file=None,
):
""" Create a Kubeflow ContainerOp to train an estimator on the single cube dataset.
Args:
gcs_bucket: GCS Bucket wh... | c9974f8683ea9de8d395beba8ac7e2ce113faf8a | 66,972 |
def preprocess_data(save=False):
"""Preprocesses the raw data and saves it to csvs if specified by the save flag"""
print("Fetching and processing data...")
X = []
y = []
# Read the image files as np arrays and resize them so each image is the same size (64x64 pixels for now)
# add the images... | 867ff2f60eb231395e031f7d0d4c7746a95ebf98 | 66,973 |
def check_transaction_rejected_3dsecure_risk(result_code: str) -> bool:
"""
Result codes for rejections due to 3Dsecure and Intercard risk checks
The regular expression pattern for filtering out this group is: /^(000\.400\.[1][0-9][1-9]|000\.400\.2)/
"""
regex = r"^(000\.400\.[1][0-9][1-9]|000\.400... | ce00debcbb16879956aed65d08ca05cbe898a298 | 66,974 |
import numpy
def get_events_in_months(desired_months, verbose, event_months=None,
event_times_unix_sec=None):
"""Finds events in desired months.
If `event_months is None`, `event_times_unix_sec` will be used.
:param desired_months: 1-D numpy array of desired months (range 1...12... | 9673c7d0c6f09b2131fd5591d9ba34a5f16890dd | 66,975 |
import os
def load_features(path: str, subset: str) -> np.ndarray:
"""
Used to load a given set of features from a specified subset
:param path: the path where the features are located
:param subset: their subset (train or test)
:return: a np.ndarray containing the features
"""
if subset =... | b0dd46beaf5e801a72ed4de7e6a424b688aaf7fb | 66,976 |
def global_step(settings, n, k, var_lower, var_upper, integer_vars,
categorical_info, node_pos, rbf_lambda, rbf_h, tfv,
Amatinv, fmin_index, current_step):
"""Perform global search step.
Perform a global search step, with a different methodology
depending on the algorith... | b3ddace778113d847cdfe9adc22af861642d87ca | 66,977 |
def graph(request):
"""Proxy Graphite graphs
We don't want to bother the user with authenticating to Graphite.
Instead, here we download the graph using our credentials and pass
it to the user.
"""
password_mgr = HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(
None,
... | f11939b7146b4f30467f8dfbfe94a0f55db7b847 | 66,978 |
def policy(scores, lives=3):
"""
no improvement in last 3 runs
"""
temp_lives = lives
last = scores[0]
for i,score in enumerate(scores):
if i > 0:
if temp_lives == 0:
return i
elif score >= last:
temp_lives -= 1
last... | 9520b26dfd83f16a331906185edaec1ab9100dc8 | 66,979 |
def clean(func):
"""
Override the ChangeFilenameFormMixin clean method
to block uploading with different file name
"""
def inner(self):
current_filename = self.instance.file.name.split('/')[-1]
cleaned_data = func(self)
file = cleaned_data.get('file')
if file and file... | 9ebefa7d42f2eba5c1d8fa58d3dd7b1aa3f4d56b | 66,980 |
def bag_of_words(tokenized_setence, all_words):
"""
- DESC :
- if tok is in all_words :
we put '1' in the index of token in the all_words list
other wise '0'
tok : ['see', 'you', 'soon']
all_words : ['adress', 'are', 'destin', 'enter', 'good', 'g... | 2f6ffe7a4d3b9d8cb2027ebc5501de2d5103f7ef | 66,981 |
def call(name, msg_len=2):
""" specific decorator function
Handle the decorator where we expect a tuple of a specific size and
the first item being an atom with specific name
"""
atom = Atom(name)
def pattern_match(msg):
if type(msg) != tuple:
return False
i... | 7dabf6f65aafec0a3840d092a48eb1ea140637d5 | 66,982 |
def starfish_ish_II(Z, p=None, Z0=None, ET=None):
"""
par_set['zoom'] = 5/8
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex)
"""
if p is None:
p = -0.051448293230 + 0.304348945637j
Z = Z**(-np.exp(Z**p)**... | eeaeb7f9d2e914a12b261a129b6b95392d5e8768 | 66,983 |
import argparse
def gpt2_setup_args():
"""
设置训练参数
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--exp_name',
default='v0',
type=str,
required=False,
)
parser.add_argument('--model_config',
default='config/model_config_d... | 69563c3e1114fba48e509531abd4ba186783c443 | 66,984 |
import yaml
def infrastructure_projects_overview(request):
""" Overview page to showcase all featured infrastructure projects """
infrastructure_projects = InfrastructureProject.get_featured_projects_from_resource()
if infrastructure_projects is None:
return HttpResponse(status=404)
projects =... | d4ef4cea88f9a889697370a8bb4dbe771e768c10 | 66,985 |
from typing import Union
def get_fi(model: Union[lgb.LGBMClassifier,
lgb.LGBMRegressor,
RandomForestClassifier,
RandomForestRegressor,
GB],
data: pd.DataFrame,
feature_names: list = None,
n... | c72653adce55ee1074944be88c784dff0f669ef5 | 66,986 |
def integrator_functionRand(pi, x0, xref, N, T, deviation = 1):
"""Function which takes input pi - 1x3 array of k values- and integrates the system equation to return a system response.
This function is called as many times as there are k triplets in the phi function input.
"""
Dt = T/N
k_vals ... | 303235552a4d47e86e8a2b171656f7c55b97ea61 | 66,987 |
def _get_api_key():
"""Fetch the API key from your configuration file.
Expects a configuration file named "secrets.ini" with structure:
[openweather]
api_key=<YOUR-OPENWEATHER-API-KEY>
"""
config = ConfigParser()
config.read("secrets.ini")
return config["openweather"]["api_key"... | 3248e6251ae91281c9b66d6e0bf20fa24542e893 | 66,988 |
def precipitation():
"""convert query results to a dictionary using date as the key and prcp as the value"""
"""return JSON representation of dictionary"""
session = Session(engine)
prcp_results = session.query(measurement.date, measurement.prcp).all()
session.close()
prcp_data = []
for dat... | 5ccfb4daacab578fdbf73b28f6570a4240e8814d | 66,989 |
def load(training_size:int, test_size:int, classes=None, features=784, random_seed=42,
normalize=True):
"""
MNIST dataset
http://yann.lecun.com/exdb/mnist/
"""
if classes is None:
classes = list(range(10))
class_lab... | 234e5a934c67127e01d0c4bc691a3c925831939e | 66,990 |
import json
def coorg_identity_links_view_by_identity(self, identity_type: str, identity_id: int) -> dict:
"""
Retrieve all existing CO Identity Links for a CO Person or an Org Identity.
:param self:
:param identity_type:
:param identity_id:
:return
{
"ResponseType":"CoOrgI... | 967a33604cbb4e4ad7bb742791aff2a1fb4484d5 | 66,991 |
def plasticity_trial(sim_pars): # place map plasticity
"""
"""
# Extract parameters from configuration --------------------------------------------------------------
N_pre = sim_pars["N_pre"]
N_dend = sim_pars["N_dend"]
T_length = sim_pars["T_length"]
dt = sim_pars["dt"]
Idend_0 = sim_... | b02e99e181e583e6b272cca15b163e4ede11ce95 | 66,992 |
from typing import Dict
from typing import Tuple
def train_step(model: nn.Module, state: TrainState,
batch: Dict[str, jnp.ndarray]) -> Tuple[TrainState, float]:
"""Performs a single training step.
Args:
model: A model configured for the batch size.
state: Current training state. Updated tr... | 546fcc95cecde9b079983849507994eb08fc9bd4 | 66,993 |
def concat_drive_path(dest_path: str, end_point: str, default_folder: str = 'mydrive') -> str:
"""
Generate file path
:param dest_path: parent path
:param end_point: file_name or folder_name
:param default_folder: if dest_path is None, use your drive home folder instead
:return:
"""
if d... | 09dd261e825379604c0c7546b3a6a68d1b35505f | 66,994 |
def savefig(file_path, tight_layout=True, both=False, dpi=DEFAULT['dpi'],
suffix='auto', close=True, **kwargs):
"""
Save figure.
:param file_path: (str) - path to file
:param tight_layout: (boolean) - whether to save with tight layout
:param both: (boolean) - whether to save both png an... | 9b2ebb58c6dbf422c1ffd58cb6684bf9f30d8b10 | 66,995 |
import torch
def _log_cdf(x, mean, log_scale):
"""Element-wise log CDF of the logistic distribution."""
z = (x - mean) * torch.exp(-log_scale)
log_p = F.logsigmoid(z)
return log_p | aad3dc25e2241babfaa7cf11be15cc431b9553ad | 66,996 |
def cfg_192x108():
"""Return config which reduces rendering workload when previewing."""
cfg = sine440_config()
# Skip frames.
assert cfg.end_time == 0.5
cfg.render_subfps = 2
# Divide dimensions.
cfg.render.width = 192
cfg.render.height = 108
cfg.render.res_divisor = 1.5
retu... | b7d52dc9225ce0b802bb4e3f1196a6d64e48d484 | 66,997 |
def temp_gradient(bottom_hole_temperature, surface_temperature, bottom_hole_depth):
"""
Temperature gradient calculation.
Parameters
----------
bottom_hole_temperature : float
Bottom hole temperature (deg F or deg C)
surface_temperature : float
Surface temperature (deg F or deg ... | f99a9215fd63a8ef564a1fc91de75ea146091712 | 66,998 |
def _get_ucry_cz(nqubits, angles):
"""
Get uniformally controlled Ry gate in in CZ-Ry as in UCPauliRotGate.
"""
nangles = len(angles)
qc = QuantumCircuit(nqubits)
q_controls = qc.qubits[:-1]
q_target = qc.qubits[-1]
if not q_controls:
if np.abs(angles[0]) > _EPS:
qc.r... | 2c0974f691588d58103347459bb2efa55ea28d61 | 66,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.