content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def pwr_y(x, a, b, e):
"""
Calculate the Power Law relation with a deviation term.
Parameters
----------
x : numeric
Input to Power Law relation.
a : numeric
Constant.
b : numeric
Exponent.
e : numeric
Deviation term.
Returns
-------
nume... | e736d9bb2e4305ef0dc0a360143a611b805f7612 | 3,648,400 |
def file_update_projects(file_id):
""" Page that allows users to interact with a single TMC file """
this_file = TMCFile.query.filter_by(uid=file_id).first()
project_form = AssignProjectsToFile()
if project_form.validate_on_submit():
data = dict((key, request.form.getlist(key) if len(... | 172d0caccb3e7ba39282cb6860fb80fca0a050bb | 3,648,401 |
def find_optimal_cut(edge, edge1, left, right):
"""Computes the index corresponding to the optimal cut such that applying
the function compute_blocks() to the sub-blocks defined by the cut reduces
the cost function comparing to the case when the function compute_blocks() is
applied to the whole matrix. ... | 63120c904a71b6dc40d75df6db19a5bdb619f9e2 | 3,648,402 |
def seq_to_networkx(header, seq, constr=None):
"""Convert sequence tuples to networkx graphs."""
graph = nx.Graph()
graph.graph['id'] = header.split()[0]
graph.graph['header'] = header
for id, character in enumerate(seq):
graph.add_node(id, label=character, position=id)
if id > 0:
... | 7c44b3aa0fb30637eda9bc7e960db1e3d65e7907 | 3,648,403 |
def add_vertex_edge_for_load_support(network, sup_dic, load_dic, bars_len, key_removed_dic):
"""
Post-Processing Function:
Adds vertices and edges in accordance with supports and loads
returns the cured network
"""
if not key_removed_dic:
load_sup_dic=merge_two_dicts(sup_dic, load_dic)
... | ce52cfac5e3bb58b31cfc1b2e243c435c5926d0f | 3,648,404 |
def mimicry(span):
"""Enrich the match."""
data = {'mimicry': span.lower_}
sexes = set()
for token in span:
if token.ent_type_ in {'female', 'male'}:
if token.lower_ in sexes:
return {}
sexes.add(token.lower_)
return data | 724d09156e97961049cb29d9f3c1f02ab5af48b0 | 3,648,405 |
def LeftBinarySearch(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums)
while low < high:
mid = (low + high) // 2
if nums[mid] < target:
low = mid + 1
else:
high = mid
assert l... | d08f72e1563ee91e9ca6c9cf95db4c794312aa59 | 3,648,406 |
def backup_file_content(jwd, filepath, content):
"""backs up a string in the .jak folder.
TODO Needs test
"""
backup_filepath = create_backup_filepath(jwd=jwd, filepath=filepath)
return create_or_overwrite_file(filepath=backup_filepath, content=content) | 8d661ca8fbf30a5d528cb79c01a6c74767084535 | 3,648,407 |
async def security_rule_get(
hub, ctx, security_rule, security_group, resource_group, **kwargs
):
"""
.. versionadded:: 1.0.0
Get a security rule within a specified network security group.
:param name: The name of the security rule to query.
:param security_group: The network security group c... | 34fb0cc8c2399f3749970b1061e2d5d209b11750 | 3,648,408 |
def create_centroid_pos(Direction, Spacing, Size, position):
# dim0, dim1,dim2, label):
"""
:param Direction,Spacing, Size: from sitk raw.GetDirection(),GetSpacing(),GetSize()
:param position:[24,3]
:return:
"""
direction = np.round(list(Direction))
direc0 = direction[0:7:3]
direc1... | 67f252a237f294bdf738bf0b5e9a89aad51201d7 | 3,648,409 |
from sklearn.model_selection import GroupKFold
def group_split_data_cv(df, cv=5, split=0):
"""
Args:
cv: number of cv folds
split: index of the cv fold to return
Note that GroupKFold is not random
"""
splitter = GroupKFold(n_splits=cv)
split_generator = splitter.split(df, group... | 4d2fb6c62bdd313aa9b16d52b637adbfd1adc654 | 3,648,410 |
def encode(valeur,base):
""" int*int -->String
hyp valeur >=0
hypothèse : base maxi = 16
"""
chaine=""
if valeur>255 or valeur<0 :
return ""
for n in range (1,9) :
calcul = valeur % base
if (calcul)>9:
if calcul==10:
bit='A'
if... | c5fe7d129ab19d1f77ac9d5160f5d714a796c0a0 | 3,648,411 |
def main(request):
"""
Main admin page.
Displayes a paginated list of files configured source directory (sorted by
most recently modified) to be previewed, published, or prepared for
preview/publish.
"""
# get sorted archive list for this user
try:
archives = request.user.archiv... | 9f10a3546dbbd209b8d91e812c4190c3498b1c03 | 3,648,412 |
def parse_char(char, invert=False):
"""Return symbols depending on the binary input
Keyword arguments:
char -- binary integer streamed into the function
invert -- boolean to invert returned symbols
"""
if invert == False:
if char == 0:
return '.'
elif char == 1... | 38c0d1c150a1c8e8f7d2f3d1bde08ec3e5ceb65b | 3,648,413 |
import subprocess
def run_blast(database, program, filestore, file_uuid, sequence, options):
"""
Perform a BLAST search on the given database using the given query
Args:
database: The database to search (full path).
program: The program to use (e.g. BLASTN, TBLASTN, BLASTX).
fil... | f3358f90b6a8e3bed2138b88f6a28634142fe3ac | 3,648,414 |
def get_transformer_dim(transformer_name='affine'):
""" Returns the size of parametrization for a given transformer """
lookup = {'affine': 6,
'affinediffeo': 6,
'homografy': 9,
'CPAB': load_basis()['d'],
'TPS': 32
}
assert (transformer_na... | 8e61b2e135c2f5933955082b4d951ff2f88283b7 | 3,648,415 |
def ListVfses(client_urns):
"""Lists all known paths for a list of clients.
Args:
client_urns: A list of `ClientURN` instances.
Returns:
A list of `RDFURN` instances corresponding to VFS paths of given clients.
"""
vfs = set()
cur = set()
for client_urn in client_urns:
cur.update([
... | 20bf77875d099106e5190d02c0c62d38eb1a6590 | 3,648,416 |
def delete_product(productId):
"""Deletes product"""
response = product2.delete_product(productId)
return response | 394848c8b9c8803140744b8a1a1eb6995cd04bf7 | 3,648,417 |
def compute_face_normals(points, trilist):
"""
Compute per-face normals of the vertices given a list of
faces.
Parameters
----------
points : (N, 3) float32/float64 ndarray
The list of points to compute normals for.
trilist : (M, 3) int16/int32/int64 ndarray
The list of face... | 4bbe9f7311f6125fd73b028c984e09ee4f124791 | 3,648,418 |
def get_deletion_confirmation(poll):
"""Get the confirmation keyboard for poll deletion."""
delete_payload = f"{CallbackType.delete.value}:{poll.id}:0"
delete_all_payload = f"{CallbackType.delete_poll_with_messages.value}:{poll.id}:0"
locale = poll.user.locale
buttons = [
[
Inlin... | 6d741aa13d3d5234c53115b8b74c353fdce9e87e | 3,648,419 |
def ngram_tokenizer(lines, ngram_len=DEFAULT_NGRAM_LEN, template=False):
"""
Return an iterable of ngram Tokens of ngram length `ngram_len` computed from
the `lines` iterable of UNICODE strings. Treat the `lines` strings as
templated if `template` is True.
"""
if not lines:
return
n... | fb7f079ddee8bac10b2ae9efd306a482042b8a0f | 3,648,420 |
def list_datasets(service, project_id):
"""Lists BigQuery datasets.
Args:
service: BigQuery service object that is authenticated. Example: service = build('bigquery','v2', http=http)
project_id: string, Name of Google project
Returns:
List containing dataset names
"""
data... | 2712e6a99427ce3b141e7948bba36e8e724f82bc | 3,648,421 |
def tors(universe, seg, i):
"""Calculation of nucleic backbone dihedral angles.
The dihedral angles are alpha, beta, gamma, delta, epsilon, zeta, chi.
The dihedral is computed based on position of atoms for resid `i`.
Parameters
----------
universe : Universe
:class:`~MDAnalysis.core... | 1efcac83c7ec6689e33830daf011bead5199e5dd | 3,648,422 |
def get_metric(metric,midi_notes,Fe,nfft,nz=1e4,eps=10,**kwargs):
"""
returns the optimal transport loss matrix from a list of midi notes (interger indexes)
"""
nbnotes=len(midi_notes)
res=np.zeros((nfft/2,nbnotes))
f=np.fft.fftfreq(nfft,1.0/Fe)[:nfft/2]
f_note=[2.0**((n-60)*1./12)*440 for n... | f21717f239431fac2e37e6b59abfdcb6b964aa0c | 3,648,423 |
def octave(track, note, dur):
"""Generate the couple of blanche"""
track.append(Message('note_on', note=note, velocity=100, time=0))
track.append(Message('note_on', note=note + 12, velocity=100, time=0))
track.append(Message('note_off', note=note, velocity=64, time=dur))
track.append(Message('note_o... | c94391677849b1aef58df1a08ade0bae3fe691f5 | 3,648,424 |
def solveTrajectoryPickle(dir_path, file_name, only_plot=False, solver='original', **kwargs):
""" Rerun the trajectory solver on the given trajectory pickle file. """
# Load the pickles trajectory
traj_p = loadPickle(dir_path, file_name)
# Run the PyLIG trajectory solver
if solver == 'original':
... | a5b5dca042906e86eb153c8889466bff983af243 | 3,648,425 |
def load_data(path):
"""
读取.mat的原始eeg数据
:param path:
:return:
"""
data=scio.loadmat(path)
labels = data['categoryLabels'].transpose(1, 0)
X = data['X_3D'].transpose(2, 1, 0)
return X,labels | 69d540529b93705b3fb3a34a607da469825185f5 | 3,648,426 |
def distance_along_glacier(nx, map_dx):
"""Calculates the distance along the glacier in km.
Parameters
----------
nx : int
number of grid points
map_dx : int
grid point spacing
Returns
-------
ndarray
distance along the glacier in km.
"""
return np.linsp... | 58acc7f48b0f901b1c3e800ea6e98046805f855a | 3,648,427 |
def make_postdict_to_fetch_token(token_endpoint: str, grant_type: str,
code: str, client_id: str,
client_secret: str,
redirect_uri: str) -> dict:
"""POST dictionary is the API of the requests library"""
return {'u... | f366fc140c70d094ff99b28a369ac96b4c2a8b49 | 3,648,428 |
def _haxe_std_lib(ctx):
"""
_haxe_std_lib implementation.
Args:
ctx: Bazel context.
"""
toolchain = ctx.toolchains["@rules_haxe//:toolchain_type"]
build_source_file = ctx.actions.declare_file("StdBuild.hx")
toolchain.create_std_build(
ctx,
ctx.attr.target,
... | 7a29757f7fa9fdcd1942b73221633a0eb7afc2f8 | 3,648,429 |
import os
def detect_vswhere_path():
"""
Attempt to detect the location of vswhere, which is used to query the installed visual studio tools (version 2017+)
:return: The validated path to vswhere
"""
# Find VS Where
path_program_files_x86 = os.environ['ProgramFiles(x86)']
if not path_progr... | f533e38bb1bddfaeaaf764cfb986aeb70b9e568d | 3,648,430 |
def spread_match_network(expr_df_in, node_names_in):
"""
Matches S (spreadsheet of gene expressions) and N (network)
The function returns expr_df_out which is formed by reshuffling columns of
expr_df_in. Also, node_names_out is formed by reshuffling node_names_in. The
intersection of node_names_out ... | c0b78263a341d3b7682922eb9a948c21ab2e7e45 | 3,648,431 |
import io
def top_level(url, data):
"""Read top level names from compressed file."""
sb = io.BytesIO(data)
txt = None
with Archive(url, sb) as archive:
file = None
for name in archive.names:
if name.lower().endswith('top_level.txt'):
file = name
... | 0fe92b1d038248f5f759d19b1e27ad013b3592c2 | 3,648,432 |
import requests
def get_timeseries_data(request):
"""
AJAX Controller for getting time series data.
"""
return_obj = {}
# -------------------- #
# VERIFIES REQUEST #
# -------------------- #
if not (request.is_ajax() and request.method == "POST"):
return_obj["error"] = "... | d8bb691f99d4a993d2b8e7c7e52f079566f45a63 | 3,648,433 |
from typing import List
from typing import Tuple
import bisect
def line_col(lbreaks: List[int], pos: int) -> Tuple[int, int]:
"""
Returns the position within a text as (line, column)-tuple based
on a list of all line breaks, including -1 and EOF.
"""
if not lbreaks and pos >= 0:
return 0, ... | 6b99e3b19ed1a490e4a9cc284f99e875085f819a | 3,648,434 |
from sys import stderr
def add_scrollbars_with_tags(outer, InnerType, *inner_args, **inner_kw):
""" Wrapper around `add_scrollbars`. Returns tuple of InnerType instance
and scroll tag. Scroll tag should be added to all `inner` child widgets that
affect scrolling.
"""
scrolltag = "tag_" + str(next(tags_co... | 64327326528e32cf1d40a8b3873be8ef034421aa | 3,648,435 |
def sample_from_script(script_path, num_lines, chars_per_line):
"""Sample num_lines from a script.
Parameters
----------
script_path : str
Path to the script
num_lines : int
Number of lines to sample.
chars_per_line : int
Numer of consecutive characters... | 52e04582ec297ac512b2d2586524c7c4cb46b1d0 | 3,648,436 |
def is_valid_uuid(x):
"""Determine whether this is a valid hex-encoded uuid."""
if not x or len(x) != 36:
return False
return (parse_uuid(x) != None) | 707618844ddb4375c855e12ca2f75966a91d7c5b | 3,648,437 |
def wait_for_needle_list(
loops: int,
needle_list: list[tuple[str, tuple[int, int, int, int]]],
sleep_range: tuple[int, int],
):
"""
Works like vision.wait_for_needle(), except multiple needles can be
searched for simultaneously.
Args:
loops: The number of tries to look for each nee... | 4f09801f54d2f29aea18eb868c7ef44ab0532627 | 3,648,438 |
import random
def get_word():
"""Returns random word."""
words = ['Charlie', 'Woodstock', 'Snoopy', 'Lucy', 'Linus',
'Schroeder', 'Patty', 'Sally', 'Marcie']
return random.choice(words).upper() | c4437edc3a1e91cd90c342eda40cfd779364d9c1 | 3,648,439 |
def is_admin(user):
"""Check if the user is administrator"""
admin_user = current_app.config['ADMIN_USER']
if user.email == admin_user or user.email.replace('@cern.ch', '') == admin_user:
current_app.logger.debug('User {user} is admin'.format(user=user.email))
return True
return False | a4a6f796f6b8a18076f8ceda9f7ac30d809973ce | 3,648,440 |
from datetime import datetime
def parsed_json_to_dict(parsed):
"""
Convert parsed dict into dict with python built-in type
param:
parsed parsed dict by json decoder
"""
new_bangumi = {}
new_bangumi['name'] = parsed['name']
new_bangumi['start_date'] = datetime.strptime(
pa... | e3bb8306e19a16c9e82d5f6e96c9b4a3707c0446 | 3,648,441 |
import pickle
import osmnx # noqa
def download_osmnx_graph(): # pragma: no cover
"""Load a simple street map from Open Street Map.
Generated from:
.. code:: python
>>> import osmnx as ox # doctest:+SKIP
>>> address = 'Holzgerlingen DE' # doctest:+SKIP
>>> graph = ox.graph_fr... | 51aa0fec3bdbe5197edb3fb3dd0f405be6f0f7df | 3,648,442 |
import pandas
def plot_shift_type_by_frequency(tidy_schedule: pandas.DataFrame) -> tuple:
"""
Plots a bar graph of shift type frequencies.
:param tidy_schedule: A pandas data frame containing a schedule,
as loaded by load_tidy_schedule().
:type tidy_schedule: pandas.DataFrame
:return: A tuple... | 81fb649cd8439932bbbbf27d9690c5ab9f96e410 | 3,648,443 |
def load_image(path, size=None):
"""
Load the image from the given file-path and resize it to the given size if not None.
Eg: size = (width, height)
"""
img = Image.open(path)
if (size != None) and (size != ''):
img = img.resize(size=size, resample=Image.LANCZOS)
img = np.array(img... | e770ea3447ce8a7d236c4712859707b8e3cd8248 | 3,648,444 |
import secrets
import ipaddress
def call_wifi(label):
"""Wifi connect function
Parameters
----------
label : str
Output label
Returns
-------
None
"""
try:
# Setup wifi and connection
print(wifi.radio.connect(secrets['ssid'], secrets['password']))
... | a1514ff756b5217b8f79b4f9af882a234b1ad17d | 3,648,445 |
def load_normalized_face_landmarks():
"""
Loads the locations of each of the 68 landmarks
:return:
"""
normalized_face_landmarks = np.float32([
(0.0792396913815, 0.339223741112), (0.0829219487236, 0.456955367943),
(0.0967927109165, 0.575648016728), (0.122141515615, 0.691921601066),
... | 2dbd191371345c4382efa3573b54e281607da37c | 3,648,446 |
import os
def vacuum_vessel(shot):
"""
Get the coordinates of the Tore Supra / WEST vacuum vessel
R_wall, Z_wall = vacuum_vessel(shot)
Arguments:
- shot: Tore Supra or WEST shot number
Returns:
- R_wall: radius of the vacuum chamber walls [m]
- Z_wall: height of the vacu... | da22ed6ae6d61238f3bda0e1e2f4fd7ede7f7f68 | 3,648,447 |
from datetime import datetime
from shutil import copyfile
def backup_file(file):
"""Create timestamp'd backup of a file
Args:
file (str): filepath
Returns:
backupfile(str)
"""
current_time = datetime.now()
time_stamp = current_time.strftime("%b-%d-%y-%H.%M.%S")
backupf... | 1c1b33028aab01b4e41ed3ef944202ecc53415df | 3,648,448 |
def svn_client_mergeinfo_log_eligible(*args):
"""
svn_client_mergeinfo_log_eligible(char path_or_url, svn_opt_revision_t peg_revision,
char merge_source_path_or_url, svn_opt_revision_t src_peg_revision,
svn_log_entry_receiver_t receiver,
svn_boolean_t discover_changed_paths,
ap... | 9f372556d56e0fdc88afc5b3fd35218fb46f3768 | 3,648,449 |
def share_nodes_sockets():
"""
Create a shared node layout where the simulation and analysis ranks share
compute nodes. Furthermore, they share sockets of the node.
"""
shared_sockets = SummitNode()
for i in range(10):
shared_sockets.cpu[i] = "simulation:{}".format(i)
shared_soc... | d34bfb1b97e4e3b06dee54a89c084dd404c3c6ca | 3,648,450 |
from glob import glob
import os
def imlist(img_dir, valid_exts=None, if_recursive=False):
"""
List images under directory
:param img_dir:
:param valid_exts:
:param if_recursive:
:return:
"""
if is_str(valid_exts):
valid_exts = [valid_exts.strip(".")]
valid_exts = list(valid... | fe13d2fe91a90c50a767d8ad3013f50ae0559d9c | 3,648,451 |
def _rle_decode(data):
"""
Decodes run-length-encoded `data`.
"""
if not data:
return data
new = b''
last = b''
for cur in data:
if last == b'\0':
new += last * cur
last = b''
else:
new += last
last = bytes([cur])
... | 8463ff6a20b3a39df7b67013d47fe81ed6d53477 | 3,648,452 |
def find_shift_between_two_models(model_1,model_2,shift_range=5,number_of_evaluations=10,rotation_angles=[0.,0.,0.],
cropping_model=0,initial_guess=[0.,0.,0.], method='brute_force',full_output=False):
"""
Find the correct shift alignment in 3D by using a different optimization... | 39dea881a5a00174b178d22910b5cee6d7ce48cd | 3,648,453 |
from typing import Optional
import requests
def get_url(
url: str,
stream: bool = False,
session: Optional[requests.Session] = None
) -> requests.Response:
"""Call requests.get() on a url and return the requests.Response."""
if not session:
session = retry_session()
resp = session.get(... | c056446cbb1966f79b472de2f140b9962246fd75 | 3,648,454 |
from typing import Optional
def uploadFromPath(localFilePath: str,
resource,
bucketName: str,
fileID: str,
headerArgs: Optional[dict] = None,
partSize: int = 50 << 20):
"""
Uploads a file to s3, using multipart uplo... | ee8ca7e177ab8538fd668a42111f86503b57edc1 | 3,648,455 |
def scale_log2lin(value):
"""
Scale value from log10 to linear scale: 10**(value/10)
Parameters
----------
value : float or array-like
Value or array to be scaled
Returns
-------
float or array-like
Scaled value
"""
return 10**(value/10) | 04f15a8b5a86a6e94dd6a0f657d7311d38da5dc0 | 3,648,456 |
from typing import Union
import torch
from typing import Optional
from typing import List
def train(
train_length:Union[int, TrainLength], model:nn.Module, dls:DataLoaders, loss_func:LossFunction,
opt:torch.optim.Optimizer, sched=None, metric:Optional[Metric]=None,
device=None, clip_grad:ClipGradOptions... | ad6e4796df66a38df2140060a2150f77b8d7c525 | 3,648,457 |
def _error_to_level(error):
"""Convert a boolean error field to 'Error' or 'Info' """
if error:
return 'Error'
else:
return 'Info' | b43e029a4bb14b10de4056758acecebc85546a95 | 3,648,458 |
def add_review(status):
"""
Adds the flags on the tracker document.
Input: tracker document.
Output: sum of the switches.
"""
cluster = status['cluster_switch']
classify = status['classify_switch']
replace = status['replace_switch']
final = status['final_switch']
finished = statu... | 8f2ba4cd8b6bd4e500e868f13733146579edd7ce | 3,648,459 |
def n_floordiv(a, b):
"""safe floordiv"""
return np.where(b != 0, o.floordiv(a, b), 1) | 461752cfceaac911ef3be2335c2eb3893d512cc7 | 3,648,460 |
def load_encoder_inputs(encoder_np_vecs='train_body_vecs.npy'):
"""
Load variables & data that are inputs to encoder.
Parameters
----------
encoder_np_vecs : str
filename of serialized numpy.array of encoder input (issue title)
Returns
-------
encoder_input_data : numpy.array
The issue body
... | 571cf13f6ff23fea5bb111ed12ac8afc06cc5f8b | 3,648,461 |
def parse_row(row):
"""Create an Event object from a data row
Args:
row: Tuple of input data.
Returns:
Event object.
"""
# Ignore either 1 or 2 columns that preceed year
if len(row) > 6:
row = row[2:]
else:
row = row[1:]
# Remove occasional 'r' or 'x' character prefix from year,
# I... | 22923ee8f8e0b3b29eab3052df0e0b8b74613f66 | 3,648,462 |
import math
import operator
from typing import Counter
def vertical_log_binning(p, data):
"""Create vertical log_binning. Used for peak sale."""
index, value = zip(*sorted(data.items(), key=operator.itemgetter(1)))
bin_result = []
value = list(value)
bin_edge = [min(value)]
i = 1
while len... | bf536250bc32a9bda54c8359589b10aa5936e902 | 3,648,463 |
def get_main_name(ext="", prefix=""):
"""Returns the base name of the main script. Can optionally add an
extension or prefix."""
return prefix + op.splitext(op.basename(__main__.__file__))[0] + ext | 03beb4da53436054bf61a4f68d8b0f3d51ac13be | 3,648,464 |
def _grad_block_to_band(op, grad):
"""
Gradient associated to the ``block_to_band`` operator.
"""
grad_block = banded_ops.band_to_block(
grad, op.get_attr("block_size"), symmetric=op.get_attr("symmetric"), gradient=True
)
return grad_block | 638c4047b224b80feb7c4f52151f96c4a62179b9 | 3,648,465 |
def LSTM(nO, nI):
"""Create an LSTM layer. Args: number out, number in"""
weights = LSTM_weights(nO, nI)
gates = LSTM_gates(weights.ops)
return Recurrent(RNN_step(weights, gates)) | 296b1a7cb73a0e5dcb50e4aa29b33c944768c688 | 3,648,466 |
import requests
def get_token(host, port, headers, auth_data):
"""Return token for a user.
"""
url = api_url(host, port, '/Users/AuthenticateByName')
r = requests.post(url, headers=headers, data=auth_data)
return r.json().get('AccessToken') | 4d58d50c1421c17e89fa2d8d2205f0e066749e73 | 3,648,467 |
from datetime import datetime
def generateDateTime(s):
"""生成时间"""
dt = datetime.fromtimestamp(float(s)/1e3)
time = dt.strftime("%H:%M:%S.%f")
date = dt.strftime("%Y%m%d")
return date, time | 8d566412230b5bb779baa395670ba06457c2074f | 3,648,468 |
def get_activation_function():
"""
Returns tf.nn activation function
"""
return ACTIVATION_FUNCTION | 9f55f5122f708120ce7a5181b7035681f37cc0c6 | 3,648,469 |
import requests
import json
def doi_and_title_from_citation(citation):
"""
Gets the DOI from
a plaintext citation.
Uses a search to CrossRef.org to retrive paper DOI.
Parameters
----------
citation : str
Full journal article citation.
Example: Senís, Elena, et al. "CRISPR... | bd51d91c414c97a9e061d889a27917c1b487edd1 | 3,648,470 |
def prep_ciphertext(ciphertext):
"""Remove whitespace."""
message = "".join(ciphertext.split())
print("\nciphertext = {}".format(ciphertext))
return message | a5cd130ed3296addf6a21460cc384d8a0582f862 | 3,648,471 |
import re
import os
def setup_sample_file(base_filename, args, num_threads=1):
"""
Return a sample data file, the ancestors file, a corresponding recombination rate
(a single number or a RateMap), a prefix to use for files, and None
"""
gmap = args.genetic_map
sd = tsinfer.load(base_filename +... | a9f7229eeaac3830d3e6fdc92214d11e5f0e3cab | 3,648,472 |
def main():
"""Runs dir()."""
call = PROCESS_POOL.submit(call_dir)
while True:
if call.done():
result = call.result().decode()
print("Results: \n\n{}".format(result))
return result | 6e02aab50023ed9b72c2f858122a2652a2f4607f | 3,648,473 |
def bacthing_predict_SVGPVAE_rotated_mnist(test_data_batch, vae, svgp,
qnet_mu, qnet_var, aux_data_train):
"""
Get predictions for test data. See chapter 3.3 in Casale's paper.
This version supports batching in prediction pipeline (contrary to function predict_SVGP... | 6603db14abbd7bbb2ba8965ee43d876d4a607b0a | 3,648,474 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""
Set up Strava Home Assistant config entry initiated through the HASS-UI.
"""
hass.data.setdefault(DOMAIN, {})
# OAuth Stuff
try:
implementation = await config_entry_oauth2_flow.async_get_config_entry_implementati... | 9ba10cf00f447d0e2038b8a542a45166c264b801 | 3,648,475 |
from typing import List
from typing import Tuple
from typing import Union
def normalize_boxes(boxes: List[Tuple], img_shape: Union[Tuple, List]) -> List[Tuple]:
"""
Transform bounding boxes back to yolo format
"""
img_height = img_shape[1]
img_width = img_shape[2]
boxes_ = []
for i in ran... | 086e0b069d06a4718e8ffd37189cf3d08c41d19f | 3,648,476 |
import copy
def _make_reference_filters(filters, ref_dimension, offset_func):
"""
Copies and replaces the reference dimension's definition in all of the filters applied to a dataset query.
This is used to shift the dimension filters to fit the reference window.
:param filters:
:param ref_dimensi... | eeeeb74bb3618c87f3540de5b44970e197885dc6 | 3,648,477 |
import os
def detect():
"""
Detects the shell the user is currently using. The logic is picked from
Docker Machine
https://github.com/docker/machine/blob/master/libmachine/shell/shell.go#L13
"""
shell = os.getenv("SHELL")
if not shell:
return None
if os.getenv("__fish_bin_dir")... | 4c6db387f21b1e4abef17efebbdc45b45c5b7fe7 | 3,648,478 |
def load_plane_dataset(name, num_points, flip_axes=False):
"""Loads and returns a plane dataset.
Args:
name: string, the name of the dataset.
num_points: int, the number of points the dataset should have,
flip_axes: bool, flip x and y axes if True.
Returns:
A Dataset object... | aee32a6aa7f2be6ae515d6f3b1e27cda4d0f705e | 3,648,479 |
def get_toxic(annotated_utterance, probs=True, default_probs=None, default_labels=None):
"""Function to get toxic classifier annotations from annotated utterance.
Args:
annotated_utterance: dictionary with annotated utterance, or annotations
probs: return probabilities or not
default: d... | ac69075af2edd9cdc84383054ba9ebe700dddb58 | 3,648,480 |
def compute_energy_lapkmode(X,C,l,W,sigma,bound_lambda):
"""
compute Laplacian K-modes energy in discrete form
"""
e_dist = ecdist(X,C,squared =True)
g_dist = np.exp(-e_dist/(2*sigma**2))
pairwise = 0
Index_list = np.arange(X.shape[0])
for k in range(C.shape[0]):
tmp=np.asa... | 3fc5c2f9695e33eb3d1ac42a3172c30f1d81d23b | 3,648,481 |
def calc_2d_wave_map(wave_grid, x_dms, y_dms, tilt, oversample=2, padding=10, maxiter=5, dtol=1e-2):
"""Compute the 2D wavelength map on the detector.
:param wave_grid: The wavelength corresponding to the x_dms, y_dms, and tilt values.
:param x_dms: the trace x position on the detector in DMS coordinates.
... | 727002a0cc61f6219c92d6db3d31eb653f849f03 | 3,648,482 |
def is_pipeline_variable(var: object) -> bool:
"""Check if the variable is a pipeline variable
Args:
var (object): The variable to be verified.
Returns:
bool: True if it is, False otherwise.
"""
# Currently Expression is on top of all kinds of pipeline variables
# as well as P... | dd33657dce848dac819f89a4820c33df1ab4479e | 3,648,483 |
def export_data():
"""Exports data to a file"""
data = {}
data['adgroup_name'] = request.args.get('name')
if data['adgroup_name']:
data['sitelist'] = c['adgroups'].find_one({'name':data['adgroup_name']}, {'sites':1})['sites']
return render_template("export.html", data=data) | a6b43f90907e174f07773b0ed7603a48a3ff35ca | 3,648,484 |
def thresh_bin(img, thresh_limit=60):
""" Threshold using blue channel """
b, g, r = cv2.split(img)
# mask = get_salient(r)
mask = cv2.threshold(b, 50, 255, cv2.THRESH_BINARY_INV)[1]
return mask | 3660179d1e1c411feb44e993a8ab94f10c63d6e4 | 3,648,485 |
from typing import Any
def get_aux():
"""Get the entire auxiliary stack. Not commonly used."""
@parser
def g(c: Cursor, a: Any):
return a, c, a
return g | b345901f4987e8849fbe35c0c997f38480d79f04 | 3,648,486 |
def _destupidize_dict(mylist):
"""The opposite of _stupidize_dict()"""
output = {}
for item in mylist:
output[item['key']] = item['value']
return output | f688e25a9d308e39f47390fef493ab80d303ea15 | 3,648,487 |
def equipment_add(request, type_, id_=None):
"""Adds an equipment."""
template = {}
if request.method == 'POST':
form = EquipmentForm(request.POST)
if form.is_valid():
form.save(request.user, id_)
return redirect('settings_equipment')
template['form'] = fo... | a8f2fce6c9aa64316edb96df9597fbfb516839a3 | 3,648,488 |
def _parse_text(val, **options):
"""
:return: Parsed value or value itself depends on 'ac_parse_value'
"""
if val and options.get('ac_parse_value', False):
return parse_single(val)
return val | cbd0d0b65237e8d3f817aa0bae1861f379a68b26 | 3,648,489 |
import os
def output_path(model, model_set):
"""Return path to model output directory
Parameters
----------
model : str
model_set : str
"""
path = model_path(model, model_set=model_set)
return os.path.join(path, 'output') | 2cd89f89417e4164fdd66ca0c544b6c623f21ddb | 3,648,490 |
def get_rotation_matrix(rotation_angles):
"""Get the rotation matrix from euler's angles
Parameters
-----
rotation_angles: array-like or list
Three euler angles in the order [sai, theta, phi] where
sai = rotation along the x-axis
theta = rotation along the y-axis
phi = r... | 2965d1ce5c688e794f7fce6e51afd2e558c1bab7 | 3,648,491 |
def _metric_list_for_check(maas_store, entity, check):
"""
Computes the metrics list for a given check.
Remote checks return a metric for each monitoring zone and
each type of metric for the check type. Agent checks return
a metric for each metric type on the check type. Check types
that Mimic ... | c295f976c8c85d60af8f6e734f666381bc0186d2 | 3,648,492 |
import matplotlib.pyplot as plt
import numpy as np
def plot_MA_values(t,X,**kwargs):
"""
Take the numpy.ndarray time array (t) of size (N,) and the state space numpy.ndarray (X) of size (2,N), (4,N), or (8,N), and plots the moment are values of the two muscles versus time and along the moment arm function.
~~~~~~... | 91e37001b689a66f53e6035b27520527ea9aa922 | 3,648,493 |
def filter_pdf_files(filepaths):
""" Returns a filtered list with strings that end with '.pdf'
Keyword arguments:
filepaths -- List of filepath strings
"""
return [x for x in filepaths if x.endswith('.pdf')] | 3f44b3af9859069de866cec3fac33a9e9de5439d | 3,648,494 |
import os
def index_file(path: str) -> dict:
"""
Indexes the files and directory under a certain directory
Arguments:
path {str} - the path of the DIRECTORY to index
Return:
{dict} - structures of the indexed directory
"""
structure = {} # Represents the directory structure
... | 9385b8577d296a43e8e2d5b3ea3517ba1e498f65 | 3,648,495 |
def hue_quadrature(h: FloatingOrArrayLike) -> FloatingOrNDArray:
"""
Return the hue quadrature from given hue :math:`h` angle in degrees.
Parameters
----------
h
Hue :math:`h` angle in degrees.
Returns
-------
:class:`numpy.floating` or :class:`numpy.ndarray`
Hue quadra... | df120ae34dfc45ecbb818718885cbbb501667bdd | 3,648,496 |
def aa_find_devices_ext (devices, unique_ids):
"""usage: (int return, u16[] devices, u32[] unique_ids) = aa_find_devices_ext(u16[] devices, u32[] unique_ids)
All arrays can be passed into the API as an ArrayType object or as
a tuple (array, length), where array is an ArrayType object and
length is an i... | 1b84cfc3d6fd52f786c2191fde4d37a6287e8b87 | 3,648,497 |
def decode_varint_in_reverse(byte_array, offset, max_varint_length=9):
"""
This function will move backwards through a byte array trying to decode a varint in reverse. A InvalidVarIntError
will be raised if a varint is not found by this algorithm used in this function. The calling logic should check
... | 528d6c40a6e53c747ffca2c88388aa58cb98ea71 | 3,648,498 |
import imp
import os
def manager_version(request):
"""
Context processor to add the rhgamestation-manager version
"""
# Tricky way to know the manager version because its version lives out of project path
root = imp.load_source('__init__', os.path.join(settings.BASE_DIR, '__init__.py'))
return... | 364887d6f8a521f12b03f4ed0dae2ebba1bf2b15 | 3,648,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.