content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def network_instance_create(network, host, attrs=None):
"""
Creates a network_instance of given kind and host, configuring it with the given attributes.
Parameter *kind*:
The parameter *kind* must be a string identifying one of the supported
network_instance kinds.
Parameter *host*:
The parameter *host* ... | 23efa27090081bc59f917cdcf7497f75be0f93b4 | 11,423 |
def update_get():
"""Fetches the state of the latest update job.
Returns:
On success, a JSON data structure with the following properties:
status: str describing the status of the job. Can be one of
["NOT_RUNNING", "DONE", "IN_PROGRESS"].
Example:
{
... | 9e1a2438fc8b4d1dd1bd1354d478c4d4e3e58098 | 11,424 |
def create_github_url(metadata, is_file=False):
"""Constrói a URL da API
Constrói a URL base da API do github a partir
dos dados presentes no metadata.
Args:
metadata: JSON com informações acerca do dataset.
is_file: FLAG usada pra sinalizar se o dataset é apenas um elemento.
"""
url_params = metadata['url'... | 6c138d92cd7b76f87c225a1fd98e7d397b0d6d28 | 11,425 |
def kge_2012(obs, sim, missing="drop", weighted=False, max_gap=30):
"""Compute the (weighted) Kling-Gupta Efficiency (KGE).
Parameters
----------
sim: pandas.Series
Series with the simulated values.
obs: pandas.Series
Series with the observed values.
missing: str, optional
... | 974735f9deb8ffedf88711af5c059ac0aae90218 | 11,426 |
def hms_to_dms(h, m, s):
"""
Convert degrees, arcminutes, arcseconds to an ``(hour, minute, second)``
tuple.
"""
return degrees_to_dms(hms_to_degrees(h, m, s)) | b99b051699f8a5395fe24e2e909f1690c0e67e4c | 11,427 |
def getChiv6ch(mol):
"""
Chiv6h related to ring 6
"""
return getChivnch(mol, 6) | 31a688b1d0b98b75d81b9c4c5e93bb8d62ee732e | 11,429 |
def is_outside_of_range(type_key: CLTypeKey, value: int) -> bool:
"""Returns flag indicating whether a value is outside of numeric range associated with the CL type.
"""
constraints = NUMERIC_CONSTRAINTS[type_key]
return value < constraints.MIN or value > constraints.MAX | fb8ec41d7edc094242df6bad13b8f32285a86007 | 11,430 |
def read_skel(dset, path):
"""
:param dset: name of dataset, either 'ntu-rgbd' or 'pku-mmd'
:param path: path to the skeleton file
:return:
"""
if dset == 'ntu-rgbd':
file = open(path, 'r')
lines = file.readlines()
num_lines = len(lines)
num_frames = int(lines[0])
# print(num_lines, num_... | f461ecb30ec1e7b66ce5d162ccc21b3ba34e6be8 | 11,431 |
def humanize_date(date_string):
""" returns dates as in this form: 'August 24 2019' """
return convert_date(date_string).strftime("%B %d %Y") | d9656af2c4091219d6ee259b557caadbde2cc393 | 11,432 |
def tree_sanity_check(tree: Node) -> bool:
"""
Sanity check for syntax trees: One and the same node must never appear
twice in the syntax tree. Frozen Nodes (EMTPY_NODE, PLACEHOLDER)
should only exist temporarily and must have been dropped or eliminated
before any kind of tree generation (i.e. parsi... | 03b61729c67859bbf9820489ef8fc9768ea59f9f | 11,435 |
def compute_std_error(g,theta,W,Omega,Nobs,Nsim=1.0e+10,step=1.0e-5,args=()):
""" calculate standard errors from minimum-distance type estimation
g should return a vector with:
data moments - simulated moments as a function of theta
Args:
g (callable): moment function (ret... | 176710e3b6c18efc535c67e257bc1014b4862135 | 11,437 |
def lhs(paramList, trials, corrMat=None, columns=None, skip=None):
"""
Produce an ndarray or DataFrame of 'trials' rows of values for the given parameter
list, respecting the correlation matrix 'corrMat' if one is specified, using Latin
Hypercube (stratified) sampling.
The values in the i'th column... | 787042db9773f4da6a2dbb4552269ac2740fb02e | 11,438 |
def percentError(mean, sd, y_output, logits):
""" Calculates the percent error between the prediction and real value.
The percent error is calculated with the formula:
100*(|real - predicted|)/(real)
The real and predicted values are un normalized to see how accurate the true
predictions ... | 017291a71388ccf2ecb8db6808965b164dfbfe3d | 11,439 |
def parse_multiple_files(*actions_files):
"""Parses multiple files. Broadly speaking, it parses sequentially all
files, and concatenates all answers.
"""
return parsing_utils.parse_multiple_files(parse_actions, *actions_files) | 186a984d91d04ae82f79e7d22f24bd834b8a0366 | 11,441 |
def frequent_combinations(spark_df: DataFrame, n=10, export=True):
"""
takes a dataframe containing visitor logs and computes n most frequent visitor-visite pairs
:param spark_df: Spark Dataframe
:param n: number of top visitors
:return: pandas dataframe with visitor-visite pairs
"""
# com... | 5a4ce5e8199acd1462414fa2de95d4af48923434 | 11,442 |
import random
def reservoir_sampling(items, k):
"""
Reservoir sampling algorithm for large sample space or unknow end list
See <http://en.wikipedia.org/wiki/Reservoir_sampling> for detail>
Type: ([a] * Int) -> [a]
Prev constrain: k is positive and items at least of k items
Post constrain: the... | ab2d0dc2bb3cb399ae7e6889f028503d165fbbe4 | 11,443 |
import json
def create_db_engine(app: Flask) -> Engine:
"""Create and return an engine instance based on the app's database configuration."""
url = URL(
drivername=app.config['DATABASE_DRIVER'],
username=app.config['DATABASE_USER'],
password=app.config['DATABASE_PASSWORD'],
hos... | 5a67f294b58e699345f517ae07c80851ae30eca9 | 11,444 |
import math
def wgs84_to_gcj02(lat, lng):
"""
WGS84转GCJ02(火星坐标系)
:param lng:WGS84坐标系的经度
:param lat:WGS84坐标系的纬度
:return:
"""
dlat = _transformlat(lng - 105.0, lat - 35.0)
dlng = _transformlng(lng - 105.0, lat - 35.0)
radlat = lat / 180.0 * pi
magic = math.sin(radlat)
magic =... | 64f2d8a088a159c5751838ba1fc00824bcc3e91e | 11,445 |
def _normalize_kwargs(kwargs, kind='patch'):
"""Convert matplotlib keywords from short to long form."""
# Source:
# github.com/tritemio/FRETBursts/blob/fit_experim/fretbursts/burst_plot.py
if kind == 'line2d':
long_names = dict(c='color', ls='linestyle', lw='linewidth',
... | 829f4dfd449064f4c1fc92aa8e481364eb997973 | 11,446 |
def fprime_to_jsonable(obj):
"""
Takes an F prime object and converts it to a jsonable type.
:param obj: object to convert
:return: object in jsonable format (can call json.dump(obj))
"""
# Otherwise try and scrape all "get_" getters in a smart way
anonymous = {}
getters = [attr for att... | 899674167b51cd752c7a8aaa9979856218759022 | 11,447 |
import torch
def subsequent_mask(size: int) -> Tensor:
"""
Mask out subsequent positions (to prevent attending to future positions)
Transformer helper function.
:param size: size of mask (2nd and 3rd dim)
:return: Tensor with 0s and 1s of shape (1, size, size)
"""
mask = np.triu(np.ones((... | e065c32164d5250215c846aef39d510f6a93f0cd | 11,448 |
def process_entries(components):
"""Process top-level entries."""
data = {}
for index, value in enumerate(STRUCTURE):
label = value[0]
mandatory = value[1]
# Raise error if mandatory elements are missing
if index >= len(components):
if mandatory is True:
... | 344b9aa601b71fd9352fdb412d9dfa7492312d1a | 11,449 |
from typing import Tuple
def normalize_input_vector(trainX: np.ndarray, testX: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Normalize the input vector
Args:
trainX (np.ndarray): train embedding array.
testX (np.ndarray): test embedding array.
Returns:
np.ndarray, np.ndarray: ... | 34324541e7db302bd46d41f70bd7fdedb6055ae6 | 11,450 |
def update_cache(cache_data, new_data, key):
"""
Add newly collected data to the pre-existing cache data
Args:
cache_data (dict): Pre-existing chip data
new_data (dict): Newly acquired chip data
key (str): The chip UL coordinates
Returns:
"""
if key in cache_data.keys(... | f439f34d1e95ccd69dc10d5f8c06ca20fc869b1e | 11,451 |
def status(command, **keys):
"""Run a subprogram capturing it's output and return the exit status."""
return _captured_output(command, **keys).status | f2bb97448a812548dfbdea770db9a43d8c46301a | 11,452 |
def normalize(flow: Tensor) -> Tensor:
"""Re-scales the optical flow vectors such that they correspond to motion on the normalized pixel coordinates
in the range [-1, 1] x [-1, 1].
Args:
flow: the optical flow tensor of shape (B, 2, H, W)
Returns:
The optical flow tensor with flow vect... | 9164686650e0728ba1d99b65e5757b0e12d6c934 | 11,453 |
def to_graph6_bytes(G, nodes=None, header=True):
"""Convert a simple undirected graph to bytes in graph6 format.
Parameters
----------
G : Graph (undirected)
nodes: list or iterable
Nodes are labeled 0...n-1 in the order provided. If None the ordering
given by ``G.nodes()`` is used.... | 05617e6ebe6d4a374bfa125e3b5afb1bca3304c1 | 11,454 |
def get_arrays_from_img_label(img, label, img_mode=None):
"""Transform a SimpleITK image and label map into numpy arrays, and
optionally select a channel.
Parameters:
img (SimpleITK.SimpleITK.Image): image
label (SimpleITK.SimpleITK.Image): label map
img_mode (int or None): optional mode c... | 902cd2cd5f31121e4a57a335a37b42b4caeafb4a | 11,455 |
def _get_error_code(exception):
"""Get the most specific error code for the exception via superclass"""
for exception in exception.mro():
try:
return error_codes[exception]
except KeyError:
continue | c4c9a2ec2f5cf510b6e9a7f6058287e4faf7b5b4 | 11,456 |
def render_pep440_branch(pieces):
"""TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
The ".dev0" means not master branch. Note that .dev0 sorts backwards
(a feature branch will appear "older" than the master branch).
Exceptions:
1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
"""
if pieces["close... | 0f1c1207016695ee1440fea214f8f92f8c6398ac | 11,457 |
import json
def read_json_file(file_name: str, encoding: str = "utf-8") -> dict:
"""Reads a json file
:param file_name: path
:param encoding: encoding to use
:return: dict content
"""
with open(file_name, "r", encoding=encoding) as json_file:
return json.load(json_f... | 313aee72b06303dfffd8a2e9f3641d1346329a91 | 11,458 |
def pretty_print_row(col_full_widths, row, max_field_size):
"""
pretty print a row such that each column is padded to have the widths in the col_full_widths vector
"""
start = "| "
if len(row) == len(col_full_widths):
end = " |"
else:
end = "|"
return start + "|".join(pretty_... | c94807e4de18e4454e0263e25f4103cd914df2cd | 11,459 |
def _get_data_for_agg(new_svarcube, new_tacube):
"""Reshape data for use in iris aggregator based on two cubes."""
dims_to_collapse = set()
dims_to_collapse.update(new_svarcube.coord_dims('air_pressure'))
untouched_dims = set(range(new_svarcube.ndim)) -\
set(dims_to_collapse)
dims = list(unt... | 51c2683e3477528809fcf229c94125020cdfee6d | 11,460 |
def refs_changed_by_other_cc(current_user):
"""
Return dictionary with id of reference and log object changed by other cooperative centers
"""
current_user_cc = current_user.profile.get_attribute('cc')
result_list = defaultdict(list)
# get last references of current user cooperative center
... | aa2012f1efe6eeb796e3871af691b685e3388e67 | 11,461 |
from typing import Dict
def chain_head(head: int, child: int, heads: Dict[int, int]):
"""
>>> chain_head(0, 2, {1: 2, 2: 3, 3: 0})
True
>>> chain_head(2, 0, {1: 2, 2: 3, 3: 0})
False
"""
curr_child = child
while curr_child != -1:
if curr_child == head:
return True
... | d786d3dbbdc496a1a7515d9df04fa2a09968b87d | 11,462 |
def UpgradeFile(file_proto):
"""In-place upgrade a FileDescriptorProto from v2[alpha\d] to v3alpha.
Args:
file_proto: v2[alpha\d] FileDescriptorProto message.
"""
# Upgrade package.
file_proto.package = UpgradedType(file_proto.package)
# Upgrade imports.
for n, d in enumerate(file_proto.dependency):
... | 942646c67bb987757449fbb16a6164008957cf99 | 11,463 |
import ipaddress
import logging
def _get_ip_block(ip_block_str):
""" Convert string into ipaddress.ip_network. Support both IPv4 or IPv6
addresses.
Args:
ip_block_str(string): network address, e.g. "192.168.0.0/24".
Returns:
ip_block(ipaddress.ip_network)
"""
... | b887c615091926ed7ebbbef8870e247348e2aa27 | 11,464 |
def mul_ntt(f_ntt, g_ntt, q):
"""Multiplication of two polynomials (coefficient representation)."""
assert len(f_ntt) == len(g_ntt)
deg = len(f_ntt)
return [(f_ntt[i] * g_ntt[i]) % q for i in range(deg)] | 504838bb812792b6bb83b1d485e4fb3221dec36e | 11,465 |
def _expected_datatypes(product_type):
"""
Aux function. Contains the most current lists of keys we expect there to be in the different forms of metadata.
"""
if product_type == "SLC":
# Only the datetimes need to be parsed.
expected_dtypes = {
"acquisition_start_utc": "pars... | ea5a2d78bc5693259955e60847de7a663dcdbf2c | 11,467 |
from typing import List
import copy
def convert_vecs_to_var(
c_sys: CompositeSystem, vecs: List[np.ndarray], on_para_eq_constraint: bool = True
) -> np.ndarray:
"""converts hs of povm to vec of variables.
Parameters
----------
c_sys : CompositeSystem
CompositeSystem of this state.
vec... | cea5d80a7213e12113b1bec425b142667f9bb36e | 11,468 |
def timetable_to_subrip(aligned_timetable):
"""
Converts the aligned timetable into the SubRip format.
Args:
aligned_timetable (list[dict]):
An aligned timetable that is output by the `Aligner` class.
Returns:
str:
Text representing a SubRip file.
"""
#... | cddcf115ccb9441966d9c1a0a2b67ba25e00e6da | 11,470 |
from re import T
def add(a: T.Tensor, b: T.Tensor) -> T.Tensor:
"""
Add tensor a to tensor b using broadcasting.
Args:
a: A tensor
b: A tensor
Returns:
tensor: a + b
"""
return a + b | a555de4341b874163c551fff4b7674af1e60ace2 | 11,471 |
def integrate(que):
"""
check if block nears another block and integrate them
@param que: init blocks
@type que: deque
@return: integrated block
@rtype: list
"""
blocks = []
t1, y, x = que.popleft()
blocks.append([y, x])
if t1 == 2:
blocks.append([y, x + 1])
elif ... | a91235f34e1151b6dd9c6c266658cca86b375278 | 11,472 |
def test_binary_query(cbcsdk_mock):
"""Testing Binary Querying"""
called = False
def post_validate(url, body, **kwargs):
nonlocal called
if not called:
called = True
assert body['expiration_seconds'] == 3600
else:
assert body['expiration_seconds']... | 5cfd7c7d1ab714b342e13c33cf896032f8387cde | 11,473 |
import typing
def parse_struct_encoding(struct_encoding: bytes) -> typing.Tuple[typing.Optional[bytes], typing.Sequence[bytes]]:
"""Parse an array type encoding into its name and field type encodings."""
if not struct_encoding.startswith(b"{"):
raise ValueError(f"Missing opening brace in struct type encoding: {... | 47455b192049b976dce392b928932d8291d1d008 | 11,474 |
def _comp_point_coordinate(self):
"""Compute the point coordinates needed to plot the Slot.
Parameters
----------
self : Slot19
A Slot19 object
Returns
-------
point_list: list
A list of Points
"""
Rbo = self.get_Rbo()
# alpha is the angle to rotate Z0 so ||Z1... | c74c28af57ea90f208ac61cd2433376e9c1a47ac | 11,475 |
import inspect
def getargspec(func):
"""Like inspect.getargspec but supports functools.partial as well."""
if inspect.ismethod(func):
func = func.__func__
if type(func) is partial:
orig_func = func.func
argspec = getargspec(orig_func)
args = list(argspec[0])
default... | df1745daaf7cad09d75937cce399d705ce10de2b | 11,476 |
from typing import Optional
from typing import Union
from typing import Tuple
from typing import Dict
def empirical_kernel_fn(f: ApplyFn,
trace_axes: Axes = (-1,),
diagonal_axes: Axes = ()
) -> EmpiricalKernelFn:
"""Returns a function that comp... | 890de1ebdd5f41f5aa257cedf1f03325f11e707c | 11,477 |
def read_image_batch(image_paths, image_size=None, as_list=False):
"""
Reads image array of np.uint8 and shape (num_images, *image_shape)
* image_paths: list of image paths
* image_size: if not None, image is resized
* as_list: if True, return list of images,
else return np.ndarray ... | 7ee4e01682c5175a6b22db5d48acdb76471d03da | 11,478 |
def dc_vm_backup(request, dc, hostname):
"""
Switch current datacenter and redirect to VM backup page.
"""
dc_switch(request, dc)
return redirect('vm_backup', hostname=hostname) | 168576ac2b3384c1e35a1f972b7362a9ba379582 | 11,479 |
def compute_total_distance(path):
"""compute total sum of distance travelled from path list"""
path_array = np.diff(np.array(path), axis=0)
segment_distance = np.sqrt((path_array ** 2).sum(axis=1))
return np.sum(segment_distance) | c0c4d0303bdeaafdfda84beb65fd4e60a4ff7436 | 11,480 |
def get_relative_positions_matrix(length_x, length_y, max_relative_position):
"""Generates matrix of relative positions between inputs."""
range_vec_x = tf.range(length_x)
range_vec_y = tf.range(length_y)
# shape: [length_x, length_y]
distance_mat = tf.expand_dims(range_vec_x, -1) - tf.expand_dims(... | 661cabfbcb3e8566dd8d9ec4e56a71a4d62091fd | 11,481 |
def func_split_item(k):
""" Computes the expected value and variance of the splitting item random variable S.
Computes the expression (26b) and (26c) in Theorem 8. Remember that r.v. S is the value of index s
such that $\sum_{i=1}^{s-1} w(i) \leq k$ and $\sum_{i=1}^s w(i) > k$.
Args:
k: Int. T... | 84ec7f4d76ced51ebdbd28efdc252b5ff3809e79 | 11,482 |
def eq(equation: str) -> int:
"""Evaluate the equation."""
code = compile(equation, "<string>", "eval")
return eval(code) | 5e88cad8009dc3dcaf36b216fa217fbadfaa50b3 | 11,483 |
def is_client_in_data(hass: HomeAssistant, unique_id: str) -> bool:
"""Check if ZoneMinder client is in the Home Assistant data."""
prime_config_data(hass, unique_id)
return const.API_CLIENT in hass.data[const.DOMAIN][const.CONFIG_DATA][unique_id] | 740e74b2d77bcf29aba7d2548930a98ec508fec0 | 11,484 |
from datetime import datetime
def parse_date(datestr):
""" Given a date in xport format, return Python date. """
return datetime.strptime(datestr, "%d%b%y:%H:%M:%S") | b802a528418a24300aeba3e33e9df8a268f0a27b | 11,485 |
def generate_database(m, n, uni_range_low=None, uni_range_high=None, exact_number=False):
"""
- Generate Universe by picking n random integers from low (inclusive) to high (exclusive).
If exact_number, then Universe.size == n
- Generate a Database of m records, over the Universe
"""
# generat... | a6fad1192d0c286f7fdb585933b5648f0ee9cb4c | 11,486 |
from Foundation import NSUserDefaults as NSUD
def interface_style():
"""Return current platform interface style (light or dark)."""
try: # currently only works on macOS
except ImportError:
return None
style = NSUD.standardUserDefaults().stringForKey_("AppleInterfaceStyle")
if style == "Da... | 5c30da34a3003ec52c3f97fb86dbf2ba73101a88 | 11,487 |
def get_num_forces(cgmodel):
"""
Given a CGModel() class object, this function determines how many forces we are including when evaluating the energy.
:param cgmodel: CGModel() class object
:type cgmodel: class
:returns:
- total_forces (int) - Number of forces in the coarse grained model
... | 5f5b897f1b0def0b858ca82319f9eebfcf75454a | 11,488 |
def cybrowser_dialog(id=None, text=None, title=None, url=None, base_url=DEFAULT_BASE_URL):
"""Launch Cytoscape's internal web browser in a separate window
Provide an id for the window if you want subsequent control of the window e.g., via cybrowser hide.
Args:
id (str): The identifier for the new ... | d892fe1a4e48cba8f8561fbe208aec7e2cb4afd7 | 11,489 |
def initialize_stat_dict():
"""Initializes a dictionary which will hold statistics about compositions.
Returns:
A dictionary containing the appropriate fields initialized to 0 or an
empty list.
"""
stat_dict = dict()
for lag in [1, 2, 3]:
stat_dict['autocorrelation' + str(lag)] = []
stat_dict... | 42a10b93a960663a42260e1a77d0e8f5a4ff693a | 11,490 |
def nrrd_to_nii(file):
"""
A function that converts the .nrrd atlas to .nii file format
Parameters
----------
file: tuples
Tuple of coronal, sagittal, and horizontal slices you want to view
Returns
-------
F_im_nii: nibabel.nifti2.Nifti2Image
A nifti file format that is... | 240e94758ef3f52d4e9a4ebb6f0574ade13a1044 | 11,491 |
def reqeustVerifyAuthhandler(request):
"""
본인인증 전자서명을 요청합니다.
- 본인인증 서비스에서 이용기관이 생성하는 Token은 사용자가 전자서명할 원문이 됩니다. 이는 보안을 위해 1회용으로 생성해야 합니다.
- 사용자는 이용기관이 생성한 1회용 토큰을 서명하고, 이용기관은 그 서명값을 검증함으로써 사용자에 대한 인증의 역할을 수행하게 됩니다.
"""
try:
# Kakaocert 이용기관코드, Kakaocert 파트너 사이트에서 확인
clientCode =... | 75bce664f11804ed0abb649ce80ef261ebfd0a34 | 11,492 |
import ipaddress
import six
def cidr_validator(value, return_ip_interface=False):
"""Validate IPv4 + optional subnet in CIDR notation"""
try:
if '/' in value:
ipaddr, netmask = value.split('/')
netmask = int(netmask)
else:
ipaddr, netmask = value, 32
... | 1c0afd08f3f4f079dc4004400449fe6e27cf0ef7 | 11,494 |
def rh2a(rh, T, e_sat_func=e_sat_gg_water):
"""
Calculate the absolute humidity from relative humidity, air temperature,
and pressure.
Parameters
----------
rh:
Relative humidity in Pa / Pa
T:
Temperature in K
e_sat_func: func, optional
Function to estimate the s... | cabbae69d28a68531cf79dfe645e0065ab34534e | 11,495 |
def encoder_decoder_generator(start_img):
"""
"""
layer1 = Conv2D(64, kernel_size=4, strides=2, activation='elu', padding='same')(start_img)
layer2 = Conv2D(64, kernel_size=4, strides=2, activation='elu', padding='same')(layer1)
layer3 = Conv2D(64, kernel_size=4, strides=1, activation='elu', paddin... | 9f0ccb7ebae8f0742fdcd464ce9cd072a9099d3e | 11,496 |
def off():
"""
Turns the buzzer off (sets frequency to zero Hz)
Returns:
None
"""
return _rc.writeAttribute(OPTYPE.BUZZER_FREQ, [0]) | 66e2160fed93ba49bf6c39dff0003a05f2875a77 | 11,497 |
def get_shodan_dicts():
"""Build Shodan dictionaries that hold definitions and naming conventions."""
risky_ports = [
"ftp",
"telnet",
"http",
"smtp",
"pop3",
"imap",
"netbios",
"snmp",
"ldap",
"smb",
"sip",
"rdp",
... | 2aace61b8339db848e95758fcb9f30856915d6fc | 11,499 |
def safe_download(f):
"""
Makes a download safe, by trapping any app errors and redirecting
to a default landing page.
Assumes that the first 2 arguments to the function after request are
domain and app_id, or there are keyword arguments with those names
"""
@wraps(f)
def _safe_download(... | 1d48c48ac067fcc180af37b90949123c5dc864d9 | 11,500 |
def Moebius(quaternion_or_infinity, a,b=None,c=None,d=None):
"""
The Moebius transformation of a quaternion (z)
with parameters a,b,c and d
>>> import qmath
>>> a = qmath.quaternion([1,1,1,0])
>>> b = qmath.quaternion([-2,1,0,1])
>>> c = qmath.quaternion([1,0,0,0])
>>> d = qmath.quaterni... | 9bfd05268caa6aad1247886717932ca332212e4b | 11,501 |
def _passthrough_zotero_data(zotero_data):
"""
Address known issues with Zotero metadata.
Assumes zotero data should contain a single bibliographic record.
"""
if not isinstance(zotero_data, list):
raise ValueError('_passthrough_zotero_data: zotero_data should be a list')
if len(zotero_d... | cec2271a7a966b77e2d380686ecccc0307f78116 | 11,502 |
import json
def telebot():
"""endpoint responsible to parse and respond bot webhook"""
payload = json.loads(request.data)
message = payload.get('message', payload.get('edited_message',''))
msg_from = message.get('from')
user_id = msg_from.get('id')
user_first_name = msg_from.get('first_name','... | 3a42fee4a89e1be3fa1ec17da21738bfcefba4ba | 11,503 |
def root(tmpdir):
"""Return a pytest temporary directory"""
return tmpdir | 9fa01d67461f8ce1e3d3ad900cf8a893c5a075aa | 11,505 |
from app.crud.core import ready
import logging
def _check_storage(log_fn: tp.Callable) -> bool:
"""See if the storage system is alive."""
try:
log_fn('Attempting to contact storage system', depth=1)
result = ready()
return result
except Exception as ex:
log_fn(ex, level=lo... | b20ca64094126a40fd8eb0ce76e3329c8b4da6cb | 11,506 |
def ignore_ip_addresses_rule_generator(ignore_ip_addresses):
"""
generate tshark rule to ignore ip addresses
Args:
ignore_ip_addresses: list of ip addresses
Returns:
rule string
"""
rules = []
for ip_address in ignore_ip_addresses:
rules.append("-Y ip.dst != {0}".fo... | 3ac43f28a4c8610d4350d0698d93675572d6ba44 | 11,507 |
def readmission(aFileName):
"""
Load a mission from a file into a list. The mission definition is in the Waypoint file
format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).
This function is used by upload_mission().
"""
print "\nReading mission from file: %s" % aFil... | 08e92ef784340dcd9bbd3ca8bb85a9c8a9211841 | 11,508 |
def remove_stop_words(words):
"""Remove all stop words.
Args:
words (list): The list of words
Returns:
list: An updated word list with stopwords removed.
"""
# http://stackoverflow.com/questions/5486337/
# how-to-remove-stop-words-using-nltk-or-python
return [w for w in wor... | 29910d1c04cb27ac281428a5401501e4c0e633ae | 11,509 |
def synthetic_costs_1():
""" Uncertainty in 5 points at [0,0] on X1 can cause it to flip
to [1,0] if needed to misclassify
Uncertainty in 1 point at [1,1] on X2 can cause it to flip
to [1,0] if needed to misclassify
All other points certain
"""
costs = np.array([[1,4],[1,4],[... | 97753d9e816feba56b609685831df2d183ab408f | 11,510 |
def example_one(request, context=None):
""" Return web page for example one. """
if context is None:
context = {}
session = request.session.get("ApiSession", None)
if session is None:
return no_session_set(request)
session = Session.deserialize(session)
origin_codes = get_codes... | 25bc3fea514e4011c3be513868fd58d0c2b80d2f | 11,511 |
from typing import Any
def decode(cls: Any, value: bytes) -> Any:
"""Decode value in katcp message to a type.
If a union type is provided, the value must decode successfully (i.e.,
without raising :exc:`ValueError`) for exactly one of the types in the
union, otherwise a :exc:`ValueError` is raised.
... | 3036b69089e68d2a47c3ca110024bde6a026ba5d | 11,512 |
from typing import TextIO
def load_f0(fhandle: TextIO) -> annotations.F0Data:
"""Load an ikala f0 annotation
Args:
fhandle (str or file-like): File-like object or path to f0 annotation file
Raises:
IOError: If f0_path does not exist
Returns:
F0Data: the f0 annotation data
... | 7c0f47e63db1a6fee4718420d74799fa73740b52 | 11,513 |
def remove_fallen(lst):
"""removes fallen orcs from a list"""
return [x for x in lst if x.standing] | 9e621321909dc7aa13da3d2a7902bb4604ae62f6 | 11,514 |
def gc_resnet152(num_classes):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(GCBottleneck, [3, 8, 36, 3], num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model | a1986afd48284471045b08322e008796ee7743bb | 11,515 |
def consume_entropy(generated_password: str, quotient: int, max_length: int) -> str:
"""
Takes the entropy (quotient) and the length of password (max_length) required
and uses the remainder of their division as the index to pick a character from
the characters list.
This process occurs recursively ... | 8ba58b34704e9db389241a255e9ec1963e508c99 | 11,516 |
def randomNormal(n, height, baseshape=[]):
"""
Generate random positions, normally distributed along z. Base shape can be:
[] (1D sim)
[Ly] (2D sim)
[Lx, Ly] (3D sim)
Where Lx, Ly are lengths along x, y.
"""
nDim = len(baseshape) + 1
pos = np.zeros([n,... | 96d703ecc059fe180b71f547dfee7f259d803a87 | 11,517 |
def _parseCellContentsSection(fileAsList, lineIdx):
""" returns fractCoords from Cell Contents section of castep
Args:
fileAsList(str list): Each entry is 1 line of the castep input file
lineIdx(int): The index containing the line "cell contents"
Returns
fractCoords: nx4 iter with each contain... | 3baa1a200442ef8681a0741bfa2a60d9ca1e20b2 | 11,520 |
def get_avg_no_of_feat_values(contents):
"""
Helper to calculate numbers of different values
of categorical features, averaged for all features
"""
total = 0
for i in range(0, len(contents[0])):
total += len(set([x[i] for x in contents]))
return float(total) / float(len(contents[0])... | 4e913298d7f133eb08afe23e4999f5b20f455dc1 | 11,521 |
def plot_trend_line(axes_, xd, yd, c='r', alpha=1, cus_loc = None, text_color='black', return_params=False,
extra_text='', t_line_1_1=True, fit_function=None, fontsize_=12, add_text=True):
"""Make a line of best fit"""
#create clean series
x_, y_ = coincidence(xd,yd)
if fit_functi... | a4d6e41bf03524f257531bbb0f2bb43d1b3b6b8b | 11,522 |
from pathlib import Path
import yaml
def get_oil_type_atb(
oil_attrs, origin, destination, transport_data_dir, random_generator
):
"""Randomly choose type of cargo oil spilled from an ATB (articulated tug and barge) based on
AIS track origin & destination, and oil cargo attribution analysis.
Unlike t... | e7e6e51ece2bb5b4fffc70d2507c2e5ff062bbd8 | 11,523 |
def get_jwt():
"""
Get Authorization token and validate its signature
against the application's secret key, .
"""
expected_errors = {
KeyError: WRONG_PAYLOAD_STRUCTURE,
AssertionError: JWK_HOST_MISSING,
InvalidSignatureError: WRONG_KEY,
DecodeError: WRONG_JWT_STRUCTU... | 9c52369b38db9815769ea8277c3e3721ba20c1c9 | 11,524 |
def start_volume(name, force=False):
"""
Start a gluster volume
name
Volume name
force
Force the volume start even if the volume is started
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' glusterfs.start mycluster
"""
cmd = "volu... | 6dc936b4e09beb9713c32e4c93e8649999f82c3c | 11,525 |
def hist_equal(img, z_max=255):
"""
直方图均衡化,将暗的地方变量,亮的地方变暗
:param img:
:param z_max: 原图像最亮的地方减去最暗的地方的值
:return:
"""
if len(img.shape) == 2:
height, width = img.shape
n_chan = 1
elif len(img.shape) == 3:
height, width, n_chan = img.shape
print(img[:, :, 0].s... | e6aaf76ce8088b9519cd896d8236a84f01761976 | 11,526 |
def combine(*indices_lists):
"""
Return all the combinations from lists of indices
:param indices_lists: each argument is a list of indices (it must be a list)
:return: The combined list of indices
"""
if len([*indices_lists]) > 1:
return [i for i in product(*indices_lists)]
else:
... | 839762c9645e0c8d6ea31a21113a5efd6b97f1de | 11,527 |
import re
def get_endpoint(query):
"""
Regex to parse domain and API endpoint from a SoQL query via FROM
statement
:param query: str, SoQL-formatted query
:return
url, endpoint, query: str objects, domain, endpoint, and
original query sans F... | 4496c85f2e6f908bd5dcef7195b821998ef79c42 | 11,528 |
def load_data(filename: str) ->pd.DataFrame:
"""
Load house prices dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (prices) - either as a single
DataFrame or a Tuple[DataFrame, Se... | 26c785cb72b883cab03b9da6c7718b71e7ccea76 | 11,529 |
def version_match(required, candidate):
"""Test that an available version is a suitable match for a required
version.
To be suitable a version must be of the same major version as required
and be at least a match in minor/patch level.
eg. 3.3 is a match for a required 3.1 but 4.1 is not.
:par... | bc537fdae084a3c3ccb7b8336703ef4c2476de6e | 11,530 |
from typing import Optional
from datetime import datetime
def get_last_upgraded_at(module: base.Module) -> Optional[datetime.datetime]:
"""
Get the timestamp of the last time this module was upgraded.
"""
return settings.get_last_upgraded_at(module.name) | bf884bf4c249448929b987504d400d6ba1b12927 | 11,531 |
import collections
import re
import logging
def parse_header_file(header_file):
"""Parse a single header file to get all defined constants out of it."""
resolved_values = collections.OrderedDict()
raw_matches = {}
with open(header_file, "r") as fd:
all_file_lines = collections.OrderedDict(
... | 1681939a78efe6426cdea1577a8781a7f046c02d | 11,532 |
import platform
def get_linux_distribution(get_full_name, supported_dists):
"""Abstract platform.linux_distribution() call which is deprecated as of
Python 3.5 and removed in Python 3.7"""
try:
supported = platform._supported_dists + (supported_dists,)
osinfo = list(
platfor... | 01ceea04eeb4e8130e9ce5899a116af557d9f954 | 11,533 |
def check_disabled(func):
"""
Decorator to wrap up checking if the Backdrop
connection is set to disabled or not
"""
@wraps(func)
def _check(*args, **kwargs):
if _DISABLED:
return
else:
return func(*args, **kwargs)
return _check | 53d6b0b44558d09ed73556f6854f004c6767856c | 11,534 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.