content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def extract_y(x, coefficients, degree):
"""
:param x: a matrix containing in each row the first 'degree' powers of a random number in the interval [-3, 2]
:param coefficients: vector of coefficients w_star' (in ascending order: from x**0 to x**n)
:return y : value of y that satisfy the polynomial given ... | 424b94b99bfcbe12e230e18ba0ecc7f7296da164 | 3,632,600 |
def model_scattered_light(data, errs, mask,
verbose=True,
deg=[5,5], sigma=3.0, maxiter=10):
"""
Fit a 2D legendre polynomial to data (only using data in the mask).
Iteratively sigma-clip outlier points.
"""
scatlight = data.copy()
scatlighterr... | 28cd9638a40db6734fe00a00bbbb76b588eb0619 | 3,632,601 |
def Convert_Data_To_GrayScale(data):
"""
This function converts an image data set in grayscale
input:
data: input data set
return: a numpy array of grayscale images
"""
return np.sum(data/3, axis=3, keepdims=True) | dc814b209e7a22981e5395cd3fead16b0d7c222c | 3,632,602 |
def jittered_center_crop(frames,
box_extract,
box_gt,
search_area_factor,
output_sz,
scale_type='original',
border_type='replicate'):
""" For each frame in frames, ex... | 477c847fe6b9d5a8baa5775c8220c267d69c22ab | 3,632,603 |
def np_sample_kumaraswamy(a, b, size):
"""
Numpy function to sample k ~ Kumaraswamy(a, b)
Args:
a: shape parameter 1
b: shape parameter 2
size: Return shape of np array
"""
assert a>0 and b>0, "Parameters can not be zero"
U = np.random.uniform(size=size)
K = (1 - (1 - U)**(1... | f1011f4a590066290f7c8ea10585432b49375987 | 3,632,604 |
import re
def find_meta(meta, file, error=True):
"""
Extract __meta__ value from METAFILE.
file may contain:
__meta__ = 'value'
__meta__ = '''value lines '''
"""
try:
text = read(file)
except Exception as err:
raise RuntimeError("Failed to read file") from err
... | 844f6000d591d145f3e267a73bf7a8ebf67c60a3 | 3,632,605 |
def get_training_input(filenames, params):
""" Get input for training stage
:param filenames: A list contains [source_filename, target_filename]
:param params: Hyper-parameters
:returns: A dictionary of pair <Key, Tensor>
"""
with tf.device("/cpu:0"):
src_dataset = tf.data.TextLineDat... | 25e2a92cce6b9dcbc89187d873ba580bd8ed3da0 | 3,632,606 |
def cbar(ni, nj, resources, commcost):
""" Average communication cost """
n = len(resources)
if n == 1:
return 0
npairs = n * (n - 1)
return 1. * sum(commcost(ni, nj, a1, a2) for a1 in resources.values() for a2 in resources.values()
if a1 != a2) / npairs | b215de30bcb019e2299edbb61591b7a1c129c58b | 3,632,607 |
import re
def get_electrostatic_potentials(outcar, atoms):
""" Retrieve the electrostatic averaged potentials from the OUTCAR file
:param outcar: content of the OUTCAR file (list of strings)
:param atoms: number of atoms of each atomic species (list of integers)
:return: dictionary with the electrosta... | 5846dc5b33d68ba19fced68fa0a6ffd76653ebb8 | 3,632,608 |
import logging
def get_metrics_delta(metric_name, label_suffix, labels, before_metrics, after_metrics):
"""Calculate the difference between 2 samples"""
s1 = find_sample_by_labels(metric_name, label_suffix, labels, before_metrics)
s2 = find_sample_by_labels(metric_name, label_suffix, labels, after_metrics... | e2baf39507bfaf281731241257796275e7284c32 | 3,632,609 |
def convert_region_type(region_type):
"""
Convert the integer region_type to the corresponding RegionType enum object.
"""
return int_to_region_type[region_type] | 2f16634c188e172a0a5a2d84db38782e7131d86f | 3,632,610 |
import os
import mimetypes
import base64
def CreateMessageWithAttachment(sender, to, subject, message_text, file_dir,
filename):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the ... | 5467241bb1ce84e0b9069a43bf8a7a64b2f8554a | 3,632,611 |
import scipy
def fit_to_data(x: np.ndarray, y: np.ndarray) -> np.ndarray:
"""
Fit @a func to data in @a x and @a y
Create an initial estimate for parameters, because timestamps are very big
"""
p0 = np.array([1.0, x[0] - 100, 0.0])
popt, _ = scipy.optimize.curve_fit(f=weight, xdata=x, ydata=y... | c9bba5795c5590cce87c4d04d8ccddfb0ce7d57f | 3,632,612 |
def new_url(fiscal_year, dept_str=DEPARTMENTS_DICT['1700']):
"""
modify the URL
https://www.fpds.gov/ddps/FY07-V1.4/1700-DEPARTMENTOFTHENAVY/1700-DEPARTMENTOFTHENAVY-DEPTOctober2006-Archive.zip
to be correct for the `fiscal_year` given.
"""
assert type(fiscal_year) is str, "fiscal year must be s... | 7d12bd1e060abcd3b382ee9eb094c193e5d3a04e | 3,632,613 |
def normalize_units(data):
"""Normalize units in datasets and their exchanges"""
for obj in data:
obj['unit'] = normalize_units_function(obj.get('unit', ''))
# for param in ds.get('parameters', {}).values():
# if 'unit' in param:
# param['unit'] = normalize_units_function(param['... | eea6cbdc7e8ad9852c0f6ab03a8f9d2789568164 | 3,632,614 |
def xvalBooklets(dfResp, dfObsResp, configObsList, configRespList):
"""
Cross-validates records for a booklet using data from a ready-made data frames. Returns a data frame containing
extracted responses from the response data table and the reconstructed responses from the observable
data, for selected ... | 29ca12be17a9b5b660ab44256deaf85f678b86d0 | 3,632,615 |
def imap_any(conditions):
"""
Generate an IMAP query expression that will match any of the expressions in
`conditions`.
In IMAP, both operands used by the OR operator appear after the OR, and
chaining ORs can create very verbose, hard to parse queries e.g. "OR OR OR
X-GM-THRID 111 X-GM-THRID 22... | de4ef1680cd2c8370d82640ff95186ed3ea81202 | 3,632,616 |
def format_sources(sources):
"""
Make a comma separated string of news source labels.
"""
formatted_sources = ""
for source in sources:
formatted_sources += source["value"] + ','
return formatted_sources | f9f86f11e4dfe9ecd3fbbd5e14d3ca750a4e1a5a | 3,632,617 |
def update_dict_to_latex(update_dict, order):
"""Returns update dictionary and order as latex string."""
ret_val = "\\begin{eqnarray*}\n"
get_line = lambda obj: wrap_long_latex_line(latex_print(obj) + "\\\\\n")
for v in reversed(order):
ret_val += latex_print(v) + " &=& "
if isinstance(u... | 4498216b5a6a224a7609d739670348e7dafa0843 | 3,632,618 |
def setup_base_empty_grade_helper(user: User, unit: models.Unit) -> models.Grade:
"""
Helper method to setup an empty grade before sending a request to the grading
view.
"""
grade = models.Grade(user=user, unit=unit)
grade.status = "sent"
grade.score = None
grade.notebook = None
gra... | 1c80a04c0de4859c050c8e09c5c8f31166898c64 | 3,632,619 |
def register_project(fn: tp.Callable = None):
"""Register new project.
Parameters
----------
call
This function will get invoked upon finding the project_path.
the function name will be used to search in $PROJECT_PATHS
"""
def _wrapper():
path = _start_proj_shell(fn.__n... | 8b379434c2cefa444d2fbb3168bf66295c6e8cac | 3,632,620 |
import asyncio
import sys
async def uart_terminal():
"""This is a simple "terminal" program that uses the Nordic Semiconductor
(nRF) UART service. It reads from stdin and sends each line of data to the
remote device. Any data received from the device is printed to stdout.
"""
def match_nus_uuid(d... | 49bac7a20cdaead9d63ea10e001ad78ccce748fc | 3,632,621 |
import re
def tag_word_in_sentence(sentence, tag_word):
"""
Use regex to wrap every derived form of a given ``tag_word`` in ``sentence`` in an html-tag.
Args:
sentence: String containing of multiple words.
tag_word: Word that should be wrapped.
Returns:
: Sentence with replacements... | 84567341d24b34cf7effca7cb1798d9c4b01533d | 3,632,622 |
def get_content_type(response: 'Response') -> str:
"""Get content type from ``response``.
Args:
response (:class:`requests.Response`): Response object.
Returns:
The content type from ``response``.
Note:
If the ``Content-Type`` header is not defined in ``response``,
the... | 34398cca048c6eb261e2481884f4496a03749c16 | 3,632,623 |
def _get_file_url_from_dropbox(dropbox_url, filename):
"""Dropbox now supports modifying the shareable url with a simple
param that will allow the tool to start downloading immediately.
"""
return dropbox_url + '?dl=1' | fe0256ae747826dbbe5ac3c3a4afa42e0584699a | 3,632,624 |
def launch_coef_scores(args):
"""
Wrapper to compute the standardized scores of the regression coefficients, used when computing the number of
features in the reduced parameter set.
@param args: Tuple containing the instance of SupervisedPCABase, feature matrix and response array.
@return: The stan... | 02423ef564b55dfcc37bddadcc813edffba05795 | 3,632,625 |
from typing import Any
def update(
configuration: dict, client: Any, issue: Any, issue_fields: dict, transition: str = None
) -> dict:
"""Updates a Jira issue."""
data = {"resource_id": issue.key, "link": f"{configuration.browser_url}/browse/{issue.key}"}
if issue_fields:
issue.update(fields=... | 13342f693e6fdce753d10856a5ff325d6ec84d9b | 3,632,626 |
def resolve_wishlist_from_user(user: "User") -> Wishlist:
"""Return wishlist of the logged in user."""
wishlist, _ = Wishlist.objects.get_or_create(user=user)
return wishlist | 2b21487bc5ee6c8da0cce7212e1065e2abb85004 | 3,632,627 |
def register_dat_matrix(file_path):
"""
Parse the registration matrix from the given file.
Parse the registration matrix from the given file in register.dat file format. See https://surfer.nmr.mgh.harvard.edu/fswiki/RegisterDat for the file format. The matrix encodes an affine transformation that can be ap... | 379c8d5b39ac448ef63412975afde50bf9f7359e | 3,632,628 |
import warnings
import math
def lnprob(theta, phi_total_data, f_blue_data, err, corr_mat_inv):
"""
Calculates log probability for emcee
Parameters
----------
theta: array
Array of parameter values
phi: array
Array of y-axis values of mass function
err: numpy.arra... | 97a884ce0af245982b806f360d16606d3eed966f | 3,632,629 |
def get_car_coordinates(list_points, x_points_traj, y_points_traj):
"""
input:
list_points - car config = phi(last point), length, width, l_base
x_points_traj, x_points_traj - current shifted position(center of back axis)
return:
car_coordinates - list(list)
len(car_coordinates) = 4
"""
list_point... | 0e1449ff39828db49ad3e5497d901ffeef135110 | 3,632,630 |
def create_module(module_name):
"""Function for create a new empty virtual module and register it"""
module = module_cls(module_name)
setattr(module, '__spec__', spec_cls(name=module_name, loader=VirtualModuleLoader))
registry[module_name] = module
return module | 9b08c7899513a4f181577b11385dc77d4e347d09 | 3,632,631 |
def _days_in_month(month_0: int, year: int) -> int:
""" Returns days in a month (0-indexed). Hope I got this right. """
if month_0 != 1:
return DAYS_IN_MONTH[month_0]
if (year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0):
return DAYS_IN_MONTH[month_0] + 1
return DAYS_IN_MONTH[... | b234491372def8c1f2da30039e8b41551d14eb84 | 3,632,632 |
def create_otfeature( featureName = "calt",
featureCode = "# empty feature code",
targetFont = None,
codeSig = "DEFAULT-CODE-SIGNATURE" ):
"""
Creates or updates an OpenType feature in the font.
Returns a status message in form of a string.
"""
... | 4e212dfaf161b3cd7c7ab5c4ffb187a73c979e67 | 3,632,633 |
def wilson_ci(num_hits, num_total, confidence=0.95):
""" Convenience wrapper for general_wilson """
z = st.norm.ppf((1+confidence)/2)
p = num_hits / num_total
return general_wilson(p, num_total, z=z) | 30706ff0848cc8c292b182ed946af71093b07e73 | 3,632,634 |
def convert_to_noun(word, from_pos):
""" Transform words given from/to POS tags """
if word.lower() in ['most', 'more'] and from_pos == 'a':
word = 'many'
synsets = wn.synsets(word, pos=from_pos)
# Word not found
if not synsets:
return []
result = derivational_conversion(word... | 02b7aba4e386297ed34d004aa55cab481c22f81f | 3,632,635 |
import itertools
def get_slug(obj, title, group):
"""
used to get unique slugs
:param obj: Model Object
:param title: Title to create slug from
:param group: Model Class
:return: Model object with unique slug
"""
if obj.pk is None:
obj.slug = slug_orig = slugify(title)
for x in itertools.count(1):
if n... | 014ac32090d70c5acda6f7f46804b88e730c54bd | 3,632,636 |
def create_link(url):
"""Create an html link for the given url"""
return (f'<a href = "{url}" target="_blank">{url}</a>') | 77a5375369be2be140a69a4521c50a92cee2d5ed | 3,632,637 |
def cummean(x):
"""Return a same-length array, containing the cumulative mean."""
return x.expanding().mean() | b5a35c56cb78e0588dd5be64a75384c4cd81ccb5 | 3,632,638 |
def validity_range_contains_range(
overall_range: DateRange,
contained_range: DateRange,
) -> bool:
"""
If the contained_range has both an upper and lower bound, check they are
both within the overall_range.
If either end is unbounded in the contained range,it must also be unbounded
in the ... | 255f0782a8b6461692a255380fdfc9079e5ca33a | 3,632,639 |
def find_reference_section_no_title_via_dots(docbody):
"""This function would generally be used when it was not possible to locate
the start of a document's reference section by means of its title.
Instead, this function will look for reference lines that have numeric
markers of the format 1., ... | 546533051b9ca8df1266ea278dd34134c1a234c9 | 3,632,640 |
def get_syntax_errors(graph):
"""List the syntax errors encountered during compilation of a BEL script.
Uses SyntaxError as a stand-in for :exc:`pybel.parser.exc.BelSyntaxError`
:param pybel.BELGraph graph: A BEL graph
:return: A list of 4-tuples of line number, line text, exception, and annotations p... | a0f3493b88b081de3613397c997d71dabdae78be | 3,632,641 |
def generate_S_tau(t):
"""
Generates the S_tau matrix for a template
Args:
t (np.array): the template vector
Returns:
np.array: the S_tau matrix
"""
t_binning = unique_binning(t)
return generate_S_from_binning(t_binning) | b438f9ddd0c36de3abb32553e21b7495f163b1a9 | 3,632,642 |
def create_neural_network(input_, output_, reservoir_, spectral_, sparsity_, noise_, input_scale, random_, silent_):
"""Create an Echo State Network.
:rtype: pyESN.ESN
:param input_: number of input units to use in ESN
:param output_: number of output units to use in ESN
:param reservoir_: number of... | 25b2048e1d3790e6386df0cfa6bdcfee4fc73db4 | 3,632,643 |
def validate_measure_for_asset_changes(asset_type: str, measure: str) -> str:
"""
Validates the range argument for asset changes command
:param asset_type: asset type argument passed by the user
:param measure: measure argument passed by the user
:return: measure if valid else raise ValueError
"... | 0bac72d07fd65cbcc589b2e6d5ea0faed13ee69a | 3,632,644 |
def create_incident(**kwargs):
"""
Creates an incident
"""
incidents = cachet.Incidents(endpoint=ENDPOINT, api_token=API_TOKEN)
if 'component_id' in kwargs:
return incidents.post(name=kwargs['name'],
message=kwargs['message'],
statu... | a19312816556a06f892da8ac9c8c6bb344ed3ce8 | 3,632,645 |
def harvey_two(frequency, tau_1, sigma_1, tau_2, sigma_2, white_noise, ab=False):
"""
Two Harvey model
Parameters
----------
frequency : numpy.ndarray
the frequency array
tau_1 : float
timescale of the first harvey component
sigma_1 : float
amplitude of the first har... | bc5860984c7bf357f18f6f7ec8e2ce592f6841cd | 3,632,646 |
def is_valid_combination( row ):
"""
Should return True if combination is valid and False otherwise.
Test row that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it.
"""
n = len(row)
if ... | c0758c3d30debbd3fc3d5f07d6728c23bfb71145 | 3,632,647 |
import os
def get_out_name(subdataset_name_tuple, out_ext=""):
"""
Get output file name for sub dataset
Takes tuple with (subdataset name, description)
"""
subdataset_name = subdataset_name_tuple[0]
outname = os.path.split(subdataset_name)[-1]
outname = outname.replace(".xml","")
out... | d55b77546e579f1f0887f4e88df2ec9825991c9f | 3,632,648 |
def PinkFilter(c):
"""Returns True if color can be classified as a shade of pink"""
if (c[0] > c[1]) and (c[2] > c[1]) and (c[2] == c[0]): return True
else: return False | 0514954e95a409901f3b7053a1c67315b556f517 | 3,632,649 |
def greedy_search(problem, h=None):
"""f(n) = h(n)"""
h = memoize(h or problem.h, 'h')
return best_first_graph_search(problem, h) | eaa1aac7e8b10f95effb32f61c765224ebe1f01e | 3,632,650 |
def get_callback(request, spider):
"""Get request.callback of a scrapy.Request, as a callable."""
if request.callback is None:
return getattr(spider, 'parse')
return request.callback | a1f62822d812bebdeabafa14edda4462949657d8 | 3,632,651 |
import requests
def veryrandom(msg, min=1, max=6, base=10, num=1):
"""Los datos generados por veryrandom provienen de random.org, lo cual
es una garantía adicional de la aleatoriedad de los resultados. Se
obtendrá un número aleatorio entre los 2 definidos, ambos inclusive.
"""
url = 'http://www.ra... | 75320750423e060ba117ed8ce6bfb84a02d16411 | 3,632,652 |
import os
import shlex
def read_configuration(start_path, configuration_filename):
"""Return compiler options from configuration.
Return None if there is no configuration.
"""
configuration_path = find_configuration(
os.path.abspath(start_path),
configuration_filename=configuration_f... | a5d4d382d8b55879cda9ce7f767a370b09360064 | 3,632,653 |
from typing import Union
from typing import List
from typing import Dict
from typing import Sequence
def clean_documents(documents: Union[List[str], Dict[str, str]], **kwargs) -> Union[Sequence[str], Dict[str, str]]:
"""Seaches for `Filth` in `documents` and replaces it with placeholders.
`documents` can be ... | 2c789e3fa5db952db452341a4e838230c01decf5 | 3,632,654 |
from math import log
def calcShannonEnt(dataSet):
"""
计算香农熵,用于判断划分
Parameters
----------
dataSet:数据集(可能是原始数据集,有可能是划分子集)
Returns:数据集的信息熵,根据分类标签信息确定
-------
"""
numEntries = len(dataSet) # 数据总量
labelCounts = {} # 创建一个数据字典,用来计数各个类别
for featVec in dataSet.values: # 每次取一行
... | bdade097a799feff0cb41eb15b3438ca1e088983 | 3,632,655 |
def Disc(
pos=(0, 0, 0),
r1=0.5,
r2=1,
c="coral",
alpha=1,
res=12,
resphi=None,
):
"""
Build a 2D disc of internal radius `r1` and outer radius `r2`.
|Disk|
"""
ps = vtk.vtkDiskSource()
ps.SetInnerRadius(r1)
ps.SetOuterRadius(r2)
ps.SetRadialResolution(res)
... | b7f79bfa2a1b8e06a028c741c590d71a93c2faf0 | 3,632,656 |
def identity_block(x, n_filters):
""" Construct a Bottleneck Residual Block with Identity Link
x : input into the block
n_filters: number of filters
"""
# Save input vector (feature maps) for the identity link
shortcut = x
## Construct the 1x1, 3x3, 1x1 residual block (fi... | 7de4980119577a5b37bf34a9394dfc779094b015 | 3,632,657 |
def makeDarker(color: colors.Color) -> colors.Color:
"""
Takes a color and returns a slightly darker version of the
original color.
:param Color color: the color you want to darken
:return: the new, darker color
:rtype: Color
:raises TypeError: if ``color`` is not a :py:class:`~.colors.Colo... | 79d89502019b66cb413a6e231b54832cd0690a54 | 3,632,658 |
import itertools
def multi_indices(n):
"""Return the list of all multi-indices within the specified bounds.
Return the list of multi-indices ``[b[0], ..., b[dim - 1]]`` such that
``0 <= b[i] < n[i]`` for all i.
"""
iterables = [range(ni) for ni in n]
return [np.asarray(b, dtype=np.intc)
... | f469e90253f4d762416b7757cc1b8de427589915 | 3,632,659 |
def removeProject(info, project):
"""
Removing an docker stack for the current project
if the checkIfComposerExistsBool == TRUE
else perform `docker rm`
:param info:
:param project:
:return:
"""
print(project)
if checkIfComposerExistsBool(project):
return "docker stack rm... | c8f3556aa67882c7241d93482d2371c9f8263793 | 3,632,660 |
def columnize_as_rows(lis, columns, horizontal=False, fill=None):
"""Like 'zip' but fill any missing elements."""
data = distribute(lis, columns, horizontal, fill)
rowcount = len(data)
length = max(len(x) for x in data)
for c, lis in enumerate(data):
n = length - len(lis)
if n > 0:
... | cce7251db42e7d17ee1e01a97eb5a0bcce7e9b60 | 3,632,661 |
from pathlib import Path
def single_extra_atom_line_v3000_sdf(tmp_path: Path) -> Path:
"""Write a single molecule to a v3000 sdf with an extra atom line.
Args:
tmp_path: pytest fixture for writing files to a temp directory
Returns:
Path to the sdf
"""
sdf_text = """
0 0 0 ... | e4fff4a730362fc2f75cb322b773853d9a6ec364 | 3,632,662 |
def add_metaclass(metaclass): # pragma: no cover
""" Class decorator for creating a class with a metaclass.
Copied from six
"""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
for slots_var in orig_... | dc101f414207e7e3c73bb7427d1bc1142c2e6a1a | 3,632,663 |
def vzerog(v):
"""vzerog(ConstSpiceDouble * v) -> SpiceBoolean"""
return _cspyce0.vzerog(v) | 7496c628dda05a01d77637fb5f8b05dbc414afcf | 3,632,664 |
from pathlib import Path
import csv
def read_barcodes(barcodes_file: Path) -> dict:
"""
Read in barcodes from file
:param barcodes_file: path to csv file with barcodes and gene name
:return barcode_dict:
barcode_dict = {
barcode_1 : {"gene": Gene_1, "count": 0}
barcode_2 : {"gene... | ee68f0172134e22b37432af9f0de2f0884b4354c | 3,632,665 |
def is_localized(node):
"""Check message wrapped by _()"""
if isinstance(node.parent, compiler.ast.CallFunc):
if isinstance(node.parent.node, compiler.ast.Name):
if node.parent.node.name == '_':
return True
return False | 09c7a0693c5aba9a984bc94a85a3476aeb15528c | 3,632,666 |
from typing import Callable
from typing import Iterable
def skip(count: int) -> Callable[[Iterable[_TSource]], Iterable[_TSource]]:
"""Returns a sequence that skips N elements of the underlying
sequence and then yields the remaining elements of the sequence.
Args:
count: The number of items to sk... | bae4c2e92940a1d2ade01f1defc7242e35a59e7a | 3,632,667 |
from threading import Thread
from pathlib import Path
import click
import json
from typing import List
def upload_to_nomad(nomad_configfile, num, mongo_configfile):
"""
upload n launchers to NOMAD using the following procedure
1. Find n launchers and split them into 10 threads
2. upload those n launch... | fc4ed41ac042ebdec429fb3c30b8c020ed7c9e15 | 3,632,668 |
import os
import logging
def model_fn(model_dir):
"""
Load the gluon model. Called once when hosting service starts.
:param: model_dir The directory where model files are stored.
:return: a model (in this case a Gluon network)
assumes that the parameters artifact is {model_name}.params
"""
... | 1856527e384ece4eb08a624dc30fe050d02c70e1 | 3,632,669 |
def init_db(uri, echo=True):
"""Initialize the database and reflect the tables"""
global meta
uri = make_url(uri)
uri.query.setdefault("charset", "utf8")
engine = create_engine(uri, echo=echo)
meta.bind = engine
Session.configure(bind=engine)
reflect_tables()
return engine | 9535a6b3f2379b65da151f1384f739ccdcf25d70 | 3,632,670 |
def get_weighted_average(We, x, w):
"""
Compute the weighted average vectors
:param We: We[i,:] is the vector for word i
:param x: x[i, :] are the indices of the words in sentence i
:param w: w[i, :] are the weights for the words in sentence i
:return: emb[i, :] are the weighted average vector f... | 6fbc2a5581a9cab4609604b771a4a27a6631b74d | 3,632,671 |
def logout_user_cleanup():
"""Logs out user."""
print("\n\nGot to logout from: {}".format(request.referrer))
logout_user()
session.clear()
flash("You were logged out!")
return redirect(request.referrer) | 60d114c94bd1409982e004840c29a3da3c3dd772 | 3,632,672 |
def read_vtk_sowfa(filename):
"""
Reads SOWFA results .vtk file and returns coordinates of cell centres and velocity field as numpy arrays.
:param filename:
:return:
"""
reader = vtk.vtkPolyDataReader()
reader.SetFileName(filename)
reader.Update()
data = reader.GetOutput()
u = v... | e78c4ee4300204af53373ca2199582b8ddacbc4a | 3,632,673 |
def compute_primary_orientations(primary_segments, angle_epsilon=0.1):
"""
Computes the primary orientations based on the given primary segments.
Parameters
----------
primary_segments : list of BoundarySegment
The primary segments.
angle_epsilon : float, optional
Angles will be... | 327a92aa493e8f6d82a760ba7087d0889ddf55e4 | 3,632,674 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.include('pyramid_chameleon')
config.include('pyramid_debugtoolbar')
# home
config.add_route('index', '/')
# Documentos da Colecao:
config.add... | 5085564cccfed7624455dd0a2608d3e241a2ae67 | 3,632,675 |
def plot_contribution_map(contribution_map, ax=None, vrange=None, vmin=None, vmax=None, hide_ticks=True, cmap="bwr",
percentile=100):
"""
Visualises a contribution map, i.e., a matrix assigning individual weights to each spatial location.
As default, this shows a contribution map w... | 2715424895926652539d8775e0629ba47dfc76c2 | 3,632,676 |
def pac_mvl(z):
""" Calculate PAC using the mean vector length.
Parameters
----------
ang: array_like
Phase of the low frequency signal.
amp: array_like
Amplitude envelop of the high frequency signal.
Returns
-------
out: float
The pac strength using the mean v... | 5412f9f4596b105e939a586fd570e1c1299b4194 | 3,632,677 |
def merge_values(list1, list2):
"""Merge two selection value lists and dedup.
All selection values should be simple value types.
"""
tmp = list1[:]
if not tmp:
return list2
else:
tmp.extend(list2)
return list(set(tmp)) | 9412dd28c6110bc6df70ac7d563cb19d1211beb8 | 3,632,678 |
def load_data(database_filepath):
"""
Load data from sqlite database
Arguments:
database_filepath: path to database file
"""
engine = create_engine(f'sqlite:///{database_filepath}')
sql = 'SELECT * FROM DisasterPipeline'
df = pd.read_sql(sql, engine)
x = df.message
... | 99371afba33d7527cc5a6a3c4f0d98b1b76ba5c0 | 3,632,679 |
import numpy as np
from .._tier0 import empty_image_like
from .._tier0 import execute
from .._tier1 import copy
from .._tier0 import create
from .._tier1 import copy_slice
from .._tier0 import _warn_of_interpolation_not_available
from typing import Union
def affine_transform(source : Image, destination : Image = None... | 78fe7ff1ea9c9afc9284a2a9248765f7ff57ba3d | 3,632,680 |
def create_host(values):
"""Create a host from the values."""
return IMPL.create_host(values) | bb49c51dfd6ef7be988da89dd12ec441948dbb2b | 3,632,681 |
import argparse
def parse_arguments():
"""Parse the command line arguments.
Returns:
Parsed arguments.
"""
parser = argparse.ArgumentParser(description='tail for BAMs')
parser.add_argument(
'filenames',
help='BAMs on which to perform the tail operation',
nargs='*',... | 4c09fecf32bcc5a4d016d012a87996f5b08b765f | 3,632,682 |
import math
def get_distance(lat_a, long_a, lat_b, long_b):
"""
Returns the distance, in meters, between two points
Uses the haversine formula, i.e.:
a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
c = 2 ⋅ atan2( √a, √(1−a) )
d = R ⋅ c
Keep in mind this is an "as the crow flies" type of estimation
... | 57b64ad307c28d87caf7015f8a16c9a5fb8562dd | 3,632,683 |
def format_heading(level, text):
"""Create a heading of <level> [1, 2 or 3 supported]."""
underlining = ['=', '-', '~', ][level-1] * len(text)
return '%s\n%s\n\n' % (text, underlining) | 6b8caaa134ddc32666a4d7ce62a775d6ffda7425 | 3,632,684 |
def get_list_of_temps(temp_string):
"""
A function to process an argument string line to an array of temperatures
"""
success = True
error = ""
temps = None
arr_string = temp_string.split(",")
arr_string_len = len(arr_string)
temps = np.zeros(arr_string_len)
for i in range(arr_string_len... | 0ad6ffd2ecf25ae3158b25b592f89824e4370633 | 3,632,685 |
def test():
"""Test
:param:
:return:
"""
print('!! Begin Test!..')
return encrypt("vigenere","hello","lemon") | d698bba18d8dba0465c5bb2bd8ac0311b9b9f64d | 3,632,686 |
def get_new_size_zoom(current_size, target_size):
"""
Returns size (width, height) to scale image so
smallest dimension fits target size.
"""
scale_w = target_size[0] / current_size[0]
scale_h = target_size[1] / current_size[1]
scale_by = max(scale_w, scale_h)
return (int(current_size[0]... | e0b42eab3d35ba5c662282cab1ffa798327ad92a | 3,632,687 |
def get_name_component(x509_name, component):
"""Gets single name component from X509 name."""
value = ""
for c in x509_name.get_components():
if c[0] == component:
value = c[1]
return value | 6a473a96b99daa6f69fd6aac45f2594af933d4bd | 3,632,688 |
def hurst(ts):
""" the implewmentation on the blog http://www.quantstart.com
http://www.quantstart.com/articles/Basics-of-Statistical-Mean-Reversion-Testing
Returns the Hurst Exponent of the time series vector ts"""
# Create the range of lag values
lags = range(2, 100)
# Calculate the array of t... | 59708d86d9f0022cf991fd60e32e9d8c59c630c7 | 3,632,689 |
def _bunchify(b):
"""Ensure all dict elements are Bunch."""
assert isinstance(b, dict)
b = Bunch(b)
for k in b:
if isinstance(b[k], dict):
b[k] = Bunch(b[k])
return b | c76bb7ba86d1958f498775ab68f944b0fcb1dd0c | 3,632,690 |
import random
def generate_random_username():
"""Generate function
Generates a random username for anonymous users.
:returns: String with the anonymous username
"""
random.seed()
return 'anon-' + str(random.randint(0, MAX_INT_ANONYMOUS)) | ef7d7897d3eeb518808547afd8e1717c7db1d5d6 | 3,632,691 |
import os
def subvolume_snapshot(source, dest=None, name=None, read_only=False):
"""
Create a snapshot of a source subvolume
source
Source subvolume from where to create the snapshot
dest
If only dest is given, the subvolume will be named as the
basename of the source
na... | 12747ee6a1db10c703cf85e918e37d8c7a432e62 | 3,632,692 |
from typing import Union
import pathlib
import io
from typing import Optional
from typing import Dict
from typing import Any
import torch
from typing import Tuple
import zipfile
import warnings
import os
def load_from_zip_file(
load_path: Union[str, pathlib.Path, io.BufferedIOBase],
load_data: bool = True,
... | 157f725244700785ccf0c0ba775606136693bafe | 3,632,693 |
import math
def GetRadar(dt):
""" Simulate radar range to object at 1K altidue and moving at 100m/s.
Adds about 5% measurement noise. Returns slant range to the object.
Call once for each new measurement at dt time from last call.
"""
if not hasattr (GetRadar, "posp"):
GetRadar.posp = 0
... | 0f61b507d57efa68825b22b0ba2d97154f97547c | 3,632,694 |
def get_gin_feature(inputs, neigh_idx, k):
"""
Aggregate neighbor features for each point with GIN
GIN conv layer:
Xu, Keyulu, Weihua Hu, Jure Leskovec, and Stefanie Jegelka.
"How Powerful are Graph Neural Networks?."
arXiv:1810.00826 (2018).
Args:
inputs: (batch_size, num_vertices... | 12fd947cd9e18e3a8755cf32b4e72a0aa0befa5f | 3,632,695 |
import os
import sys
def gen_training_matrix(directory_path, output_file, cols_to_ignore):
"""
Reads the csv files in directory_path and assembles the training matrix with
the features extracted using the functions from EEG_feature_extraction.
Parameters:
directory_path (str): directory containing the CSV fi... | 1a8828c1ceb9d7b11bb114508920a3653762b258 | 3,632,696 |
def five_crops(image, crop_size):
""" Returns the central and four corner crops of `crop_size` from `image`. """
image_size = tf.shape(image)[:2]
crop_margin = tf.subtract(image_size, crop_size)
assert_size = tf.assert_non_negative(
crop_margin, message='Crop size must be smaller or equal to the... | 16f699f8569ca8271c180027db4df199543a62b1 | 3,632,697 |
from typing import Dict
from re import A
def get_tfms(conf: DictConfig) -> Dict[str, A.Compose]:
"""
Loads in albumentation augmentations for train, valid, test
from given config as a dictionary.
"""
trn_tfms = [
load_obj(i["class_name"])(**i["params"]) for i in conf.augmentation.train
... | e4d47d19a52027fd413f501aa05d1e659e232ace | 3,632,698 |
def song_line(line):
"""Parse one line
Parameters
----------
line: str
One line in the musixmatch dataset
Returns
-------
dict
track_id: Million song dataset track id, track_id_musixmatch:
Musixmatch track id and bag_of_words: Bag of words dict in
{word: cou... | 2108dfa037aa6293a0b3111a97c354e62c0dd2a5 | 3,632,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.