content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def updateShaderState(self):
"""Updates all shader program variables. """
if not self.ready():
return
opts = self.opts
self.shader.load()
voxValXform = self.imageTexture.voxValXform
voxValXform = [voxValXform[0, 0], voxValXform[0, 3], 0, 0]
invNumLabels = 1.0 / (opts.lut.max() ... | 611b093ce51e99e5c7c1e3da5dcc7cd1a8c07b01 | 30,000 |
import _winreg
from cake.registry import queryString
def _getMinGWInstallDir():
"""Returns the MinGW install directory.
Typically: 'C:\MinGW'.
@return: The path to the MinGW install directory.
@rtype: string
@raise WindowsError: If MinGW is not installed.
"""
possibleSubKeys = [
r"SOFTW... | 262f65aaf413fe718b753ffa706c97c80b73f349 | 30,001 |
import urllib
def nextbus(a, r, c="vehicleLocations", e=0):
"""Returns the most recent latitude and
longitude of the selected bus line using
the NextBus API (nbapi)
Arguments: a=agency, r=route, c=command,
e=epoch timestamp for start date of track,
0 = the last 15 minutes
"""
nbapi = "... | 08ce12f3a1d96572014dc528de255f89e5b0ee46 | 30,002 |
def latest_blog_posts(context, num):
"""
Displays the most recent blog posts. It takes an argument, num
and displays so many posts depending on the value.
"""
latest_blog_posts = Post.objects.all()[:num].select_related()
return {
'latest_blog_posts': latest_blog_posts
} | 74ee23753e674e1dd1f8fa8af92002c739a28ee3 | 30,003 |
from typing import List
from typing import Dict
import copy
def _expand_array_paths_to_preserve(paths: List[DetailedPath]) -> Dict[str, List[int]]:
"""
Used by "filter_element_match" - Returns a dictionary of string paths mapped to array indices that we want
to preserve.
:param paths: A list of lists... | 7f44a717285bc30c3162d39dcf18a1cdc3920bed | 30,004 |
def get_request_fixture_names(request):
"""Get list of fixture names for the given FixtureRequest.
Get the internal and mutable list of fixture names in the enclosing scope of
the given request object.
Compatibility with pytest 3.0.
"""
return request._pyfuncitem._fixtureinfo.names_closure | 665fff4538f3817b6eb882f9a873683d69003bfd | 30,005 |
def _unique(values, *, return_inverse=False):
"""Helper function to find unique values with support for python objects.
Uses pure python method for object dtype, and numpy method for
all other dtypes.
Parameters
----------
values : ndarray
Values to check for unknowns.
return_inve... | 4768b0e055cfd9a42b5332f7a47aa608aa7b90c0 | 30,006 |
def _create_range_tool(
data,
min_time,
max_time,
plot_range,
width,
height,
time_column: str = None,
y: str = "y_index",
):
"""Create plot bar to act as as range selector."""
ext_min = min_time - ((max_time - min_time) * 0.15)
ext_max = max_time + ((max_time - min_time) * 0.... | 42cf2d4f5986dd454a9aa968ce4db4136b5acd1f | 30,007 |
def pivot(df, index, column, value):
"""
Pivot a dataframe. Reverse operation of melting. Useful for configuring evolution
See pandas' pivot_table documentation for more details
Args:
- index (list): indexes argument of pd.pivot_table
- column (str): column name to pivot on
- val... | b9a8c63d5ce320f4a156c8f42b92173dd1d86ca0 | 30,008 |
def split_pdf_image_into_row_image_block(pdf_image):
"""
split the whole pdf image into row image block
:param pdf_image: the whole color pdf image
:return:
"""
gray_image = cv2.cvtColor(pdf_image, cv2.COLOR_BGR2GRAY)
binarized_image = cv2.adaptiveThreshold(
src=gray_image,
m... | 9a304f54167c4fbb7739c7022b12c5b574240861 | 30,009 |
def get_tokens():
""" Get all the active tokens in the datbase."""
return query_db('select token from token') | 960c613147d3d55a3e56dcef06fc974a4c553929 | 30,010 |
def setup(app):
"""Setup sphinx-gallery sphinx extension"""
sphinx_compatibility._app = app
app.add_config_value('sphinx_gallery_conf', DEFAULT_GALLERY_CONF, 'html')
for key in ['plot_gallery', 'abort_on_example_error']:
app.add_config_value(key, get_default_config_value(key), 'html')
app.... | 75886cf003fe6611651e515224e81b1cc730512f | 30,011 |
def get_stats(beta0, n, sigma, lam, pen, ntrials=100, maxiter=100):
"""
run ntrials regression problems
return mean of the mse, and 95% confidence interval
"""
if pen is None:
mses = run_trials_ols(beta0, n, sigma, ntrials=ntrials)
else:
mses = run_trials(beta0, n, sigma, lam, p... | e6357f64b40eb424e295088920f5f8dcba558896 | 30,012 |
def squeeze_output_dim_0(initial_ndims, point_types):
"""Determine if the output needs to squeeze a singular dimension 0.
The dimension 0 is squeezed iff all input parameters:
- contain one sample,
- have the corresponding dimension 0 squeezed,
i.e. if all input parameters have ndim strictly less t... | 448291f75d758867e65c1693de6c40ab80a7b642 | 30,013 |
import math
def quaternion_from_matrix(matrix, isprecise=False):
"""Return quaternion from rotation matrix.
If isprecise is True, the input matrix is assumed to be a precise rotation
matrix and a faster algorithm is used.
"""
M = np.array(matrix, dtype=np.float64, copy=False)[:4, :4]
if ispre... | dcc4ee7e6b2493a96a78b7da45b6f6edb12be550 | 30,014 |
def check_version(stdout):
"""Check version of Ensembl-VEP.
Example of the first part of an output from the command `vep --help`:
#----------------------------------#
# ENSEMBL VARIANT EFFECT PREDICTOR #
#----------------------------------#
Versions:
ensembl : 104.1af1dce
... | 5c3b716db7016f1b612f764fb54e3b25d970b0f2 | 30,015 |
def tf_config():
""" Default tensorflow config. """
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return config | fdc28c9968457af92afb18f8315e07c04890ff50 | 30,016 |
import argparse
def parse_cli_args():
"""
These flags are the ones required by the Stream Deck SDK's registration procedure.
They'll be set by the Stream Deck desktop software when it launches our plugin.
"""
parser = argparse.ArgumentParser(
description='Stream Deck Google Meet Plugin')
... | adcad9860336482b2072ef8aecd398a2f4ce3b45 | 30,017 |
import tensorflow.compat.v1 as tf
def op(scalars_layout, collections=None):
"""Creates a summary that contains a layout.
When users navigate to the custom scalars dashboard, they will see a layout
based on the proto provided to this function.
Args:
scalars_layout: The scalars_layout_pb2.Layout proto tha... | 852fa62c69271c897d0f4e0c4b9517520d7f7b77 | 30,018 |
def customize_response_cros(data):
"""定制跨域响应体"""
response = make_response(jsonify(data))
# 设置响应请求头
response.headers["Access-Control-Allow-Origin"] = '*' # 允许使用响应数据的域。也可以利用请求header中的host字段做一个过滤器。
response.headers["Access-Control-Allow-Methods"] = 'POST' # 允许的请求方法
response.headers["Access-Contro... | c702644bc9faae45057263a207e42e110d125165 | 30,019 |
def shortdateformat(value, default_value=None):
"""
Example value: datetime.strptime("2018-07-25 10:15:00", "%Y-%m-%d %H:%M:%S")
Example output: '25 July'
"shortdateformat" was designed for use in summary tables where space is tight and dates are shown on their own line.
The original intended use w... | 31ce7fa824df3d746d5e81e960864fabb1329307 | 30,020 |
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text starts.
"""
order = sort_characters(text)
... | 05eb036cb749e030d84bb2d494a447faa7f93e6c | 30,021 |
import re
import os
import codecs
def load_page(content_path, page_path):
"""Load the page file and return the path, URL and contents"""
# Extract the part of the page_path that will be used as the URL path
pattern = URL_PATH_REGEX % content_path
matches = re.match(pattern, page_path)
if matches:... | 985061e9632bbb96bb1236dbdaca1f5ece657e48 | 30,022 |
from mne.utils import _time_mask
def compute_auc(dip, tmin=-np.inf, tmax=np.inf):
"""Compute the AUC values for a DipoleFixed object."""
if not isinstance(dip, DipoleFixed):
raise TypeError('dip must be a DipoleFixed, got "%s"' % (type(dip),))
pick = pick_types(dip.info, meg=False, dipole=True)
... | cedfeb7934ee86e6c1ae702ba0cbecceb83c90db | 30,023 |
def left_join(ht1, ht2):
"""
:param ht1: left hash table
:param ht2: right hash table
:return: list of joined values from both hash tables
"""
results = []
for item in ht1.table:
while item is not None:
key = item.val[0]
joined = [key, ht1.get(key), ht2.get(k... | 8f34e03d055a32ea337b27cd800eeb393d136dfa | 30,024 |
from typing import Tuple
import torch
import re
def load_pretrained_cifar10_model(
path: str, resnet_size: int = 32,
) -> Tuple[nn.Module, DifferentiableNormalize]:
"""
Loads a pretrained CIFAR-10 ResNet from the given path along with its
associated normalizer.
"""
model: nn.Module = getattr(ci... | 2d1a907b2d90459661bdd0e578828ac0949d68e3 | 30,025 |
import os
import glob
def find(path):
"""Find files in the filesystem in order
Expands and normalizes relative paths.
Ignores unreadable files and unexplorable directories.
:param dir_path: Path to a config file or dir containing configs
:returns: List of full paths of the files in the directory... | 8c94874f4d2d62608a3791cfceb67b8aebe4fa54 | 30,026 |
import logging
def create_project(**kwargs): # noqa: E501
"""Creates a project with an original network file.
Creates a project with an original network file. # noqa: E501
:param designation:
:type designation: str
:param description:
:type description: str
:param network_designation:
... | c57951358383b18f35fdf9c6ca899f09979565ae | 30,027 |
def _get_boto_client(cluster, access_key, secret_key):
"""
Returns a boto client object that can be used to communicate with the Object
Storage cluster.
"""
client = boto.connect_s3(aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
... | 4351e74610948c17c8c35ae86a5fa1ca15f4158f | 30,028 |
def triangleArea(a: Vec3, b: Vec3, c: Vec3) -> float:
"""
Calculate area of triangle
:return: area
"""
return cross3(b - a, c - a).length() / 2.0 | ad5c73e07421c01f3db3a9d4592ec218307c8a80 | 30,029 |
async def read_object_name(app, device_id, addr):
"""
Execute a single request using `ReadPropertyRequest`.
This will read the `objectName` property of a remote device.
:param app: An app instance
:param device_id: BACnet device id (integer number)
:param addr: The network address of the remote ... | 3e9e023be615911ca0f43ff2a0aec62cec695d25 | 30,030 |
import requests
from bs4 import BeautifulSoup
def jws_omex_dict():
""" Returns dictionary of available JWS combine archives.
:return: { id: download_url } dict
"""
jws_omex = {}
num_omex = 0
for page_iter in range(NUM_PAGES):
url = URL.format(page_iter+1) # 1 based counting
p... | 21e378038bbce07a166d315a183a08ce69f9a544 | 30,031 |
def ztrsv(A,
x,
Uplo=CblasLower,
TransA=CblasNoTrans,
Diag=CblasNonUnit):
"""
returns x'
This function computes inv(op(A)) x for x, where op(A) = A, A^T, A^H
for TransA = CblasNoTrans, CblasTrans, CblasConjTrans. When Uplo is
CblasUpper then the upper triangl... | 11b3420e09718fabc907b484142b67ce4f828c4f | 30,032 |
def get_trainable_vars(name=None):
"""Return the trainable variables.
Parameters
----------
name : str
the scope
Returns
-------
list of tf.Variable
trainable variables
"""
return tf.compat.v1.get_collection(
tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES, scope... | 3c5b005613a7a6f0cd0420e60337ed7bf88bf92f | 30,033 |
def player_to_string(game: reversi.ReversiGame, player_colour: str, player: ai_players.Player) \
-> str:
""" Returns the string representation of the type of the player.
Preconditions:
- player_colour in {'white', 'black'}
"""
if game.get_human_player() == 1 and player_colour == 'black'... | a1e6dfe184d471616fac7a1ab1bbb2d959c5457c | 30,034 |
from typing import Any
def encode_pd_timestamp(v: pd.Timestamp) -> Any:
"""
Specializes :func:`encode` for invocations where ``v`` is an instance of
the :class:`~pandas.Timestamp` class.
"""
return {
"__kind__": kind_inst,
"class": "pandas.Timestamp",
"args": encode([str(v)... | fec08229d2a9b8f7115986e4c97677b401200adf | 30,035 |
async def getWebUserAmount(cls:"WebIndex", where:str="1=1", values:tuple=()) -> int:
""" simply gives a number of all matched user """
res:list = cls.Web.BASE.PhaazeDB.selectQuery(f"SELECT COUNT(*) AS `I` FROM `user` WHERE {where}", values)
return res[0]['I'] | a019a8de0644a7295cfafdce80a544ae31bcb225 | 30,036 |
def randomise_spikes(spiketrain, n_surrogates=1, decimals=None):
"""
Generates surrogates of a spike train by spike time randomization.
The surrogates are obtained by keeping the spike count of the original
`spiketrain`, but placing the spikes randomly in the interval
`[spiketrain.t_start, spiketra... | cf8d911f73a3a62b9586ea41c4683ba84a91b8a1 | 30,037 |
def interface_PSO(theta, args):
"""
Function to interface the PSO with the ANFIS. Each particle has its own
ANFIS instance.
theta (nPop, n_var)
learners (nPop, )
J (nPop, )
"""
args_PSO = (args[0], args[1])
learners = args[2]
nPop = theta.shape[0]
... | a725db597ccf4a5928c305ad1493bcd0c99b94a5 | 30,038 |
def corr2d(X, K):
"""计算二维互相关运算。"""
h, w = K.shape
Y = mnp.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))
for i in range(Y.shape[0]):
for j in range(Y.shape[1]):
Y[i, j] = (X[i:i + h, j:j + w] * K).sum()
return Y | dcbd523879df0f2529a0e68b6c65d829addbc786 | 30,039 |
from src.praxxis.sqlite import sqlite_scene
from src.praxxis.sqlite import sqlite_notebook
from src.praxxis.display import display_scene
def history(history_db, library_db, current_scene_db):
"""displays the notebook history of the sceen"""
curr_scene = sqlite_scene.get_current_scene(history_db)
not... | c6ac411488f69b61678fb298639a8dfa0a103901 | 30,040 |
def get_optimal_parameters_from_dict(selected_dict, num_features):
""" Find optimal parameters from dictionary of selected features
Arguments
---------
selected_dict: dictionary
keys = parameters
values = dictionary
keys = task index
values = list of list of sel... | d473f963c482bcdd8a2eebd65f2e9ae50fe46a32 | 30,041 |
async def _get_input_dialog(self: 'TelegramClient', dialog):
"""
Returns a :tl:`InputDialogPeer`. This is a bit tricky because
it may or not need access to the client to convert what's given
into an input entity.
"""
try:
if dialog.SUBCLASS_OF_ID == 0xa21c9795: # crc32(b'InputDialogPeer... | a58570d5192713e3813cd3cfc6d1295916684a96 | 30,042 |
from datetime import datetime
def kep_to_sat(kep,epoch,bstar=0.21109E-4,whichconst=wgs72,afspc_mode=False):
"""kep_to_sat(kep,epoch,bstar=0.21109E-4,whichconst=wgs72,afspc_mode=False)
Converts a set of keplerian elements into a Satellite object.
Args:
kep(1x6 numpy array): the osculatin... | 9f5a9f3d487d9ea924ea1c8858c8b0796e543bf2 | 30,043 |
def enumerate ():
""" Returns an iterator to the features map.
"""
return __all_features.iteritems () | fda0a96102add04c4282a61f99d9a664e76f2bd6 | 30,044 |
def _create_forward(out_node):
"""Create a user-friendly forward function.
Ensures that a single value instead of a tuple is returned if the user asked
for the gradient with respect to only one input.
Args:
out_node: The function definition AST.
Returns:
The function definition with potentially cha... | 80cdd1814d62b282c1cde37c783d97a067264e51 | 30,045 |
import os
import glob
import warnings
def get_geos_install_prefix():
"""Return GEOS installation prefix or None if not found."""
env_candidate = os.environ.get("GEOS_DIR", None)
if env_candidate is not None:
candidates = [env_candidate]
else:
candidates = [os.path.expanduser("~/local"... | 79193b7a515f961dacdb666a6c25d038b3a14e0c | 30,046 |
def _get_trip_from_id(trip_obj_list, trip_id):
""" Get a trip from a list, based on a trip id """
found_trip_obj = None
for trip_obj in trip_obj_list:
if trip_obj.id == trip_id:
found_trip_obj = trip_obj
break
return found_trip_obj | f2bbacfccda1e4ff778ba793ad238f744400f020 | 30,047 |
def density_plot(df, y_column, models, model_names=(), columns_to_exclude=()):
"""This function creates the density plot of predicted positive class probability on actual positive and negative
data by each model in models in the same plot. It also computes the difference between the distributions on
p... | e3120e3b5fc0b07e12e5fa41fe0f288a9d98495c | 30,048 |
def clip_chk(x, lb, ub, allow_nan=False):
"""Clip all element of `x` to be between `lb` and `ub` like :func:`numpy:numpy.clip`, but also check
:func:`numpy:numpy.isclose`.
Shapes of all input variables must be broadcast compatible.
Parameters
----------
x : :class:`numpy:numpy.ndarray`
... | e799e00adb4152a7d2ca2faf95eb82744149e59d | 30,049 |
def grid_arc_seconds_1d_to_grid_pixel_indexes_1d(grid_arc_seconds_1d, shape, pixel_scales, origin=(0.0, 0.0)):
""" Convert a grid of (y,x) arc second coordinates to a grid of (y,x) pixel 1D indexes. Pixel coordinates are \
returned as integers such that they are the pixel from the top-left of the 2D grid going ... | 966133fe0a979c913b704a448d02124005a9946d | 30,050 |
import fnmatch
def make_test_run_filter(
complete: bool = False, failed: bool = False, incomplete: bool = False,
name: str = None,
newer_than: dt.datetime = None, older_than: dt.datetime = None,
passed: bool = False, result_error: bool = False,
show_skipped: bool = False, sys_n... | 57f20287ac957b394b8ac25946da3da42deec8ec | 30,051 |
def get_runnable_tasks(graph):
"""Parse a graph and return all runnable tasks."""
tasks = []
to_remove = []
# tasks that follow task that raises an error
following_err = dict()
for tsk in graph.sorted_nodes:
if tsk not in graph.sorted_nodes:
continue
# since the list ... | 155206f67986e65b74148e173d6641d994dd08bd | 30,052 |
def get_defaults(lang):
"""Get the language-specific defaults, if available in spaCy. This allows
using lexical attribute getters that depend on static language data, e.g.
Token.like_num, Token.is_stop, Doc.noun_chunks etc.
lang (unicode): ISO 639-1 language code.
RETURNS (Language.Defaults): The l... | 3ef08b4bd410407ad8519d1c4f84c6c279aa8257 | 30,053 |
def h2(*text, **kwargs):
"""Return a header 2"""
return tydoc().h2(*text, **kwargs) | 7b5b465282222c31d84121e6f890da964cb63fd5 | 30,054 |
def update_comment(comment_id, data):
"""
update comment using its id.
"""
comment = Comment.query.get(comment_id)
for attribute in data:
setattr(comment, attribute, data[attribute])
db.session.commit()
return comment_schema.dump(comment).data | aaeb88479bf82ea3ac09a56d17e09c4ba05eda47 | 30,055 |
import os
def countOriginals(subfolderPath):
"""return count of original vids"""
items = os.listdir(subfolderPath)
count = 0
for file in items:
if file.startswith("Original_") and file.endswith(".description"):
count = count + 1
return count | 116ffa4fecf911d0dec436c5003acb2c9f42a673 | 30,056 |
def RMSE(A, A_tilde):
"""
Root mean square error. Gives the standard deviation of the residuals
(prediction errors).
Parameters
----------
A : ndarray
Forecast.
A_tilde : ndarray
Observation.
Returns
-------
float
Root mean square error.
"""
ret... | 58a5b833725497be224804a71855819afa9fc33f | 30,057 |
def remove_punct(tokens):
"""
Remove punctuation marks from lists of tokens
Parameters
----------
tokens: list
a nested list containing lists of tokens or a list of spacy docs
Returns
-------
filtered_comments: list
nested lists of tokens
"""
filtered_comments... | c6d7b70a6bf3efe7be3dd144f10ac0f8f5b11e72 | 30,058 |
def to_camel_case(string: str) -> str:
"""
Converts a ``snake_case`` string to ``camelCase``.
:param string: A ``snake_case`` string.
:return: A ``camelCase`` version of the input.
"""
components = string.split("_")
return components[0] + "".join(x.capitalize() for x in components[1:]) | ae0d82efd9a5a65ef16cc401a0fe302b4f04d524 | 30,059 |
import requests
def reconnect(user_data):
"""
Attempt to perform a login to the Unistudium website, saving the cookies in user_data.
Returns:
"OK" if the login was performed correctly, else a description with the error that can be used to inform the users.
"""
# Check if user's session ex... | e05096d69605300680b29bc12784faa3734f40b2 | 30,060 |
from typing import Optional
from typing import Collection
from typing import List
from typing import Tuple
from typing import Set
from typing import Dict
import operator
def yake(
doc: Doc,
*,
normalize: Optional[str] = "lemma",
ngrams: int | Collection[int] = (1, 2, 3),
include_pos: Optional[str ... | b467f0598c70dbf1cec70dafec12ac4259720f91 | 30,061 |
def parse_qsub_defaults(parsed):
"""Unpack QSUB_DEFAULTS."""
d = parsed.split() if type(parsed) == str else parsed
options={}
for arg in d:
if "=" in arg:
k,v = arg.split("=")
options[k.strip("-")] = v.strip()
else:
options[arg.strip("-")] = ""
... | a5c50aef405d88bcb018af48904a384b090d22a2 | 30,062 |
import torch
def load_embeddings(word_map=None, binary=True):
"""
Creates an embedding tensor for the specified word map, for loading into the model.
:param word_emb_file: file containing embeddings (stored in GloVe format)
:param word_map: word map. If None, it will be comprised from the embeddings v... | 9c43d00411dd6036297c21569a232d52bd71acac | 30,063 |
from typing import Dict
import json
import requests
def update_business_profile(business: Business, profile_info: Dict) -> Dict:
"""Set the legal type of the business."""
if not business or not profile_info:
return {'error': babel('Business and profile_info required.')}
# contact phone is optiona... | 68c0ce0d9d205d34b02f7933ca3bc0e7179c7a12 | 30,064 |
def nextpow2(i):
""" Find the next power of 2 for number i """
n = 1
while n < i:
n *= 2
return n | 5dbe396b222ccf79d3cd2017b32174f9e894a5f2 | 30,065 |
from typing import Sequence
from typing import Dict
from typing import List
from typing import Set
from typing import Tuple
def _extra_topo_sort(bad_ordering: Sequence[DiscoveredExtension]) -> Sequence[DiscoveredExtension]:
"""
Simple depth-first search version of a topological sort, but without
recursion... | cdaf0229dda2460e68ee24afb987ca9f7e029d4d | 30,066 |
def getclasesbyid_(numid):
"""
Returns all defined clases by id [number]
"""
data = get_info_token()
user_ = data['User']
rol_ = data['Rol']
data_response = ''
if rol_ == 'Professor':
try:
bool_, data_response = getclassbyid_(data['User'],numid)
if bool_:
... | 75603f40621f51313863aa8977b71241a31c3d84 | 30,067 |
import json
def load_versions():
"""Load Bioversions data."""
with open(VERSIONS_PATH) as file:
return json.load(file) | e5e3b2a3dd4ae17fe6cf6b00700b33e9bc55e6b5 | 30,068 |
async def retrieve_document(document_id: str, collection: str) -> dict:
"""
:param document_id:
:param collection:
:return:
"""
document_filter = {"_id": ObjectId(document_id)}
if document := await greens.app.state.mongo_collection[collection].find_one(document_filter):
return await... | 4865acd4e553f651a68d694171c76d609eceff98 | 30,069 |
import requests
def get_kalliope_poststukken_uit(path, session, from_,
to=None,
dossier_types=None):
"""
Perform the API-call to get all poststukken-uit that are ready to be processed.
:param path: url of the api endpoint that we want to f... | 2976979bfcccd64939e56c2d0874f6d419028b62 | 30,070 |
import re
def export_image(filename=None, type='PNG', resolution=None, units=None, height=None, width=None, zoom=None,
network=None, base_url=DEFAULT_BASE_URL):
""" Save the current network view as an image file.
The image is cropped per the current view in Cytoscape. Consider applying :meth... | a6de6bedfea171e191500900f357709bb1a8880e | 30,071 |
import scipy
def lstsq_cholesky(
coefs: np.ndarray,
result: np.ndarray,
) -> np.ndarray:
"""Solve OLS problem using a Cholesky decomposition."""
left = coefs.T @ coefs
right = coefs.T @ result
return scipy.linalg.solve(left, right, assume_a="pos") | 08ec0988062daef04b55852d6673fb21031f9a87 | 30,072 |
import os
def get_packages(package):
"""Return root package and all sub-packages.
"""
return [dirpath
for dirpath, dirnames, filenames in os.walk(package)
if os.path.exists(os.path.join(dirpath, "__init__.py"))] | c6f51ca80d0091c448947087364fcb1ac71dc5ff | 30,073 |
import sys
def load_class_by_alias_or_classname(namespace, name):
"""Load a class using stevedore alias or the class name.
:param namespace: The namespace where the alias is defined.
:param name: The alias or class name of the class to be loaded.
:returns: Class if it can be loaded.
:raises Impor... | 30d724ea17916e523535485ed51ca610226ac39e | 30,074 |
import warnings
def _standardize(signals, demean=True, normalize=True, inplace=True,
verbose=False):
""" Center and norm a given signal (time is along first axis)
Attention: this will not center constant signals
but will replace these with colums of ones
... | f207af4e0e18f6f9f544a18ae89d0e86fd8ae493 | 30,075 |
def bbox_to_poly(bboxes: np.ndarray) -> np.ndarray:
"""
Expects bboxes in xyxy format. Turns each into a 1D array with 8 entries,
every consecutive pair being for one vertex (starting from top left and
going around clockwise)
Works with single bboxes (shape is (4, )) or multiple bboxes (shape is
... | 12a06d343ac5a1f4bd16168bf04dc7e9dfaff4ec | 30,076 |
def waypts_2_pwsplines(wp_traj, dt, degree=1, plot=False):
"""
Convert a sequence of multi-dimensional sparse waypoints
to a sequence of interpolated multi-dimensional waypoints via splines.
Parameters
----------
wp_traj: horizon * n_s, a sequence of waypoints.
dt: duration of 1 time step o... | b133159e19513fa80a282a71786e5976cad1ab9a | 30,077 |
def _bin_data(aa, bb, bins=10, verbose=False):
"""
If unbinned data has come in, do something smart
with it here.
Uses numpy.histogram for binning.
bins can be:
- int: number of bins
- list or array: bin boundaries, from min to max, half open on right,
like numpy, when bins=[1, 2, ... | a938cabaa2678a89cb1402d553041d409bfa4967 | 30,078 |
import logging
def initialize_logger(logger, logger_id, progress_bar=None, log_queue=None):
"""
Initialize logger for the :class:`pyro.infer.mcmc` module.
:param logger: logger instance.
:param str logger_id: identifier for the log record,
e.g. chain id in case of multiple samplers.
:para... | 4ea94d0bc1d6d9943cce2097f19256e3524d9521 | 30,079 |
def test_meta_plus_classmethod(namespaceable, namespace):
"""Test using a classmethod in a Namespace, while messing with metaclasses.
This might have been purely for coverage of some kind? I forget.
"""
class Meta(namespaceable, type(namespaceable)):
"""A throwaway test metaclass."""
wi... | 48ed58e8b4a0c68700ee8941087d015b76596c57 | 30,080 |
def EncodeConstants(const_dict):
"""the NPU requires that weights are compressed and bias/scales are 'encoded', both
of which are performed by this pass.
This pass modifies both the constant dict to contain the post-encoding values of the
constants and the IR to adjust buffer types/sizes/accesses so th... | 851e080bdf44e6de890fb87a1d2df1c0aefc0bf6 | 30,081 |
import collections
def count_tweet_shed_words_freq(tweet_text, ind_shed_word_dict, shed_word_ind_dict, shed_words_set):
"""
Count the frequency of selected Hedonometer words in tweet text.
param tweet_text: String of text field of tweet
return: dict of shed_word_ind to shed_word_freq mapping... | 129130f5b9def7320c6e3dd2d8ef82493d21eb8a | 30,082 |
def parse_date(text):
"""Return POSIX timestamp obtained from parsing date and time from given
date string.
Return None if no text given.
"""
if text:
return dateparser.parse(text).timestamp() | 6f089096cdd43eb2d0af1db6066e75a6ec6efb09 | 30,083 |
def format(table, field, fmt, **kwargs):
"""
Convenience function to format all values in the given `field` using the
`fmt` format string.
The ``where`` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
conversion shou... | a66e351bca42f8e385d8859db720e86c7e6fac7c | 30,084 |
def colorbias(img, refcolor=np.array([1.,0,0])):
""" Compute Color Bias """
img_hsv = skimage.color.rgb2hsv(img)
refcolor = skimage.color.rgb2hsv(refcolor.reshape(1,1,3)) # to make it compatible
#dH = np.abs(np.sin((img_hsv[...,0] - refcolor[...,0])))
#dS = np.abs(img_hsv[...,1] - refcolor[...,1])
... | 5ab089fd7a72fe647e5da5c62380544b87c41739 | 30,085 |
import six
import numbers
import collections
def walk_json(e, dict_fct=i, list_fct=i, num_fct=i, str_fct=i, bool_fct=i, null_fct=i, not_found=not_found_default):
"""
Go throught a json and call each function accordingly of the element type
for each element, the value returned is used for the json output
... | d0c9f57180327b8fca218f3ba4f413b410c2a2da | 30,086 |
def colIm(z):
"""Returns a colour where log(Im(z)) is represented by hue.
This makes it easy to see where Im(z) converges to 0"""
h = np.log(z.imag)*pi
l = np.clip(0.5+0.05*z.real,0.1,0.9)
s = 1
c = hsl2rgb(h,s,l)
return c | 0ebefac4c7c5355ba735bfa46177b6f267f74cb9 | 30,087 |
def gsl_blas_zdotc(*args, **kwargs):
"""gsl_blas_zdotc(gsl_vector_complex const * X, gsl_vector_complex const * Y, gsl_complex * dotc) -> int"""
return _gslwrap.gsl_blas_zdotc(*args, **kwargs) | 953a9cd06d0f7a948d625acad9fd8ec8ce31249e | 30,088 |
def random_neighbour(vec,myid,n):
"""Generates a random binary vector that is 1-bit away (a unit Hamming distance)
Args:
vec (list or numpy.ndarray): An input vector
myid (int): An id of an agent of interest
n (int): Number of tasks allocated to a single agent
Returns:
list... | 816115c335e556815ff8ee20ae50ac9b9c9d6f22 | 30,089 |
import torch
def _degree_of_endstopping(model, block, image, weight_id0, weight_id1, weight_id2):
"""Passes image to model and records the activations of block. The
activations are normalized to be in [0, 1] and then summed over using
different weighted masks.
Parameters
----------
model : ... | 830e8fd5b008fb8d2a852f1f365d3da1ddc24075 | 30,090 |
def posts(parsed):
"""Calculates number of every type of post"""
num_t_post = 0
num_corner_post = 0
num_line_post = 0
num_end_post = 0
num_gate_posts = 0
for post in parsed.posts():
if not post.isRemoval:
if post.postType == 'tPost':
num_t_post += 1
... | e8c5905a38ab560f0dba595eecf67865efc27121 | 30,091 |
def _compute_populations(mvts: pd.DataFrame, label_col_name) -> dict:
"""
A private method that computes the population corresponding to each class label.
:param mvts: The dataframe who class population is of interest.
:param label_col_name: The column-name corresponding to the class labels in `mvts`.
... | d47b78d8f30f6cb15c9b98cb13d9fb7c883d62f1 | 30,092 |
def plot_avg_sum_capacity_comparison(
df: pd.DataFrame, port1: str, port2: str, vessel_type: str
) -> go.Figure:
"""
Returns a figure for the first chart on the Compare tab. It shows per day comparison between
average sum of capacity by applied conditions.
:param df: Pandas DataFrame, input data
... | 8551fac8720c3d8433a5242c8ea099626a5b6e0c | 30,093 |
def fetchUrlPages(url: str, cacheDir: str = None) -> dict:
"""
Realiza a requisição dos dados da API retornando os dados paginados.
https://openbanking-brasil.github.io/areadesenvolvedor-fase1/#introducao-paginacao
"""
root = fetchUrl(url, cacheDir = cacheDir)
if root == None or not type(root) ... | 5b970007343484aff70c552887143cb0b21453b4 | 30,094 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up the rinnaitouch integration from a config entry."""
ip_address = entry.data.get(CONF_HOST)
_LOGGER.debug("Get controller with IP: %s", ip_address)
try:
system = RinnaiSystem.get_instance(ip_address)
#scenes... | 4fc535a17bffdd84a88d7808f183aee63c2bb904 | 30,095 |
def num_neighbours(lag=1):
"""
Calculate number of neigbour pixels for a given lag.
Parameters
----------
lag : int
Lag distance, defaults to 1.
Returns
-------
int
Number of neighbours
"""
win_size = 2*lag + 1
neighbours = win_size**2 - (2*(lag-... | aca8c4e1fdac14cde111a7db2dd274767fc53d5a | 30,096 |
import requests
def get_solr_data_recommend(function, reader, rows=5, sort='entry_date', cutoff_days=5, top_n_reads=10):
"""
:param reader:
:param rows:
:param sort:
:param cutoff_days:
:param top_n_reads:
:return:
"""
query = '({function}(topn({topn}, reader:{reader}, {sort} desc... | b7dbf5fc2cd8772532ab98115369199e87e80a3c | 30,097 |
def normalize_key(key):
"""
Formata a chave para ser utilizada no json.
Args:
key (string): Campo coletado no scraping dos dados do MEC.
Returns:
Retorna a sttring formatada para ser utilizada no json.
"""
aux = key.strip(' :').replace(' ', '_').lower()
... | 1065bbbd4d6c435fe9db477ee0f7a047692eaf63 | 30,098 |
def line(p0=(0,0), p1=(1,0)):
"""
p0 p1
o-----------o
+--> u
"""
p0 = np.asarray(p0, dtype='d')
p1 = np.asarray(p1, dtype='d')
points = np.zeros((2,3), dtype='d')
points[0,:p0.size] = p0
points[1,:p1.size] = p1
knots = [0,0,1,1]
return NURBS([knots], points) | 0abf0688a2e7f84322f56b35796d75497f6f65c2 | 30,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.