content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _custom_openapi(app: FastAPI):
"""Custom OpenAPI schema generator function, supporting:
- Cache the schema
- Set custom logo in ReDoc
"""
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title=settings.title,
version=settings.version,
... | 487418d582a17b854f77d94d89a92fde58f60625 | 3,626,500 |
import torch
def get_hidden_states(
model: BertModel,
sent_data: np.array
) -> torch.Tensor:
"""
Grab the hidden state values from the model using the sentence data,
and return the tensor.
:param model: A BertModel object, already instantiated.
:param sent_data: The sentence data ... | 980b7e10d77c5b2e03a9b0ec1fd394352d34f46f | 3,626,501 |
import os
def test_get_cache_file_loc_not_file(monkeypatch):
"""Irregular existing cache files will raise FileExistsError"""
def mock_exists(x):
return True
def mock_isfile(x):
return False
monkeypatch.setattr(os.path, "exists", mock_exists)
monkeypatch.setattr(os.path, "isfile"... | 8e0814bf29b37e1a4866a69d7ec524ac1702f78e | 3,626,502 |
def search(term, category=Categories.ALL, pages=1, sort=None, order=None):
"""Return a search result for term in category. Can also be
sorted and span multiple pages."""
s = Search()
s.search(term=term, category=category, pages=pages, sort=sort, order=order)
return s | 6baee421c0268b69ed53989c8bd07f56c03e3c40 | 3,626,503 |
import logging
import sys
def UninstallService():
"""Uninstall the service."""
service_main = _MainServiceScriptPath()
if not service_main:
logging.error('Unexpected: missing service main script [%s].', service_main)
return False
try:
if _IsServiceInStatus(win32service.SERVICE_RUNNING) and not St... | cba8e11df5ae3993f30a78c2fa314bfefb5e102a | 3,626,504 |
def update_self_profile(request):
"""
Get current session profile details
"""
user = get_object_or_404(User, id=request.user.id)
user.first_name = request.data['first_name']
user.last_name = request.data['last_name']
user.save()
return HttpResponseRest(request, {}) | c85a52d8d903499d539d7505b3de1b16646a7958 | 3,626,505 |
def ex_verb_voice(sent, ex_set, be_outside_ex=True):
"""
Finds verb voice feature.
1. One of the tokens in the set must be partisip - VBG
2. One of the tokens in the set must be lemma 'be'
3. VBN's head has lemma 'be'
If none of the tokens is verb, returns string 'None'
@param sent Lis... | 8891a792528af0c44865e4bbc63f269a85df4da9 | 3,626,506 |
def add_sensorgroup_filter_by_ihost(query, value):
"""Adds an sensorgroup-specific filter to a query.
Filters results by hostid, if supplied value is an integer.
Otherwise attempts to filter results by UUID.
:param query: Initial query to add filter to.
:param value: Value for filtering results by... | 17ef948cdeed719426d8a84c302f4e8d2434ffbd | 3,626,507 |
def compute_residuals(data, targets, weights):
"""
Squared error function.
param list(list(float)) data: independent variable(s)
param list targets: dependent variable
param list weights: weight vector
"""
assert type(weights) == list
residuals = []
for i, values in enumerate(data)... | 36a40cb50e959d9ba8b557e3063d95c1dec69832 | 3,626,508 |
import os
def get_webapp():
"""
start web applicatioin
"""
# get template file and static file path.
templatepath = os.path.join(config_parser.ConfigParser.get_rootpath(), "ui/templates")
staticfilepath = os.path.join(config_parser.ConfigParser.get_rootpath(), "ui/static")
# create applic... | 9d592f52c10d69d64ddde46c27328e57640b56f1 | 3,626,509 |
def _at_least_x_are_equal(a, b, x):
"""At least x of a and b Tensors are equal."""
match = tf.equal(a, b)
match = tf.cast(match, tf.int32)
return tf.greater_equal(tf.reduce_sum(match), x) | 6ada1c5bde1f075268ca5cbe6b4105da7daf2599 | 3,626,510 |
def _imergeother(*args, **kwargs):
"""
Like :merge, but resolve all conflicts non-interactively in favor
of the other `p2()` changes."""
success, status = _imergeauto(localorother='other', *args, **kwargs)
return success, status, False | 663589082161ad5ce16d50b8da12b64c1837d044 | 3,626,511 |
def MakeExtractor(sess, config, import_scope=None):
"""Creates a function to extract features from an image.
Args:
sess: TensorFlow session to use.
config: DelfConfig proto containing the model configuration.
import_scope: Optional scope to use for model.
Returns:
Function that receives an image... | 55cc86fb13459064c64156f86ffaff24acdc1909 | 3,626,512 |
import sys
import json
def main():
"""
Clears outputs from Notebook. Print errors and help messages as needed
"""
if len(sys.argv) == 1:
print('\t')
print('\tClean Output of Jupyter Notebook Files (note: must be in JSON format)')
print('\t')
print('\t\t-f : Force read o... | 3905f12357490d38a3a2e101a03bf027d531605d | 3,626,513 |
def identifyTextures( datFile ): # todo: this function should be a method on various kinds of distinct dat file objects
""" Returns a list of tuples containing texture info. Each tuple is of the following form:
( imageDataOffset, imageHeaderOffset, paletteDataOffset, paletteHeaderOffset, width, height, imageType,... | fe4ff7e3778f2c89db220cfd37d38ff7d8dd8927 | 3,626,514 |
def solution(resources, args):
"""Problem 3 - Version 1
Find the largest prime factor with the use of this project's prime
number utilities.
Parameters:
args.number The number whose largest prime factor to find
Return:
Return the largest prime factor of args.number.
"""
... | 5d1c72329c08a97d59cf0e977fb959332fc2e6eb | 3,626,515 |
def get_player_actions(game, player):
"""
Returns player's actions for a game.
:param game: game.models.Game
:param player: string
:rtype: set
"""
qs = game.action_set.filter(player=player)
return set(list(qs.values_list('box', flat=True))) | 9b961afbee7c3a0e8f44e78c269f37a9b6613488 | 3,626,516 |
from unittest.mock import patch
def mock_library(**attributes):
"""
Used to replace an attribute the library that :func:`dist.load`
returns. Useful for replacing part of the compiled library as part
of the test.
"""
ffi, library = dist.load()
return patch.object(
dist, "load", lam... | 58e5ef41da0f27f72df1880f3fe72655f41e0d94 | 3,626,517 |
def CV_IS_SPARSE_MAT_HDR(*args):
"""CV_IS_SPARSE_MAT_HDR(CvMat mat) -> int"""
return _cv.CV_IS_SPARSE_MAT_HDR(*args) | cdb438c362383b762c750e67bf7a8abf01e3dce7 | 3,626,518 |
def parse_host_port(endpoint, default_protocol):
"""
parse protocol, host, port from endpoint in config
:type: string
:param endpoint: endpoint in config
:type: baidubce.protocol.HTTP or baidubce.protocol.HTTPS
:param default_protocol: if there is no scheme in endpoint,
... | fe80b1eee4a4d76fcfda1bdcb534eeef74662dcc | 3,626,519 |
def nfvi_kube_rootca_update_generate_cert(expiry_date, subject, callback):
"""Kube RootCA Update - Generate Cert"""
cmd_id = _infrastructure_plugin.invoke_plugin(
'kube_rootca_update_generate_cert',
expiry_date=expiry_date,
subject=subject,
callback=callback)
return cmd_id | 8effed9b004901e9938c545241fbf4234a3480cd | 3,626,520 |
def _default_link_table2table(left, right):
"""Find default reference link between left and right tables.
Returns (keyref, refop).
Raises exception.ConflictModel if no default can be found.
"""
if left == right:
raise exception.ConflictModel('Ambiguous self-link for table %s' % left)... | a7d5b589f811512f70bb5ba00d611745d1c3a353 | 3,626,521 |
def quit_() -> None:
"""Quits the program, returns None."""
win.quit()
win.destroy()
return None | e98fac70384f46c5a5abbf6dd9ca90ee2b846fad | 3,626,522 |
def create_lkas_ui(packer, main_on, enabled, steer_alert):
"""Creates a CAN message for the Ford Steer Ui."""
if not main_on:
lines = 0xf
elif enabled:
lines = 0x3
else:
lines = 0x6
values = {
"Set_Me_X80": 0x80,
"Set_Me_X45": 0x45,
"Set_Me_X30": 0x30,
"Lines_Hud": lines,
"Ha... | 16c226698160b14194daf63baf61bb3952e1cd59 | 3,626,523 |
def recover_password(user: schemas.UserBase) -> JSONResponse:
"""
Password Recovery
"""
db_user = get_active_user(email=user.email)
if db_user is None:
return JSONResponse(status_code=404, content={
"message": "The user with this email "
"does not exist in... | 03b270a743b8c262e8622860672493c649079b36 | 3,626,524 |
def plot_ellipses_MacAdam1942_in_chromaticity_diagram_CIE1960UCS(
chromaticity_diagram_callable_CIE1960UCS=(
plot_chromaticity_diagram_CIE1960UCS),
chromaticity_diagram_clipping=False,
ellipse_kwargs=None,
**kwargs):
"""
Plots *MacAdam (1942) Ellipses (Observer PGN)* ... | 04157ae011619f6bc9cb4207ff09e7edf86d91b9 | 3,626,525 |
import torch
def get_pytorch_device() -> torch.device:
"""Checks if a CUDA enabled GPU is available, and returns the
approriate device, either CPU or GPU.
Returns
-------
device : torch.device
"""
device = torch.device("cpu")
if torch.cuda.is_available():
device = torch.devic... | 0109f3146c96bec08bbe6fa62e5a8bc5638e461c | 3,626,526 |
import logging
def test_execution_store(cfg):
"""
Creates a proper test_execution store based on the current configuration.
:param cfg: Config object. Mandatory.
:return: A test_execution store implementation.
"""
logger = logging.getLogger(__name__)
if cfg.opts("results_publishing", "data... | 8684f2ea65019e9c49444bbc25a8e1b0f59e687e | 3,626,527 |
import time
import random
def creat_order_num(user_id):
"""
生成订单号
:param user_id: 用户id
:return: 订单号
"""
time_stamp = int(round(time.time() * 1000))
randomnum = '%04d' % random.randint(0, 100000)
order_num = str(time_stamp) + str(randomnum) + str(user_id)
return order_num | 339764f7dc943c46d959a9bfdc6c48dc9ecd6bef | 3,626,528 |
def get_rst_title_char(level):
"""Return character used for the given title level in rst files.
:param level: Level of the title.
:type: int
:returns: Character used for the given title level in rst files.
:rtype: str
"""
chars = (u'=', u'-', u'`', u"'", u'.', u'~', u'*', u'+', u'^')
if... | b646b9e0010d87ece7f5c8c53c8abf89ca557a21 | 3,626,529 |
def python_to_ir(f, imports=None):
"""Compile a piece of python code to an ir module.
Args:
f (file-like-object): a file like object containing the python code
imports: Dictionary with symbols that are present.
Returns:
A :class:`ppci.ir.Module` module
.. doctest::
>>... | 67ae702485ad664667b80efc8c3ff3d9ec13ab57 | 3,626,530 |
def get_endpoint_url(env, endpoint='public'):
"""Gets the Endpoint to use."""
endpoint_type = env.input('Endpoint (public|private|custom)', default=endpoint)
endpoint_type = endpoint_type.lower()
if endpoint_type == 'public':
endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT
elif endpoint_type ... | 37eec3f0d9499b079867af233922a49afe4c40cf | 3,626,531 |
def compute_temperature_high_altitude(altitude: pint.Quantity) -> pint.Quantity:
"""Compute temperature in high-altitude region.
Parameters
----------
altitude: quantity
Altitude.
Returns
-------
quantity
Temperature.
"""
r0 = R0
a = -76.3232 # K
b = -19.94... | c626e901e291f66f03056b288ab05738adbb67d0 | 3,626,532 |
import sys
def load(config):
"""Load a CFNgin configuration by modifying syspath, loading lookups, etc.
Args:
config (:class:`Config`): The CFNgin config to load.
Returns:
:class:`Config`: The CFNgin config provided above.
"""
if config.sys_path:
LOGGER.debug("appending ... | 3b4d11191e06a2067f94bdf75424d169e2bc0aa4 | 3,626,533 |
import attr
import tqdm
import sys
def merge_block_set(block_set: t.Iterable[Block], header: Header):
"""Merge a block set from a related collection of snapshots.
The snapshots should belong to a single simulation. Otherwise,
the routine could break, or data consistency is not guaranteed.
:param blo... | b1d0b3b24a4db01a12049b80b8be6d14e1db4cf6 | 3,626,534 |
def _get_individual_lists(ws, ind_numbers = INDIVIDUAL_NUMBERS, behav_map = BEHAVIOR_MAPPING):
""" returns {1 : [time, behav, start/stop] }"""
start_row = _get_first_content_row(ws = ws)
ret_dict = {}
for j in range(start_row, ws.max_row + 1):
if j % 100 == 0:
print("******Proce... | 3a68795d1083abd6f876a014a1e873341ba04b79 | 3,626,535 |
import os
import yaml
import shutil
def generate_all(pkg_path, dest_path=os.getcwd()):
"""Generate a set of nsr and vnfrs based on a service package
:param pkg_path: A string, a path to the package
:param dest_path: A string, the target directory for the set of files
:returns: a tuple with two eleme... | 155c492896e0c91853d145e0dd80785accf62be1 | 3,626,536 |
def normalize_prob_dictionary(prob_dict):
"""
Given a dictionary that describes probabilities of parameter values,
normalize the probabilities so that they sum up to 1
:param dict:
:return:
"""
sum = np.sum(list(prob_dict.values()))
if sum > 0:
for key in prob_dict.keys():
... | 57432f66c5bf569d080e251e877632b9cfbec743 | 3,626,537 |
def stsci_extraction_ranges(x1d, seg=''):
"""
Parameters
----------
x1d
seg
Returns
-------
ysignal, yback
"""
cos, stis = _iscos(x1d), _isstis(x1d)
xh, xd = x1d[1].header, x1d[1].data
# below these will all be divided by 2 (except bk off). initially they specify the f... | 6e2843656ae1955da36a1bca059fec7ae454d624 | 3,626,538 |
def ending_at(row_key: str) -> pbt_C.RowRange:
"""Create a row range ending at given row (inclusive).
Args:
row_key (str): The ending row key of the range (inclusive).
Returns:
RowRange: The row range which ends at `row_key` (inclusive).
"""
return pbt_C.ending_at_row_range(row_key) | b15b65c74bcf8524d3d1932dcde8dca678d5c967 | 3,626,539 |
def train_model(model, X_data_train, y_target_train, early_stopping):
"""
:param model: compiled model
:param X_data_train: 3d array
:param y_target_train: 1d array
:param flag: true if googlnet (output expect 3d array) else false if 1d array for output
:return: fitted model
"""
if earl... | 1510c7887a503d9a1fca6faf7f2eadb583af70a1 | 3,626,540 |
import os
def toPath(prefix, metric):
"""Translate the metric key name in metric to its OS path location
rooted under prefix."""
m = metric.replace(".", "/") + ".wsp"
return os.path.join(prefix, m) | 161ea82432c9e6a5e23ab9305133156ba35755f3 | 3,626,541 |
import torch
import torch.nn as nn
def bn_model_pytorch():
"""Same as bn_model but with PyTorch."""
bounds = (0, 1)
num_classes = 10
class Net(nn.Module):
def forward(self, x):
assert isinstance(x.data, torch.FloatTensor)
x = torch.mean(x, 3)
x = torch.m... | f4e16cb8283fa5ad58a0c65bb94f295d14ebec0c | 3,626,542 |
def check_point(x, y, d, length, alpha):
"""
Проверяет точку на принадлежность волноводу
Точка в ск Федера
"""
if -d / 2 <= y <= d / 2:
return 0 <= x <= length or is_inside_cone(x - length, y, d, alpha) | 747db69665134096077bdc29ccd162de5c14bda5 | 3,626,543 |
import os
import json
def load_result_from_file(filename):
"""Load a results dictionary file (.json) to a Result object.
Note: The json file may not load properly if it was saved with a previous
version of the SDK.
Args:
filename (str): filename of the dictionary
Returns:
tuple(R... | 59573d738dc9f4fb80dd588c183a686945f575bc | 3,626,544 |
def comments_list(request, locker_id, submission_id):
"""Returns a list of comments for the specified submission"""
submission = get_object_or_404(Submission, pk=submission_id)
if submission.locker.discussion_enabled():
is_owner = submission.locker.is_owner(request.user)
is_user = submission... | b3202414cf2174e9329538c1f617a3734e5c97b2 | 3,626,545 |
import sys
import threading
def runProject(samweb, projectname=None, defname=None, snapshot_id=None, callback=None,
deliveryLocation=None, node=None, station=None, maxFiles=0, schemas=None,
application=('runproject','runproject',get_version()), nparallel=1, quiet=False ):
""" Run a project
ar... | a95542799d3d83d5225f2094309fb5668ecba8c8 | 3,626,546 |
def massage_spectrum(cov, shape):
"""given a spectrum cov[nl] or cov[n,n,nl] and a shape
(stokes,ny,nx) or (ny,nx), return a new ocov that has
a shape compatible with shape, padded with zeros if necessary.
If shape is scalar (ny,nx), then ocov will be scalar (nl).
If shape is (stokes,ny,nx), then ocov will be (sto... | 18a7bf9b8704f1ada174b523fb9ddd3fdf135ff7 | 3,626,547 |
def get_device_by_label(session, label):
"""get Device by label
Args:
session: Active database session
label: label to get device that matches
Returns:
device found or None
"""
return session.query(Resource).filter(Resource.label == label).one_or_none() | 624acfd77be27d89f00f3e594f179c9a4f285639 | 3,626,548 |
from bs4 import BeautifulSoup
def fetch_MX_exchange(sorted_zone_keys, s):
"""
Finds current flow between two Mexican control areas.
Returns a float.
"""
req = s.get(MX_EXCHANGE_URL)
soup = BeautifulSoup(req.text, 'html.parser')
exchange_div = soup.find("div", attrs={'id': EXCHANGES[sorted... | c2316f6c3bbd4d823fd2e34057f2fa8df248e3a6 | 3,626,549 |
def mlp(X_train, targets):
"""Fully Connected Neural Network, known as MLP(Multi-Layer Perceptons).
"""
feature_number = X_train.shape[1]
output_number = targets.shape[1]
model = tf.keras.Sequential()
model.add(Dense((output_number+feature_number)/2+40,
input_dim=feature_numb... | 37a651a0007a6d31cc5c277db49085b9bd303c25 | 3,626,550 |
def make_ir_context() -> ir.Context:
"""Creates an MLIR context suitable for JAX IR."""
context = ir.Context()
mhlo.register_mhlo_dialect(context)
chlo.register_chlo_dialect(context)
return context | 7e34ade63d47e763784277d05fcb8d979b28715b | 3,626,551 |
import os
def get_fobj(fname, mode='w+'): # pragma: no cover
"""Obtain a proper file object.
Parameters
----------
fname : string, file object, file descriptor
If a string or file descriptor, then we create a file object. If *fname*
is a file object, then we do nothing and ignore the... | b179277aea3bfd33ab65fac0f7e69798b1c52e80 | 3,626,552 |
def parse_patch(patch_string):
"""Parse a patch string and return the affected files."""
patch = DiffParser(patch_string.splitlines())
return patch.files | 8b53d5443290fc6cdb1162ab0a607d42313ed9ba | 3,626,553 |
def adjust_color_lightness_scalar(r, g, b, factor):
"""
r,g,b between 0 and 1
factor between 0 and +infty, but lightness bounded between 0 and 1
"""
h, l, s = rgb_to_hls_scalar(r, g, b)
l = max(min(l * factor, 1.0), 0.0)
r, g, b = hls_to_rgb_scalar(h, l, s)
return r,g,b | 0e541f92c3df11a8bce1e5988d2a329ee15d933b | 3,626,554 |
def get_sample_ids(fams):
""" create a ditionary mapping family ID to sample, to subID
Returns:
e.g {'10000': {'p': 'p1', 's': 's1'}, ...}
"""
sample_ids = {}
for i, row in fams.iterrows():
ids = set()
for col in ['CSHL', 'UW', 'YALE']:
col = 'SequencedA... | 443e63b486a1bdb8a64595beda30f75468af7560 | 3,626,555 |
def mesh_conway_join(mesh):
"""Generates the join mesh from a seed mesh.
Parameters
----------
mesh : Mesh
A seed mesh
Returns
-------
Mesh
The join mesh.
Examples
--------
>>> mesh = Mesh.from_polyhedron(6)
>>> join = conway_join(mesh)
>>> join.number_... | 53f6358798f3421f98524fbcf166834a579a5f45 | 3,626,556 |
def calcbw(K, N, srate):
"""Calculate the bandwidth given K."""
return float(K + 1) * srate / N | 13e99bcb729352feb66a34aac66e12b1c5e158ef | 3,626,557 |
import requests
import json
def get_all_devices(auth):
"""
Function to get all devices for the account linked to the token
:param auth: pyawair.auth.AwairAuth object which contains a valid authentication token
:return: Object of Dict type which contains a list of all devices for this account
"""
... | ec46bd1be167e8df4d6cce94bddd3725eca73b43 | 3,626,558 |
def supports_display(handler_input):
# type: (HandlerInput) -> bool
"""Check if display is supported by the skill."""
#check the incoming request to the skill from the AVS to determine if the device the user invoked the skill on has a screen
try:
if hasattr(handler_input.request_envelope.context... | 98c45257b034637549e687dfe5e500d5cc4ffcb7 | 3,626,559 |
def format_sqlexec(result_rows, maxlen):
"""
Format rows of a SQL query as a discord message, adhering to a maximum
length.
If the message needs to be truncated, a (truncated) note will be added.
"""
codeblock = "\n".join(str(row) for row in result_rows)
message = f"```\n{codeblock}```"
... | 3b98590c72245241ba488e07fdfdd20acae441cf | 3,626,560 |
def is_calibration_produced(drs4_pedestal_run_id: int, pedcal_run_id: int) -> bool:
"""
Check if both daily calibration (DRS4 baseline and
charge calibration) files are already produced.
"""
return (
drs4_pedestal_exists(drs4_pedestal_run_id)
and calibration_file_exists(pedcal_run_id... | 2ce3a469bb3fa84493379d758b9573c6170986da | 3,626,561 |
def parse_date_literal(ast, _variables=None):
""" Parse a string value node in the AST.
"""
if isinstance(ast, StringValueNode):
# TODO: Must be a datetime.
return ast.value
return INVALID | 4381fdc5540e1447c0a50745a2acc2ce1c90e48c | 3,626,562 |
from pathlib import Path
import os
import wget
import shutil
import subprocess
import tqdm
def gen_lubm_graph(destination_folder: Path, count: int) -> Path:
"""
Generates LUBM graph by specified number of generated graphs to create one LUBM graph
:param destination_folder: directory to save the graph
... | 9f0c422cb7b32dd08aaa2c2374e38f46123169c2 | 3,626,563 |
def generate_initial_population(network_info, network_layout):
"""
Generates the initial population for network optimization.
:param NetworkInfo network_info: Object storing global network information (information about the whole
optimization)
:param NetworkLayout ... | 0c07f873f162ed8c87f9335fc1eadf8e84990311 | 3,626,564 |
def split_zip(zip_code):
""" split the zip code into 5 and 4 digit codes """
if not valid_zip(zip_code):
return None, None
if len(zip_code) == 5:
return zip_code[:5], None
return zip_code[:5], zip_code[-4:] | 86d6c37e2dce4a840e6198c9aa86c52716eff256 | 3,626,565 |
from typing import Dict
from typing import Any
from typing import Iterable
import warnings
def parse_initial_conditions(
ic: Dict[str, Any],
start_date_simulation: pd.Timestamp,
virus_strains: Dict[str, Any],
) -> Dict[str, Any]:
"""Parse the initial conditions."""
ic = {**INITIAL_CONDITIONS} if i... | 2e47bcff366870425b738381ac7abfb4c860103c | 3,626,566 |
def rq2responses(request):
"""
Converts a request to a list of responses.
:param request: Flask Request object
:return: list of response strings
"""
i, responses = 0, []
for i in range(int(request.form['num_questions'])):
name = Question.ID_FORMAT % i
if request.form.get(nam... | 83e42a33d6f3a23134819fcba16b4422ac7cffc3 | 3,626,567 |
def image_show(image, nrows=1, ncols=1, cmap='gray', **kwargs):
"""
Taken from :
https://github.com/gmagannaDevelop/skimage-tutorials/blob/master/lectures/4_segmentation.ipynb
"""
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(16, 16))
ax.imshow(image, cmap='gray')
ax.axis... | b2293d254a942b5f6534cc7394031dbefb87978b | 3,626,568 |
def normalize(arr):
"""Normalizes an array to its mean values.
Parameters
----------
arr : array-like | shape = [N]
The array to normalize.
Returns
-------
normalized_array : np.ndarray | shape = [arr.shape]
"""
return arr / np.mean(arr) | 6021296c5a86f770be59de259945e2ac28532154 | 3,626,569 |
from typing import List
from typing import Tuple
def find_matching_parens(
assertion_str, matched_quotes, errors: List[ValidationError]
) -> Tuple[List[Pair], List[ValidationError]]:
"""Find and return the location of the matching parentheses pairs in s.
Given a string, s, return a dictionary of start: e... | 07259774357cc04bd9ededdf0e1557207ed301ca | 3,626,570 |
import re
def regex_sub_groups_global(pattern, repl, string):
"""
Globally replace all groups inside pattern with `repl`.
If `pattern` doesn't have groups the whole match is replaced.
"""
for search in reversed(list(re.finditer(pattern, string))):
for i in range(len(search.groups()), 0 if ... | 67e909778d9565d498fc3e7b3c9522378e971846 | 3,626,571 |
def _parse( filepath : str ) -> list:
"""
[summary]
Arguments:
filepath {str} -- [description]
Returns:
list -- [description]
"""
with open( filepath, 'r' ) as f:
raw_data = f.read( ) # not readlines( ), as this needs to be one long string
data = list( map( int, raw_data.split( ) ) )
return data | 6814c4f45aee453f6387761ee7c4f3e64c669b1c | 3,626,572 |
from typing import Optional
def get_app_sec_eval(config_id: Optional[int] = None,
security_policy_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppSecEvalResult:
"""
Use this data source to access information about an existing r... | 2499b44e1b59ab989fb6b14a4d60145610a0d0b1 | 3,626,573 |
def write_merged_bioassembly(inpath, outdir, outname, force_rerun=False):
"""Utility to take as input a bioassembly file and merge all its models into multiple chains in a single model.
Args:
infile (str): Path to input PDB file with multiple models that represent an oligomeric form of a structure.
... | e53779b0c466a730028d91ff10779137a186c288 | 3,626,574 |
def get_final_loss(src_logits, src_one_hot_labels, dst_logits,
finetune_one_hot_labels, global_step, loss_weights,
inst_weights):
"""Gets the final loss for ."""
if FLAGS.uniform_weight:
inst_weights = 1.0
src_loss = get_loss(src_logits, inst_weights, src_one_hot_labels)
... | 2b87a024394e983eea9dbd5a1df9b30a9bff74f4 | 3,626,575 |
def causal_kernel(alpha):
"""
The causal kernel.
.. math::
w(\\tau) = [\\alpha^2 \\tau \\exp(- \\alpha \\tau)]_+
example:
.. code-block:: python
>>> kernel('causal', {'alpha': 0.4})
"""
def causal(t):
v = alpha**2 * t * np.exp(-alpha*t)
v[v<0] = 0
return v
return caus... | f49766f44f1532e11ef1ad88f162d1cf4bc03e0a | 3,626,576 |
import numpy
def read_nasa_planets(csv_filename,
eliminate=('SWEEPS-11',
'HD 41004 B',
'PSR J1719-1438',
'K2-22'),
fill_missing=manual_data,
need_ages=Tr... | a39f96be4f5b2b9f8e3e642117f5338db542fabb | 3,626,577 |
def e8(s: str) -> str:
"""
Encode Unicode string with stanard options
"""
return s.encode('utf-8', 'ignore') | ae28011d7d71c28399d81012fac26012693de9aa | 3,626,578 |
import os
import json
def _get_user_authentication_credentials(client_secret_file, scopes, credential_directory=None, local=False):
"""Returns user credentials."""
if credential_directory is None:
credential_directory = os.getcwd()
elif credential_directory == 'global':
home_dir = os.path.... | df444bd42ea0b3622d3987fcfdbc5415467d6b61 | 3,626,579 |
import requests
def download_seed_seqs(acc):
"""
Download seed sequences from PFAM.
Input
-----
acc : str
Accession number of a Pfam domain
Output
------
fasta : str
Seed sequences in fasta format
"""
url = "http://pfam.xfam.org/family/%s/alignment/seed" % acc... | e067e5e6e0669812151a680d6f785b19be01fb01 | 3,626,580 |
import numpy
def fit_spline(points, smoothing=None, order=None, force_endpoints=True):
"""Fit a parametric smoothing spline to a given set of x,y points. (Fits
x(p) and y(p) as functions for some parameter p.)
Parameters:
points: array of n points x,y; shape=(n,2)
smoothing: smoothing factor: 0 r... | e694736af14999881a9fd1cf3c8fd070802b137b | 3,626,581 |
def get_list_of_teams():
"""Get a list of all teams."""
teamlist = []
for team in cursor.execute('SELECT * from teams'):
teamlist.append(team[0]) # man isn't it cool that order matters
return teamlist | 82121e2fc8a652c4ee3630a4cba80aeb4f026520 | 3,626,582 |
def linear_activation_forward(A_prev, W, b, activation):
"""
activation of forward propagation
:param A_prev: np.array, activations from previous layer
:param W: np.array, weights matrix of current layer
:param b: np.array, biases vector of current layer
:param activation: str, activation mode o... | a8290d71b1660c5a154cc47e3674560a24c6d2e8 | 3,626,583 |
def stoll_auc_subjects(ds, skip_samples=0, dur_samples=10000):
""" Calculate AUC for each subject in a dataset
using the Stoll (2013) classification method """
aucs = []
for sub in np.unique(ds.trials_ppid):
tpr = []
fpr = []
tr = ds.trials[ds.trials_ppid == sub, :]
... | b3398c52d9f8d0fc8b90621b301e8d27770a18e6 | 3,626,584 |
def stations_level_over_threshold(stations, tol):
"""Returns a list of the tuples, each containing the name of a station at which the relative
water level is above tol and the relative water level at that station"""
output = []
for station in stations:
relative_level = station.relative_water_l... | 87be1329ea8b7e58796ebfe33a6f9e9503777227 | 3,626,585 |
def plot_classification_performance(cm=None, y_true=None, y_pred=None, cmap="RdBu", answer_label="answer", predict_label="predict", ax=None):
"""Plot model"s classification performance.
Args:
cm (array) : Confusion matrix whose i-th row and j-th column entry indicates the number of samples wit... | 93d27a68a2005d23f94250d21dc209726d6d8c4c | 3,626,586 |
def get_issue_close_comment(testcase):
"""Generate the closing comment of the issue"""
return ISSUE_ClOSE_COMMENT_TEXT.format(
bug_information=testcase.bug_information) | 080b63298fd2a28a9ce3cf4b86f293e0b1294cce | 3,626,587 |
def select_ensembl_species(species, table):
"""
Filters the species of interests, called group, from a table containing all the species in the Current release
"""
# Read the species table from Ensembl Genomes
df = pd.read_csv(table, sep='\t', index_col=False)
# Filter out the species that are ... | eb7f0a75842745a27b11296d602088770002eae8 | 3,626,588 |
def normalize_power_spectrum(Q):
"""transform spectrum to complex vectors with unit length
Parameters
----------
Q : np.array, size=(m,n), dtype=complex
cross-spectrum
Returns
-------
Qn : np.array, size=(m,n), dtype=complex
normalized cross-spectrum, that i... | 783fc5def698289f45721080c91ef74554604a4c | 3,626,589 |
import torch
def img2tensor(
img: pillow.Image,
size: tuple = None,
) -> torch.Tensor:
"""
Args:
img: image to convert
size: (W, H) of output tensor
Returns:
tensor of shape (1, 3, H, W)
the first dimension (batch size) is neccesary for the CNN
3 cha... | d90bc998d1a476287b0e2c2444d3dce4a035b7c6 | 3,626,590 |
def handler(event, context):
"""
function handler
"""
if 'imageDiscard' in event and event['imageDiscard']:
return None
if 'imageLocation' not in event or len(event['imageLocation']) == 0:
return None
if 'imageObjects' not in event or len(event['imageObjects']) == 0:
re... | 82d723d913f1c2d0631157a27702a889faa4c1b4 | 3,626,591 |
def set_smb_netbios_name(session, smb_netbios_name, force="YES", return_type=None, **kwargs):
"""
Get VPSA cache
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type smb_netbios_name: str
:param smb_netbios_name: The smb ne... | 964877297f8814da9ca9af92bb93b3bc7fd2718d | 3,626,592 |
def extract_nice_name(spec, nuke_pattern=True):
"""
>>> extract_nice_name("foo (bar::baz)")
'bar::baz'
"""
if nuke_pattern:
# get rid of pattern
i = spec.find("[")
j = spec.find("]", i + 1)
if i == -1:
assert j == -1
else:
assert j != -1
pattern = spec[i + 1:j]
match = re_pattern.match(patter... | 87ab077bd59b8acc27fa777572f2cd99456d4ae5 | 3,626,593 |
def _random_correlated_image(mean, sigma, image_shape, alpha=0.3, rng=None):
"""
Creates a random image with correlated neighbors.
pixel covariance is sigma^2, direct neighors pixel covariance is alpha * sigma^2.
Parameters
----------
mean : the mean value of the image pixel values.
sigma :... | 71a81630c29e271265b8bace4136a4fbce83137b | 3,626,594 |
def gen_polygons_cdnp(pdnp, name='cdnp_polygons', radius=.01):
"""
:param trimeshmodel:
:param name:
:param radius: TODO
:return:
author: weiwei
date: 20210204
"""
collision_node = CollisionNode(name)
# counter = 0
for geom in pdnp.findAllMatches('**/+GeomNode'):
geom... | 6442febfec258e0bb68a37797aebb1b99ccc3d33 | 3,626,595 |
def diameter(aabb):
"""
Compute the length of the diameter of an AABB.
:param aabb: AABB defined by its min and max point.
:type aabb: Pair of n-dimensional vectors
:return: Length of the diameter of the AABB.
"""
if not is_valid(aabb):
return None
return np.linalg.norm(aabb[1] ... | 675c0a2a445c18b7d1da75f9f78cb7a529ed1a05 | 3,626,596 |
def deregister_device(device):
"""
Task that deregisters a device.
:param device: device to be deregistered.
:return: response from SNS
"""
return device.deregister() | 44bec0e3ac356f150a0c4a6a0632939a20caafb0 | 3,626,597 |
async def peko(message):
"""peko"""
"""returns [content, embed, view]"""
url = "https://holodex.net/api/v2/users/live"
params = {
"channels": "UC1DCedRgGHBdm81E1llLhOQ,UCdn5BQ06XqgXoAxIhbqw5Rg,UC5CwaMl1eIgY8h02uZw7u8A,UChAnqc_AY5_I3Px5dig3X1Q"
}
headers = {"Content-Type": "application/js... | 674927c77fc6e4dc54a7eab6c4f42f7b64d84c00 | 3,626,598 |
def sequential_colors(n):
"""
Between 3 and 9 sequential colors.
.. seealso:: `<https://personal.sron.nl/~pault/#sec:sequential>`_
"""
# https://personal.sron.nl/~pault/
# as implemented by drmccloy here https://github.com/drammock/colorblind
assert 3 <= n <= 9
cols = ['#FFFFE5', '#FFFB... | d2ad5f8993f8c7dac99a577b6115a8452ad30024 | 3,626,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.