content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def requires_testing_data(func):
"""Skip testing data test."""
return _pytest_mark()(func) | a3f5116bc3ac1639de13355795f2bd1da67521aa | 24,700 |
def mfcc_derivative_loss(y, y_hat, derivative_op=None):
"""
Expects y/y_hat to be of shape batch_size x features_dim x time_steps (default=128)
"""
if derivative_op is None:
derivative_op = delta_matrix()
y_derivative = tf.matmul(y, derivative_op)
y_hat_derivative = tf.matmul(y_hat, deri... | 8d2b05d65ae3efb10d00f0b30d75ca45abf92064 | 24,701 |
from typing import Iterable
from typing import Tuple
from typing import Counter
def get_representative_terms(
abilities_corpus: Iterable[str], skills_corpus: Iterable[str]
) -> Tuple[list, list]:
"""Return representative terms in order of importance from the abilities and skills
corpora.
Parameters
... | 7ccb79315f50d37af9ce2c670529a6a612d1c238 | 24,702 |
import os
import yaml
from typing import OrderedDict
import sys
def get_tags_from_playbook(playbook_file):
"""Get available tags from Ansible playbook"""
tags = []
playbook_path = os.path.dirname(playbook_file)
with open(playbook_file) as playbook_fp:
playbook = yaml.safe_load(playbook_fp)
... | 0ecb9b80b29a776729bebc8f0f4da135e12c116a | 24,703 |
from typing import List
def get_mprocess_names_type1() -> List[str]:
"""returns the list of valid MProcess names of type1.
Returns
-------
List[str]
the list of valid MProcess names of type1.
"""
names = (
get_mprocess_names_type1_set_pure_state_vectors()
+ get_mproces... | e02b8e5ccc6153899fd999d669a34f14f2258170 | 24,704 |
def LoadAI(FileName):
"""LoadSC: This loads an IGOR binary file saved by LabView.
Loads LabView Scope data from igor and extracts a bunch of interesting
information (inf) from the data header"""
IBWData = igor.LoadIBW(FileName);
# I am going to store the experimental information in a dictionary
... | d1d434c72e1d50bd857bddba1c4e750f74ea901b | 24,705 |
def accept_message_request(request, user_id):
"""
Ajax call to accept a message request.
"""
sender = get_object_or_404(User, id=user_id)
acceptor = request.user
if sender in acceptor.profile.pending_list.all():
acceptor.profile.pending_list.remove(sender)
acceptor.profile.conta... | 52a7701433a3ff4acbc6adf6cea3ee64303eee02 | 24,706 |
import pytz
def pytz_timezones_from_utc_offset(tz_offset, common_only=True):
"""
Determine timezone strings corresponding to the given timezone (UTC) offset
Parameters
----------
tz_offset : int, or float
Hours of offset from UTC
common_only : bool
Whether to only return ... | 4890acae850530b4b7809afb1c09a5cf4795b443 | 24,707 |
from sage.arith.all import rising_factorial
def _sympysage_rf(self):
"""
EXAMPLES::
sage: from sympy import Symbol, rf
sage: _ = var('x, y')
sage: rfxy = rf(Symbol('x'), Symbol('y'))
sage: assert rising_factorial(x,y)._sympy_() == rfxy.rewrite('gamma')
sage: assert ris... | c3f55efdcca393cb795f35160131eb781721202a | 24,708 |
import os
def plotting_data_for_inspection(xdata,ydata,plot_title,plot_xlabel,plot_ylabel,filename_for_saving,folder_to_save, block_boolean):
"""
Plots data for user to look at within program
parameters
----------
xdata,ydata: x and y data to be plotted
plot_xlabel,plot_ylabel: label x and y... | a49b1112b27a0c69c188a0f5544e447b253ae6b3 | 24,709 |
def run_sax_on_sequences(rdd_sequences_data, paa, alphabet_size):
"""
Perform the Symbolic Aggregate Approximation (SAX) on the data provided in **ts_data**
:param rdd_sequences_data: rdd containing all sequences: returned by function *sliding_windows()*:
*sequences_data* contain a list of all seq : tu... | 4f23894355abfa29094c0b8974e2a7a2e50b6789 | 24,710 |
from typing import Union
def attack_speed(game: FireEmblemGame, unit: ActiveUnit, weapon: Union[ActiveWeapon, None]) -> int:
"""
Calculates and returns the unit's Attack Speed, based on the AS calculation method
of the current game, the unit's stats, the given weapon's Weight. If the weapon
is None, a... | 268af7ee65e6bab291818a5fece35006b1209c90 | 24,711 |
def set_pow_ref_by_upstream_turbines_in_radius(
df, df_upstream, turb_no, x_turbs,
y_turbs, max_radius, include_itself=False):
"""Add a column called 'pow_ref' to your dataframe, which is the
mean of the columns pow_%03d for turbines that are upstream and
also within radius [max_radius] of the turbi... | 10ee016f3dbd86bd047dc75a10fa13701cf64fca | 24,712 |
def load_block_production(config: ValidatorConfig, identity_account_pubkey: str):
"""
loads block production
https://docs.solana.com/developing/clients/jsonrpc-api#getblockproduction
"""
params = [
{
'identity': identity_account_pubkey
}
]
return smart_rpc_call(co... | 3af5bc21772699fa10102147fb4a3d90569d8cff | 24,713 |
from pathlib import Path
import os
import subprocess
def run_doxygen(*, conf: DoxygenConfiguration, root_dir: Path) -> int:
"""Run Doxygen.
Parameters
----------
conf
A `DoxygenConfiguration` that configures the Doxygen build.
root_dir
The directory that is considered the root of ... | ab25967fabb9848cad230c66a6a37b5cc8c7b76c | 24,714 |
def remove_metatlas_objects_by_list(object_list, field, filter_list):
"""
inputs:
object_list: iterable to be filtered by its attribute values
field: name of attribute to filter on
filter_list: strings that are tested to see if they are substrings of the attribute value
returns filte... | 8885a355fcf79696ef84d13242c28943999693b5 | 24,715 |
def resnet_encoder(inputs,
input_depth=16,
block_type='wide',
activation_fn=tf.nn.relu,
is_training=True,
reuse=None,
outputs_collections=None, scope=None):
"""Defines an encoder network based on resnet... | 80a136a2d6a4047a92a9c924e92523136017354b | 24,716 |
def execute_stored_proc(cursor, sql):
"""Execute a stored-procedure.
Parameters
----------
cursor: `OracleCursor`
sql: `str`
stored-proc sql statement.
"""
stored_proc_name, stored_proc_args = _sql_to_stored_proc_cursor_args(sql)
status = cursor.callproc(stored_proc_name, pa... | 528a5b19c208695db0eff8efdb18c1e30cb484b4 | 24,717 |
def no_order_func_nb(c: OrderContext, *args) -> Order:
"""Placeholder order function that returns no order."""
return NoOrder | 8bfb6c93930acdf03b83e90271e6904ce5a8e689 | 24,718 |
def get_queued():
"""
Returns a list of notifications that should be sent:
- Status is queued
- Has scheduled_time lower than the current time or None
"""
return PushNotification.objects.filter(status=STATUS.queued) \
.select_related('template') \
.filter(Q(scheduled_time__lte=... | 4fa14ad21a2954e1f55df562ccd10edf356b3d02 | 24,719 |
def hue_of_color(color):
"""
Gets the hue of a color.
:param color: The RGB color tuple.
:return: The hue of the color (0.0-1.0).
"""
return rgb_to_hsv(*[x / 255 for x in color])[0] | 06fd67639f707d149c1b0b21ffc0f337faf1fbe0 | 24,720 |
import requests
def recent_tracks(user, api_key, page):
"""Get the most recent tracks from `user` using `api_key`. Start at page `page` and limit results to `limit`."""
return requests.get(
api_url % (user, api_key, page, LastfmStats.plays_per_page)).json() | f0814fca86dfdcb434527ebbefcea867045359fe | 24,721 |
def extract_hdf5_frames(hdf5_frames):
"""
Extract frames from HDF5 dataset. This converts the frames to a list.
:param hdf5_frames: original video frames
:return [frame] list of frames
"""
frames = []
for i in range(len(hdf5_frames)):
hdf5_frame = hdf5_frames[str(i)]
assert l... | f22b8ef61a86de45c0801ab3ff8cba679549387b | 24,722 |
def st_oid(draw, max_value=2**512, max_size=50):
"""
Hypothesis strategy that returns valid OBJECT IDENTIFIERs as tuples
:param max_value: maximum value of any single sub-identifier
:param max_size: maximum length of the generated OID
"""
first = draw(st.integers(min_value=0, max_value=2))
... | e43daccf3b123a1d35e1c1cc9c313b580161971a | 24,723 |
import torchvision
def predict(model, image_pth=None, dataset=None):
"""
Args:
model : model
image (str): path of the image >>> ".../image.png"
dataset [Dataset.Tensor]:
Returns:
--------
predicted class
"""
transform = transforms.Compose([
transforms... | 16a0a429b0fb42ac2c58df94b25d52478d5288a7 | 24,724 |
def to_centers(sids):
""" Converts a (collection of) sid(s) into a (collection of) trixel center longitude, latitude pairs.
Parameters
----------
sids: int or collection of ints
sids to covert to vertices
Returns
--------
Centers: (list of) tuple(s)
List of centers. A cente... | 795e6f60d21997b425d60a2859a34ca56f94c7fb | 24,725 |
def get_atlas_by_id(atlas_id: str, request: Request):
"""
Get more information for a specific atlas with links to further objects.
"""
for atlas in siibra.atlases:
if atlas.id == atlas_id.replace('%2F', '/'):
return __atlas_to_result_object(atlas, request)
raise HTTPException(
... | f37079c16c6bbcf17295e7e14be21cbc3c38bd1e | 24,726 |
def load_etod(event):
"""Called at startup or when the Reload Ephemeris Time of Day rule is
triggered, deletes and recreates the Ephemeris Time of Day rule. Should be
called at startup and when the metadata is added to or removed from Items.
"""
# Remove the existing rule if it exists.
if not d... | 74f9b1d4644417263eb2bfe56543baa9ebf0d0a1 | 24,727 |
def extract_title(html):
"""Return the article title from the article HTML"""
# List of xpaths for HTML tags that could contain a title
# Tuple scores reflect confidence in these xpaths and the preference
# used for extraction
xpaths = [
('//header[@class="entry-header"]/h1[@class="entry-ti... | c9a26c6e54e0e4d26c9f807499103bce51b3a1b3 | 24,728 |
def re_send_mail(request, user_id):
"""
re-send the email verification email
"""
user = User.objects.get(pk=user_id)
try:
verify = EmailVerify.objects.filter(user = user).get()
verify.delete()
except EmailVerify.DoesNotExist:
pass
email_verify = EmailVerify(user=... | f07c7f55e8bd5b4b1282d314bf96250a031937db | 24,729 |
import os
import glob
def get_snap_filenames(base, snap_prefix, num):
"""Return a list of paths (without file extensions) to snapshot files
corresponding to the snapshot indicated by num. The list may consist of
one or multiple files, depending on how the snapshot was written.
"""
num_pad = str(n... | 305308385abb5af3da1750c8cf964f07f1a7d35b | 24,730 |
import ansible.constants
import os
def apply_playbook(playbook_path, hosts_inv=None, host_user=None,
ssh_priv_key_file_path=None, password=None, variables=None,
proxy_setting=None, inventory_file=None, become_user=None):
"""
Executes an Ansible playbook to the given host
... | f778c7ee46286fa7c9495957d66502693fd7ca3b | 24,731 |
def add_map_widget(
width: int,
height: int,
center: tuple[float, float],
zoom_level: int,
tile_server: TileServer,
) -> int | str:
"""Add map widget
Args:
width (int): Widget width
height (int): Widget height
center (tuple[float, float]): Center point coordinates:
... | b6a9bd455f8394485a48f6ba45d0084baa1b24b1 | 24,732 |
from typing import List
def _index_within_range(query: List[int], source: List[int]) -> bool:
"""Check if query is within range of source index.
:param query: List of query int
:param source: List of soure int
"""
dim_num = len(query)
for i in range(dim_num):
if query[i] > source[i]:
... | 34c595a3c498fbe1cce24eea5d5dc1866bbbcfac | 24,733 |
import json
def path_sender():
"""
Sends computed path to drones
"""
#TODO
return json.dumps({"result":2}) | 54399dffbab3c22c54e77842550ffd7fa50d4295 | 24,734 |
from typing import List
def test_transactions() -> List[TransactionObject]:
"""
Load some example transactions
"""
transaction_dict_1 = {
"amount": 1.0,
"asset_id": 23043,
"category_id": 229134,
"currency": "usd",
"date": "2021-09-19",
"external_id": Non... | 8aa52fdbf719793e9f93a276097498f70b4973a6 | 24,735 |
def modified(mctx, x):
"""``modified()``
File that is modified according to status.
"""
# i18n: "modified" is a keyword
getargs(x, 0, 0, _("modified takes no arguments"))
s = mctx.status()[0]
return [f for f in mctx.subset if f in s] | ec647f7478c587b35e9a1d7b219754fabf3940a8 | 24,736 |
def parse_declarations(lang, state, code_only=False, keep_tokens=True):
"""
Return the comments or code of state.line.
Unlike parse_line, this function assumes the parser is *not*
in the context of a multi-line comment.
Args:
lang (Language):
Syntax description for the language being... | 48b1ea0259795ef3f7acd783b704be5e4be8a79b | 24,737 |
import math
def rads_to_degs(rad):
"""Helper radians to degrees"""
return rad * 180.0 / math.pi | 1be742aa4010e2fc5678e6f911dcb21b0b4d1b59 | 24,738 |
def get_employer_jobpost(profile):
""" """
jobs = None
if profile.is_employer:
jobs = JobPost.objects.filter(user=profile.user).order_by('title', 'employment_option', 'is_active')
return jobs | d1be49c5381aedfd21d6dbceb07eeb98f1ef3dc4 | 24,739 |
def _paginate_issues_with_cursor(page_url,
request,
query,
cursor,
limit,
template,
extra_nav_parameters=None,
... | a315163a9d0e53473ce77e262edf3b7f6e663802 | 24,740 |
def overlapping(startAttribute, # X
endAttribute, # Y
startValue, # A
endValue, # B
):
"""
Return an L{axiom.iaxiom.IComparison} (an object that can be passed as the
'comparison' argument to Store.query/.sum/.count) which will const... | 66e56c9a7c66cbc385e4b7bbea4aa6c08212993e | 24,741 |
def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
many_series : list[pd.Series]
Returns
-------
aligned_series : list[pd.Series... | 6598dff7814ef20dd0f4904b6c140b6883f9283b | 24,742 |
def structConfMat(confmat, index=0, multiple=False):
"""
Creates a pandas dataframe from the confusion matrix. It distinguishes
between binary and multi-class classification.
Parameters
----------
confmat : numpy.ndarray
Array with n rows, each of one being a flattened confusion matrix... | 25b458a81a96c8d38d990cd43d3fab5c6526dabd | 24,743 |
from . import data
import datasets
import pkg_resources
def get_img(ds):
"""Get a standard image file as a Niimg
Parameters
----------
ds : str
Name of image to get.\n
Volume Masks:\n
"MNI152_T1_2mm_brain"\n
"MNI152_T1_2mm_brain_mask"\n
"MNI152_T1_2mm_brain_mas... | 0df5bbd1d5188a8d67a7078625734f4b186ca2e9 | 24,744 |
import os
def load_fish(return_X_y: bool = False, as_frame: bool = False):
"""
Loads in a subset of the Fish market dataset. You can find the full dataset [here](https://www.kaggle.com/aungpyaeap/fish-market).
Arguments:
return_X_y: return a tuple of (`X`, `y`) for convenience
as_frame: r... | c9848b4c6b83448899966d4b392de47c519bcc59 | 24,745 |
from typing import Tuple
from typing import Optional
def check_for_missing_kmers(is_fastq: bool,
subtype_result: str,
scheme: str,
df: pd.DataFrame,
exp: int,
obs: int,
... | add7449112c7720bb56a8d682030c7220991ff7b | 24,746 |
import torch
import itertools
def splat_feat_nd(init_grid, feat, coords):
"""
Args:
init_grid: B X nF X W X H X D X ..
feat: B X nF X nPt
coords: B X nDims X nPt in [-1, 1]
Returns:
grid: B X nF X W X H X D X ..
"""
wts_dim = []
pos_dim = []
grid_dims = init... | 24e798dd9cdaf51988c5229442bef4ebed14c4be | 24,747 |
from typing import Any
from typing import Optional
import torch
def q_nstep_td_error_ngu(
data: namedtuple,
gamma: Any, # float,
nstep: int = 1,
cum_reward: bool = False,
value_gamma: Optional[torch.Tensor] = None,
criterion: torch.nn.modules = nn.MSELoss(reduction='no... | eac618bddf77252e6be77f8254fa14f8e00e2c68 | 24,748 |
import time
import hashlib
def generate_activation_code(email : str) -> str:
"""
Takes email address and combines it with a timestamp before encrypting everything with the ACTIVATION_LINK_SECRET
No database storage required for this action
:param email: email
:type email: unicode
:return: act... | d2770bf9e2d15e361fa5dcf145fba978f40cb06f | 24,749 |
def fmin_sgd(*args, **kwargs):
"""
See FMinSGD for documentation. This function creates that object, exhausts
the iterator, and then returns the final self.current_args values.
"""
print_interval = kwargs.pop('print_interval', sys.maxint)
obj = FMinSGD(*args, **kwargs)
while True:
t ... | 91173eb8c2b4732c217be4ff170d5821eb1e9e5f | 24,750 |
from datetime import datetime
import time
import dateutil
import pytz
def normalize_timestamp(date_time):
"""
TODO: get rid of this function and all references to it / uses of it.
Attempt to convert a string timestamp in to a TruSTAR compatible format for submission.
Will return current time with UTC ... | 9b54dd03a3f14c42601d8d959737b7b7cfa45e88 | 24,751 |
import os
def strings_from_apk(app_file, app_dir, elf_strings):
"""Extract the strings from an app."""
try:
logger.info('Extracting Strings from APK')
dat = []
secrets = []
urls = []
urls_nf = []
emails_nf = []
apk_file = os.path.join(app_dir, app_file)
... | 6b15b340c3a5d7a00022a8db42931527216c6002 | 24,752 |
def scan(this, accumulator, seed=None):
"""Applies an accumulator function over an observable sequence and
returns each intermediate result. The optional seed value is used as
the initial accumulator value.
For aggregation behavior with no intermediate results, see OutputThing.aggregate.
1 - scanne... | 4d69686f41c93549208b2e0721e14d95c7c52321 | 24,753 |
def get_efficient_pin_order_scramble():
""" Gets an efficient pin order scramble for a Rubik's Clock. """
return _UTIL_SCRAMBLER.call("util_scramble.getClockEfficientPinOrderScramble") | edf20cd55f9e2c8e7e3aa0f73f08c34958336a44 | 24,754 |
def fixed_padding(inputs, kernel_size):
"""Pad the input along the spatial dimensions independently of input size.
This function is copied/modified from original repo:
https://github.com/tensorflow/tpu/blob/acb331c8878ce5a4124d4d7687df5fe0fadcd43b/models/official/resnet/resnet_model.py#L357
Args:
... | ac20d85fff8abd1ea6b160294f1f0a3118e09527 | 24,755 |
def _is_si_object(storage_instance):
"""
Helper method for determining if a storage instance is object.
Args:
storage_instance:
Returns: (Bool) True if object, False if not.
"""
si_type = storage_instance.get("service_configuration", None)
if si_type is None:
# object not su... | 3cc2591bb0391e6d9d62197d0bb593f5006215c8 | 24,756 |
def wgs84_to_bd09(lng, lat):
"""WGS84 -> BD09"""
lng, lat = wgs84_to_gcj02(lng, lat)
lng, lat = gcj02_to_bd09(lng, lat)
return lng, lat | e0d0b7dfa70b8e260b8fb061b50e838463ccec08 | 24,757 |
import math
def spin_images(pc1, pc2, opt = spin_image_options()):
"""Compute spin image descriptors for a point cloud
Parameters
----------
pc1 : pcloud
The function computes a spin image descriptor for each point in
the point cloud pc1
pc2 : pcloud
The points in the poi... | 2011d2c1d610655dd752f30c4efa3abe9c7d4d29 | 24,758 |
def clone_file_info(input, output):
"""clone_file_info(FileConstHandle input, FileHandle output)"""
return _RMF.clone_file_info(input, output) | 226ee2a0a2547f4bf57754187517301e649cd919 | 24,759 |
def queries_to_retract_from_dataset(client,
project_id,
dataset_id,
person_id_query,
retraction_type=None):
"""
Get list of queries to remove all records in all tables ... | b0e2512da10bf1d4742995d8b5a7ed0ec15bca6a | 24,760 |
def calc_moments(imcube, rmscube, mask=None):
"""
Calculate moments of a masked cube and their errors
Parameters
----------
imcube : SpectralCube
The image cube for which to calculate the moments and their errors.
rmscube : SpectralCube
A cube representing the noise estimate at ... | 00c43af169f650efe155dca87b3755f128a13f7f | 24,761 |
import types
import array
def value(*, source: str, current_location: types.Location) -> types.TSourceMapEntries:
"""
Calculate the source map of any value.
Args:
source: The JSON document.
current_location: The current location in the source.
Returns:
A list of JSON pointers... | 093b2df66c3577c7f24ec1cc1da3cd71bf3cdd4f | 24,762 |
import numpy as np
import re
def greplines(lines, regexpr_list, reflags=0):
"""
grepfile - greps a specific file
TODO: move to util_str, rework to be core of grepfile
"""
found_lines = []
found_lxs = []
# Ensure a list
islist = isinstance(regexpr_list, (list, tuple))
islist2 = isi... | 9bfcb7f274e2742b16caa00cded99dd42f42d694 | 24,763 |
def get_class_cnts_by_feature_null(df, class_col, feature, normalize=True):
"""
Break out class fequencies (in `df[class_col]`) by whether or not
`df[feature]` is null.
Parameters
----------
df : pandas.DataFrame
DataFrame on which this function will operate.
class_col : str
... | 9ac2ae717c2aca90ca988ad0f960365e8475a555 | 24,764 |
import gc
def systemic_vel_est(z,param_dict,burn_in,run_dir,plot_param_hist=True):
"""
Estimates the systemic (stellar) velocity of the galaxy and corrects
the SDSS redshift (which is based on emission lines).
"""
c = 299792.458
# Get measured stellar velocity
stel_vel = np.array(param_dict['stel_vel']['c... | 3d5c957147ad7f16cd664d08326ad40196f46d5e | 24,765 |
import os
def bookmark_fn(outdir):
"""Single line text file storing the epoch,brick,batch number of last ckpt"""
return os.path.join(outdir,'ckpts',
'last_epoch_brick_batch.txt') | 38680f4f723e8d724c115dddd6dbd0b7100d909a | 24,766 |
def set_model_weights(model, weights):
"""Set the given weights to keras model
Args:
model : Keras model instance
weights (dict): Dictionary of weights
Return:
Keras model instance with weights set
"""
for key in weights.keys():
model.get_layer(key).set_weights(wei... | 0adb7294348af379df0d2a7ce2101a6dc3a43be4 | 24,767 |
import os
def check_history(history_file, inputList):
"""
Method to check in the given history file if
data files have been already processed.
"""
unprocessed = list(inputList)
if not (os.path.isfile(history_file)):
LOG.warning(history_file + " does not exist yet!")
return un... | 899effc75687f461643a0d5f661e6327ee40b7a7 | 24,768 |
import re
def extract_manage_vlan(strValue):
"""处理show manage-vlan得到的信息
Args:
strValue(str): show manage-vlan得到的信息
Returns:
list: 包含管理Vlan字典的列表
"""
# ------------------------------------
# Manage name : xx
# ------------------------------------
# Svlan ... | 83ff7d5af37c9caf9bf557caa9e1d845e96706fb | 24,769 |
from typing import List
def generate_sample_space_plot_detailed(
run_directory: str,
step: int = 0,
agent_ids: List[int] = [0],
contour_z: str = "action_value",
circle_size: str = "action_visits",
) -> List[dcc.Graph]:
"""Generates detailed sample space plots for the given agents.
Paramet... | 544e3bebcb2ecb6d62f4228b13527e392a3dc51a | 24,770 |
import ntpath
def raw_path_basename(path):
"""Returns basename from raw path string"""
path = raw(path)
return ntpath.basename(path) | d1282ead5a8d5bf9705302347b2769421ece409b | 24,771 |
from typing import Dict
from typing import Tuple
from typing import Optional
def prepare_request(
url: str,
access_token: str = None,
user_agent: str = None,
ids: MultiInt = None,
params: RequestParams = None,
headers: Dict = None,
json: Dict = None,
) -> Tuple[str, RequestParams, Dict, Op... | f1ab81d32146a102c2ac7518228c4f880d988214 | 24,772 |
def require_permission(permission):
"""Pyramid decorator to check permissions for a request."""
def handler(f, *args, **kwargs):
request = args[0]
if check_permission(request, request.current_user, permission):
return f(*args, **kwargs)
elif request.current_user:
... | e9321d6eaf84b80bd41d253ebd26aabecd6660ee | 24,773 |
import _uuid
def _collapse_subgraph(graph_def, inputs, outputs, op_definition):
"""Substitute a custom op for the subgraph delimited by inputs and outputs."""
name = _uuid.uuid1().hex
# We need a default type, but it can be changed using 'op_definition'.
default_type = types_pb2.DT_FLOAT
new_graph = fuse_op... | f0f562c7d26876761a3d251d41a64aac5c432db0 | 24,774 |
def downsample_filter_simple(data_in, n_iter=1, offset=0):
"""
Do nearest-neighbor remixing to downsample data_in (..., nsamps)
by a power of 2.
"""
if n_iter <= 0:
return None
ns_in = data_in.shape[-1]
ns_out = ns_in // 2
dims = data_in.shape[:-1] + (ns_out,)
data_out = np.e... | f3b247e552ed95f28bd9f68ac00ff39db6741d77 | 24,775 |
from datetime import datetime
def _session_setup(calling_function_name='[FUNCTION NAME NOT GIVEN]'):
""" Typically called at the top of lightcurve workflow functions, to collect commonly required data.
:return: tuple of data elements: context [tuple], defaults_dict [py dict], log_file [file object].
"""
... | 95dd3cada63e8970b3f39ff2b3f3d14797f86cd8 | 24,776 |
def find_center(image, center_guess, cutout_size=30, max_iters=10):
"""
Find the centroid of a star from an initial guess of its position. Originally
written to find star from a mouse click.
Parameters
----------
image : numpy array or CCDData
Image containing the star.
center_gue... | 9357b6655ec094b058af0710eb6f410b49019b9b | 24,777 |
def zGetTraceArray(numRays, hx=None, hy=None, px=None, py=None, intensity=None,
waveNum=None, mode=0, surf=-1, want_opd=0, timeout=5000):
"""Trace large number of rays defined by their normalized field and pupil
coordinates on lens file in the LDE of main Zemax application (not in the DDE ser... | 986d69d3adae09841fb1b276e9b182a93f4c7fd7 | 24,778 |
def bin2bytes(binvalue):
"""Convert binary string to bytes.
Sould be BYTE aligned"""
hexvalue = bin2hex(binvalue)
bytevalue = unhexlify(hexvalue)
return bytevalue | ecc90282e7b247f0e87f8349e382d2b2a194cf77 | 24,779 |
import six
import os
def bind_and_listen_on_posix_socket(socket_name, accept_callback):
"""
:param accept_callback: Called with `PosixSocketConnection` when a new
connection is established.
"""
assert socket_name is None or isinstance(socket_name, six.text_type)
assert callable(accept_call... | 70223fc193a0071ddc34b8362983002f02343e6c | 24,780 |
from typing import Optional
def _report_maker(
*,
tback: str,
func_name: Optional[str] = None,
header: Optional[str] = None,
as_attached: bool = False,
) -> Report:
"""
Make report from
Args:
tback(str): traceback for report.
func_name(str, optional)... | a4ff80557944d774b162ac0671dd6997243ff49f | 24,781 |
def moments(data,x0=None,y0=None):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution by calculating its
moments """
total = data.sum()
X, Y = np.indices(data.shape)
x = (X*data).sum()/total
y = (Y*data).sum()/total
col = data[:, int(y)]
width_x ... | d88f8aa9938d397c205135bd1174be64bdf32d5f | 24,782 |
def string_to_bytes(size, assume_binary=False):
"""Convert human-readable size str to bytes and return an int."""
LOG.debug('size: %s, assume_binary: %s', size, assume_binary)
scale = 1000
size = str(size)
tmp = REGEX_SIZE_STRING.search(size.upper())
# Raise exception if string can't be parsed as a size
... | 7d87cecacf48e854016d428edc7b93704b2ad5ad | 24,783 |
def VecStack(vector_list, axis=0):
""" This is a helper function to stack vectors """
# Determine output size
single_vector_shape = [max([shape(vector)[0] for vector in vector_list]), max([shape(vector)[1] for vector in vector_list])]
vector_shape = dcopy(single_vector_shape)
vector_shape[axis] *= ... | 5a2b00ec25fc34dc7a24a493b7e72edb13fbf1b9 | 24,784 |
def precook(s, n=4, out=False):
"""
Takes a string as input and returns an object that can be given to
either cook_refs or cook_test. This is optional: cook_refs and cook_test
can take string arguments as well.
:param s: string : sentence to be converted into ngrams
:param n: int : number of ... | 556af462015429173464574de0103a6f661355f7 | 24,785 |
def get_full_path(path, nx_list_subgraph):
"""Creates a numpy array of the line result.
Args:
path (str): Result of ``nx.shortest_path``
nx_list_subgraph (list): See ``create_shortest path`` function
Returns:
ndarray: Coordinate pairs along a path.
"""
p_list = []
curp ... | 1849341431bf24d0dbe0920ca1ae955a6280415f | 24,786 |
def get_compliance_site_case_notifications(data, request):
"""
returns the count of notification for a compliance site case and all visit cases under it.
"""
ids = [item["id"] for item in data]
notifications = (
ExporterNotification.objects.filter(
user_id=request.user.pk, organ... | 639b4ef0425573e3f7806b18c7d03221d5db3932 | 24,787 |
def _call_function(self, *args, **kwargs):
"""
Monkey patching method. Odoo 11.0
Hiện tại request webhook của facebook gửi cả 2 type là 'http' và 'json' nên rơi vào exception BadRequest.
Phương thức này ghi đè lên method ban đầu.
TODO: Cần tìm giải pháp tối ưu hơn, ví dụ tạo một server riêng để nhận... | 1c42d03d7e09094ed3903423f3eeb797870f8069 | 24,788 |
def compare_two_data_lists(data1, data2):
"""
Gets two lists and returns set difference of the two lists.
But if one of them is None (file loading error) then the return value is None
"""
set_difference = None
if data1 is None or data2 is None:
set_difference = None
else:
set... | 6e926d3958544d0d8ce1cbcb54c13535c74ab66b | 24,789 |
from typing import Any
from datetime import datetime
def get_on_request(field: Any, default_value: Any) -> Any:
"""
Функция получения значений
Args:
field: поле
default_value: если пустое то подставим это значение
Return:
значение поля или дефолтное
"""
if isinstance(fi... | 598f47d996618cfcf3790fe7497c6d51508efc48 | 24,790 |
def aptamer(ligand, piece='whole', liu=False):
"""
Construct aptamer sequences.
Parameters
----------
ligand: 'theo'
Specify the aptamer to generate. Right now only the theophylline
aptamer is known.
piece: 'whole', '5', '3', or 'splitter'
Specify which part of the ap... | 1d3b3803022d0529ff9fa393779aec5fd36cb94b | 24,791 |
def bootstrap_ci(dataframe, kind='basic'):
"""Generate confidence intervals on the 1-sigma level for bootstrapped data
given in a DataFrame.
Parameters
----------
dataframe: DataFrame
DataFrame with the results of each bootstrap fit on a row. If the
t-method is to be used, a Panel i... | 073276c5cf28b384716352ec386091ed252de72c | 24,792 |
import re
def get_Trinity_gene_name(transcript_name):
"""
extracts the gene name from the Trinity identifier as the prefix
"""
(gene_name, count) = re.subn("_i\d+$", "", transcript_name)
if count != 1:
errmsg = "Error, couldn't extract gene_id from transcript_id: {}".format(transcript_nam... | 4c1ab87285dbb9cdd6a94c050e6dbed27f9f39bf | 24,793 |
import regex
def exclude_block_notation(pattern: str, text: str) -> str:
"""
行を表現するテキストから、ブロック要素の記法を除外\n
除外した結果をInline Parserへ渡すことで、Block/Inlineの処理を分離することができる
:param pattern: 記法パターン
:param text: 行テキスト
:return: 行テキストからブロック要素の記法を除外した文字列
"""
return regex.extract_from_group(pattern, text,... | 803d084a383b454da6d1c69a5d99ad0b4777eea7 | 24,794 |
def envfile_to_params(data):
"""
Converts environment file content into a dictionary with all the parameters.
If your input looks like:
# comment
NUMBER=123
KEY="value"
Then the generated dictionary will be the following:
{
"NUMBER": "123",
"KEY": "value"
}
"""
params = filter(lambda x: len(x) == 2,... | 03d3b4eb7ea5552938e6d42dcfd4554a1fe89422 | 24,795 |
import tokenize
def greedy_decode(input_sentence, model, next_symbol=next_symbol, tokenize=tokenize, detokenize=detokenize):
"""Greedy decode function.
Args:
input_sentence (string): a sentence or article.
model (trax.layers.combinators.Serial): Transformer model.
Returns:
string... | 416d61827ecb54c5ef85e2669c9905d5b20ecbf3 | 24,796 |
def get_browser_errors(driver):
"""
Checks browser for errors, returns a list of errors
:param driver:
:return:
"""
try:
browserlogs = driver.get_log('browser')
except (ValueError, WebDriverException) as e:
# Some browsers does not support getting logs
print(f"Could n... | fda6953703053fa16280b8a99aa91165625f6aa9 | 24,797 |
def get_user(request, user_id):
"""
Endpoint for profile given a user id.
:param request: session request.
:param user_id: id of user.
:return: 200 - user profile.
401 - login required.
404 - user not found.
"""
try:
get_user = User.objects.get(id=user_id)
... | cd790d93ed9f5f974fe4b6868f10cf2f4470f93c | 24,798 |
def get_file_ext(url):
""" Returns extension of filename of the url or path """
return get_filename(url).split('.')[-1] | 419f8b1e8caac13aed500563e94cc28e40669156 | 24,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.