content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def bitbucketBaseIssue():
"""
BitbucketIssueのベースとなるデータを生成して返します。
"""
return {
'assignee': None,
'component': None,
'content': 'issue_summary',
'content_updated_on': '4000-01-01T00:00:00Z',
'created_on': '3000-01-01T00:00:00Z',
'edited_on': '4000-01-01T00:0... | b0a81a9442377967b0838ffe49468dd21631b1c0 | 17,908 |
def is_hour_staffed(coverage_events_for_hour, level_mappings):
"""
Logic for determining if a shift is correctly staffed. The required subcalendar id determines which logic to apply
coverage_events_for_hour is a list of coverage events for the hour (a list of CoverageOffered JSON objects)
"""
retur... | 7afda68593610a572f15ff791013db570b7c69a6 | 17,910 |
import json
def sqliteAdminBlueprint(
dbPath,
bpName='sqliteAdmin',
tables=[],
title='标题',
h1='页标题',
baseLayout='flask_sqlite_admin/sqlite_base.html',
extraRules=[],
decorator=defaultDecorator):
""" create routes for admin """
sqlite = Blueprint(bpName, __name__,template_folder='templates... | 6dc7f38db36f38835f2ee5274a716bde14284480 | 17,911 |
def AccountsUrl(command):
"""Generates the Google Accounts URL.
Args:
command: The command to execute.
Returns:
A URL for the given command.
"""
return '%s/%s' % (GOOGLE_ACCOUNTS_BASE_URL, command) | 7c686ef8648abf3123ba1448594c333c3210331c | 17,912 |
def iter_input_annotation_output_df_df(inspection_index, input_df, annotation_df, output_df):
"""
Create an efficient iterator for the inspection input
"""
# pylint: disable=too-many-locals
# Performance tips:
# https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe... | 4e275565bfa570f48b0eacbe07029a7724305f9a | 17,913 |
def measure_curvatures(left_fit, right_fit, ym_per_pix=1., xm_per_pix=1.,
y_eval=0):
""" Calculate left and right lane line curvature
Args:
left_fit: `numpy.ndarray` second order linear regression of left lane line
right_fit: `numpy.ndarray` second order linear regression of right lane li... | f602563e36cbff3e2eca00a7532c37fdb127a6c1 | 17,914 |
def ensure_present(params, check_mode):
"""
Ensure that the specified Hipersockets adapter exists and has the
specified properties set.
Raises:
ParameterError: An issue with the module parameters.
Error: Other errors during processing.
zhmcclient.Error: Any zhmcclient exception can ha... | 9a574df51dd8755e0d973438ec16d7209995b26a | 17,915 |
import requests
import base64
def get_processed_image(username):
"""Gets the b64 strings of the processed images from the server and
converts them to image files
Args:
username (tkinter.StringVar): user-specified username to identify
each unique user
Returns:
JpegImageFile: t... | 6ced5ce2b8cf48a8a4ca04799ae6b61956c59bb8 | 17,916 |
def make_cse_path(raw_ticker: str, raw_industry: str) -> str:
"""makes slug for ticker for the cse
Parameters:
raw_ticker - cse ticker from xlsx sheet
raw_industry - verbatim industry from ticker, not slugified
Returns:
description - url for cse files for download
"""
if pd.isna(r... | 4466cd2e5c7416266db080b7b273b41c7469c790 | 17,917 |
def interface(inp, xdata, ydata):
""" splits the c function output to two variables, the RMSE and the derivative of RMSE with respect to the parameters"""
p = _gauss.gaussjac(xdata,ydata,inp)
return p[0],p[1:] | 28707bd4781f2e19623068c01dca3cf82f8f79df | 17,919 |
import torch
def generateCoverText_BERT(mod, tok, startOfText, ranks, completeMessage):
"""
Function to get the cover text that is sent from Alice to Bob based on the ranks of the secret text
"""
inputs = tok.encode(startOfText, return_tensors="pt", add_special_tokens=False)
for s in ranks:
tab = inputs... | 405eb656db91eb073be580c8d10f8beb435d1bde | 17,920 |
def Fanstatic(app,
publisher_signature=fanstatic.DEFAULT_SIGNATURE,
injector=None,
**config):
"""Fanstatic WSGI framework component.
:param app: The WSGI app to wrap with Fanstatic.
:param publisher_signature: Optional argument to define the
signature of the... | 8813441736ffb05dcac7ea87d691a10ef9e582d7 | 17,922 |
def predicate_id(namespace, predicate, cursor=None):
"""
Get a RDF predicate ID, creating it if necessary.
"""
data = {'namespace': namespace, 'predicate': predicate}
cursor = relations_reader.predicate_id(data, cursor=cursor)
if not cursor.rowcount:
relations_writer.upsert_predicate(da... | 95925711f1cf7cbf3c648a954a431e66cda31e30 | 17,923 |
import copy
def _create_filter_list(user_list, request=None):
"""
[メソッド概要]
フィルタのリストを作成する
[引数]
user_list :_getUserData(filters)により作成されるuser_list
request :logger.logic_logでuserId sessionIDを表示するために使用する
[戻り値]
filter_list
"""
logger.logic_log('LOSI00001', 'user_list: %s'... | 730cf9140c3c66903f4223938090e6667af4d741 | 17,924 |
from typing import List
from typing import Dict
def get_events() -> List[Dict]:
"""Represents set of sales events"""
return [{
"Txid": 1,
"productname": "Product 2",
"qty": 2,
"sales": 489.5
}, {
"Txid": 2,
"productname": "Product 3 XL",
"qty": 2,
... | 22361fc66926a9adb5b10f4ad9ba04767a7d7a25 | 17,926 |
def jump_handler(s):
"""Handling single and double jumps"""
jump = 1 if s.poG or s.ljump and not s.poG and s.fz > 0 else 0
if jump and s.ljump != s.lljump or not s.ljump:
s.pitch = s.yaw = s.roll = 0
if min(0.18, s.dT + 0.05) < s.airtime and s.fz > 100:
jump = not s.ljump
return ... | 44826e6b55ff4ceda5a78c7dc0943e5f13f5934e | 17,927 |
def sec2hms(sec):
"""
Convert seconds to hours, minutes and seconds.
"""
hours = int(sec/3600)
minutes = int((sec -3600*hours)/60)
seconds = int(sec -3600*hours -60*minutes)
return hours,minutes,seconds | efea3a641c5f13313adb571c201cc25d2895757e | 17,928 |
import tokenizers
def to_english_like_sentence(sentence: str, tokenizer = tokenizers.JiebaTokenizer()):
"""
:param sentence:
:return:
"""
return ' '.join(tokenizer(sentence)) | 6f63377885c07b9dd723178f2fbe7e6245659e2a | 17,929 |
from datetime import datetime
def get_month_range(start_date):
"""
Get the start and end datetimes for the month
:param start_date: period start_date
:type start_date: datetime.datetime()
:return: tuple start_datetime, end_datetime
"""
start_date = datetime(start_date.year, start_date.mon... | 74816209024cbd382121575ba27a9dd8cf967c2b | 17,930 |
def convert_to_rotation_fdot(
gwfrequency=None,
rotationfrequency=None,
rotationperiod=None,
gwfdot=None,
rotationpdot=None,
**kwargs,
):
"""
Convert the GW frequency (assumed to be twice the rotation frequency) or
the rotation period and GW rotation frequency derivative or rotation
... | 8d2321111c7f5d13f1ee93c828b5e6d0691a4fb2 | 17,932 |
import json
def send_block(
cmd=None,
section=None,
item=None,
identifier=None,
zone=None,
owner=None,
ttl=None,
rtype=None,
data=None,
flags=None,
filter_=None,
):
"""Send block command to Libknot server control."""
ctl = connect_knot()
resp = None
try:
... | b6edac27b74d432c796d759dd373a24cf6710abd | 17,933 |
def _poisson_covariance(dist, lambda0):
""" Poisson covariance model on the sphere.
Parameters
----------
dist: float
Great circle distance.
lambda0: float
Lengthscale parameter.
"""
cov = (1 - lambda0**2) / (1 - 2*lambda0*np.cos(dist) + lambda0**2)**(3/2)
return cov | e2ebb694258d94b56a81ff44ee703871b722a0ad | 17,934 |
def snot(N=None, target=None):
"""Quantum object representing the SNOT (2-qubit Hadamard) gate.
Returns
-------
snot_gate : qobj
Quantum object representation of SNOT gate.
Examples
--------
>>> snot()
Quantum object: dims = [[2], [2]], \
shape = [2, 2], type = oper, isHerm = T... | 6b0820eda38b3eba0da9bdc6ca1b2e01c1b7ddc0 | 17,935 |
from typing import Callable
from typing import Dict
from typing import Type
from pydantic import BaseModel # noqa: E0611
from typing import Any
def _do_wrapper(
func: Callable,
*,
responses: Dict[str, Type[BaseModel]] = None,
header: Type[BaseModel] = None,
cookie: Type[BaseMo... | 5fe2a2698d5aadcbd8f2731d06158d02aaa0df31 | 17,936 |
def make_divisible(v, divisor, min_val=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
"""
if m... | e843378d276518ac26a7896523da247c41437297 | 17,937 |
def mock_query_object(LCClient):
"""
Creating a Query Response object and prefilling it with some information
"""
# Creating a Query Response Object
start = '2016/1/1'
end = '2016/1/2'
obj = {
'TimeRange': TimeRange(parse_time(start), parse_time(end)),
'Time_start': parse_tim... | cce825c17e902334db05d16f923aaa3f195bf2a8 | 17,938 |
def edit(photo_id):
"""
Edit uploaded photo information.
:param photo_id: target photo id
:return: HTML template for edit form or Json data
"""
if request.method == 'GET':
photo = Photo.get(current_user.id, photo_id)
return render_template('upload.html', photo=photo, gmaps_key=c... | 2664cf584e5a303aac6afa75828fc873ea7e09ed | 17,939 |
def crop_only(net1, net2):
"""
the size(net1) <= size(net2)
"""
net1_shape = net1.get_shape().as_list()
net2_shape = net2.get_shape().as_list()
# print(net1_shape)
# print(net2_shape)
# if net2_shape[1] >= net1_shape[1] and net2_shape[2] >= net1_shape[2]:
offsets = [0, (net2_shape[1]... | 0cc2462244efabfd0a40eb6571adfca080906d86 | 17,940 |
def normalize(image):
""" Normalize to 0-255, dtype: np.uint8
"""
if np.min(image) < 0:
image = image - np.min(image)
if np.max(image) != 0:
image = image / np.max(image)
image = image * 255
image = np.uint8(image)
return image | 4de22a943d4db3c54b433c833cd721cb94c4c5d6 | 17,941 |
import tempfile
def temp_file(contents, suffix=''):
"""Create a self-deleting temp file with the given content"""
tmpdir = get_test_tmpdir()
t = tempfile.NamedTemporaryFile(suffix=suffix, dir=tmpdir)
t.write(contents)
t.flush()
return t | 2d5c5fa07322f1d2acf6d576c43007a5f1ae6977 | 17,942 |
def string_to_charlist(string):
"""Return a list of characters with extra empty strings after wide chars"""
if not set(string) - ASCIIONLY:
return list(string)
result = []
if PY3:
for c in string:
result.append(c)
if east_asian_width(c) in WIDE_SYMBOLS:
... | dde3d72c05c1e86f3d5a795280b80934b598c0ae | 17,943 |
def urlparams(url_, hash=None, **query):
"""Add a fragment and/or query paramaters to a URL.
New query params will be appended to exising parameters, except duplicate
names, which will be replaced.
"""
url = urlparse.urlparse(url_)
fragment = hash if hash is not None else url.fragment
# Us... | 4eb1f66778540470bb710970a8db712aa3cde9a8 | 17,944 |
def get(word, cache=True):
"""
Load the word 'word' and return the DudenWord instance
"""
html_content = request_word(word, cache=cache) # pylint: disable=unexpected-keyword-arg
if html_content is None:
return None
soup = bs4.BeautifulSoup(html_content, 'html.parser')
return DudenW... | face281ce5eb2ab1b398b573afeaebbb78da47d6 | 17,945 |
def cubespace(start, stop=False, num=10, include_start=True):
"""
Return sequence of *num* floats between *start* and *stop*.
Analogously to numpy's linspace, values in returned list are chosen
so that their cubes (hence name) are spread evenly in equal distance.
If the parameter *stop* is not give... | d011ce033895465e9cb2ed0eb86598163d035208 | 17,946 |
def to_ndarray(arr):
"""
Convert a list of lists to a multidimensional numpy array
@param arr:
@return:
"""
return np.array([np.array(x) for x in arr]) | 1bf5ac651921a631e46d8ecae50b81082f9aea6e | 17,947 |
def spectre_avatar(avatar, size="sm", **kwargs):
"""
render avatar
:param avatar:
:param size:
:param kwargs:
:return: HTML
"""
avatar_kwargs = kwargs.copy()
avatar_kwargs['avatar_url'] = avatar
avatar_kwargs['size'] = size
if "background" not in avatar_kwargs.keys():
... | d573336c13f63cb647d40241d2c37f78fd4cc292 | 17,948 |
def get_modules_by_appid(app_id):
"""
查询业务下的所有模块信息
注意:企业版使用get_modules_by_property代替
"""
cc_data = bk.cc.get_modules_by_property(app_id=app_id)
return cc_data | d57277ec09433da3c03c8ece67cc994f27dfcd21 | 17,949 |
def do_json_counts(df, target_name):
""" count of records where name=target_name in a dataframe with column 'name' """
return df.filter(df.name == target_name).count() | c4b0cb52f28372a7d53a92984b3212c66c1556ab | 17,951 |
def is_a(file_name):
"""
Tests whether a given file_name corresponds to a ICEYE file. Returns a reader instance, if so.
Parameters
----------
file_name : str|BinaryIO
the file_name to check
Returns
-------
CSKReader|None
`CSKReader` instance if Cosmo Skymed file, `None`... | 744d2ff8f940e220f0e41b8739a535c1afe6476e | 17,952 |
def fetch_optimizer(args, model):
""" Create the optimizer and learning rate scheduler """
optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wdecay, eps=args.epsilon)
scheduler = optim.lr_scheduler.OneCycleLR(optimizer=optimizer, max_lr=args.lr, total_steps=args.num_steps+100,
... | d5fab8b0b665267c8b90eb25fe9dab3a7ce428e7 | 17,953 |
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings, freeze_bert, finetune_module,
num_train_examples):
"""Returns `model_fn` closure for TPUEstimator."""
... | a2ec1fd2a41916170ec34b1b988ce0b5c4466fd6 | 17,954 |
def load_series_spectrum_df(series_dict_channels):
"""
Takes a series of dictionaries generated by pd.Series.apply(load_channels)
and returns a dataframe with the frequencies expanded as columns.
If the frequencies are not identically overlapping across rows, the resulting
set of columns will the t... | d2b398f11b3dc6d67c60f62f4e49938ce7817177 | 17,955 |
from typing import Dict
def get_mujoco_features_dict(
builder_config: BuilderConfig,
ds_config: DatasetConfig) -> Dict[str, tfds.features.FeatureConnector]:
"""Builds the features dict of a Mujoco dataset.
Args:
builder_config: builder config of the Mujoco dataset.
ds_config: config of the Mujoco... | 96f12353f880028b231d1ebe67678b0c39118f42 | 17,956 |
def weighted_cross_entropy(y_true, y_pred):
"""
Weighted cross entropy loss
:param y_true: Ground truth
:param y_pred: Prediction
:return: Loss value between y_true and y_pred
"""
try:
[seg, weight] = tf.unstack(y_true, 2, axis=3)
seg = tf.expand_dims(seg, -1)
weigh... | 9e91f93396975109a8f05ac56d4cc3ddc4460eb9 | 17,957 |
def union(a, b):
"""Find union of two lists, sequences, etc.
Returns a list that includes repetitions if they occur in the input lists.
"""
return list(a) + list(b) | bf154b6222122aa61cf590022475dcd38eed6df4 | 17,959 |
def update_intervals(M, s, B):
"""
After found the s value, compute the new list of intervals
"""
M_new = []
for a, b in M:
r_lower = ceil(a * s - 3 * B + 1, n)
r_upper = ceil(b * s - 2 * B, n)
for r in range(r_lower, r_upper):
lower_bound = max(a, ceil(2 * B +... | 3056a5e957317155b6ad2da28f2d05831e77af43 | 17,960 |
def mixer_l16_224_in21k(pretrained=False, **kwargs):
""" Mixer-L/16 224x224. ImageNet-21k pretrained weights.
Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
"""
model_args = dict(patch_size=16, num_blocks=24, embed_dim=1024, **kwargs)
model = _create_mixer... | cead4a01ef964af2ee9a9509881c2e58dcba9b6f | 17,961 |
def isoslice(var, iso_values, grid=None, iso_array=None, axis="Z"):
"""Interpolate var to iso_values.
This wraps `xgcm` `transform` function for slice interpolation,
though `transform` has additional functionality.
Inputs
------
var: DataArray
Variable to operate on.
iso_values: li... | 2bd475623b5862f5325250bd6b27d771c55e7e99 | 17,963 |
def user_prompt(msg: str, sound: bool = False, timeout: int = -1):
"""Open user prompt."""
return f'B;UserPrompt("{msg}",{sound:d},{timeout});'.encode() | 25e2941c212c487f9a319159a3eab66d3ff38050 | 17,964 |
def ComputeWk(X, labels, classes):
"""
X - (d x n) data matrix, where n is samples and d is dimentionality
lables - n dimentional vector which are class labels
"""
Wk = 0
for i in range(classes):
mask = (labels == i)
Wk = Wk + np.sum(np.sum((X[:, mask] - np.mean(X[:, mas... | 3d68a2e6635194827e39762df566d24cc86a5e30 | 17,965 |
def vad_split(audio, rate, frame_duration, aggressiveness=1):
"""Splits the audio into audio segments on non-speech frames.
params:
audio: A numpy ndarray, which has 1 dimension and values within
-1.0 to 1.0 (inclusive)
rate: An integer, which is the rate at which samples are take... | e75ae1bd4681936922cbf53076da5bb10c0306c5 | 17,966 |
def is_extant_string(string):
"""Check if the string exists in the database"""
return HyperlinkModel.objects.filter(internal=string).exists() | e87b1dc88359301a5bdd7a22b2ac47e65fd3559f | 17,967 |
def time_to_convergence(T,P0,final_beliefs=False,tolerance=0,max_iter=10000):
"""
This function calculates the number of periods that it takes for opinions to stop changing in the DeGroot Model.
Optionally, one can also get the final belief profile.
"""
T = np.asarray(T)
P0 = np.transpose(np.asa... | b2cd345cfe573b11689a67108d9205a558ac2485 | 17,968 |
def count_subset_sum_recur(arr, total, n):
"""Count subsets given sum by recusrion.
Time complexity: O(2^n), where n is length of array.
Space complexity: O(1).
"""
if total < 0:
return 0
if total == 0:
return 1
if n < 0:
return 0
if total < arr[n]:
ret... | 981b83014e75122dea814ace5b34b18f9803c3ad | 17,969 |
def monthcalendar(year, month):
"""Return a matrix representing a month's calendar.
Each row represents a week; days outside this month are zero."""
day1, ndays = monthrange(year, month)
rows = []
r7 = range(7)
day = (_firstweekday - day1 + 6) % 7 - 5 # for leading 0's in first week
whi... | e5d9f370c0c3937d102f24aa342d0a755b234ca4 | 17,970 |
def Contap_HCurve2dTool_Bezier(*args):
"""
:param C:
:type C: Handle_Adaptor2d_HCurve2d &
:rtype: Handle_Geom2d_BezierCurve
"""
return _Contap.Contap_HCurve2dTool_Bezier(*args) | 02e4c876c304383003b8cabe55cb233a59b9fdd9 | 17,971 |
def api_view_issue(repo, issueid, username=None, namespace=None):
"""
Issue information
-----------------
Retrieve information of a specific issue.
::
GET /api/0/<repo>/issue/<issue id>
GET /api/0/<namespace>/<repo>/issue/<issue id>
::
GET /api/0/fork/<username>/<repo... | 3094d788a08c5547092fecab85bec08676ef323b | 17,972 |
import torch
def mcc_class_loss(
predictions: torch.tensor,
targets: torch.tensor,
data_weights: torch.tensor,
mask: torch.tensor,
) -> torch.tensor:
"""
A classification loss using a soft version of the Matthews Correlation Coefficient.
:param predictions: Model predictions with shape(ba... | 501d21791d88d4aacfc799f1bb8b64bf49da5bc7 | 17,973 |
def inverse(fun, value):
"""Calculate argument of f given its value"""
epsilon = 1e-09
start = middle = 1e-09
end = 1e9
while abs(end - start) > epsilon:
middle = (start + end) / 2
if isclose(fun(middle) - value, 0.0):
break
elif fun(middle) - value > 0 and fun(st... | fe9eb8b4e90cb8c6216620b6518bbf92404fd3c6 | 17,974 |
from backend.caffe.path_loader import PathLoader
def getCaffemodelFromSolverstate(solverstate):
""" Parse the filename of the caffemodel file from the solverstate file.
"""
proto = PathLoader().importProto()
try:
state = proto.SolverState()
with open(solverstate, 'rb') as f:
... | ffdc936eed5e0dfe4b5a7c5321ed60cf67166b81 | 17,976 |
import re
def get_L_from_D(line):
"""
Assume line contains one or more <Dn>
Return list of all n
"""
a = []
for m in re.finditer(r'<D([0-9]+)>',line):
a.append(m.group(1))
return a | 2cd5c710709c38ea7a2b1890e084116a7fd5ee43 | 17,977 |
def per_pixel_mean_stddev(dataset, image_size):
"""
Compute the mean of each pixel over the entire dataset.
"""
#NOTE: Replace "3" by the number of channels
initial_state = tf.constant(0., dtype=tf.float32, shape=[image_size, image_size, 3])
dataset = dataset.map(lambda x: resize(x, image_si... | 38f479d7f1b1d422f15a5e5a6363552edb07fe69 | 17,978 |
def get_indexes_from_list(lst, find, exact=True):
"""
Helper function that search for element in a list and
returns a list of indexes for element match
E.g.
get_indexes_from_list([1,2,3,1,5,1], 1) returns [0,3,5]
get_indexes_from_list(['apple','banana','orange','lemon'], 'orange') -> returns [2]... | 416d94de975603a60bf41974b8564cd868e503c0 | 17,979 |
def simplify_polygon(polygon, tolerance=0.01):
"""Remove doubles coords from a polygon."""
assert isinstance(polygon, Polygon) or isinstance(polygon, MultiPolygon)
# Get the coordinates
coords = []
if isinstance(polygon, Polygon):
coords = polygon.exterior.coords
elif isinstance(polygon,... | 73fe9d950e5aa908e99c8fe21e28837852f7f3c6 | 17,980 |
def looks_like_PEM(text):
"""
Guess whether text looks like a PEM encoding.
"""
i = text.find("-----BEGIN ")
return i >= 0 and text.find("\n-----END ", i) > i | ff310d6ffcf6d4ebd63331fdae66774009ef2b39 | 17,981 |
from typing import Counter
def find_duplicates(list_to_check):
"""
This finds duplicates in a list of values of any type and then returns the values that are duplicates. Given Counter
only works with hashable types, ie it can't work with lists, create a tuple of the lists and then count if the
list_to... | 1d608a70e7fb9be2001c73b72d3c1b62047539b5 | 17,982 |
from typing import Any
def none_to_default(field: Any, default: Any) -> Any:
"""Convert None values into default values.
:param field: the original value that may be None.
:param default: the new, default, value.
:return: field; the new value if field is None, the old value
otherwise.
:rt... | 894d71c2cc89b02dc14fd7ddcd3a949bdc336692 | 17,983 |
def fetch_pauli2018(data_dir=None, url=None, resume=True, verbose=1):
"""
Downloads files for Pauli et al., 2018 subcortical parcellation
Parameters
----------
data_dir : str, optional
Path to use as data directory. If not specified, will check for
environmental variable 'NNT_DATA';... | 3b81073509b8e7986f28bde38e9c19fe73e616b4 | 17,984 |
def lambda_to_ent(la):
""" entanglement from a schmidt coeff lambda
ent = - [la * log(la) + (1 - la) * log(1 - la)]
where la (lambda) is the Schmidt coefficient
"""
return - np.nan_to_num((1-la)*np.log(1-la) + la*np.log(la)) | 7f3e128931100f23897d1a36fce6994e95f58bef | 17,985 |
from typing import Dict
from typing import Callable
import logging
def parse_states(
value_field: str,
selected_values: selected_values_type,
selected_fields: selected_fields_type,
*,
field_cleaners: Dict[str, Callable[[pd.DataFrame, str], pd.DataFrame]] = None,
) -> parsed_data_type:
"""
... | 79060844d0c5c555881458b20a70a0589780e027 | 17,986 |
def is_diagonal_segment(vector_start, vector_end):
"""Diagonal as defined by a slope of 1 or -1"""
return slope(vector_start, vector_end) in (1, -1) | fbd56b3cbecf907b0e0a5fdd533b99472d532387 | 17,987 |
def properties_table(segment_props, columns=None, exclude_columns=None):
"""
Construct a `~astropy.table.Table` of properties from a list of
`SegmentProperties` objects.
If ``columns`` or ``exclude_columns`` are not input, then the
`~astropy.table.Table` will include all scalar-valued properties.
... | 82f2b69a9c6289a62200e4e3cead83d9a1fb3fd9 | 17,988 |
def create_mutation(model, app):
"""Create Class-Mutation."""
app_name_lower = app.name.lower()
type_name = f"{ app_name_lower }{ app.model.name }Type"
mutation_name = f"{ app_name_lower }{ app.model.name }Mutation"
form_name = f"{ app_name_lower }{ app.model.name }Form"
api_uri = f"{ app_name_l... | 6a4837e0369bc2e0f1967edabc97edf8eba9fac1 | 17,989 |
def read_players_info():
"""Get players info - [player 1 name, player 1 sign]"""
first_player_name = input("Player one name: ")
second_player_name = input("Player two name: ")
first_player_sign = read_first_player_sign(first_player_name)
second_player_sign = "O" if first_player_sign == "X" else "X"
... | ceff930373ae4abd2c7605297ea9b0259282110a | 17,990 |
def z_gate_circuits_deterministic(final_measure=True):
"""Z-gate test circuits with deterministic counts."""
circuits = []
qr = QuantumRegister(1)
if final_measure:
cr = ClassicalRegister(1)
regs = (qr, cr)
else:
regs = (qr, )
# Z alone
circuit = QuantumCircuit(*regs... | 7137b04a351ecca99bf0c6e59058cd1ef49e2ba7 | 17,991 |
from sympy import Add
import sympy
def symbol_sum(variables):
"""
``` python
a = symbols('a0:100')
%timeit Add(*a)
# >>> 10000 loops, best of 3: 34.1 µs per loop
b = symbols('b0:1000')
%timeit Add(*b)
# >>> 1000 loops, best of 3: 343 µs per loop
c = symbols... | f923d504760858d3cc7c4dc77ce50fe9fd4036f6 | 17,992 |
from typing import Optional
def any_specified_encoding(sequence: bytes, search_zone: int = 4096) -> Optional[str]:
"""
Extract using ASCII-only decoder any specified encoding in the first n-bytes.
"""
if not isinstance(sequence, bytes):
raise TypeError
seq_len = len(sequence) # type: int... | f8cfe1bcb2b4fc4f2b498b252c0f946ff4773c04 | 17,993 |
import warnings
def maf(genotypes):
"""Computes the MAF and returns a boolean indicating if the minor allele
is currently the coded allele.
"""
warnings.warn("deprecated: use 'Genotypes.maf'", DeprecationWarning)
g = genotypes.genotypes
maf = np.nansum(g) / (2 * np.sum(~np.isnan(g)))
if m... | 192d43b46cd8028245e4df45bdda5d3227495e18 | 17,994 |
def lower_bound_jensen_shannon(logu, joint_sample_mask=None,
validate_args=False, name=None):
"""Lower bound on Jensen-Shannon (JS) divergence.
This lower bound on JS divergence is proposed in
[Goodfellow et al. (2014)][1] and [Nowozin et al. (2016)][2].
When estimating lower bou... | 4cdf48b5a018e33cca4a7f4aeab55d649664c5c5 | 17,995 |
import numpy
import scipy
def competition_ranking(data, dtype="int32"):
"""
Ranks the given data in increasing order and resolving duplicates using the
lowest common rank and skipping as many ranks as there are duplicates, i.e.,
[0.5, 1.2, 3.4, 1.2, 1.2] -> [1, 2, 5, 2, 2].
Parameters
--... | d4e05b9f35a0706faa2f09840391ee45d12062ce | 17,996 |
def fmt_dashes(name: str) -> str:
"""
Converts name to words separated by dashes. Words are identified by
capitalization, dashes, and underscores.
"""
return '-'.join([word.lower() for word in split_words(name)]) | b58bba1beee9870fcc46d0abeba5f33a54066afe | 17,997 |
def stringify_dict_key(_dict):
"""
保证_dict中所有key为str类型
:param _dict:
:return:
"""
for key, value in _dict.copy().items():
if isinstance(value, dict):
value = stringify_dict_key(value)
if not isinstance(key, str):
del _dict[key]
_dict[str(key)] ... | e83df720772aa4122d9a435da20279d4a800e074 | 17,998 |
def bestIndividual(hof, X, y):
"""
Get the best individual
"""
maxAccurcy = 0.0
for individual in hof:
if(individual.fitness.values > maxAccurcy):
maxAccurcy = individual.fitness.values
_individual = individual
_individualHeader = [list(X)[i] for i in range(
... | 7643001710ba644b2d5886d6a2e86b3ae1c79018 | 17,999 |
import requests
def make_new_paste(devkey, paste_text, user_key=None, paste_title=None, paste_format=None, paste_type=None, paste_expiry: int=None):
"""This function creates a new paste
on pastebin with the given arguments."""
data = {'api_dev_key': devkey, 'api_option': 'paste', 'api_paste_code': paste_... | 59b5be916c007e778ac0cf7a22b49b094f68dfaa | 18,000 |
def not_none(value):
"""
This function ensures that passed value is not None:
>>> schema = Schema(not_none)
>>> assert 1 == schema(1)
>>> try:
... schema(None)
... assert False, "an exception should've been raised"
... except MultipleInvalid:
... pass
"""
if val... | d3381c51d2d25edfbd56f6e1008d39056b0a0bda | 18,001 |
def j1c_dblprime(amplitudes):
"""Calculate j''1c angular observable"""
[_, _, _, _, a_0_l, a_0_r, a_00_l, a_00_r] = amplitudes
return (2 / tf.sqrt(3.0)) * (
tf.math.real(a_00_l * tf.math.conj(a_0_l) * bw_k700_k892) +
tf.math.real(a_00_r * tf.math.conj(a_0_r) * bw_k700_k892)
) | eead7c64e7033262aa98ccb966fd83a51419a065 | 18,002 |
def preprocess(img):
"""Changes RGB [0,1] valued image to BGR [0,255] with mean subtracted."""
mean_bgr = load_mean_bgr()
print 'mean blue', np.mean(mean_bgr[:, :, 0])
print 'mean green', np.mean(mean_bgr[:, :, 1])
print 'mean red', np.mean(mean_bgr[:, :, 2])
out = np.copy(img) * 255.0
out =... | 759110f2004315ab45aed1b18dbe5a1132366dd5 | 18,003 |
def profile_detail(request, username, template_name='userena/profile_detail.html', extra_context=None, **kwargs):
"""
Detailed view of an user.
:param username:
String of the username of which the profile should be viewed.
:param template_name:
String representing the template name tha... | c81d3cb2910e6358760c742c7b4081df4ed95a45 | 18,004 |
def prepare_ternary(figsize, scale):
"""Help function to ternary plot"""
fig, ax = plt.subplots(figsize=figsize)
tax = ternary.TernaryAxesSubplot(ax=ax, scale=scale)
ax.axis('off')
gm = 0.1 * scale
blw = 1
tlw = 1
# Draw Boundary and Gridlines
tax.boundary(linewidth=blw)
tax.grid... | 67b40d55d2296957cbe152bce69a5afcd22c2624 | 18,005 |
from typing import Dict
def parse_spreadsheet(hca_spreadsheet: Workbook, entity_dictionary: Dict):
"""
Parse the spreadsheet and fill the metadata with accessions.
:param hca_spreadsheet: Workbook object of the spreadsheet
:param entity_dictionary: Dictionary mapping by entity UUID to the proper arch... | 83607766eda5b0f9d5a6fc09035a12d29fb8b44c | 18,006 |
def decode(data):
"""Decode JSON serialized string, with possible embedded Python objects.
"""
return _decoder.decode(data) | b82d55eb7e704f9396aab3642314f172c2205a04 | 18,007 |
def p_correction(p_values):
"""
Corrects p_values for multiple testing.
:param p_values: Dictionary storing p_values with corresponding feature names as keys.
:return: DataFrame which shows the results of the analysis; p-value, corrected p-value and boolean indicating \
significance.
"""
p... | f1e7faa35176cdf41aca273413d7eb9d784dfdb1 | 18,008 |
def GetFlippedPoints3(paths, array):
"""same as first version, but doesnt flip locations: just sets to -1
used for random walks with self intersections - err type 6"""
# this may not work for double ups?
for i in paths:
for j in i: # for the rest of the steps...
array[j[0]][j[1]][j[... | ad0bc7a03e293beb2542ee555a341bdfc8706408 | 18,009 |
from typing import Callable
async def _silent_except(f: Callable, *args, **kwargs):
"""
Helper Function that calls a function or coroutine and returns its result excepting all errors
"""
try:
called = f(*args, **kwargs)
except:
return
if isawaitable(called):
try:
... | adaaf3e4a35dfed86d8fa83f8254396e0fa5245b | 18,010 |
def get_concat_h(im1, im2):
"""Concatenate two images horizontally."""
dst = Image.new("RGB", (im1.width + im2.width, im1.height))
dst.paste(im1, (0, 0))
dst.paste(im2, (im1.width, 0))
return dst | 60c67011c25ace5e0491bc365256364a9b677798 | 18,011 |
def get_taxname(taxid):
"""Return scientific name for NCBI Taxonomy ID."""
if get_taxname.id_name_map is None:
get_taxname.id_name_map = load_taxid_name_map('data/taxnames.tsv')
if get_taxname.id_name_map is None: # assume fail, fallback
get_taxname.id_name_map = TAXID_NAME_MAP
... | 8a42b542fef9a003e7f40542513d8d4a9d5d8e88 | 18,012 |
def lrfn(epoch):
"""
lrfn(epoch)
This function creates a custom piecewise linear-exponential learning rate function for a custom learning rate scheduler. It is linear to a max, then exponentially decays
* INPUTS: current `epoch` number
* OPTIONAL INPUTS: None
* GLOBAL INPUTS:`START_LR`, `MIN_LR... | f71e776e07ac9f4be5802127e8c9ca84e864de58 | 18,014 |
import numbers
def get_balances():
"""
Get the balances of the configured validator (if possible)
"""
balances = account.get_balance_on_all_shards(validator_config['validator-addr'], endpoint=node_config['endpoint'])
for bal in balances:
bal['balance'] = float(numbers.convert_atto_to_one(b... | ed79137e7eb8482f86246174b1bf107229c59b90 | 18,015 |
import collections
def _make_ordered_node_map(
pipeline: pipeline_pb2.Pipeline
) -> 'collections.OrderedDict[str, pipeline_pb2.PipelineNode]':
"""Prepares the Pipeline proto for DAG traversal.
Args:
pipeline: The input Pipeline proto, which must already be topologically
sorted.
Returns:
An O... | 04d766081bffe000509a70a43208b6998b764a49 | 18,016 |
def energy(_x, _params):
"""Kinetic and Potential Energy of point mass pendulum.
_x is an array/list in the following order:
q1: Angle of first pendulum link relative to vertical (0 downwards)
u1: A[1] measure number of the inertial angular velocity of the first link.
_params is an array... | 0796149bab5a5a36717a67477661633eaf3a29c2 | 18,017 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.