content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def upload_avatar():
"""保存图片"""
# 提取参数
req_data = request.files.get("image")
# 校验参数
if not req_data:
return jsonify(errno=RET.PARAMERR, errmsg="请选择图片文件")
# 保存图片
file_data = req_data.read()
try:
filename = upload_image(file_data)
except Exception as e:
current... | 170e9ad7755cc5d3e83d35b8406835aff2077b43 | 52,300 |
def get_roster_alltime(team_id, start_year=START_YEAR, end_year=END_YEAR):
"""Return the roster file of team with matching id."""
try:
return urlopen(ROSTER_ALLTIME_URL.format(team_id, start_year, end_year))
except HTTPError:
raise ValueError('Could not find a roster for a team with that id.... | af8bf9f6b8cc994092a76ba07f9dfa8b359283ca | 52,301 |
def induced_subgraph(G, nbunch):
"""Returns a independent deep copy subgraph induced on nbunch.
The induced subgraph of a graph on a set of nodes N is the
graph with nodes N and edges from G which have both ends in N.
Parameters
----------
G : NetworkX Graph
nbunch : node, container of nod... | af991494e424f75a7232295a160f0663e03bfd03 | 52,302 |
def get_calib_images(calib_img_paths, calib_img_names, resimgs=False):
"""Reads and returns images used for calibration."""
calibImages = []
calibImgNames = []
for calib_img_path, calib_img_name in zip(calib_img_paths, calib_img_names):
calibImage = cv2.imread(calib_img_path)
if calibIma... | 69025e2fef61316eaea7711fb723e0b0796e72ff | 52,303 |
import io
def make_image(imagePath, detections):
"""
returns "image": a numpy array representing an image, compatible with scikit-image
"""
image = io.imread(imagePath)
logger.info("*** "+str(len(detections))+" Results, color coded by confidence ***")
imcaption = []
for detection in de... | c81deeeac9d25d81c85bd9a6845046d9d528c567 | 52,304 |
import re
def html_chemname_format(name):
"""
Format a chemical formula to display subscripts and superscripts in HTML
(e.g., Plotly plots)
Example, "CH3COO-" becomes "CH<sub>3</sub>COO<sup>-</sup>"
Parameters
----------
name : str
A chemical formula.
Returns
... | d6fc5d11c13abe27961ffe118ea077a963883225 | 52,305 |
def from_shape_and_word(shape, word):
"""
Returns the ribbon corresponding to the given ribbon shape and
word.
EXAMPLES::
sage: import sage.combinat.ribbon as ribbon
sage: ribbon.from_shape_and_word([2,3],[1,2,3,4,5])
[[1, 2], [3, 4, 5]]
"""
pos = 0
r = []
for l... | a472bc5a2f653d29a9e846dbc9083a5270c17471 | 52,306 |
import warnings
def dcm_to_hvdict(
unique_id,
slice_paths,
patient_name='',
mri_type = '',
segmentation_info=None,
seg_label_info=None,
visualization_parameters_override=None
):
"""
Given a list of dcm file names, creates a dehydrated version of an hv object as a dict.
Slices w... | 96641fcb79cb2ab3576e45b75e06d075e7acc46c | 52,307 |
def normalize(X, Y=None):
"""
Normalise X and Y according to the mean and standard deviation of the X values only.
"""
# # It would be possible to normalize with last rather than mean, such as:
# lasts = np.expand_dims(X[:, -1, :], axis=1)
# assert (lasts[:, :] == X[:, -1, :]).all(), "{}, {}, {}... | 23c134a800c7df6c3e22872f2f24cb1fdc4cb7ab | 52,308 |
def import_maplight_from_json_view(request):
"""
Take data from Test XML file and store in the local Voting Info Project database
"""
# If person isn't signed in, we don't want to let them visit this page yet
if not request.user.is_authenticated():
return redirect('/admin')
import_mapli... | 8834d24456be065edfb8123b40283424778056f3 | 52,309 |
from . import routes
def create_app():
"""
Function Construct the core application for the flask
"""
app = Flask(__name__)
CORS(app)
app.config.from_object('config.Config')
"""
Initializing the sqlalchemy db with the app
"""
db.init_app(app)
"""
Creating the app cont... | efc3fddbf1313937171cfa67263b2a269a3eb727 | 52,310 |
def move_polygons(polygons, from_grid, to_grid=None):
"""
A function that moves polygons to the origin bounding box (0, 250, 250, 250)
"""
if(to_grid):
x_displacement = (from_grid // 10) - (to_grid // 10)
y_displacement = (from_grid % 10) - (to_grid % 10)
else:
x_displacemen... | 3b7667bed2fdcf70331adf107bb4759f8d4d90ab | 52,311 |
from typing import Dict
from typing import Union
import os
def get_output_template(config: Dict, software: Union[PlacementSoftware, AlignmentSoftware],
extension: str, **kwargs) -> str:
"""
Creates a name template of .{extension} output files produced by specific software.
Used to ... | 38574ba7bf034706c17142d550ae0bea0887a349 | 52,312 |
def create_tf_strings_model():
"""
A model that concatenates two input strings
"""
g = tf.Graph()
with g.as_default():
with tf.name_scope("some_namespace"):
x = tf.placeholder(tf.string, name="in_x")
y = tf.placeholder(tf.string, name="in_y")
# Assigned t... | 8f084f7b7cf15523ac5c3feb26d5e1d14b5b7790 | 52,313 |
import json
def get_numeric_project_id(gcloud, project_id):
"""Get the numeric project ID."""
project_info = json.loads(
gcloud.run('projects', 'describe', project_id, '--format=json'))
return project_info['projectNumber'] | f9e3086ed1436d4ce075960c191ff4f64a76582b | 52,314 |
def vstran(d1: np.ndarray, d2: np.ndarray) -> tuple:
"""calculate variance stabilized weights
Calculation of variance stabilized weights which describes in paper
in section "Variance stabilized weights"
Parameters
----------
d1 : np.ndarray
1d ndarray of diagonal elements
d2 : np.n... | b08d56f7a776f7a01fc905f6d81993c34f745eeb | 52,315 |
def count_local_minmax(A):
"""
Count local max and min
@author Akafael
"""
n = len(A)
# Trivial Solution
if n <= 1:
return 1
# Calculate the diff
B = []
count = 0
isRising = False
isFalling = False
for i in range(1, n - 1):
B.append(A[i + 1] - A[i]... | 03fc5439aad1bf93e8d08d8056beece2c2fe2aee | 52,316 |
from functools import reduce
from operator import add
def fitness(individual,target):
"""
individual : the individual to evaluate (a list)
target : the target sum the individuals are aiming for
"""
sum = reduce(add,individual,0)
return abs(target-sum) | bcfb4d857be926df249149e224babbc98d358780 | 52,317 |
def dynamic_gru(input,
size,
param_attr=None,
bias_attr=None,
is_reverse=False,
gate_activation='sigmoid',
candidate_activation='tanh',
h_0=None,
origin_mode=False):
"""
:api_attr: Static... | d44744fc6c427d901273fa05937e4b38b5f65b3b | 52,318 |
def create_schema(name: str) -> str:
"""Function for generating create schema statements
:param str name: The name of the schema
:return: Create statement
:rtype: str
"""
statement = f"CREATE SCHEMA {name}"
return statement | a82d392ec411e2c412ef3f1959ff7ab229130532 | 52,319 |
def test_existing_path_FileLinks_repr_alt_formatter():
"""FileLinks: Calling repr() functions as expected w/ alt formatter
"""
td = mkdtemp()
tf1 = NamedTemporaryFile(dir=td)
tf2 = NamedTemporaryFile(dir=td)
def fake_formatter(dirname,fnames,included_suffixes):
return ["hello","world"]
... | 976c299cfaf05b1e7af4c55710dc793571b191e4 | 52,320 |
def model_cv_mse(Model, X, y, alphas, k = 5):
"""
This function calculates the MSE resulting from k-fold CV using lasso regression performed on a training subset of
X and y for different values of alpha.
Inputs:
Model (sklearn model): the type of sklearn model with which to fit the data - Ridg... | 4e7b815a9f5895a112ddcf8fe58a392007bbc2cd | 52,321 |
def latent_samples_FGPVAE(train_images, train_aux_data, vae, GP, N_t, clipping_qs=False):
"""
Get latent samples for training data. For t-SNE plots :)
:param train_images:
:param train_aux_data:
:param vae:
:param GP:
:param clipping_qs:
:return:
"""
train_aux_data = tf.reshape... | 4f95691ad97c6ed2898ac1388f9db296534fd3a7 | 52,322 |
def rotate_matrix_cw(matrix, angle = 90):
"""Rotate the matrix clockwise by certain angle (multiples of 90 deg)."""
def rotate_matrix_90(matrix):
rows, columns = matrix.shape
matrix_new = np.zeros((columns, rows))
for i in range(rows):
for j in range(columns):
... | 82c90fec062c36dea4d6d9a55640ba483c6b07ad | 52,323 |
import copy
def SplitRM(instruction):
"""Split instruction into two versions (using register or memory).
Args:
instruction: instruction.
Returns:
List of one or two instructions. If original instruction contains operand
that can be either register or memory (such as 'E'), two specific versions
... | 5e294f0ce2fa206ad88e7e734280541c272b7d98 | 52,324 |
def reduce_mem_usage(df, verbose=False):
""" iterate through all the columns of a dataframe and modify the data type
to reduce memory usage.
"""
df = pd.DataFrame(df)
UINT8 = np.iinfo(np.uint8)
UINT16 = np.iinfo(np.uint16)
UINT32 = np.iinfo(np.uint32)
UINT64 = np.iinfo(np.uint64)
... | 22d8633010caf2f5afdd7609f195357a200f42b5 | 52,325 |
import io
import json
def deserialize_ndarray_npy(d):
"""
Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's
:obj:`save` function.
Args:
d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created
using :obj:`numpy.save`.
Return... | 9c7fa7563b04c715ff0b4c057e1f7e0e880fc7d1 | 52,326 |
def lic_flow(vectors,len_pix=10):
""" MANU: was side to side with lic_internal????? """
vectors = np.asarray(vectors)
m,n,two = vectors.shape
if two!=2:
raise ValueError
result = np.zeros((2*len_pix+1,m,n,2),dtype=np.int32) # FIXME: int16?
center = len_pix
result[center,:,:,0] = np.a... | 1824295efcb3d04d4db82095851f57d1d0d9c963 | 52,327 |
def compute_hessian(image):
""" Compute Hessian components of 2D image using finite difference.
Parameters
----------
image: array_like
Input image.
Returns
-------
hxx, hxy, hyy: ndarray, ndim=2
Gradients in x, y directions respectively.
"""
image = np.asarray(ima... | 693feb8ec954e22c3d025b9bf1aa6742439db7b8 | 52,328 |
import time
import subprocess
import json
def run_port_465_command(target_list, tnum):
"""
Use ZGrab to test for SMTPS on port 465
"""
if global_sleep_time > 0:
time.sleep(global_sleep_time)
targets = ""
for ip in target_list:
targets = targets + ip + "\\n"
targets = targe... | 980068991965b46ae701470cd14a19031db36ca2 | 52,329 |
def projectToImage(pts_3D, P):
"""
PROJECTTOIMAGE projects 3D points in given coordinate system in the image
plane using the given projection matrix P.
Usage: pts_2D = projectToImage(pts_3D, P)
input: pts_3D: 3xn matrix
P: 3x4 projection matrix
output: pts_2D: 2xn matrix
las... | 4120834e3e6f50de2d176935fa7b34b7983a19d6 | 52,330 |
def docs():
"""
Displays the API documentation at '/'
"""
return render_template('index.html',
last_updated=dir_last_updated('app/static')) | f7f0aff36c3ff287cc16220a0f4be79dc2a0530c | 52,331 |
def courant(dx, dt, v_max, **kwargs):
"""
Calculate the Courant's number describing
stability of the numerical scheme.
Parameters
----------
dx : float
Size of the spatial grid cell [m].
dt : float
Time step [s].
v_max : float
Max. velocity of the model.
Returns
-------
C : flo... | 58b09b545c4679b845c3e2702af8bffe4262c599 | 52,332 |
def weighted_count(instances_obj, m_weights):
"""Weight nt count by nt weights at each position"""
weighted_counts = {}
for letter in instances_obj.alphabet:
weighted_counts[letter] = [0] * instances_obj.length
for idx, instance in enumerate(instances_obj):
for position, letter in enumer... | 458a6c013fd72c1e418a27c3a6f5511c86be834d | 52,333 |
import tqdm
def plot_interaction_network(
kg_data: pd.DataFrame
) -> nx.DiGraph:
"""Plot a knowledge graph based on the interaction data."""
interaction_graph = nx.DiGraph()
# Append the source to target mapping to the main data edgelist
for idx in tqdm(kg_data.index, desc='Plotting interacti... | c45986f34773b6fcbef789b00c0a41377b6b0c39 | 52,334 |
def space_linear_tree(actions, sent=None, SHIFT=0, REDUCE=1):
""" Use `( ` instead of `(`. Similarly for ` )`.
"""
stack = []
pointer = 0
if sent is None:
sent = list(map(str, range((len(actions)+1) // 2)))
for action in actions:
if action == SHIFT:
word = sent[poin... | 36a7c1d2ba669259f5a2810d1746766470966da4 | 52,335 |
def n_thermal_qbits(pops: list) -> DensityMatrix:
"""
Args:
pops: a list of population numbers between 0 and .5
Returns:
A density matrix for n thermal qbits with the specified populations
"""
num_states = 2 ** len(pops)
data = []
for i in range(num_states):
state = ... | ac2c53514aaafbedf8d908011dd3579c5828047f | 52,336 |
def entropysea(salt=None,temp=None,pres=None,dliq=None,chkvals=False,
chktol=_CHKTOL,salt0=None,temp0=None,pres0=None,dliq0=None,
chkbnd=False,useext=False,mathargs=None):
"""Calculate sea-ice seawater entropy.
Calculate the specific entropy of seawater in sea-ice.
:arg salt: Salinity in k... | e32102631b047df15e083555ac684bc79e6d4d29 | 52,337 |
import time
import subprocess
def alpha_beta_pruning(board, color, depth):
"""
Returns the best move calculated using the C++ compiled binary
"""
st = time.time()
player = 16
proc = subprocess.Popen(
["ai/minimax", str(player), str(depth)],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
)
... | efffbddd58dd4138a2f50b487f23c6f743c36d34 | 52,338 |
def rm(args):
"""
Remove files from tracking and delete the file.
Args:
args (obj): Arguments from command line.
"""
args.delete = True
return remove(args) | b772df32d546deb3680a8c472ad8419b632aa88e | 52,339 |
def compute_cost_rmsle(Y, Y_hat):
"""
Computes the RMSLE cost.
Arguments:
Y : true labels vector placeholder, same shape as Y_hat
Y_hat : output of forward propagation of shape (1, number of examples)
Returns:
cost : Tensor of the cost function.
"""
return tf.sq... | 673305a816af99bd3619dc41ba1fe0a93791af0e | 52,340 |
import math
def standard_deviation(series):
"""
implements the sample standard deviation of a series from scratch
you may need a for loop and your average function
also the function math.sqrt
you should get the same result as calling .std() on your data
https://pandas.pydata.org/pandas-docs/st... | 01a488f4bc8168a92d4a0590daa88bad08032fed | 52,341 |
def ldns_rdf2buffer_str_time(*args):
"""LDNS buffer."""
return _ldns.ldns_rdf2buffer_str_time(*args) | c994fddcb98570a8f2106af8c1504412e0bad509 | 52,342 |
def read_file(netcdf_file_name):
"""Reads SHIPS data from NetCDF file.
:param netcdf_file_name: Path to input file.
:return: ships_table_xarray: xarray table. Documentation in the xarray
table should make values self-explanatory.
"""
return xarray.open_dataset(netcdf_file_name) | da193379703d3e15c02de4b5d2117ede7ba5fff4 | 52,343 |
def get_settings(values):
"""
Retrieve settings from command line, and set them up
"""
settings = Settings()
settings.input.XC.GGA = values['functional']
if values['dispersion'] is not None:
settings.input.XC.DISPERSION = values['dispersion']
settings.input.BASIS.type = values['b... | 4e7a4b12c8a9ea14a6e96c1ca9ab80021b72d1f9 | 52,344 |
def o2satv2b(salinity: np.ndarray, temp: np.ndarray) -> np.ndarray:
"""
Calculate oxygen concentration at saturation
:param salinity:
:param temp:
:return:
"""
# Define constants, etc. for saturation calculation
# The constants used are for units of umol O2/kg
a0 = 5.80818
a1 = ... | 914169c1b87bd420c6f7b458f7d8ee0990c7dbb6 | 52,345 |
def get_factories(
config,
device,
debug = False,
):
"""Feed config to factories and return objects."""
pretrain_loaders = get_pretraining_dataloaders(config, debug)
downstream_loaders = get_downstream_dataloaders(config, debug)
model = factory.model_from_config(config)
optimizer = factory.optim_f... | afefcdf901477fe84f76807519534e2929a82515 | 52,346 |
def _get_crm_resource_v2(credentials):
"""
Instantiates a Google Compute Resource Manager v2 resource object to call the Resource Manager API.
We need a v2 resource object to query for GCP folders.
:param credentials: The GoogleCredentials object
:return: A CRM v2 resource object
"""
return ... | e72c64c5a5dac52a576837066a62b9d96bc6fee9 | 52,347 |
import argparse
def make_parser(inheritable=False):
"""Expose parser for ``main``.
Parameters
----------
inheritable: bool
whether the parser can be inherited from (default False).
if True, sets ``add_help=False`` and ``conflict_hander='resolve'``
Returns
-------
parser: ... | 5214e56706619d12e7e77ea0b5836a402bf91066 | 52,348 |
def _obtain_rapt(http_request, access_token, requested_scopes, rounds_num=5):
"""Given an http request method and reauth access token, get rapt token.
Args:
http_request: callable to run http requests. Accepts uri, method, body
and headers. Returns a tuple: (response, content)
acces... | 36bec3b8e25139860d861da5b1c7d4f7f0312687 | 52,349 |
import io
def format_attribute(
el,
visibility=False,
is_derived=False,
type=False,
multiplicity=False,
default=False,
tags=False,
):
"""
Create a OCL representation of the attribute,
Returns the attribute as a string.
If one or more of the parameters (visibility, is_derive... | a879269e3739a66264c26c536ec7fe3909091cc4 | 52,350 |
def function(op):
"""
Convert a function into a delayed evaluator.
The value of the function is computed from the values of the parameters
at the time that the function value is requested rather than when the
function is created.
"""
# Note: @functools.wraps(op) does not work with numpy ufu... | 9169d12064fc4012eade59de86efc2596e157662 | 52,351 |
def convolve(x, W, input_multi_channel=False, output_multi_channel=False, mode='full'):
"""Convolution that supports multi-dimensional and multi-channel inputs.
Args:
x (array): input array with shape batch_shape + input_shape
if input_multi_channel=False.
Otherwise with shape ... | 66dcc629c0c863d5498c47b31708d8b01f26a979 | 52,352 |
def unify_projection(dic):
"""Unifies names of projections.
Some projections are referred using different names like
'Universal Transverse Mercator' and 'Universe Transverse Mercator'.
This function replaces synonyms by a unified name.
Example of common typo in UTM replaced by correct spelling::
... | a3cdf4bb2a26ee0391281e8f8b0d3e7ea5c8a962 | 52,353 |
def diagonal_zigzag_square(x):
"""
Fill square matrix in diagonal order.
x = [0, ..., 8]
y = diagonal_zigzag_square(x)
y = [[0 2 5]
[1 4 7]
[3 6 8]]
:param x: vector of length n**2.
:return: y
"""
x = np.array(x)
# length of the square side
n = np.sqrt(le... | fdbe1dc487f501d028585955555596912e28c551 | 52,354 |
def make_access_var(name, agent, target_variable=False, target_value=False,
radius=1000, agg_function='sum', decay='flat', log=True,
filters=False):
"""
Generator function for accessibility variables. Registers with orca.
"""
@orca.column('nodes', name, cache=Tru... | 3c34f1d6c4996431098cf3cbc7392fdbbaa44bf7 | 52,355 |
import torch
def make_path(index):
"""
Given a size of a node to add get the binary path to reach it.
"""
order = "{0:b}".format(index + 1)
order = torch.tensor(list(map(int, order)))
print(order)
out = [1]
for i in range(1, len(order)):
out.append(order[i] + 2 * out[-1])
r... | 4d41c969407cc1a0634ae33a8e588c0766394efc | 52,356 |
def getName(full_name):
"""
the getName function splits the name of the application returning the executable name and
ignoring the path details.
:param full_name: the path and executable name
:return: the executable name
"""
# Determine if '\\' and ':' are within the full_name
if ':' in ... | 797825903c3794533b134fc3c03afc79304d62b6 | 52,357 |
def batchnorm_backward_alt(dout, cache):
"""
Alternative backward pass for batch normalization.
For this implementation you should work out the derivatives for the batch
normalizaton backward pass on paper and simplify as much as possible. You
should be able to derive a simple expression for the backward p... | d04369fd41bb73abf6da91588139a1817b43efb0 | 52,358 |
import importlib
import os
def _package_rootdir(name):
"""Get the root directory of the installed package with the given name."""
initfile = importlib.util.find_spec(name).origin
return os.path.split(os.path.split(initfile)[0])[0] | b97ba3b9c9a5d59202e2da1d7df8dd380f5d4101 | 52,359 |
def _cor_coeff(X, y):
"""
pearson correlation coefficient
"""
corr, _ = pearsonr(X, y)
return corr | b7e65d203b264acd0602a979525efd6a0656f3ba | 52,360 |
def __battery_charge_decoder__(port: serial.Serial, *args, **kwargs):
"""Returns the raw battery value as a byte."""
return port.read(1)[0] | 5b2763ec1ad61185e997610823d99a1295c39116 | 52,361 |
def transform_viewpoint(v):
"""Transforms the viewpoint vector into a consistentrepresentation"""
return np.concatenate([v[:, :3],
np.cos(v[:, 3:4]),
np.sin(v[:, 3:4]),
np.cos(v[:, 4:5]),
np.sin(v[:, 4:5... | cb4dcc8f106190a32825d3f766de604db02634ac | 52,362 |
from ._alpino import tokenize, parse_raw, interpret_parse
def alpino(doc, output="raw"):
"""Wrapper around the Alpino (dependency) parser for Dutch.
Expects an environment variable ALPINO_HOME to point at
the Alpino installation dir.
The script uses the 'dependencies' end_hook to generate lemmata an... | 4f21c29136e85f63bd7454f12f4d23c9a91a2a15 | 52,363 |
import math
import random
import scipy
def inverseKinematics(target, rootJoint, numJoints):
"""
Solve the inverse Kinematics problem using the BFGS optimisation algorithm as described in:
Inverse Kinematics The state of the art (http://image.diku.dk/projects/media/morten.engell_noerregaard.07.pdf)
target - The t... | 1382ffbdf5d15d698e2c16dcebe46ac4027d7cd6 | 52,364 |
def contar_consonantes(cadena):
"""
Cuenta las vocales en una cadena
>>> contar_consonantes('hola')
2
>>> contar_consonantes('Duque')
2
>>> contar_consonantes('qwqwqwq')
7
:param cadena:
:return:
"""
return len(cadena) - contar_vocales(cadena) | af6d7db663451bcb64391a727050f38409005a2b | 52,365 |
import os
def list_all_csv_files(dir):
"""List all sgf-files in a dir
Recursively explores a path and returns the filepaths
for all files ending in .sgf
"""
root_dir = os.path.abspath(dir)
sgf_files = []
for root, sub_dirs, files in os.walk(root_dir):
for file in files:
... | 239b43a80123d16a21b7dd23bf0c8e50a6a7f8ad | 52,366 |
def SpecificSub(subject): #Aditi edit
"""
Function to separate correct and wrong answers on a subject basis from sub_correct and sub_wrong
sub_resp is a dictionary with correct and wrong answers for each subject
"""
sub_resp = {}
str1 = subject + '_correct'
str2 = subject + '_wrong'
cor... | d19bf9992cbe99462240a798d7e2e3239260208b | 52,367 |
import colorsys
def get_color(rgb):
"""Get the name of a color for a RGB value.
Resolve the human readable names for a RBG value. This method is a great
speed increase over the `get_most_likely_colors` method, however it assumes
that the hue is the exact color name and is limited to 16 colors (for no... | ca95f2fc6d1aec73f6393fdd9eb609664eca4a19 | 52,368 |
def other_sentence(type, request, sentence):
"""
process the other from of a sentence
Input=type and requesting of sentence and the sentence
Output=class Sentence
"""
#init... | 7d63fbc78e38b5ad3b54c0b4c2fe271a63e0dd84 | 52,369 |
import os
from sys import path
def get_host_file(_path=None):
"""
If ``_path`` is passed in, return that (makes it easier for the caller if
it can pass a ``None``) otherwise look into the most common locations for
a host file and if found, return that.
"""
if _path:
return _path
# ... | 9d682c6ad7d1c380edc8f34a5fc157b1e062e41e | 52,370 |
from indra.tools.expand_families import Expander
def expand_families(stmts_in, **kwargs):
"""Expand FamPlex Agents to individual genes.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to expand.
save : Optional[str]
The name of a pickle file ... | af62452c7ef526c2e4b00a3e1010da144c908ab1 | 52,371 |
def _run_suite(test_class, config=default_config, debug=ENABLE_DEBUG,
**kwargs):
"""Run a test of the given class, passing extra parameters as arguments.
Args:
test_class (type): class inheriting from AbstractTest.
config (dict): run configuration dict.
debug (bool): whet... | ec71e9e5914861e60cb3a62abeec0bbbc8ff6d55 | 52,372 |
import time
import uuid
def prep_img_motors(n_mot, img_motors, prev_out=True, tail_in=True,
timeout=None):
"""
Plan to prepare image motors for taking data. Moves the correct imagers in
and waits for them to be ready.
Parameters
----------
n_mot: int
Index of the m... | df21b74d6a8679c70bad251d347e875b73622f81 | 52,373 |
from typing import Optional
from typing import Type
from typing import Any
from typing import Sequence
import sys
def get_all_classes_of_module(
module: str,
base_class: Optional[Type[Any]] = None,
ignore: Sequence[Type[Any]] = tuple(),
):
"""Get a set of classes defined in the specified module to inc... | 9b87517997454da6b067af8f3bd796c9a67c8f43 | 52,374 |
def approx_eq_above(a, b):
"""
a < b
:param a:
:param b:
:return:
"""
if approx_eq(a, b):
return True
else:
return a <= b | edadc02ccb70c46cd6ef95b60b345309adb23ef2 | 52,375 |
def precision_score(targets, preds, cm=None, w=None, average='binary'):
"""
:purpose:
Calculates the precision score between a discrete target and pred array
:params:
targets, preds : discrete input arrays, both of shape (n,)
cm : if you have previously calculated a confusion matrix... | 5304af75c5c9f42a5dc7d3104cbc9fdd4303500f | 52,376 |
def complete_feature(ctx, args, incomplete):
"""Completion function that returns feature/<id> for open issues."""
return sorted([('feature/{}'.format(id), description) for id, description in complete_issue(ctx, args, incomplete)]) | c9a4fc34c327c0e8cfb5a37e40970990267708a3 | 52,377 |
from typing import Optional
from typing import Callable
from typing import List
def min_weight_simple_path_anneal(
graph: nx.Graph,
n: int,
start_path=None,
anneal_schedule: Optional[np.array] = None,
weight_fun: Callable[[nx.Graph, List], float] = path_weight):
"""A simula... | baa1c2be28ab309f0bb845f574c90fa7eadd54da | 52,378 |
def creer_entete(nomFichier) :
"""!Crée l'en-tête du fichier
Prend le nom de base du fichier et sa taille, et l'écrit dans l'en-tête.
@param nomFichier Nom du fichier à concaténer
@return L'en-tête à écrire dans le fichier d'archive
"""
# Pour l'en-tête, on fait un truc simple avec le nom du ... | f35b8391da7a77beea4e1932cb280f8f54cf879b | 52,379 |
import array
def dX_dt_Duffing(X,t=0):
""" Return the Duffing oscillator derivative """
return array([X[1],
-epsi*X[1] -X[0]*(beta*X[0]**2+alpha)]) | 2cec2c5dadf42e881bf1c8b6eea34ebfd3502e4f | 52,380 |
def mySettings():
""" Define your trading system settings here """
settings = {}
print('your call')
# Futures Contracts
settings['markets'] = ['CASH', 'KSU', 'VLO', 'ZTS', 'GOOG', 'AMZN', 'AAPL', 'BA', 'FB', 'NFLX', 'THC', 'F_US',
'F_TU', 'F_ES']
# settings['markets... | 2f24d687a2d0b2324c9519b8bb584324fa0c9421 | 52,381 |
def iou(segments1, segments2):
"""Computes pairwise intersection-over-union between segment collections.
Args:
segments1 (numpy array): shape [N, 2] holding N segments
segments2 (numpy array): shape [M, 4] holding N boxes.
Returns:
a numpy array with shape [N, M] representing pairwi... | bd7365f4c9b7f1bcdf42b7f39db29196c067bfc0 | 52,382 |
def to_feed(df):
"""Generate and return a feed item for the given data frame"""
fg = FeedGenerator()
fg.id(feed["id"])
fg.title(feed["title"])
fg.link(href=feed["link"], rel="self")
fg.language(feed["language"])
fg.description(feed["description"])
fg.generator("SNSZ")
fg.rights(feed[... | 7db6244f37c1a871f84a38f90665351c1754a915 | 52,383 |
import re
def find_index(filename):
"""Search the file index of the filename, if any, or return None."""
r = re.search(r"([^\n]+)\.([^\.]+)\.([0-9]+)$", filename)
if r:
return int(r.group(3))
# If the filename has no index in it, and if the file does not actually
# exist, return the index ... | 83f963b26a356c6b7d0d96f8335bb1a73031e0aa | 52,384 |
import os
def validate_auth_keys(path, extension):
"""
validates and maintains ZMQ Auth Keys/Certificates
"""
#check for valid path
if not(os.path.exists(path)): return False
#check if directory empty
if not(os.listdir(path)): return False
keys_buffer = [] #stores auth-keys
# loop over auth-keys
for ke... | 95742b4c8eb2080a4b74803a18aa5f6e5f9fda13 | 52,385 |
def filter_links(links, **kwargs):
"""
"""
filtered_links = {}
for url, v in links.items():
parsed = urlparse(url)
if parsed.netloc in ['scholar.google.com', 'scholar.google.ca']:
# At this point for google scholar, we are only
# interested in the links
... | 7e39304b12f2047d54297a55349d3aa85b111691 | 52,386 |
def runtimeerror_error(e):
"""Flask error handler for RuntimeError exceptions"""
log.exception("RuntimeError exception raised")
return json_error(500, "Internal Server Error", str(e)) | 57978614ad8a7c6a5512c1776323709724dc747b | 52,387 |
from typing import Dict
import json
def arg_types_from_json(arg_types_json: str) -> Dict[str, type]:
"""Reify the encoded argument types from the format produced by arg_types_to_json."""
arg_types = json.loads(arg_types_json)
return {name: type_from_dict(type_dict) for name, type_dict in arg_types.items()... | ad8ff9d0335224ae597c0a7c95ca2f0fe758c887 | 52,388 |
def service_signal(service, ident=None):
"""Encode service and identifier into signal."""
signal = "{}_{}".format(DOMAIN, service)
if ident:
signal += "_{}".format(ident.replace(".", "_"))
return signal | fd141a04b83ea7c081ba84960c6ba8a8c1607c5d | 52,389 |
from typing import Mapping
from typing import Optional
import click
def is_version_bump_enabled(bump_config: Mapping, ctx: Optional[click.Context] = None, *, is_publish_from_branch_allowed: Optional[bool] = None) -> bool:
"""
Check if current branch with version configuration is allowed to bump version
To... | c3b4f1a77194b447b8beab70ad57c996ec6c7304 | 52,390 |
def add_index(body):
"""
Added a new Index
:param body: Object that needs to be added to the db.
:type body: dict | bytes
:rtype: AddIndexResponse
"""
return Indexes.add_index(connexion) | 635fdc6f14bd4f3f32e268b2c5b00ea21e8af24c | 52,391 |
def sum_reduce(iter, params):
"""
Sums the values for each key.
This is a convenience function for performing a basic sum in the reduce.
"""
buf = {}
for key, value in iter:
buf[key] = buf.get(key, 0) + value
return buf.iteritems() | 282a45d14db4f693a095331ff5f3a17296994697 | 52,392 |
def compose_graph(graph_dict, composed_name, name_list):
"""
Compose multiple graph together coming from a dictionary under a new
entry of the dictionary.
Parameters
----------
graph_dict : dict
Dictionary of every graph.
composed_name : str
Name of the new key of graph_dict... | e4f01b2d895299d97282aee8293f9168e24e472b | 52,393 |
import ctypes
def subslr(method, target, et, fixref, abcorr, obsrvr):
"""
Compute the rectangular coordinates of the sub-solar point on
a target body at a specified epoch, optionally corrected for
light time and stellar aberration.
This routine supersedes subsol_c.
http://naif.jpl.nasa.gov/p... | 8d566d8a55019ca7f47e614704356e0423c6ab09 | 52,394 |
def init_default_extractor():
"""
create a new extractor, providing the default (all available
extractors)
"""
return SchemaExtractorSet(DEFAULT_EXTRACTOR_LIST) | 4f93cf193283a82d1ecd27cbff771f49c721e22e | 52,395 |
import importlib
def load_class_from_path(path_and_class: str):
"""
Dynamically load a class from a module at the specified path
Args:
path_and_class: relative path where to find the module and its class name
i.e. 'neo3.<package>.<package>.<module>.<class name>'
Raises:
ValueEr... | fc00c6ee3bea277a5c8cc12b1fa29b5c294ff069 | 52,396 |
def ROC(ds, count, timeperiod=-2**31):
"""Rate of change : ((price/prevPrice)-1)*100"""
return call_talib_with_ds(ds, count, talib.ROC, timeperiod) | 2f50fc35858e983a981604499aba53a76e5722ab | 52,397 |
from io import StringIO
def get_xml_bones(document):
"""
This function returns the "bones" of an XML document, replacing all the
text-data and attribute values with a round(length)
For example:
<xml></xml> ---> xml0/xml
<xml>hello</xml> ---> xml0/xm... | 5e132f20dd2c5e74888ea7296fabb911a52a9c40 | 52,398 |
def graph_encoder_layer(enc_input, # (batch_size, n_block, emb_dim)
attn_bias, # (batch_size, n_head, n_block, n_block)
graph_attn_bias, # (batch_size, n_head, n_block, n_block)
pos_win,
n_head,
d_... | 511c4b4e45b37bffbc8759e9f3ba3bc5463fa763 | 52,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.