content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def partition(arr, left, right):
"""[summary]
The point of a pivot value is to select a value,
find out where it belongs in the array while moving everything lower than that value
to the left, and everything higher to the right.
Args:
arr ([array]): [Unorderd array]
left ([int]... | 30f1448861a7a9fa2f119e31482f1f715c9e1ce0 | 11,600 |
def graphatbottleneck(g,m,shallfp=True):
"""handles the bottleneck transformations for a pure graph ae, return g, compressed, new input, shallfp=True=>convert vector in matrix (with gfromparam), can use redense to add a couple dense layers around the bottleneck (defined by m.redense*)"""
comp=ggoparam(gs=g.s.gs,par... | b46967b40fce669c3e74d52e31f814bbf96ce8c0 | 11,601 |
def categorical_onehot_binarizer(feature, feature_scale=None, prefix='columns', dtype='int8'):
"""Transform between iterable of iterables and a multilabel format, sample is simple categories.
Args:
feature: pd.Series, sample feature.
feature_scale: list, feature categories list.
pre... | eb3a2b38d323c72bb298b64ebbd6567d143471fc | 11,602 |
import subprocess
import shlex
def mtp_file_list2():
"""
Returns the output of 'mtp-files' as a Python list.
Uses subprocess.
"""
cmd_str = "sudo mtp-files"
try: result = subprocess.check_output(shlex.split(cmd_str))
except subprocess.CalledProcessError as e:
log.error("Could not ... | 530ecea3ee8cd3c30e03c5554ea04f7c602d75fa | 11,603 |
def add_selfloops(adj_matrix: sp.csr_matrix, fill_weight=1.0):
"""add selfloops for adjacency matrix.
>>>add_selfloops(adj, fill_weight=1.0) # return an adjacency matrix with selfloops
# return a list of adjacency matrices with selfloops
>>>add_selfloops(adj, adj, fill_weight=[1.0, 2.0])
Paramet... | 867bdf380995b6ff48aac9741facd09066ad03bd | 11,604 |
def handle(event, _ctxt):
""" Handle the Lambda Invocation """
response = {
'message': '',
'event': event
}
ssm = boto3.client('ssm')
vpc_ids = ssm.get_parameter(Name=f'{PARAM_BASE}/vpc_ids')['Parameter']['Value']
vpc_ids = vpc_ids.split(',')
args = {
'vpc_ids': vp... | 8cf0dc52b641bd28b002caef1d97c7e3a60be647 | 11,605 |
def _get_indice_map(chisqr_set):
"""Find element with lowest chisqr at each voxel """
#make chisqr array of dims [x,y,z,0,rcvr,chisqr]
chisqr_arr = np.stack(chisqr_set,axis=5)
indice_arr = np.argmin(chisqr_arr,axis=5)
return indice_arr | 9ac00310628d3f45f72542dbfff5345845053acd | 11,606 |
import sys
def _train(params, fpath, hyperopt=False):
"""
:param params: hyperparameters. Its structure is consistent with how search space is defined. See below.
:param fpath: Path or URL for the training data used with the model.
:param hyperopt: Use hyperopt for hyperparameter search during trainin... | 2ed5d8c0a7f688f0babb187f3aee71c83f22b6f9 | 11,607 |
def noct_synthesis(spectrum, freqs, fmin, fmax, n=3, G=10, fr=1000):
"""Adapt input spectrum to nth-octave band spectrum
Convert the input spectrum to third-octave band spectrum
between "fc_min" and "fc_max".
Parameters
----------
spectrum : numpy.ndarray
amplitude rms of the one-sided... | 89c6be2be262b153bd63ecf498cf92cf93de9e31 | 11,608 |
def get_model_prediction(model_input, stub, model_name='amazon_review', signature_name='serving_default'):
""" no error handling at all, just poc"""
request = predict_pb2.PredictRequest()
request.model_spec.name = model_name
request.model_spec.signature_name = signature_name
request.inputs['input_in... | 6de7e35305e0d9fe9fe0b03e3b0ab0c82937778c | 11,609 |
def _make_feature_stats_proto(
common_stats, feature_name,
q_combiner,
num_values_histogram_buckets,
is_categorical, has_weights
):
"""Convert the partial common stats into a FeatureNameStatistics proto.
Args:
common_stats: The partial common stats associated with a feature.
feature_name: T... | 16b55556d76f5d5cb01f2dc3142b42a86f85bcb8 | 11,610 |
from typing import Optional
import requests
def serial_chunked_download(
d_obj: Download,
end_action: Optional[Action] = None,
session: Optional[requests.Session] = None,
*,
progress_data: Optional[DownloadProgressSave] = None,
start: int = 0,
end: int = 0,
chunk_id: Optional[int] = 0,... | 3307407f25e2d68700697953122ef08acd92f069 | 11,611 |
def get_device():
"""
Returns the id of the current device.
"""
c_dev = c_int_t(0)
safe_call(backend.get().af_get_device(c_pointer(c_dev)))
return c_dev.value | 4be37aa83bf822aac794680d9f30fe24edb38231 | 11,612 |
def plotLatentsSweep(yhat,nmodels=1):
"""plotLatentsSweep(yhat):
plots model latents and a subset of the corresponding stimuli,
generated from sweepCircleLatents()
---e.g.,---
yhat, x = sweepCircleLatents(vae)
plotCircleSweep(yhat,x)
alternatively,
plotLatents... | f43ffd9b45981254a550c8b187da649522522dd0 | 11,613 |
def calc_lipophilicity(seq, method="mean"):
""" Calculates the average hydrophobicity of a sequence according to the Hessa biological scale.
Hessa T, Kim H, Bihlmaier K, Lundin C, Boekel J, Andersson H, Nilsson I, White SH, von Heijne G. Nature. 2005 Jan 27;433(7024):377-81
The Hessa scale has been calcul... | a8858a62b3c76d466b510507b1ce9f158b5c8c9c | 11,614 |
def get_enrollments(username, include_inactive=False):
"""Retrieves all the courses a user is enrolled in.
Takes a user and retrieves all relative enrollments. Includes information regarding how the user is enrolled
in the the course.
Args:
username: The username of the user we want to retriev... | 0cbc9a60929fd06f8f5ca90d6c2458867ae474e7 | 11,615 |
async def connections_accept_request(request: web.BaseRequest):
"""
Request handler for accepting a stored connection request.
Args:
request: aiohttp request object
Returns:
The resulting connection record details
"""
context = request.app["request_context"]
outbound_handl... | 78a469d306c3306f8b9a0ba1a3364f7b30a36f85 | 11,616 |
def nearest(x, base=1.):
"""
Round the inputs to the nearest base. Beware, due to the nature of
floating point arithmetic, this maybe not work as you expect.
INPUTS
x : input value of array
OPTIONS
base : number to which x should be rounded
"""
return np.round... | ca1ddcd75c20ea82c18368b548c36ef5207ab77f | 11,617 |
def sort_nesting(list1, list2):
"""Takes a list of start points and end points and sorts the second list according to nesting"""
temp_list = []
while list2 != temp_list:
temp_list = list2[:] # Make a copy of list2 instead of reference
for i in range(1, len(list1)):
if list2[i] > ... | 11693e54eeba2016d21c0c23450008e823bdf1c1 | 11,618 |
def confusion_matrix(Y_hat, Y, norm=None):
"""
Calculate confusion matrix.
Parameters
----------
Y_hat : array-like
List of data labels.
Y : array-like
List of target truth labels.
norm : {'label', 'target', 'all', None}, default=None
Normalization on resulting matrix. Must be one of:
- 'l... | b1ed79b71cef8cdcaa2cfe06435a3b2a56c659dd | 11,619 |
def reroot(original_node: Tree, new_node: Tree):
"""
:param original_node: the node in the original tree
:param new_node: the new node to give children
new_node should have as chldren, the relations of original_node except for new_node's parent
"""
new_node.children = [
Tree(relation.l... | f37141fc7645dfbab401eb2be3255d917372ef11 | 11,620 |
import uuid
import time
def update_users():
"""Sync LDAP users with local users in the DB."""
log_uuid = str(uuid.uuid4())
start_time = time.time()
patron_cls = current_app_ils.patron_cls
patron_indexer = PatronBaseIndexer()
invenio_users_updated_count = 0
invenio_users_added_count = 0
... | 8aef4e258629dd6e36b0a8b7b722031316df1154 | 11,621 |
def opt(dfs, col='new', a=1, b=3, rlprior=None, clprior=None):
"""Returns maximum likelihood estimates of the model parameters `r` and `c`.
The optimised parameters `r` and `c` refer to the failure count of the
model's negative binomial likelihood function and the variance factor
introduced by each pre... | d40e63892676f18734d3b4789656606e898f69d9 | 11,622 |
import json
def unpackage_datasets(dirname, dataobject_format=False):
"""
This function unpackages all sub packages, (i.e. train, valid, test)
You should use this function if you want everything
args:
dirname: directory path that has the train, valid, test folders in it
dataobject_form... | d1748b3729b4177315553eab5075d14ea2edf3a7 | 11,623 |
from typing import Sequence
from typing import Tuple
import cmd
from typing import OrderedDict
def get_command_view(
is_running: bool = False,
stop_requested: bool = False,
commands_by_id: Sequence[Tuple[str, cmd.Command]] = (),
) -> CommandView:
"""Get a command view test subject."""
state = Comm... | 3eaf1b8845d87c7eb6fef086bd2af3b2dd65409a | 11,624 |
import os
def _split_by_size(in_fastq, split_size, out_dir):
"""Split FASTQ files by a specified number of records.
"""
existing = _find_current_split(in_fastq, out_dir)
if len(existing) > 0:
return existing
def new_handle(num):
base, ext = os.path.splitext(os.path.basename(in_fast... | 00fa4f99204b57da50f7ae12bc31a96100703048 | 11,625 |
def get_node_ip_addresses(ipkind):
"""
Gets a dictionary of required IP addresses for all nodes
Args:
ipkind: ExternalIP or InternalIP or Hostname
Returns:
dict: Internal or Exteranl IP addresses keyed off of node name
"""
ocp = OCP(kind=constants.NODE)
masternodes = ocp.g... | 622217c12b763c6dbf5c520d90811bdfe374e876 | 11,626 |
def fill_cache(msg="Fetching cache"):
"""Fill the cache with the packages."""
import os # pylint: disable=import-outside-toplevel
import requests # pylint: disable=import-outside-toplevel
from rich.progress import Progress # pylint: disable=import-outside-toplevel
all_packages_url = f"{base_url... | 113a55f73c1d8f3dd430b4e497aeae8045c9b255 | 11,627 |
def house_filter(size, low, high):
"""
Function that returns the "gold standard" filter.
This window is designed to produce low sidelobes
for Fourier filters.
In essence it resembles a sigmoid function that
smoothly goes between zero and one, from short
... | ef7f3fe3bb4410ce81fcd061e24d6f34a36f3a04 | 11,628 |
def PToData(inGFA, data, err):
"""
Copy host array to data
Copys data from GPUFArray locked host array to data
* inFA = input Python GPUFArray
* data = FArray containing data array
* err = Obit error/message stack
"""
################################################################... | 0f943a8340c2587c75f7ba6783f160d5d3bede76 | 11,629 |
import os
def download_vendor_image(image):
""" Downloads specified vendor binary image
Args:
image (str): Path of image filename to begin downloading
Returns:
"""
# TODO Prevent sending hidden files
return send_from_directory(os.path.join(_AEON_TOPDIR, 'vendor_images'), image) | 15926f4217539e40c6c3656792e4deb2094cca82 | 11,630 |
def maker(sql_connection, echo=False):
"""
Get an sessionmaker object from a sql_connection.
"""
engine = get_engine(sql_connection, echo=echo)
m = orm.sessionmaker(bind=engine, autocommit=True, expire_on_commit=False)
return m | 1296fa49058c8a583cf442355534d22b00bdaeea | 11,631 |
def test_auth(request):
"""Tests authentication worked successfuly."""
return Response({"message": "You successfuly authenticated!"}) | 59e065687333a4dd612e514e0f8ea459062c7cb3 | 11,632 |
def streak_condition_block() -> Block:
"""
Create block with 'streak' condition, when rotation probability is low and
target orientation repeats continuously in 1-8 trials.
:return: 'Streak' condition block.
"""
return Block(configuration.STREAK_CONDITION_NAME,
streak_rotations... | 769b0f7b9ce8549f4bea75da066814b3e1f8a103 | 11,633 |
def resolve_appinstance(request,
appinstanceid,
permission='base.change_resourcebase',
msg=_PERMISSION_MSG_GENERIC,
**kwargs):
"""
Resolve the document by the provided primary key
and check the optional permissio... | bb17c2a842c4f2fced1bce46bd1d05293a7b0edf | 11,634 |
def statementTVM(pReact):
"""Use this funciton to produce the TVM statemet"""
T,V,mass = pReact.T,pReact.volume,pReact.mass
statement="\n{}: T: {:0.2f} K, V: {:0.2f} m^3, mass: {:0.2f} kg".format(pReact.name,T,V,mass)
return statement | cda356678d914f90d14905bdcadf2079c9ebfbea | 11,635 |
def fill_NaNs_with_nearest_neighbour(data, lons, lats):
"""At each depth level and time, fill in NaN values with nearest lateral
neighbour. If the entire depth level is NaN, fill with values from level
above. The last two dimensions of data are the lateral dimensions.
lons.shape and lats.shape = (data.s... | cacde1f5a7e52535f08cd1154f504fb24293182e | 11,636 |
def transform_type_postorder(type_signature, transform_fn):
"""Walks type tree of `type_signature` postorder, calling `transform_fn`.
Args:
type_signature: Instance of `computation_types.Type` to transform
recursively.
transform_fn: Transformation function to apply to each node in the type tree
... | 9a6b493e2dd5f7edf1ab5a53d24141b1f269441d | 11,637 |
from resource_management.libraries.functions.default import default
from resource_management.libraries.functions.version import compare_versions
import json
def check_stack_feature(stack_feature, stack_version):
"""
Given a stack_feature and a specific stack_version, it validates that the feature is supported by ... | e7417738f285d94d666ac8b72d1b8c5079469f02 | 11,638 |
def get_random_action_weights():
"""Get random weights for each action.
e.g. [0.23, 0.57, 0.19, 0.92]"""
return np.random.random((1, NUM_ACTIONS)) | da929c6a64c87ddf9af22ab17636d0db011c8a45 | 11,639 |
import time
from datetime import datetime
def rpg_radar2nc(data, path, larda_git_path, **kwargs):
"""
This routine generates a daily NetCDF4 file for the RPG 94 GHz FMCW radar 'LIMRAD94'.
Args:
data (dict): dictionary of larda containers
path (string): path where the NetCDF file is stored... | d59a46c2872b6f82e81b54cfca953ebc0bc18a90 | 11,640 |
def load_ssl_user_from_request(request):
"""
Loads SSL user from current request.
SSL_CLIENT_VERIFY and SSL_CLIENT_S_DN needs to be set in
request.environ. This is set by frontend httpd mod_ssl module.
"""
ssl_client_verify = request.environ.get('SSL_CLIENT_VERIFY')
if ssl_client_verify != ... | ff716c139f57f00345d622a849b714c67468d7bb | 11,641 |
def get_all_users():
"""Gets all users"""
response = user_info.get_all_users()
return jsonify({'Users' : response}), 200 | f178c509afdae44831c1ede0cdfee39ca7ea6cec | 11,642 |
def open_mailbox_maildir(directory, create=False):
""" There is a mailbox here.
"""
return lazyMaildir(directory, create=create) | c19e5bf97da7adfe9a37e515f1b46047ced75108 | 11,643 |
def TANH(*args) -> Function:
"""
Returns the hyperbolic tangent of any real number.
Learn more: https//support.google.com/docs/answer/3093755
"""
return Function("TANH", args) | 1bb3dbe8147f366415cf78c39f5cf6df3b80ffca | 11,644 |
def value_frequencies_chart_from_blocking_rules(
blocking_rules: list, df: DataFrame, spark: SparkSession, top_n=20, bottom_n=10
):
"""Produce value frequency charts for the provided blocking rules
Args:
blocking_rules (list): A list of blocking rules as specified in a Splink
settings d... | e9160c9cd14ced1b904fad67c72c10a027179f7f | 11,645 |
def getOfflineStockDataManifest():
"""Returns manifest for the available offline data.
If manifest is not found, creates an empty one.
Returns:
A dict with the manifest. For example:
{'STOCK_1':
{'first_available_date': datetime(2016, 1, 1),
'last_available_date': ... | 40482daa96bf18a843f91bb4af00f37917e51340 | 11,646 |
def align_buf(buf: bytes, sample_width: bytes):
"""In case of buffer size not aligned to sample_width pad it with 0s"""
remainder = len(buf) % sample_width
if remainder != 0:
buf += b'\0' * (sample_width - remainder)
return buf | 9d4996a8338fe532701ee82843d055d6d747f591 | 11,647 |
import json
def update_alert():
""" Make Rest API call to security graph to update an alert """
if flask.request.method == 'POST':
flask.session.pop('UpdateAlertData', None)
result = flask.request.form
flask.session['VIEW_DATA'].clear()
alert_data = {_: result[_] for _ in resul... | 52248bda1271fbd39ab056c5384f6318e30cc712 | 11,648 |
def simulate_bet(odds, stake):
"""
Simulate the bet taking place assuming the odds accurately represent the probability of the event
:param odds: numeric: the odds given for the event
:param stake: numeric: the amount of money being staked
:return: decimal: the returns from the bet
"""
proba... | 0a56bc4b9a3071cc777786a1a7cf8b1410e3f941 | 11,649 |
from typing import OrderedDict
def lrcn(num_classes, lrcn_time_steps, lstm_hidden_size=200, lstm_num_layers=2):
"""
Args:
num_classes (int):
Returns:
torch.nn.modules.module.Module
"""
class TimeDistributed(nn.Module):
def __init__(self, layer, time_steps):
su... | a17f58906f4d5b514e56f5cba22ac60bdf739b9c | 11,650 |
import tokenize
def index_document(connection, doc_id, content):
"""对document建立反向索引"""
words = tokenize(content)
pipe = connection.pipeline(True)
for word in words:
pipe.sadd('idx:' + word, doc_id)
return len(pipe.execute()) | 89572980c0bfadef9e1557b7e7831fc7aebe6716 | 11,651 |
def get_incar_magmoms(incarpath,poscarpath):
"""
Read in the magnetic moments in the INCAR
Args:
incarpath (string): path to INCAR
poscarpath (string): path to POSCAR
Returns:
mof_mag_list (list of floats): magnetic moments
"""
mof_mag_list = []
init_mof = read(poscarpath)
with open(incarpath,'r') as in... | 6b75f415e7128213bab63d251a3fb6feb7576656 | 11,652 |
from utils.deprecations import deprecate_old_command_line_tools
import optparse
import sys
def main(config_path=None):
""" The main entry point for the unix version of dogstatsd. """
# Deprecation notice
deprecate_old_command_line_tools()
COMMANDS_START_DOGSTATSD = [
'start',
'stop',
... | 8c8a44f216c87aff87f20b504346e2713307bb4f | 11,653 |
import plistlib
def remove_report_from_plist(plist_file_obj, skip_handler):
"""
Parse the original plist content provided by the analyzer
and return a new plist content where reports were removed
if they should be skipped. If the remove failed for some reason None
will be returned.
WARN !!!!
... | fb14ccf1b0a1ad6b5e3b3e536e21386dbbcac84e | 11,654 |
def isTask(item): # pragma: no cover
"""Is the given item an OmniFocus task?"""
return item.isKindOfClass_(taskClass) | b0e2c813b29315e7b84cd9f2a4d211552dab9baf | 11,655 |
import os
def add2grouppvalue_real1():
"""
add2grouppvalue_real1
description:
Uses the raw data from real_data_1.csv to compute p-values for 2 group comparisons on a bunch of pairs of
groups and using all 3 stats tests
Test fails if there are any errors or if the shape of any of the f... | 291b2d4e7c72ff43e0b0fb8f67eea8819e384121 | 11,656 |
from typing import Tuple
import torch
def cox_cc_loss(g_case: Tensor, g_control: Tensor, shrink : float = 0.,
clamp: Tuple[float, float] = (-3e+38, 80.)) -> Tensor:
"""Torch loss function for the Cox case-control models.
For only one control, see `cox_cc_loss_single_ctrl` instead.
Arg... | 1f528ff25984e0bb09bc49edf59d793a44281ddb | 11,657 |
def vector_field(mesh, v):
"""
Returns a np.array with values specified by `v`, where `v` should
be a iterable of length 3, or a function that returns an iterable of
length 3 when getting the coordinates of a cell of `mesh`.
"""
return field(mesh, v, dim=3) | 2d82fa86bc76367e2668b37815c068097d88c6fa | 11,658 |
def is_fav_recipe(request):
"""
Handles the requests from /ajax/is_fav_recipe/
Checks if a :model:`matega.recipe` is a saved recipe for a :model:'matega.user'
**Data**
Boolean if :model:`matega.recipe` is a saved recipe for :model:'matega.user'
"""
user_id = int(request.GET.get('user_id', N... | f5ee3b21409f7a9ffe4ee427e19317f03b8db9c3 | 11,659 |
def people_interp():
"""
<enumeratedValueSet variable="People"> <value value="500"/> </enumeratedValueSet>
Integer between 1 and 500
"""
return f'<enumeratedValueSet variable="People"> <value value="%s"/> </enumeratedValueSet>' | 2aba1330a774e022c280d2e50e3fb63631989a88 | 11,660 |
import subprocess
import re
import os
def check_lint(path, lint_name="md"):
"""lint命令及检测信息提取,同时删除中间文档xxx_lint.md或者xxx_lint.py"""
error_infos = []
lint_ext = "_lint.md" if lint_name == "md" else "_lint.py"
check_command = "mdl -s mdrules.rb" if lint_name == "md" else "pylint -j 4"
if lint_name == "... | 554e8a8742822b334c65e70fb8187d4fd38b72da | 11,661 |
def through_omas_s3(ods, method=['function', 'class_method'][1]):
"""
Test save and load S3
:param ods: ods
:return: ods
"""
filename = 'test.pkl'
if method == 'function':
save_omas_s3(ods, filename, user='omas_test')
ods1 = load_omas_s3(filename, user='omas_test')
els... | f89bb1c31a9bcbae869d07313ab10a7df658fd1c | 11,662 |
def read_packages(filename):
"""Return a python list of tuples (repository, branch), given a file
containing one package (and branch) per line.
Comments are excluded
"""
lines = load_order_file(filename)
packages = []
for line in lines:
if "," in line: # user specified a branch
... | e73573003bd0388ed850fd2e996643a91199d30a | 11,663 |
import heapq
def find_min(x0, capacities):
"""
(int list, int list) --> (int list, int)
Find the schedule that minimizes the passenger wait time with the given capacity distribution
Uses a mixture of Local beam search and Genetic Algorithm
Returns the min result
"""
scores_and_schedules =... | 016cdd310f4b59e61349edd94b3b7cc387c3c7c1 | 11,664 |
def versioning(version: str) -> str:
"""
version to specification
Author: Huan <zixia@zixia.net> (https://github.com/huan)
X.Y.Z -> X.Y.devZ
"""
sem_ver = semver.parse(version)
major = sem_ver['major']
minor = sem_ver['minor']
patch = str(sem_ver['patch'])
if minor % 2:
... | bfef27712b8595f52314f300743012270a42e64f | 11,665 |
def freshdesk_sync_contacts(contacts=None, companies=None, agents=None):
"""Iterate through all DepartmentUser objects, and ensure that each user's
information is synced correctly to a Freshdesk contact.
May optionally be passed in dicts of contacts & companies.
"""
try:
if not contacts:
... | efa90bb449843472e0e65819b10845595398a4cc | 11,666 |
def device_create_from_symmetric_key(transportType, deviceId, hostname, symmetricKey): # noqa: E501
"""Create a device client from a symmetric key
# noqa: E501
:param transportType: Transport to use
:type transportType: str
:param deviceId:
:type deviceId: str
:param hostname: name of t... | 15ac85df5a41f88044cf449f0f9d99bfcd72d570 | 11,667 |
def create_with_index(data, columns):
"""
Create a new indexed pd.DataFrame
"""
to_df = {columns[0]: [x for x in range(1, len(data) + 1)], columns[1]: data}
data_frame = pd.DataFrame(to_df)
data_frame.set_index("Index", inplace=True)
return data_frame | f9bb854af5d77f4355d64c8c56a9fdda7bd2cf93 | 11,668 |
def random_aes_key(blocksize=16):
"""Set 2 - Challenge 11"""
return afb(np.random.bytes(blocksize)) | f5bfad117886e51bbb810274c62e44e89ec2c79a | 11,669 |
import json
import torch
def create_and_load(directory: str,
name: str,
new_name: str = None) -> nn.Module:
"""Instantiate an unkown function (uf) required
by the high-order functions with a trained neural network
Args:
directory: directory to the saved we... | 1ebf471fb624918b52953748a4f275b22aeaba1a | 11,670 |
def select_region_climatedata(gcm_name, rcp, main_glac_rgi):
"""
Get the regional temperature and precipitation for a given dataset.
Extracts all nearest neighbor temperature and precipitation data for a given set of glaciers. The mean temperature
and precipitation of the group of glaciers is retu... | 8e2c4bf8a942b4a21d5549e9af87bacb75f92f26 | 11,671 |
def get_patch_boundaries(mask_slice, eps=2):
"""
Computes coordinates of SINGLE patch on the slice. Behaves incorrectly in the case of multiple tumors on the slice.
:mask_slice: 2D ndarray, contains mask with <0, 1, 2> values of pixels
:eps: int, number of additional pixels we extract ar... | 0af985273b3e509bf9ee2580a64c8ddd6392d5a7 | 11,672 |
from typing import Union
from typing import List
def get_sqrt_ggn_extension(
subsampling: Union[None, List[int]], mc_samples: int
) -> Union[SqrtGGNExact, SqrtGGNMC]:
"""Instantiate ``SqrtGGN{Exact, MC} extension.
Args:
subsampling: Indices of active samples.
mc_samples: Number of MC-samp... | 47f074a387d0a6182d93061cbaaf4fc397be26c0 | 11,673 |
def gray_to_rgb(image):
"""convert cv2 image from GRAYSCALE to RGB
:param image: the image to be converted
:type image: cv2 image
:return: converted image
:rtype: cv2 image
"""
return cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) | feede538a2822d6d7f36bb6bbe40c845ca55808d | 11,674 |
def win_to_cygwin(winpath):
"""run `cygpath winpath` to get cygwin path"""
x = detail.command.run(['cygpath', winpath])
assert(len(x) == 1)
return x[0] | 1f941628fae51cfca7621c62c454e80d984f7019 | 11,675 |
def nucleotide_composition_to_letter(composition):
"""
Converts dictionary of {nucleotide letter: proportion} pairs
to IUPAC degenerate DNA letter.
Usage:
c = {'A': 1}
print(nucleotide_composition_to_letter(c)) --> 'A'
c = dict(zip('ACGT', [1, 1, 1, 1]))
print(nucleotide_composition_to... | 2ad080d3a04cfc754f46d490a272362cadecbfd2 | 11,676 |
def forcast(doc):
"""
:param: doc object
:returns: tuple with grade level, age level
"""
word_tokens = doc.word_tokens
monosyllables = 0
for i in word_tokens:
if i.isalpha() == False and len(i) < 2:
word_tokens.remove(i)
for i in word_tokens[10:159]:
if sylla... | e71debbdaf057c61eaa620419b0357e603868989 | 11,677 |
def convert_coordinates_to_country(deg_x: float, deg_y: float) -> str:
""" returns country name """
return geocoder.osm([deg_x, deg_y], method="reverse").country | 5dca9d54bfa154a33a94550f983a3e9457cf2d52 | 11,678 |
def fixture_items(test_list):
"""Returns an instance of ItemCollection for testing"""
return test_list.get_items(query=QUERY) | 6351ffdb9ce8a65d7a08d55c6cfa9db8ef4aa978 | 11,679 |
def numbers_lists_entry_widget(
list_param: list,
name: str,
expect_amount: int = -1,
expect_int: bool = False,
help=None,
) -> list:
"""
create a list text input field and checks if expected amount and type matches if set.
:param list_param: a list variable handled by this wiget
:pa... | c997089835eba0328100a638210b33aea0ca0507 | 11,680 |
def get_daily_discussion_post(subreddit_instance: praw.models.Subreddit):
"""Try to get the daily discussions post for a subreddit.
Args:
subreddit_instance
Returns:
The submission object for the discussion post, or None if it couldn't be found.
Works by searching the stickied posts of ... | 841612a8b2d2fa7a8a74f081e360a69884b20925 | 11,681 |
def metric_by_training_size(X, y, classifier_list, training_set, metric, as_percentage=True):
"""
This is a refactoriation of code to repeat metrics for best fitted models by training set percentage size.
i.e.: Find accuracy rating for multiple training-test splits for svm, random forests, and naive bayes a... | 3d918989b28db47479da3479b1804b7a502b9ce0 | 11,682 |
from typing import Optional
def apply_back_defence(
board: Board, opponent: Optional[Player] = None
) -> Optional[Action]:
"""
Move to intercept.
"""
player = board.controlled_player
ball = board.ball
if not opponent:
opponent = ball.player
if opponent.vector.x < 0:
... | 20af2f28a5d2c55c19c821fff218843d0ff69164 | 11,683 |
def remove_namespace(tag, ns):
"""Remove namespace from xml tag."""
for n in ns.values():
tag = tag.replace('{' + n + '}', '')
return tag | d4837a3d906baf8e439806ccfea76284e8fd9b87 | 11,684 |
def false_prediction_pairs(y_pred, y_true):
"""
Prints pairs of predicted and true classes that differ.
Returns
-------
false_pairs
The pairs of classes that differ.
counts
Number of occurences of the pairs.
"""
cond = y_pred != y_true
false_preds = np.stack([y_true[... | 460acb967b95d9e4c03e557e6bd1ede2dd7d0902 | 11,685 |
def draw_boxes_and_labels_to_image_multi_classes(image, classes, coords, scores=None, classes_name=None, classes_colors=None, font_color=[0, 0, 255]):
"""
Draw bboxes and class labels on image. Return or save the image with bboxes
Parameters
-----------
image : numpy.array
The RGB image [hei... | 5a11dd98019e5096c83137c43457a312598e2be8 | 11,686 |
import os
def route_open_file_dialog(fqname):
"""Return html of file structure for that parameter"""
# these arguments are only set when called with the `navigate_to` function on an already open
# file dialog
current_folder = request.args.get('current_folder')
folder = request.args.get('folder')
... | 22c3f5f1b43fd473e2e15a5da8c2c5d570fee372 | 11,687 |
def simulate():
"""
Runs a simulation given a context, a simulator, a trace, and a depth
Method PUT
"""
context = request.get_json()['context']
simulator = request.get_json()['simulator']
trace = request.get_json()['trace']
depth = request.get_json()['depth']
if context is None or si... | d905eb9fa34454588d4d1ab95794a6b9c41074ac | 11,688 |
def soft_expected_backup_rl(
next_q: Array,
next_pol: Array,
next_log_pol: Array,
rew: Array,
done: Array,
discount: float,
er_coef: float,
) -> Array:
"""Do soft expected bellman-backup :math:`r + \gamma P \langle \pi, q - \tau * \log{\pi}\rangle`.
Args:
next_q (Array): ? x... | fb1fed9946e05e4ad464f54c559be5e32c1f2e8e | 11,689 |
import os
from typing import OrderedDict
def readcal(calfile):
"""
This reads all of the information from a master calibration index and returns
it in a dictionary where each calibration type has a structured arrays that
can be accessed by the calibration name (e.g. 'dark').
"""
if os.path.ex... | ec2dc4531f9504695c3f4f65952510ccaa913944 | 11,690 |
import os
import sys
import subprocess
def global_attributes_dict():
# type: () -> Dict[str, str]
"""Set global attributes required by conventions.
Currently CF-1.6 and ACDD-1.3.
Returns
-------
global_atts: dict
Still needs title, summary, source, creator_institution,
produc... | 3dfcadeb7e17d969836966b1974bba092e5c00b8 | 11,691 |
def generate_bias(series: pd.Series, effect_size: float = 1, power: float = 1) -> pd.Series:
"""
Calculate bias for sensitive attribute
Parameters
----------
series : pd.Series
sensitive attribute for which the bias is calculated.
effect_size : float, optional
Size of the bias f... | a23a201dfeac8ed25cb923080f9c968d1a8a6583 | 11,692 |
def compress_coils(kspace,
num_output_coils=None,
tol=None,
coil_axis=-1,
matrix=None,
method='svd',
**kwargs):
"""Coil compression gateway.
This function estimates a coil compression matrix and uses i... | abb3a4ecd8c98a27fa0f8d4bc5a02567056fef2a | 11,693 |
def get_thellier_gui_meas_mapping(input_df, output=2):
"""
Get the appropriate mapping for translating measurements in Thellier GUI.
This requires special handling for treat_step_num/measurement/measurement_number.
Parameters
----------
input_df : pandas DataFrame
MagIC records
outp... | ba32104db56cfdb450015a0a43f0717263d5ea44 | 11,694 |
import time
def new_unsigned_vaccination_credential(
passenger_first_name: str,
passenger_last_name: str,
passenger_id_number: str,
passenger_date_of_birth: str,
vaccination_disease: str,
vaccination_vaccine: str,
vaccination_product: str,
vaccination_auth_holder: str,
vaccination_... | e3a072e1d16a3520a5bad92e692e5f4de72e8b1d | 11,695 |
def calc_pk_integrated_intensities(p,x,pktype,num_pks):
"""
Calculates the area under the curve (integrated intensities) for fit peaks
Required Arguments:
p -- (m x u + v) peak parameters for number of peaks, m is the number of
parameters per peak ("gaussian" and "lorentzian" - 3, "pvoigt" - 4, "... | d3ab50d6e6e5d2187917e06a8258a46ac5d4db18 | 11,696 |
def read_fid_ntraces(filename, shape=None, torder='flat', as_2d=False,
read_blockhead=False):
"""
Read a Agilent/Varian binary (fid) file possibility having multiple
traces per block.
Parameters
----------
filename : str
Filename of Agilent/Varian binary file (fid) ... | d82f341326d089dad9def8a95b4233cf4dde607d | 11,697 |
import typing
async def async_get_erc20_decimals(
token: spec.ERC20Reference,
block: typing.Optional[spec.BlockNumberReference] = None,
**rpc_kwargs: typing.Any
) -> int:
"""get decimals of an erc20"""
return await erc20_generic.async_erc20_eth_call(
function_name='decimals', token=token, ... | 665c9e697caffd9470c4f71769c8d215ce7d14a0 | 11,698 |
def get_game_log(game_id: int):
"""
Method used to get list of important events of macau game with given game id.
:param game_id: integer value of existing game
:return: list with string with all important events in game
"""
if game_id >= len(games_container):
return JSONResponse(content... | 837b43b24f747fabb819fe5eeb3e284694fd02a3 | 11,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.