content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def is_allowed_file(filename):
"""Check if a file extension is allowed.
Args:
filename (str): Name of the file to check.
Returns:
True if the file upload is allowed.
"""
return '.' in filename and \
filename.rsplit('.', 1)[1] in current_app.config['ALLOWED_EXTENSIONS'] | db9368d48655bba85ea91e847cc5e1fd7a60c06e | 37,700 |
def _build_distance_estimator(X, y, w2v, PoS, NER, regressor, verbose=1):
"""Build a vector reprensation of a pair of signatures."""
if w2v == 'glove':
PairVecTransformer = PairGloveTransformer
elif w2v == 'spacy':
PairVecTransformer = PairSpacyVecTransformer
elif w2v == 'polyglot':
... | 475309904ced42479b197974b2e48dca6c200160 | 37,701 |
from project.main.views import main_blueprint
from project.matrix.views import matrix_blueprint
from project.evaluate.views import evaluate_blueprint
import os
def create_app(**kwargs):
"""
Create a new WSGI application, register blueprints and initialize extensions.
:key name : The name of the Fl... | 70de3ae21ea11edc62ada7d069999d0b4d7b02f7 | 37,702 |
from typing import Optional
from typing import Union
from typing import List
import logging
import csv
def n15hsqc(bmrb_ids: Optional[Union[str, List[str], int, List[int]]] = None,
input_file_names: Optional[Union[str, List[str]]] = None,
entry_objects: Optional[Union[pynmrstar.Entry, List[pyn... | 1d66d698cade1c77195dcdd599cdcdbe00d2148b | 37,703 |
def binary_prediction_results(y_true, y_pred):
""" Returns a dictionary with counts of TP, TN, FP, and FN
Args:
y_true, y_pred (numpy-compatible, 1D array-like): binary valued
objects holding the ground truth and predictions (respectively),
on which validation has already been run.
... | 583b161155dd0465918f9be6caadfc28cec4385b | 37,704 |
from typing import Optional
from typing import Sequence
def SplitFMNIST(n_experiences: int,
first_batch_with_half_classes: bool = False,
return_task_id=False,
seed: Optional[int] = None,
fixed_class_order: Optional[Sequence[int]] = None,
... | ad0bc32448d80435fa31ab356689a18f48adb4da | 37,705 |
from typing import Union
from typing import Dict
from typing import List
def group_by(value, key: Union[str, int] = "", count=False, *, context) -> Dict[any, Union[List[any], int]]:
"""
Group the incoming values
:param value: Incoming list
:param key: The key to use in grouping the items. If no key, t... | b28ae115aec54e03202287dcc8f3119b562a7830 | 37,706 |
import html
def create_index_page():
""" Dynamically create links for all app pages """
links = []
for page in pages:
links.append(dcc.Link("Go to Page " + page, href="/pages/" + page))
links.append(html.Br())
return links | 4a949ac7a0803d8c22ea1dc72a110617d50bc213 | 37,707 |
import six
import asyncio
def maybe_coroutine(obj):
"""
If 'obj' is a coroutine and we're using Python3, wrap it in
ensureDeferred. Otherwise return the original object.
(This is to insert in all callback chains from user code, in case
that user code is Python3 and used 'async def')
"""
i... | d02703f283b32349c756f8d5539f3cf395ccea5c | 37,708 |
def inchi(xgr):
""" InChI string of this connectivity graph
"""
ich, _ = _inchi_with_atom_inchi_numbers(xgr)
return ich | 385c2d89d8b3fc450f1fb7d34dca18c09c3db5c8 | 37,709 |
def _compute_dloss_by_dmin_using_dmax(dloss_by_dmax):
"""
compute derivative of loss w.r.t min, it is sign flipped version of derivative w.r.t max
:param dq_by_dmax derivative w.r.t max
:return: derivative w.r.t min
"""
return tf.negative(dloss_by_dmax) | 986dd73f9d50b1a1a2ddc5569f45a7b8b153b7a8 | 37,710 |
import requests
def get_gitlab_groups(default_val=False):
"""
Get a list of groups for display in a drop-down menu box.
:return: List of groups name tuples.
"""
groups = {}
try:
groups = requests.get(
gitlab_import_config.gitlab_url + 'groups?search=' + gitlab_import_conf... | b73caa42659ce11290ddd89b36be4424d2989b13 | 37,711 |
def unsalt():
"""
Remove salt/solvates.
Examples and documentation: [https://wwwdev.ebi.ac.uk/chembl/extra/francis/standardiser/04\_unsalt.html](https://wwwdev.ebi.ac.uk/chembl/extra/francis/standardiser/04_unsalt.html)
CTAB is either single molfile or SDF file.
cURL examples:
curl -X POST --data-binary @unsal... | d9664d3c7c044f4e83ef282e9bcd5d6b616e2a05 | 37,712 |
def Select3D_SensitiveTriangle_Status(*args):
"""
:param X:
:type X: float
:param Y:
:type Y: float
:param aTol:
:type aTol: float
:param Dmin:
:type Dmin: float &
:rtype: int
* Dmin gives the distance between the cdg and aPoint return
:param p0:
:type p0: gp_XY
:... | e547e8a589cd218c1c182089f362fc39d94356cd | 37,713 |
def confirm_action(config, msg=None, allow_auto=True):
# type: (dict, str, bool) -> bool
"""Confirm action with user before proceeding
:param dict config: configuration dict
:param msg str: confirmation message
:param bool allow_auto: allow auto confirmation
:rtype: bool
:return: if user con... | 16911ed6095e25e7e7d738ba5112e207717c5332 | 37,714 |
import numpy
def read_nam_maps(netcdf_file_name, PREDICTOR_NAMES):
"""Reads fog-centered maps from NetCDF file.
E = number of examples (fog objects) in file
M = number of rows in each fog-centered grid
N = number of columns in each fog-centered grid
C = number of channels (predictor variables)
... | b3c253014dbec3ee3dc9866d977915d7a563a54a | 37,715 |
import subprocess
import os
def get_base_dir():
# type: () -> str
"""
Get the base directory for mongo repo.
This script assumes that it is running in buildscripts/, and uses
that to find the base directory.
"""
try:
return subprocess.check_output(['git', 'rev-parse', '--show-topl... | 08cea1d513668958fa6a64c9525cf2cba0defae9 | 37,716 |
import socket
def pick_free_port():
""" Pick free port using socket """
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 0))
addr, port = s.getsockname()
s.close()
return port | 9199b167ae8400e4796cb42c6c89fed47f2b3214 | 37,717 |
def borders(district, unit):
"""Check if a unit borders a district."""
if district == []:
return True
neighbour_coords = [(unit.x+i, unit.y+j) for i in [1, 0, -1]
for j in [1, 0, -1] if bool(i) ^ bool(j)]
district_coords = [(d_unit.x, d_unit.y) for d_unit in district]
... | d95bf55b54f0df63980236def80610dcdc6cbfeb | 37,718 |
def get_step_g(step_f, norm_L2, N=1, M=1):
"""Get step_g compatible with step_f (and L) for ADMM, SDMM, GLMM.
"""
# Nominally: minimum step size is step_f * norm_L2
# see Parikh 2013, sect. 4.4.2
#
# BUT: For multiple constraints, need to multiply by M.
# AND: For multiple variables, need to... | 4adec493ff82450ff0546088af86bac2372b862f | 37,719 |
def isDefinition():
"""Matches if the cursor is a definition
>>> from glud import *
>>> config = '''
... class X {};
... class Y;
... '''
>>> m = cxxRecordDecl(isDefinition())
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)
X
"""
return PredM... | cd3dfe601ccdd6caae7c66e5d26a7e437eab475b | 37,720 |
def read_string(buff, byteorder="big"):
"""Read a string from a file-like object."""
length = read_numeric(USHORT, buff, byteorder)
return buff.read(length).decode("utf-8") | 46f1deb426b38a54b5b47ae49bcaadb694d07b95 | 37,721 |
import sys
def parse_config():
"""
Checks the config file for the correct format and directs params to main
"""
checklist = ["n", "r", "graph_seeds", "output_dir", "num_threads",
"algo_seed", "timeout", "verbose", "docker_verbose",
"algorithms", "csv_filename"]
e... | 20d332c77759ab4db8a0673813b5b4bb20585cab | 37,722 |
def SGD_ninits(setup):
"""Perform stochastic gradiend descent for a number of initial models.
Arguments:
setup -- SGDsetup object which contains SGD parameters.
"""
print_SGDsetup(setup)
dRMSEs = []
models_costmin = []
zs_hist = []
mRMSEs = []
for j in range(setup.ninits):
... | cb9c199eff1186958748225d996c22b253106684 | 37,723 |
def _cv_checkerboard(image_size, square_size):
"""Generates a checkerboard level set function.
According to Pascal Getreuer, such a level set function has fast convergence.
"""
yv = np.arange(image_size[0]).reshape(image_size[0], 1)
xv = np.arange(image_size[1])
return (np.sin(np.pi/square_size... | 9a8fa8c72605591dac7e65c7bdaf587e48c2d3e8 | 37,724 |
from typing import Tuple
def calc_sigma_units(time_vector: np.ndarray, range_los: np.ndarray) -> Tuple[float, float]:
"""Calculates Gaussian peak std parameters.
The amount of smoothing is hard coded. This function calculates
how many steps in time and height corresponds to this smoothing.
Args:
... | cee943aa800bfbd7b5ef6389561db8d2c201047f | 37,725 |
def format_request(routes, route, method, base_url="{{base_Url}}"):
"""Populates atomic_request dictionary with route metatdata.
Returns a postman formatted dictionary request item."""
request = atomic_request()
doc = get_route_doc_string(routes, route, method)
name = get_route_name(route)
url ... | 96c1b7b6430b260ae897ee0668db6ae21b0508ff | 37,726 |
def reachable(fanin, n):
"""
Figure out what circuits are reachable from gates with limited fanin.
"""
seen = set()
answer = []
atoms = Toffoli.generate(fanin, n)
pending = list(atoms)
while pending:
circuit = pending.pop()
sig = signature(circuit, n)
if sig in se... | ef7512574eae0fc3db37a6f5c04d323c04391857 | 37,727 |
def calc_fixPos(etdata, fix, w=50):
"""
TODO: dublicate function. Update to use calc_event_data
"""
data=etdata.data
ws=round_up_to_odd(w/1000.0*etdata.fs)
fix_pos=[]
for f in fix:
ind_s=f[0]+ws
ind_s = ind_s if ind_s < f[1] else f[1]
ind_e=f[1]-ws
ind_e = ind... | 386eaa0af61b4a98958acd18a9f2a704314b1d8f | 37,728 |
from typing import Dict
from typing import List
from typing import Any
import re
def process_action(action_info: Dict, sentences_info: List[Dict[str, Any]],
words: List[str], sentence_number: int) -> Action:
"""
Create action and his object
Parameters
----------
action_info
... | 4390ba373e356a8f766b4c417c1295ac0d673f58 | 37,729 |
def unique_slugify(data, models, duplicate_key=''):
"""Returns a unique slug string. If duplicate_key is provided, this is
appended for non-unique slugs before adding a count."""
slug_base = slugify(data)
counter = 0
slug = slug_base
while any(model.objects.filter(slug=slug).exists() for mod... | 0fea02eb2efd1a0b06fc7a06d8fd78d270076445 | 37,730 |
import torch
def affine_del_homogeneous(affine):
"""Ensure that the last row of the matrix is _not_ (*zeros, 1).
This function is more generic than `make_rect` because it
works with images where the dimension of the output space differs
from the dimension of the input space.
Parameters
-----... | 65e0b0d8b99828445452c1129806aa25be5b92d3 | 37,731 |
def Kurt(poly, dist=None, fisher=True, **kws):
"""
Kurtosis operator.
Element by element 4rd order statistics of a distribution or polynomial.
Args:
poly (numpoly.ndpoly, Distribution):
Input to take kurtosis on.
dist (Distribution):
Defines the space the skewne... | 74ba9fdd76b4e7a4d02ba83459a2446dcecf8643 | 37,732 |
import copy
def relabel_graph_nodes(graph, label_dict=None, with_data=True):
"""
Relabel graph nodes.The graph
is relabelled (and returned) according to the label
dictionary and an inverted dictionary is returned.
Only integers are allowed as labels. If some other
objects will be passed inn th... | 65aa8707691e3c6b9b13a6ae18efa9be30989832 | 37,733 |
def add_form_shared(request, client_api, form_acess="", external=False):
"""
Method to render form request vip
"""
try:
lists = dict()
lists["action"] = reverse('vip-request.form')
lists['ports'] = ''
lists['ports_error'] = ''
lists['reals_error'] = ''
l... | 18e1e64c822be571f0441b4e577d060846ee10d9 | 37,734 |
import time
from datetime import datetime
def adv_results(request):
"""
Process the form from an advanced search.
We expect to always get here from the advanced search page and
always on a get, either from the submit button on the form or the
paging navigation buttons.
* On first search sub... | 0a2fd13061500b72345bf4270d1630483dfa706b | 37,735 |
def code_duplication_figure(metrics):
"""Create the code duplication donut."""
duplicated_loc = metrics["duplicated_loc"]
total_loc = metrics["total_loc"]
labels = ["Duplicated code", "Non duplicated code"]
values = [duplicated_loc, (total_loc - duplicated_loc)]
percentage = (duplicated_loc /... | fc37e896e45aa120e9b5f5f2302d3fd8d41e3be9 | 37,736 |
def adduser(username, uid=None, system=False, no_login=True, no_password=False, gecos=None,
arg_mapping=CmdArgMappings.DEBIAN, **kwargs):
"""
Formats an ``adduser`` command.
:param username: User name.
:type username: unicode | str
:param uid: Optional user id to use.
:type uid: lon... | d1ddd2e07bfb94e9081f1fa445a504f4ac28f722 | 37,737 |
def lin(p,x):
""" Linear function for fitting """
return p[0]+np.dot(p[1],x) | 9b711c9a3aed6dd4786283cb291bd3697f100219 | 37,738 |
import argparse
def _setup_argparser():
"""Setup the command line arguments"""
# Description
parser = argparse.ArgumentParser(
description=(
"The storescu application implements a Service Class User "
"(SCU) for the Storage Service Class. For each DICOM "
"file ... | 9166da220220800fa8dd320f6541b6b032e979e1 | 37,739 |
def _chartToDF(c):
"""internal"""
df = pd.DataFrame(c)
_toDatetime(df)
_reindex(df, "date")
return df | ebe443ac083a64f498a14d90963d2a739e06801b | 37,740 |
def file_diff_format(filename1, filename2):
"""
Inputs:
filename1 - name of first file
filename2 - name of second file
Output:
Returns a four line string showing the location of the first
difference between the two files named by the inputs.
If the files are identical, the fun... | d2e190754982ba429af369f5b404108a5e507214 | 37,741 |
import sys
def isQuerynameSorted(fname, file_type):
"""Check if a given file file is sorted based on the queryname.
Args:
fname: a input file name
Returns:
True if fname is a bam file sorted by read name, otherwise False
"""
if file_type == "bam":
return(isBamQuer... | 5ffd3b2a0e0861772a0cb5585552886084ddd83e | 37,742 |
def qlength(rcd):
"""
Returns "quality length"
"""
qscore = rcd.letter_annotations["phred_quality"]
nq = np.array(qscore)
q_mean = []
for i in range(1,len(nq)):
q_mean.append(abs(nq[:i].mean() - nq[i:].mean()))
q_mean[0] = q_mean[1]
return q_mean.index(max(q_mean)) | d0854483e9a93c39e7c278ac1235e65a5f4503f7 | 37,743 |
def social():
"""Redirects to the Accent Twitter profile."""
return redirect(SOCIAL_URL) | ca2ca341155dbed9b57f704c90486dc1b479d6bc | 37,744 |
def MakeCircleRange(circle_size, slice_side):
"""factory function that pre computes all circular slices
slices are assumed to be 2*slice_side+1 in length
"""
assert (circle_size - 1) % 2 == 0
slice_collection = {}
full_indices = list(range(0, circle_size))
for centre_index in range(circle_s... | f952b7b110233780164916afcef102364c3b7399 | 37,745 |
import os
import logging
import tarfile
import gzip
def get_data(directory, tar_filename):
"""
Extract data and return filenames, grouped by paper.
Parameters
----------
directory : string
The path to a directory which contains .gz files of the arXiv.
tar_filename : string
The... | 03c8efe739026893bd3f88c1e3760258e78d0333 | 37,746 |
def TDataXtd_Constraint_GetID(*args):
"""
* Returns the GUID for constraints.
:rtype: Standard_GUID
"""
return _TDataXtd.TDataXtd_Constraint_GetID(*args) | 761883f727e6c4a7ecc280b7fc6f7246e31293cf | 37,747 |
import fnmatch
def get_memory_usage(pids, verbose=False, exclude=None, use_pss=True):
"""Returns memory stats for list of pids, aggregated by cmd line."""
# TODO: pylint complains about too many branches, need to refactor.
# pylint: disable=R0912
meminfos = []
for pid in pids:
thread_id =... | cee5a22883d21ce4cc4d9535c6247c31d99fb814 | 37,748 |
def dependency_on_infectiousness_width_homogeneous_model_example():
"""
Example of several computations of the limit Eff_∞ in homogeneous scenarios (i.e. with no app usage)
in which the default distribution ρ^0 of the generation time is rescaled by different factors.
"""
infectiousness_rescale_fact... | 31b505d9c42d0c805deabf116f730a1297fe3d4e | 37,749 |
def octree_et(sc, margin, idx=None, eidx=None, bounds=None, cloth=None):
"""Adaptive octree. Good for finding doubles or broad
phase collision culling. et does edges and tris.
Also groups edges in boxes.""" # first box is based on bounds so first box could be any shape rectangle
#sh = cloth.pierce_co.s... | 523c3eeffac13d8aefd640e3a844e4ae46fed9e9 | 37,750 |
from .base import IODescriptorBase
def descriptor_dict_to_uri(ddict):
"""
Translates a descriptor dictionary into a uri.
:param ddict: descriptor dictionary
:returns: descriptor uri
"""
return IODescriptorBase.uri_from_dict(ddict) | 81eac77d3ef12103af457665ea28e6a6a32ef09a | 37,751 |
def process_df(df,
sentence_column='SentenceID',
word_column='Word',
tag_column='Tag',
verbose=1):
"""
Extract words, tags, and sentences from dataframe
"""
# get words and tags
words = list(set(df[word_column].values))
n_words = l... | 64ec6fabb657712524e333bb805a9352a93d6017 | 37,752 |
def ramp_geometric(phi, A):
""" Weighted geometric mean according to phi. """
return A[0]**(0.5*(1.+phi))*A[1]**(0.5*(1.-phi)) | 0f79e345336f4038e03947b10446031bd9f3e404 | 37,753 |
from sys import path
def secondary_structure(**kwargs):
"""
Predict or load secondary structure for an
input sequence
Parameters
----------
Mandatory kwargs arguments:
See list below in code where calling check_required
Returns
-------
residues : pandas.DataFrame
... | 67fa0c92be86b5312a51e09a68b549228dcd34a8 | 37,754 |
import inspect
from datetime import datetime
async def post_login_infos(
*,
resp_: Response,
request : Request,
# access_token: str = p_access_token,
user_login: UserLogin = Body(..., embed=True),
api_key: APIKey = Depends(get_api_key),
):
"""
Needs an anonymous access_token
"""
### DEBUGGI... | 057de965bc307c2e811f624137e504f72fd23bf7 | 37,755 |
def dipole(sign, simplified=False):
"""Segmented BC dipole model."""
segtypes = {
'b': ('B', _pyaccel.elements.rbend),
'b_edge': ('edgeB', _pyaccel.elements.marker),
'b_pb': ('physB', _pyaccel.elements.marker),
}
# FIELDMAP
# trajectory centered in good-field region. init_... | f2a228ee722e4424c875af982350daba344aa588 | 37,756 |
def edge_to_string(token, is_head=False):
"""
Converts the token to an edge string representation
:param token: the token
:return: the edge string
"""
t = token
if not isinstance(token, spacy.tokens.token.Token):
t = token.root
return '/'.join([token_to_lemma(token), t.pos_, t.d... | 9473e543b635ee34e0723b15ad22bc8c2b20b21c | 37,757 |
def sknet152(**kwargs):
"""
SKNet-152 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.tensorflow/models'
Location for... | 2cd81b34d8d2d5d9316d956dbc997ff61ea8a993 | 37,758 |
import os
def compressBaseName(path):
"""if a file is compressed, return the path without the compressed extension"""
if isCompressed(path):
return os.path.splitext(path)[0]
else:
return path | ac7457e645e29c3b3ec4179e2c03756522a5c523 | 37,759 |
import pathlib
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
current_dir = pathlib.Path(__file__).parent.absolute()
return (resources.GetResource(f'{current_dir}/ball_in_cup_explore.xml'),
common.ASSETS) | c344513a4416273de90fccb95ed9e74d4d4ddd34 | 37,760 |
import sys
def _index_argv(argument):
"""Returns the location of the argument in sys.argv, or None.
Since long options can be passed as either '--option value' or '--option=value' we need to check for both forms.
"""
for i, arg in enumerate(sys.argv):
if arg.split('=')[0] == argument:
... | e7fc00cce5722a81f92f76cb27f6b1ddc00e5887 | 37,761 |
def render_file(path: str, **kwargs):
"""
Renders a file at the specified absolute path. The file can reside
anywhere on the local disk as Cauldron's template environment path
searching is ignored.
:param path:
Absolute path to a template file to render
:param kwargs:
Named argu... | 207e70699efb936f2f84fd8f01b6293626c8f6e1 | 37,762 |
import subprocess
def find_file(value: str) -> bool:
"""
Find a file in the system explorer.
value: str corresponding to the dbfid (just the int part).
returns True if the file was found, and False otherwise.
"""
# Ensure that the id is a number.
try:
float(value)
except Valu... | dfb9c8a43c32c366bea59a30f7b6019c7eeac6bc | 37,763 |
import io
import csv
from datetime import datetime
async def export_books_csv():
"""export `Book`s to csv file"""
session = Session()
books = session.query(
BookTable.title,
BookTable.author,
BookTable.publisher,
BookTable.shorthand,
BookTable.number,
BookTa... | 0a641f42c9ffd2a416bae03f7cadd5692ef00c46 | 37,764 |
def export_videos(videos, email):
"""
Exporting videos is done in a seperate Celery process from the Flask handler.
Args:
videos (array): Array of video objects (See README.md for general idea of formats).
email (string): Email address (string) where a download link of the export results wi... | 2f2ad9e6aadf6d391f910157882fa861768fd880 | 37,765 |
def text_words(tree, show_traces=False):
"""Print just the words in the tree."""
text = []
for node in tree:
if node.is_terminal():
if node.is_trace() and not show_traces:
continue
text.append(node.word)
return ' '.join(text) | 58ae53ec1f10b8eb189d6714cbbdf391391c3728 | 37,766 |
from typing import Protocol
def edit_protocol(protocol_id):
"""Edit details of a protocol."""
current_protocol = Protocol.query.filter_by(id=protocol_id).first()
if current_protocol.user != current_user:
flash('Not your protocol!', 'danger')
return redirect('.')
form = ProtocolForm(r... | 407d0282e99449c3684bb4659b2ea6e89f895bf6 | 37,767 |
def get_win_drives():
""" Return list of detected drives """
assert NT
drives = []
bitmask = windll.kernel32.GetLogicalDrives()
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
if (bitmask & 1) and win32file.GetDriveType('%s:\\' % letter) in DRIVES:
drives.append(letter)
bitma... | 982f984ff1ee9fafcb26f065e594b6b4324b9d3b | 37,768 |
def query_grakn(session, query_object) -> dict:
"""
Purpose:
Gateway to the grakn queries
Args:
session: The Grakn session
query_object: the query_object
Returns:
answers_df_map: Answers to the queries by entity
"""
answers = {}
if query_object.action == "Find... | de2b6255a66302511c581b307d765686d6101fcd | 37,769 |
def skewa(s):
"""
SKEWA creates augmented skew-symmetric matrix
:param s: 3 or 6 vector
:return: augmented skew-symmetric matrix
SKEWA(V) is an augmented skew-symmetric matrix formed from V.
If V (1x3) then S =
| 0 -v3 v1 |
| v3 0 v2 |
| 0 0 0 |
... | 8dbdd9a4b885f9e96b1007fca42def50ef107374 | 37,770 |
import hashlib
def generate_server_uuid(input_string):
""" Create your own server_uuid
@param input_string (str): information to be encoded as server_uuid
@returns server_uuid (str): your unique server_uuid
"""
s = hashlib.sha256()
data = (input_string+SALT).encode("utf-8")
s.update(data)
... | 0857beb322ab2bbe280e8714ef7b8daa926e018f | 37,771 |
def get_subject_data(layout: BIDSLayout, subject: str):
"""
Gathers subject specific experimental data
"""
# Get the high resolution T1-weighted anatomical MRI scan
"""
In addition to the functional scan, a high resolution T1-weighted anatomical MRI scan was
made (3D gradient echo sequence,... | 1eb9fe9199b3314a29851d4de45b4ab63d897989 | 37,772 |
def multi_point(point_gdf):
"""Create a multi-point GeoDataFrame."""
multi_point = point_gdf.unary_union
out_df = GeoDataFrame(
geometry=GeoSeries(
[multi_point, Point(2, 5), Point(-11, -14), Point(-10, -12)]
),
crs="EPSG:4326",
)
out_df["attr"] = ["tree", "anothe... | 2f6e281f068273f7e100465c8c33da3dbc0cc378 | 37,773 |
def get_service_auth(context, endpoint, service_auth):
"""Create auth plugin wrapping both user and service auth.
When properly configured and using auth_token middleware,
requests with valid service auth will not fail
if the user token is expired.
Ideally we would use the plugin provided by auth_... | 20d669370242d637c7565183eed6da040dcc0a01 | 37,774 |
def download_topo_land(load=True): # pragma: no cover
"""Download topo land dataset.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returned.
Returns
-------
pyvista.Poly... | 65137c5f8dfe6e6a0d7b2bc564f934ced6402b11 | 37,775 |
import time
def wait(msg='', exceptions=None, timeout=10):
"""
Decorator to handle generic waiting situations.
Will handle StaleElementReferenceErrors.
:param msg: Error message
:param exceptions: Extra exceptions to handle
:param timeout: time to keep trying (default: 10 seconds)
:retur... | 00d3092c913d80027d566b99b25b2345f1fbd80e | 37,776 |
def transform_skycoordinates_to_radec(df, names, move_to_rad=True):
"""
Transform ``SkyCoordinate`` column to ``sindec``, ``sinra``, ``cosra``.
:param df:
Data frame with ``SkyCoordinate`` column.
:param names:
Iterable with names of columns with ``SkyCoordinate``s.
:param move... | 354d84b989d1468003c76c58412058e102b15821 | 37,777 |
def rot13(encoded: str) -> str:
"""
>>> rot13("har crefbaar abeznyr crafr dh’ha xvyb-bpgrg rfg étny à 1000 bpgrgf, ha vasbezngvpvra rfg pbainvaph dh’haxvybzèger rfg étny à 1024 zègerf.")
'une personne normale pense qu’un kilo-octet est égal à 1000 octets, un informaticien est convaincu qu’unkilomètre est ég... | 790d260a1cc517c49d3ea6e4c481fba32dca0831 | 37,778 |
def create_scene(gym, sim, props, assets_biotac, assets_indenters, biotac_offset=0.05, indenter_offset=0.01785938):
"""Create a scene (i.e., ground plane, environments, BioTac actors, and indenter actors)."""
plane_params = gymapi.PlaneParams()
gym.add_ground(sim, plane_params)
env_handles = []
ac... | 4b8df3a7f27b43e211235c6863f482e0754cef9b | 37,779 |
def ni_parse(*, df_list, year, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param args: dictionary, used to run flowbyactivity.py
('year' and 'source')
:return: df, parsed and partially formatted to flowbyactivity
... | 4a7bb161154d24f96cd94bf846423458b7f1885b | 37,780 |
from re import X
from re import T
def run(dx, Tf, generator="cython", sorder=None, withPlot=True):
"""
Parameters
----------
dx: double
spatial step
Tf: double
final time
generator: pylbm generator
sorder: list
storage order
withPlot: boolean
if Tru... | 9e9dee091ae3bff151e310391fd3fc5416dbee2f | 37,781 |
def get_policy(arn: str, configuration: Configuration = None,
secrets: Secrets = None) -> bool:
"""
Get a policy by its ARN
"""
client = aws_client("iam", configuration, secrets)
return client.get_policy(PolicyArn=arn) | e37c20893d44bc1d59fbb04247a35ae0f96e624a | 37,782 |
def soft_crossentropy(predicted_logprobs, target_probs):
"""
Cross-entropy loss capable of handling soft target probabilities.
"""
return -(target_probs * predicted_logprobs).sum(1).mean(0) | 8f6f0168c67cd0b3f432a5c91c7f4069c54de7c8 | 37,783 |
def is_slashable_attestation_data(data_1: AttestationData, data_2: AttestationData) -> bool:
"""
Check if ``data_1`` and ``data_2`` are slashable according to Casper FFG rules.
"""
return (
# Double vote
(data_1 != data_2 and data_1.target.epoch == data_2.target.epoch) or
# Surro... | 9c6f7c933c45b0643ea476feac56a57b0f3091b6 | 37,784 |
def trunc(x):
"""
Truncate the values to the integer value without rounding
"""
if isinstance(x, UncertainFunction):
mcpts = np.trunc(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.trunc(x) | e1a48ca75903ee869d571677034afce7305f6d0b | 37,785 |
def _mine_store(mine_data, clear=False):
"""
Helper function to store the provided mine data.
This will store either locally in the cache (for masterless setups), or in
the master's cache.
:param dict mine_data: Dictionary with function_name: function_data to store.
:param bool clear: Whether o... | 2c568a8652876e24a22cc381bb58f855294411fc | 37,786 |
def semivariogram(F, sites, xbin=None, robust=True, trimmed=True, cloud=False, counts=False, se=False):
"""
Classical semivariogram estimator with option for Cressie's robust
estimator. Can also return a semivariogram "cloud".
Parameters
----------
F : ndarray, (N, ...)
One or more sam... | 42c9c0dec1167bca86e06a8adff4ebc9a4c598b7 | 37,787 |
def linelength(x0, y0, x1, y1):
"""Returns the length of the line."""
a = pow(abs(x0 - x1), 2)
b = pow(abs(y0 - y1), 2)
return sqrt(a+b) | 9df83b77666b88b07230ae09bafde701312bbd1c | 37,788 |
def get_table_max_columns_width(table, column_mapping):
""" Returns a list with columns width
Args:
table (list): of dictionaries must correspond to column_mapping
column_mapping (list): of tuples: mapping of final table column names to actual `table keys`
.. code-block:: python
... | f80e7ab053dee415570c64f2a96565f9c59aedcc | 37,789 |
def create_switch_with_ecobee_clear_hold_button(accessory):
"""Define setup button characteristics."""
service = accessory.add_service(ServicesTypes.OUTLET)
setup = service.add_char(CharacteristicsTypes.Vendor.ECOBEE_CLEAR_HOLD)
setup.value = ""
setup.format = "string"
cur_state = service.add... | a541f36dd7c5c90490e5dc876140c3c21e9aa548 | 37,790 |
def infer_mime(
mime,
args,
vocab,
data,
fuzz_ops,
emotion=None,
format_data_output_path=None,
):
"""
Infer
"""
fuzzed_data = fuzz(data, {"ops": fuzz_ops})
formatter = MIMEPipeline(vocab)
formatter.format([[obj["fuzzed"]] for obj in fuzzed_data], emotion=emotion)
... | 044d2714d0b00b47d9f123fd3862fa39eb315c7b | 37,791 |
def request_priority_access(requester: str, trusted_by: str = None,
url: str = None):
"""(draft) Request priority to access data (eg Overloaded server allow you)
Example:
please = hxlm.routing.request_priority_access(
url='https://example.org/dataset/data... | a9f03d6b8f67f7551562fa6a078a7d0aca686e15 | 37,792 |
def trycmd(*args, **kwargs):
"""Convenience wrapper around oslo's trycmd() function."""
if 'run_as_root' in kwargs and 'root_helper' not in kwargs:
kwargs['root_helper'] = _get_root_helper()
return processutils.trycmd(*args, **kwargs) | e69f389b4fb8adeea0a2fae8ad47a7b7dceda236 | 37,793 |
import nomenclator.utilities
def mocked_fetch_next_version(mocker):
"""Return mocked 'nomenclator.utilities.fetch_next_version' function."""
return mocker.patch.object(nomenclator.utilities, "fetch_next_version", ) | e9506caf038ef7a6a2b39000d856c2d807b2849c | 37,794 |
from re import T
def is_from_keyword(token):
"""
「FROM」判定
"""
return token.match(T.Keyword, "FROM") | 006dede893eb4e9978dda7e669cc27145a1cd3b3 | 37,795 |
import copy
def get_saved_state(model, optimizer, lr_scheduler, epoch, hyp):
"""Get the information to save with checkpoints"""
if hasattr(model, 'module'):
model_state_dict = model.module.state_dict()
else:
model_state_dict = model.state_dict()
utils_state_dict = {
'epoch': ep... | ab4d9642c1a55e4a006844d21522c4d081d9595a | 37,796 |
def compact(number):
"""Convert the number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
return clean(number, ' -.').strip() | 55208b33fddcc8d53f2dec737010c4871d0f96f8 | 37,797 |
def pretty_status_str(status,color,bold):
"""return pretty status string from status code"""
if bold:
bold_str='1'
else:
bold_str='0'
color_map = {
0: 32, # green
10: 32, # green
15: 37, # white
20: 31, # red
30: 31, # red
}
color_code=color_map.get(st... | 7612c87289270d09cf6685b044cea2f6d91e925d | 37,798 |
def dynamic_import(import_string):
"""
Dynamically import a module or object.
"""
# Use rfind rather than rsplit for Python 2.3 compatibility.
lastdot = import_string.rfind('.')
if lastdot == -1:
return __import__(import_string, {}, {}, [])
module_name, attr = import_string[:las... | 5dabdf31632502a5352ee4e1cc707846eb3a3843 | 37,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.