content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def output_message(message, detail):
"""This function will output an error message formatted in JSON to display on the StatusBoard app"""
statusbar_output = {"graph": {"title": GRAPH_TITLE, "error": {"message": message, "detail": detail}}}
output = json.dumps(statusbar_output)
return outpu... | 1d68c8507b1102a0f317f13a6a8d7cce7a51d91f | 3,600,005 |
def get_techs_yaml_set(scenario_id, year):
""" Function pulls tech parameters from Database for YAML """
loc_techs = Scenario_Loc_Tech.objects.filter(scenario_id=scenario_id)
tech_ids = list(loc_techs.values_list('loc_tech__technology',
flat=True).distinct())
pa... | c09c9673302fe45873fb4e5933dc33e9b1720a22 | 3,600,006 |
def findT1(lost, gained):
"""Find T1-like events: lost and gained edges that intersect.
Works on output of changedEdges_fast(). Returns a pair of arrays,
where each pair of elements indexes 'lost' and 'gained', respectively,
identifying the 2 edges associated with a T1 event.
"""
# Make a line... | f36cf60788ac347845ecc2e12ba214b1255cee4c | 3,600,007 |
def calculate_direct_qs(q0, sD, k):
"""This function computes the source-to-hr pressure as
described in Var der Aa (2010) eqs 2.25 in page 18.
Parameters
----------
q0 (float): Initial source stength (pressure) (Pa)
sD (float): Distance from source to HR centers (m)
k (float): wavenumbe... | 979c804583f02639ac7fc3df57b4269a2c05ee69 | 3,600,008 |
def dup_prem(f, g, K):
"""Polynomial pseudo-remainder in `K[x]`. """
df = dup_degree(f)
dg = dup_degree(g)
r = f
if not g:
raise ZeroDivisionError("polynomial division")
elif df < dg:
return r
N = df - dg + 1
lc_g = dup_LC(g, K)
while True:
dr = dup_degree... | f74f4defec9128dca1c57b83a61a2cbaa047f3c9 | 3,600,009 |
def rotate_crop(image, angle):
"""Rotate the given image counterclockwise by the specified angle (degrees), removing whitespace."""
# Based on Adrian Rosebrock's imutils (https://www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/)
# Get image dimensions
h, w = image.shape[... | 32478dd1038de75b681a13049601934d6a81ecf0 | 3,600,010 |
def body_ortho_3 (size):
"""Generates symmetry preserving HNF's of a given size
for a body centered orthogonal basis
Args:
size (int): The determinate of the HNF matricies
Returns:
list (int): The generated HNF matricies
"""
symHNF = []
diags = find_HNF_diagonal(size)
... | 92c3f53d6bb983d4db953670c516150b08b7add8 | 3,600,011 |
import re
def storage_blob_containers_list(client, args):
"""
Gets a blob container if an container name is specified, and a list of blob containers if not.
Args:
client: The microsoft client.
args: The users arguments, (like account name, container name).
Retu... | 66eeea605f2a430e8bc1e9a6c3ef230fc3acd0a7 | 3,600,012 |
def link_id_confirm(upload_id, sample_id):
"""
Confirm link for upload id and sample id.
:param upload_id: upload id
:type upload_id: int
:param sample_id: sample id
:type sample_id: int
:raises QueuedSampleNotFoundException: when upload id is not found
:return: redirect to index
:r... | 6d2db418dd513a2a6bfe7126287d459c2b50c90c | 3,600,014 |
def flatten(iterable):
"""
Extracts nested file items from path
to single iter.
"""
return iterable
# Os walk with absolute path returns
# non-nested
#
# return [item for it in iterable for item in it] | c0b53c44c12a9307c62ce8cb54d5214b2648388f | 3,600,015 |
import logging
def keyword_prediction(key, input_dir, monitor, normal, fake=False, args=None):
"""Predict batches for given keyword
Args
----
key : str
target keyword to predict
input_dir : str
root directory to load data
monitor : nnet.NeuralNetworkManager
neural netw... | 0fb4bb0f4482f3f88d150e085c26dd49d67bd6e2 | 3,600,016 |
def measure_resonator_pulse_with_scope(
daq,
device_id,
channel,
trigger_input,
pulse_length_seconds,
envelope_delay=0,
margin_seconds=400e-9,
):
"""Uses the scope to measure the pulse used for probing the resonator in pulsed spectroscopy.
NOTE: this only works if the device under te... | 89353be56fd60bd13b3efaca2e535f9ecf506409 | 3,600,017 |
def unzscore(mat, unzvals):
"""Un-Z-scores the rows of [mat] by multiplying by unzvals[:,0] (the standard deviations)
and then adding unzvals[:,1] (the row means).
"""
unzmat = np.empty(mat.shape)
for ri in range(mat.shape[0]):
unzmat[ri,:] = mat[ri,:]*(1e-10+unzvals[ri,0])+unzvals[ri,1]
... | 1a6e84b4cc2b48329b65fd6207057cbc641d594b | 3,600,018 |
import re
def get_restriction_period(text: str) -> int:
"""
Extract restriction period (in seconds) from text using regex search
:param text: text to parse
:return: restriction period in seconds (0 if nothing found, which means permanent restriction)
"""
multipliers = {"m": 60, "h": 3600, "d"... | 52e2e4828f916f885c229083f6833744db004719 | 3,600,020 |
def SumBasket(self):
"""Compute sum(n) for node n"""
return unary(self, "sum({})".format(self._name_no_id), (lambda x: sum(x))) | 73f6ad3427d8b39345a93f36dea9653c33655b12 | 3,600,021 |
def load_lcd(**kwargs):
"""
::
Size: (104,3)
Example:
C T group
0 0 1 alluvial_fan
1 0 1 alluvial_fan
2 0 1 alluvial_fan
3 0 1 alluvial_fan
4 1 1 alluvial_fan
"""
return _load_dataset("CuZ... | 7d45c32dd5ffae38d157b994b780b95f3e6e72c4 | 3,600,022 |
def broadcastFuncForFindNearestNPickDepth(
df_new_cleaned_plus_nn, pickColInt, newPickColName, UWI_col
):
"""
Takes in:
Returns:
"""
df = df_new_cleaned_plus_nn
#### For each row in dataframe,
df[newPickColName] = np.nan
print(df.iloc[0:1][newPickColName])
for eachRow in range(l... | f9f7db8e7ab7efe8279939573df2b66ad77ac4f0 | 3,600,023 |
def bounding_box(ptlist):
"""
Returns the bounding box for the list of points, in the form
(x1, y1, x2, y2), where (x1, y1) is the top left of the box and
(x2, y2) is the bottom right of the box.
"""
xs = [pt[0] for pt in ptlist]
ys = [pt[1] for pt in ptlist]
return (min(xs), max(ys), ma... | cd27b3e5783ee7dd8c5960389079b32768516e4d | 3,600,024 |
from typing import Iterable
async def get_cloud_sql_entity(ctx: Context, project_id: str, svc_def: GCPService) -> Iterable[Entity]:
""" Retrieve entity info on GCP Cloud SQL from google api. """
url = f"https://sqladmin.googleapis.com/sql/v1beta4/projects/{project_id}/instances"
mapper_func = partial(_clo... | 9cee351ef302e5cf90e540c4a0922197bdabc528 | 3,600,025 |
def goodreads(soup):
"""
Read the book titles from the image alt text.
"""
tags = soup.find_all(lambda x: x.next_element.name ==
'img' and '/book/show/' in x.get('href', ''))
titles = set(map(lambda x: x.img.get('alt').strip(), tags))
return titles | b2385a8778711661f7ead88cc9357663dce38e32 | 3,600,026 |
def s3_components(url: str) -> tuple:
"""Returns a tuple with the S3 bucket, key, and file names parsed from the S3 URL.
Note: the url should be a valid S3 url. For example ::
s3://bucket-name/full/path/data.nc
In this case, the function will return the tuple:
('bucket-name', 'full/path'... | 88e4e54854c484c1f3a1785a1f3c61698bc13fd4 | 3,600,027 |
def plib_GetPoles(*args):
"""
* Get from FP the coordinates of the poles.
:param FP:
:type FP: TColStd_Array1OfReal &
:param Poles:
:type Poles: TColgp_Array1OfPnt
:rtype: void
* Get from FP the coordinates of the poles.
:param FP:
:type FP: TColStd_Array1OfReal &
:param Pol... | c04d38f59478deeb2e5d559cbc73b796ca5e0903 | 3,600,028 |
def compute_direct_std(vcm_direct_hat, model_dat):
"""compute direct effects standard deviations from direct effects covariance matrix"""
direct_std = diag(vcm_direct_hat) ** (1 / 2)
mx_std, my_std = utils.directmat_alg(direct_std, model_dat["idx"], model_dat["idy"])
return mx_std, my_std | f60feafd58e285638fb74e8b353970cd189a5e09 | 3,600,029 |
def eamap_free(*args):
"""
eamap_free(map)
Delete eamap_t instance.
@param map (C++: eamap_t *)
"""
return _ida_hexrays.eamap_free(*args) | 32bfcf3b8dc89e4df0f9993d05c3cc4dd1c86af7 | 3,600,030 |
def is_good(filename: str, force: bool = False) -> bool:
"""
Verify whether a file is good or not, i.e., it does not need
any shape or illumination modification. By default a file is
good if it is a pdf.
Parameters
----------
filename
The file name.
force
Wether to forc... | acaee589288db3eb48bd7bc89dc21c0a7d75822c | 3,600,031 |
import requests
def get_vcdr_pg_snap_details_json(strVCDRProdURL, cloud_fs_id, pg_id, snap_id, session_token):
"""Get Protection Group Snapshot Details - Get detailed information for a protection group snapshot."""
myHeader = {'x-da-access-token': session_token}
myURL = f'{strVCDRProdURL}/api/vcdr/v1alpha... | df6cd7833e2345845cf14ccfb8a52299fe7f478a | 3,600,032 |
from pathlib import Path
from typing import List
import copy
def create_sample_test_dir_if_needed(
dst: Path = Path("../../data/testing/raw"),
) -> List[Path]:
"""Creates samples for a test set"""
dst.mkdir(parents=True, exist_ok=True)
if len(list(dst.glob("*"))) == 0:
files = get_one_image_fo... | e4f3d303b9cfa51be71bb864129217524334583a | 3,600,033 |
def lists_to_matrix(G):
"""takes a graph represented by a vertex set and adjacency lists and returns
an adjacency matrix as list of lists
test with function test2()"""
V, E, directed = G
#initialize matrix
M = []
x=0
for ele in V:
M.append([0]*len(V))
for i in V:
... | ec2da97b40c13885ebd58c62172d73c5c9b16917 | 3,600,034 |
def StdDed( DSI, _earned, STD, e04470, e00100, e60000,
MARS, MIDR, e15360, AGEP, AGES, PBI, SBI, _exact, e04200, e02400, STD_Aged,
c04470, c00100, c21060, c21040, e37717, c04600, e04805, t04470,
f6251, _feided, c02700, FDED, II_rt1, II_rt2, II_rt3, II_rt4, II_rt5, II_rt6, II_rt7,
... | bf6afaeb3fb35c07a14b88b14590f249c344e91c | 3,600,035 |
def customizations(record):
"""Use some functions delivered by the library
:param record: a record
:returns: -- customized record
"""
record = bc.convert_to_unicode(record)
record = bc.type(record) # lowercase
record = bc.author(record)
record = bc.editor(record)
record = bc.jou... | d4d5bd43bfb6cbf495e13bc9485ec09c33235fd7 | 3,600,037 |
def patched_repo_get_default_identity(original_repo_get_default_identity):
""" Allow to run without valid identity """
def patched_function():
try:
return original_repo_get_default_identity()
except: # pylint: disable=W0702
return ("Git User", "git@localhost")
return... | 99049874102efbec318b4ba0f23e7a8732695665 | 3,600,038 |
def discovery(request):
"""
defined in Core API Specification 7
:type request: pyramid.request.Request
:rtype: dict
"""
resp = request.response
resp.content = """\
<XRDS xmlns="xri://$xrds">
<XRD xmlns:simple="http://xrds-simple.net/core/1.0" xmlns="xri://$XRD*($v*2.0)" version="2.0">
... | c8ffad72903ab13298fc71f150f20c2e7dd47136 | 3,600,039 |
def im2col_indices(x, field_height, field_width, padding=1, stride=1):
# from cs231n assignments
""" An implementation of im2col based on some fancy indexing """
# Zero-pad the input
p = padding
x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant')
k, i, j = get_im2col_indices... | f599eade6bed33faf053422dbae6b81720ab2cf6 | 3,600,040 |
from typing import Any
def run_notebooks(taskConfiguration: dict) -> Any:
"""
Runs Notebooks Tasks
Parameters
----------
taskConfiguration : dict
A task definition to execute.
notebooks : lst
A list of notebook task definition to run.
notebookName : str
... | 8c5bbbbba881cca7efbeebbdebd9fb160194e861 | 3,600,041 |
def get_token(callback_url):
"""
Retrieve the OAuth token from the server based on the authorization code in the callback_url.
This function returns the access token, and it sets the upapi.credentials object.
:param callback_url: the URL on your server that Jawbone sent the user back to
:return: a ... | a4d122212089de24997cb7934cd3f5e81e57c2d4 | 3,600,042 |
def requires_parallel(task):
"""
Returns True if given ``task`` should be run in parallel mode.
Specifically:
* It's been explicitly marked with ``@parallel``, or:
* It's *not* been explicitly marked with ``@serial`` *and* the global
parallel option (``env.parallel``) is set to ``True``.
... | dc2784adaf2cfdb4c2fa8972f191d6aa1e8e32e7 | 3,600,043 |
def extract_x_y(polygon: list) -> (list, list):
"""Extract the x and y coordinates as two separate lists"""
x_list = []
y_list = []
for vertex in polygon:
x_list.append(vertex[X_COORDINATE])
y_list.append(vertex[Y_COORDINATE])
return (x_list, y_list) | f0632ec8ab7e95c6a2b8e07f3ddf6c4f8ab47ee4 | 3,600,044 |
def copy_or_link_file(source, target, options):
"""copies, links, or converts an image file."""
# looks at options.link and options.update
global _supports_macostools
try:
if options.size:
mode = " (convert)"
elif options.link:
mode = " (link)"
else:
... | 0fadb8abe7a20ff7aad3e4dcbbcd5f73fb5e746e | 3,600,045 |
from typing import Sequence
from typing import Tuple
def touch_position_to_pixel_position(
touch_position: np.ndarray,
width_height: Sequence[int],
) -> Tuple[int, int]:
"""Maps touch position in [0,1] to the corresponding pixel on the screen."""
touch_pixels = (touch_position * width_height).astype(np.in... | 8af4356d663b69ccebd93cfe8a716e1a4da3ef1b | 3,600,046 |
def get_models_from_table_ids(table_ids, force=None):
"""
Convert list of table ids to table model classes.
"""
models = []
errors = []
for table_id in table_ids:
try:
models.append(
get_model_from_table_id(table_id)
)
except (
... | cfde380feb71ef38776a996baf9ad125898753d1 | 3,600,047 |
import logging
def get_indexers_from_1d(cond):
"""
Get indexers from a dataset with 1 dimension.
Parameters
----------
cond : xarray.Dataset
Contains the result of the initial lat lon condition.
Returns
-------
dict
Indexer dictionary for the provided condition.
"... | fc6a14e31e5417df4bdacc87137ceb0ccd5d0c46 | 3,600,048 |
def mn_amp_rms(syllable):
"""
Parameters
----------
syllable : syllable object
Returns
-------
root_mean_squared : scalar
square root of value returned by mn_amp_smooth_rect
"""
return np.sqrt(mn_amp_smooth_rect(syllable)) | 09cb62bfb506a14eed3adae7550c27fecf6c0050 | 3,600,049 |
def cifar10_vgg19(num_classes, initial_sparsity_conv=0.95, initial_sparsity_fc=0.95, sub_kernel_granularity=4, sparse=True):
"""VGG 19-layer model (configuration "E")"""
return VGG(num_classes, initial_sparsity_conv=initial_sparsity_conv, initial_sparsity_fc=initial_sparsity_fc, sub_kernel_granularity=sub_kerne... | 1d67376192f70a118ba9d23e969b68e07a1f779a | 3,600,051 |
def xtimeGetYear(xtime):
"""Get an array of years from an xtime array, ignoring any partial year information"""
# First parse the xtime character array into a string
xtimestr = netCDF4.chartostring(xtime) # convert from the character array to an array of strings using the netCDF4 module's function
years = np.ze... | 45ed460593c46f84070528d70d03ccc62e108f12 | 3,600,052 |
def eta(x, w, gamma):
"""matrice de taille n,t"""
gamma = gamma.reshape(1,-1)
n = x.shape[0]
#print("Yo")
#print(np.dot(x,w) - gamma )
return 1/(1+np.exp(-np.dot(x,w) - gamma )) #+ 1*np.ones(gamma.shape) | f588a9ec4dceb226d187f16d032e95fbe4dee2ca | 3,600,053 |
from re import U
def _tabular_model(
name,
train_data,
multilabel=None,
is_regression=False,
metrics=["accuracy"],
hidden_layers=[1000, 500],
hidden_dropouts=[0.0, 0.5],
bn=False,
verbose=1,
):
"""
```
Build and return a classification or regression model for tabular da... | 5683dc442c30204fc450d708a956944b014016c0 | 3,600,054 |
def reshape_like_all_dims(a, b):
"""Reshapes a to match the shape of b."""
ret = tf.reshape(a, tf.shape(b))
if not tf.executing_eagerly():
ret.set_shape(b.get_shape())
return ret | e44d97a26228a3141b58144679c79667bd1160c0 | 3,600,055 |
import torch
def pop_feature(input_, feat_idx):
"""Pops out the feature at idx feat_idx in the last dimension of the list of tensors or tensor."""
if not isinstance(feat_idx, list):
feat_idx = [feat_idx]
# Get indices of features to keep:
idcs = list(filter(lambda x: x not in feat_idx,
... | 945f73a957838fb52e74c862bf51d8494c479937 | 3,600,056 |
def release_resource(res_type, resource_id):
"""释放资源
:param res_type: 资源类型
:type res_type: str
:param resource_id: 资源ID
:type resource_id: str
"""
return _current_resmgr_session().release_resource(res_type, resource_id) | 4c8518392a502d2d7c9c81b47567faf02ad03f64 | 3,600,057 |
def load_drivers(namespace,names,conf):
"""
return:
{
'zk',zkcli
'redis': rediscli
}
"""
LOG.info("Start load drivers: %s, namespace: %s" % (names,namespace))
drivers = dict()
extensions = named.NamedExtensionManager(
namespace = namespace,
... | 7200408f02dfacb152f3e5217f98f5b112cd6113 | 3,600,058 |
def green_diff(s: str) -> str:
"""green_diff(s) is deprecated.
"""
return colorama.Fore.RESET + colorama.Back.GREEN + colorama.Style.BRIGHT + s + colorama.Style.NORMAL + colorama.Back.RESET + colorama.Fore.GREEN | c09ff7ee13bc25e6f231b837f772c8984b3106d4 | 3,600,059 |
from typing import Dict
from typing import Type
from typing import Tuple
def find_isinstance_check(node: Node,
type_map: Dict[Node, Type],
weak: bool=False) -> Tuple[Node, Type, Type, int]:
"""Check if node is an isinstance(variable, type) check.
If success... | 225640ba5112c1020ba0c29aed60126f080297ea | 3,600,060 |
def AsyncAutoProxy(token, serializer, manager=None, authkey=None,
exposed=None, incref=True):
"""Return an auto-proxy for `token`."""
_Client = listener_client[serializer][1]
if exposed is None:
conn = _Client(token.address, authkey=authkey)
try:
exposed = dis... | 5bbde3c8a309f3e18f37763cc1c5414a3aa7eba8 | 3,600,061 |
def extract_top_level_dict(current_dict):
"""
Builds a graph dictionary from the passed depth_keys, value pair. Useful for dynamically passing external params
:param depth_keys: A list of strings making up the name of a variable. Used to make a graph for that params tree.
:param value: Param value
:... | 11c3a0dc2582bebff5114bd2963c790f3dd7f630 | 3,600,062 |
def collaborate_document(writer, maxlines=14):
"""Creates a single document by collaboration between human and model
Inputs
writer: Writer object for automated text generation
Returns the created collaboration.
"""
print("Human, let's write a new composition! You start:\n\n")
token = N... | 777a56e745f13d3fc3abe952242221d17e32577d | 3,600,063 |
def filter_submissions_with_querystring(submissions_queryset, query_string):
"""Filters a FormSubmission queryset based on a query_string
"""
return submissions_queryset.filter(
Q(first_name__icontains=query_string) |
Q(last_name__icontains=query_string) |
Q(ssn__icontain... | c948765a49f094e7bc9285e109d7abcdb9a6fda6 | 3,600,064 |
def get_estimation(data_format):
"""
Endpoint that can take the input data and
return the estimation for it.
It returns a json format as default or xml format
if provided as part of the url.
"""
data = request.get_json()
region_data = get_region_data(data)
try:
cleaned_data =... | 5b5eda0c03bdbb9ec2512b8a28e2988ebf2367d6 | 3,600,065 |
def ignore_unknown_attribs(maybe_cls = None, converter=None):
"""Register a "tolerant" cattr.structure overload for the classk."""
def bound(cls):
_register_ignore_unknown_attribs(cls, converter = converter)
return cls
if maybe_cls:
return bound(maybe_cls)
else:
return b... | c7c457865d33614067e09877af76c6f8755bf283 | 3,600,066 |
def api_test_researcher_study_access(block_test_studies: bool) -> (Study, Researcher):
""" Checks whether the researcher is allowed to do api access on this study.
Parameter allows control of whether to allow the api call to hit a test study. """
study = api_get_study_confirm_exists()
researcher = api_g... | 0679ff365cecbb76d3e37bc33181fe9864671344 | 3,600,067 |
def is_id_start(s):
"""
Checks if all characters in `s` are alphabetic characters (Unicode standard, so diacritics, indian vowels, non-latin
numbers, etc. all pass). Synonymous with a Python `ID_START` identifier. See PEP 3131 for details.
"""
return _test_unicode_category(s, _ID_START) | 7b4e8cc9530866c49aa470545376e3f366d89e81 | 3,600,068 |
import logging
import json
from functools import reduce
def make_dataframe2(json_results):
"""This function creates a meta data frame to be used for
post-processing the multinode benchmark Results.
Args:
json_file (file): json file to be used for creating a dataframe
Returns:
meta_df... | b439e86ee8995c7d8ab647867fe2e0699c7ade77 | 3,600,070 |
from datetime import datetime
def sign(hostname, path, region, credentials):
"""
Provides a SigV4 signature for a CodeCommit url.
:param str hostname: aws hostname request is for
:param str path: resource the request is for
:param str region: region the repository resides within
:param botocore.credentia... | 3f623357a78b2d3c99f20116a635ceb7dce315f6 | 3,600,071 |
def findPoints(listofps, allpoints, Anti = False):
"""
Check if point is in the list
Depends on 'Anti' arg
for False value: looks for vacancies
True value: looks for atoms
allpoints list is transposed in this function
"""
for ps in listofps:
indx = findindex(ps,allpoint... | 2a5c2deaa429f00b3181fd1daa501f41c69a9a98 | 3,600,072 |
def run_commands(env, work_dir, commands, process_start, process_finish):
"""Run commands in separate processes."""
code = 0
errors = None
for cmd in commands:
print("Running command:", cmd)
code, errors = run_process(
cmd,
process_start=process_start,
... | ef919f5e19fbb999de4a1b88e38562b7e0f501b3 | 3,600,073 |
def onoff(value):
"""Display Boolean as Font Awesome Icon Icon darstellen.
We use Font Awesome `toogle-on <http://fontawesome.io/icon/toggle-on/>`_
and `toogle-of <http://fontawesome.io/icon/toggle-off/>`_ to indicate state.
"""
if value:
return Markup('<i class="fa fa-toggle-on" aria-hidde... | 047516c00ee3a8d2139e718b5252d305d77ebe3c | 3,600,074 |
def ticks_per_bar_division(res, **kwargs):
"""
Resolution and Time Signature to Ticks Per Measure
Converts a resolution and time signature to ticks per beat
if raw=1 the the denominator of the tsig is in the python-midi format
i.e. a negative power of 2: 2 = quarter, 3 = eight notes etc...
The ... | b7c55cc85a58037f17cbcb402bf1f02c201007b7 | 3,600,075 |
def binary_mask_to_polygon(binary_mask, tolerance):
"""Converts a binary mask to COCO polygon representation
Args:
binary_mask: a 2D binary numpy array where '1's represent the object
tolerance: Maximum distance from original points of polygon to approximated
polygonal chain. If tole... | 3b4a8983eecf2454b19d1dd09b9925f26e0cb50d | 3,600,076 |
import platform
def is_windows():
"""是否Windows操作系统"""
return 'Windows' in platform.system() | 5d0820d442668ad42fbc3253664be8a67f508159 | 3,600,077 |
import ctypes
def xrtDeviceLoadXclbin(handle, buf):
"""
xrtDeviceLoadXclbin(): Load an xclbin image
:param handle: XRT device handle
:param buf: Pointer to complete axlf in memory image
:return: 0 on success or appropriate error number
"""
libcoreutil.xrtDeviceLoadXclbin.restype = ctypes.... | 6b5654a4a2de241e2e599f5e256ab48cd787819d | 3,600,078 |
import numba
def tensor_reduce(fn):
"""
CUDA higher-order tensor reduce function.
Args:
fn: reduction function maps two floats to float.
out (array): storage for `out` tensor.
out_shape (array): shape for `out` tensor.
out_strides (array): strides for `out` tensor.
... | 5dfc6913aa11d73d0ea3bbba3b549b090c7a9158 | 3,600,079 |
import threading
import functools
def load_data_frame(X_data, y_data, batch_size=128, shuffle=False):
"""
For low RAM this methods allows us to keep only the original data
in RAM and calculate the features (which are orders of magnitude bigger
on the fly). This keeps only 10 batches worth of features ... | c054bf970e66f2f1219d008af4cad71857d25352 | 3,600,080 |
def arg_parser():
"""Arg parser"""
parser = ArgumentParser()
parser.add_argument('--project', metavar='DIR', help='path to projects')
parser.add_argument('--projectname', metavar='DIR', help='name projects')
parser.add_argument('--pathdataset', metavar='DIR', help='path to dataset')
p... | 07dc1b2f1c05fa979f9f3583e7fb3a4faa7ce5f7 | 3,600,081 |
def create_df_from_s3(bucket='re-raw-data'):
"""
Wrapper to collect and append DataFrames from an s3 bucket
:param bucket: Name of the s3 bucket
:return: Compiled DataFrame from the s3 bucket
"""
s3 = boto3.client('s3',
region_name='us-east-1',
aws_acc... | 92b57b03bac8bde1861f609fdcf8021faf060b98 | 3,600,082 |
def migration_one_station_stack(stream, method="PWS", power=2, time_range=[8, 16], coeff=0.5):
"""
Stacking of migrated traces for one station. Currently not used.
:param stream:
:param method: "PWS" for phase-weighted stacking and "linear" for linear stacking
:param power: used by "PWS" only. powe... | 4a6dedd2801be51c55f10af646721a77f2bd5910 | 3,600,083 |
def losses(logits, labels):
"""Calculates losses from the logits and the labels.
Args:
logits: input tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size].
Returns:
losses: list of loss tensors of type float.
"""
xentropy = tf.nn.sparse_softma... | 542485ecc973ec93f67b8f1b0d81dd8f9168a574 | 3,600,084 |
def removeBG(image: Image.Image):
"""Remove the background from an image or a layeredimage.
Args:
image (Image.Image|layeredimage.layeredimage.LayeredImage): An image or a layered
image
Returns:
Image: image without bg
"""
if isinstance(image, Image.Image):
return findAndReplace(image, getSortedColours(i... | c24a2583544315000baa804c1f0308fea2b49dbf | 3,600,085 |
def filter_letters(letter_strings):
"""Used to take a list of letters like ["A","ABC","AB"] and filter out any duplicate letters."""
# There is probably a cute one liner, but this is easy to follow and
# probably same speed
unique_letters = set()
if isinstance(letter_strings, str):
letter_strings = [lette... | 2e999fa53d850e18f4fdcd9e69144fccd844c6c4 | 3,600,086 |
from typing import cast
def get_alembic_version() -> AlembicVersion:
"""
Fetches the alembic version at head from the database
"""
db = db_session.get_db_read_replica()
with db.scoped_session() as session:
version = session.execute(
sqlalchemy.text(
"""
... | e3bc2b2fee62fcc058c4841a4d63d051d96796d5 | 3,600,087 |
def home(request):
""" Uses index.html to display a list of all the user's tags """
ctx = {}
ctx["area"] = "tags"
ctx["tags"] = make_page(Tag.by_user(request.user), request.GET.get("p"))
ctx["untag_count"] = Bookmark.by_user(request.user).filter(tags=None).count()
return TemplateRespon... | 68e131023b541a654ba354814397cae800995a48 | 3,600,088 |
import io
def getByIDOld(identifier):
"""
Retrieves the object that has the given identifier from the Redis database.
That is, given an identifier, retrieves the contents from the backend
that correspond to this key, deserializes it and returns the reconstructed
object.
"""
logger.warn(HEA... | dc64df85490084c8ae81c9c6ce306ee07f05b311 | 3,600,089 |
def PCA(X: np.ndarray, correlation: bool=False, sort: bool=True) -> tuple:
"""
Perform PCA on the input data
Parameters
----------
`X` (`np.ndarray`): input data
`correlation` (`bool`): differentiate between using `np.cov()` or `np.corrcoef()`, `False` for `np.cov()`
`sort` (`bool`): if s... | 6fb8916434c7368acd7555b53aa94e7bd90189e9 | 3,600,090 |
def computeJeffreysPriorAR1(study, t=1):
"""
This function encodes the Jeffreys prior for the AR1 process as derived by Harald Uhlig in the work "On Jeffreys
prior when using the exact likelihood function." (Econometric Theory 10 (1994): 633-633. Equation 31). Note that
only the case of abs(r) < 1 (stat... | 2875d3a0667ac8a4457e49120e8fd7a019b9285e | 3,600,091 |
from pypy.module.cppyy import interp_cppyy
def ttree_Branch(space, w_self, args_w):
"""Pythonized version of TTree::Branch(): takes proxy objects and by-passes
the CINT-manual layer."""
tree_class = interp_cppyy.scope_byname(space, "TTree")
# sigs to modify (and by-pass CINT):
# 1. (const char*... | 585fd064006f46f499ac8fc28dbe4096e68c8d0f | 3,600,092 |
def zero_pad(X, pad):
"""
Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image.
Argument: X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images
pad -- integer, amount of padding around each image on vertical ... | 175b4979bd8ec5bb1203d76f3fc09aabb36b6f15 | 3,600,093 |
def get_agent_rule_str(agent):
"""Construct a string from an Agent as part of a PySB rule name."""
rule_str_list = [_n(agent.name)]
# If it's a molecular agent
if isinstance(agent, ist.Agent):
for mod in agent.mods:
mstr = abbrevs[mod.mod_type]
if mod.residue is not None:... | 7c498366e2ab11b4c40468bf6c087662b836ee66 | 3,600,094 |
def add_args(parser):
"""
parser : argparse.ArgumentParser
return a parser added with args required by fit
"""
# Training settings
parser.add_argument(
"--model",
type=str,
default="mobilenet",
metavar="M",
help="neural network used in training",
)
... | 2b802e01d63727667d3d7346adbaed8b115445e5 | 3,600,095 |
def is_artist_a_group(cursor, artist_id):
"""
Return True if the artist is a group
Return False if not
"""
command = "SELECT * FROM link_artist_group WHERE group_id == ?;"
return True if run_sql_command(cursor, command, [artist_id]) else False | e175c2f60bd598a988099862e2471f97c9a64d36 | 3,600,096 |
def load(**loadconfig):
"""Load data to RAM."""
# Load raw data
volX = ndu.fromh5(path=pathsy(loadconfig['X']['path']), datapath=loadconfig['X']['h5path'],
dataslice=eval(loadconfig['X']['dataslice']))
# Transpose volX to CREMI-esque format
volX = volX.transpose(2, 1, 0)
... | af70017014911766f15d387bdda6bfa39a08de8c | 3,600,097 |
def strong(*text, other_attr={}):
"""
strong tag
args:
other_attr <dict> : other attributes
"""
return f"<strong {_parse_attr(other_attr)}>{''.join(text)}</strong>" | f5461b54b2dd27c84bfd04ba558c82c4dedff4a7 | 3,600,098 |
def notinLRG_mask(primary=None, rflux=None, zflux=None, w1flux=None,
zfiberflux=None, gnobs=None, rnobs=None, znobs=None,
rflux_snr=None, zflux_snr=None, w1flux_snr=None,
maskbits=None):
"""See :func:`~desitarget.sv1.sv1_cuts.isLRG` for details.
Returns
... | 76d8481567bbe8b7e6d21b8f87f86939b4546483 | 3,600,099 |
import math
def riley_slice(a, b, max_denom, solver='mpsolve' if mpsolve_avail else 'scipy', **kwargs):
""" Return an accurate approximation to the Riley slice.
There are three possible solvers: the mpsolve solver (see https://numpi.dm.unipi.it/software/mpsolve), the solver built
in to scipy foll... | df25eff8d798e7643cf01c4b87d4cbfced0433d1 | 3,600,100 |
import operator
def gaussian_mixture_model(
data,
ntl_col='ntl2016',
n_components=3,
max_iter=1000,
tol=1e-10,
covariance_type='full',
bin_labels=['low', 'medium', 'high']
):
""" Implements Gaussian Mixture Model (GMM) on the nighttime light intensities
Parameters
----------
... | 754b2b34f2736d94206707eee8fc817a4272e1dd | 3,600,101 |
import re
def pretty_element(s):
"""
Returns formatted element name.
Parameters
----------
s : str
of format [A-Z][a-z]?[0-9]+
Returns
-------
str
LaTeX formatted string with superscript numbers.
"""
el = re.match('.*?([A-z]{1,3}).*?', s).groups()[0]
m = r... | d67101fd7e55e5ff25b2f4e4d6db98eeffca06c8 | 3,600,102 |
def toLabel(x):
""" Helper function for converting `x` to a single Label object """
if isinstance(x, _Label): return x
# # do this manually when desired, as it "boxes" a circuit being inserted
#elif isinstance(x,Circuit): return x.to_circuit_label()
else: return _Label(x) | d68de645bb3c11f873ca184465fa279eed52c021 | 3,600,103 |
def tsps(x: np.ndarray):
"""Calculate tissue specificity score as defined in:
> Ravasi, Timothy, Harukazu Suzuki, Carlo Vittorio Cannistraci, Shintaro
> Katayama, Vladimir B. Bajic, Kai Tan, Altuna Akalin, et al. 2010. “An
> Atlas of Combinatorial Transcriptional Regulation in Mouse and Man.” Cell
... | 76962777299b537b6290abb8467f186dda235d02 | 3,600,104 |
def least_squares(y, tx):
"""Least squares regression using normal equations"""
w = np.linalg.solve(tx.T@tx, tx.T@y)
loss = compute_mse_loss(y, tx, w)
return w, loss | 172d4254aec8ac781206522daad082483088ba7a | 3,600,105 |
def test_tensor_method_sub():
"""test_tensor_method_sub"""
class Net(Cell):
def __init__(self):
super(Net, self).__init__()
self.sub = P.Sub()
def construct(self, x, y):
out = x - y
return out.transpose()
net = Net()
x = ms.Tensor(np.on... | dc9ab1f371ee06cd90698eba9975728b3ec359a1 | 3,600,106 |
import re
def grep(patterns, file_name):
"""
Search for the patterns in the given list in a file.
Example:
grep(["St9bad_alloc", "FATAL"], "athena_stdout.txt")
-> [list containing the lines below]
CaloTrkMuIdAlg2.sysExecute() ERROR St9bad_alloc
AthAlgSeq.sysExecute... | 4da0c77822bcf3e13f441dffb42e013a20fc6298 | 3,600,107 |
import re
def all_whitespace(string):
""" all_whitespace(string : str) -> bool
>>> all_whitespace(' ')
True
Returns True if a string has only whitespace.
"""
return re.search('^[ \t]*(\r|\n|$)', string) | 766b92da0b6e91fbcd05eed408cb5651cdf42b4e | 3,600,108 |
import copy
import uuid
import collections
def deep_copy(item_original):
"""Return a recursive deep-copy of item where each copy has a new ID."""
item = copy.copy(item_original)
item._id = uuid.uuid4().hex
if hasattr(item, '_children') and len(item._children) > 0:
children_new = collections.Or... | 83c8ee5dd620e30a518391752905ba1966d27aa4 | 3,600,111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.