content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import nipype.interfaces.io as io # Data i/o
import nipype.interfaces.utility as util # utility
import nipype.pipeline.engine as pe # pipeline engine
import nipype.interfaces.fsl as fsl
import nipype.interfaces.vista as vista
import os.path as op # system functions
import numpy as np
from nipype.interfaces.utility ... | d253a69493a3edc8219e0dc71d1dab61fc2d2dcf | 63,400 |
def deg2rad(value):
"""
Convert value in degrees to radians (as required used cairo)
"""
return value * (pi / 180.0) | 29432918834f2ee7c907d9f18b50b41c69516770 | 63,401 |
from typing import Set
from typing import Tuple
import torch
def get_reversed_fusions() -> Set[Tuple[NSFusionType, int]]:
"""
Set of potential fusions, in reverse order. The order is reversed
to match how fusion patterns are defined in quantization code.
Fusion format:
((fusion_op_0, fusion_op_1... | fa5284c76a66ad1590279e20fc190b1740670b17 | 63,402 |
from typing import Dict
def build_node_ingestion_query(node_label: str, node_property_map: Dict[str, str]) -> str:
"""
Generates Neo4j query string to write a list of dicts as nodes to the graph with the
given node_label, id_field, and other arbitrary fields as provided by field_list. The
resulting qu... | 5bf76a2cf7f3e4d633762a8f32a1c56a941e1936 | 63,403 |
import os
import pickle
def load_varible(_self, key):
"""
@ description: 加载公共变量
@ param _self {dict} api参数字典,例如包括"model_id"
@ return: {any} 公共变量
"""
assert 'model_id' in _self.keys()
assert 'version_id' in _self.keys()
model_id = _self['model_id']
version_id = _self['version_id']
... | 459b56ca429fe5bec19734a70ed7b0ef8d5c7f26 | 63,404 |
def debugtimer(_larch=None):
"""debugtimer returns a Timer object that can be used
to time the running of portions of code, and then
write a simple report of the results. the Timer object
has methods:
clear() -- reset Timer
add(msg) -- record time, with message
show_report -- prin... | dbb1247aee08debeca6ad55772d5d48819d8bcb9 | 63,405 |
def get_ability_by_path(game: Game, obj: str) -> Ability:
"""Gets the ability by 'path' made of names.
Assuming PATH_SEP is "/", this will parse as:
"{actor_name}/ability/{ability_name}"
This will do fuzzy matching on Actor and Ability separately.
TODO: Maybe do fuzzy matching on total string... | 4b5b8638e59ae4329096a1432b6effcb18bc316b | 63,406 |
import codecs
def load_vocabulary(vocabulary_path, reverse=False):
"""Load vocabulary from file.
We assume the vocabulary is stored one-item-per-line, so a file:
d
c
will result in a vocabulary {"d": 0, "c": 1}, and this function may
also return the reversed-vocabulary [0, 1].
Args:
vocabulary_... | 0bbe55a64657f53a66df7f55b3e85dcb579593a5 | 63,407 |
from typing import Dict
def biology_qualifiers(session: Session) -> Dict[str, BiologyQualifier]:
"""Return a map from biology qualifiers to database instances."""
BiologyQualifier.load(session)
return BiologyQualifier.get_map(session) | e46c71d6159ba6959d9107e6a4e7e071ce847f81 | 63,408 |
def alignments_to_report(alignments):
"""Determine which alignments should be reported and used to call variants.
In the simplest and best case, there is only a single alignment to
consider. If there is more than one alignment, determine which ones are
interpretable as a variant, and of these return th... | 0a8adfb3146ffee4ac8272e5e515fb75ad2f13b4 | 63,409 |
import re
def read_urls(filename):
"""Returns a list of the puzzle urls from the given log file,
extracting the hostname from the filename itself.
Screens out duplicate urls and returns the urls sorted into
increasing order.
/edu/languages/google-python-class/images/puzzle/a-babb.jpg
into
https://develo... | 2693ce95260a2f941c7532f5f477c97cd198ec57 | 63,410 |
import argparse
def _CreateArgumentParser():
"""Creates and returns the argument parser."""
parser = argparse.ArgumentParser()
parser.add_argument('--target-arch', help='Unused')
parser.add_argument('--unpatched-orderfile', required=True,
help='Path to the unpatched orderfile')
parser.... | be2607668ebcaf7e19efdf4cc1414acbeedb1ba5 | 63,411 |
from typing import Union
from typing import List
from typing import Any
from typing import Tuple
from typing import Dict
def decode(
spec: Union[List[Any], Tuple[Any], Dict[str, Any]]
) -> Union[specs.Array, List[Any], Tuple[Any], Dict[str, Any]]:
"""Parses `spec` into the supported dm_env spec formats."""
if... | ed4627a85e138e28d53dfba9660fe7837cbfb3bd | 63,412 |
import torch
def rescale_actions(
actions: torch.Tensor,
new_min: torch.Tensor,
new_max: torch.Tensor,
prev_min: torch.Tensor,
prev_max: torch.Tensor,
) -> torch.Tensor:
""" Scale from [prev_min, prev_max] to [new_min, new_max] """
assert torch.all(prev_min <= actions) and torch.all(
... | 1304cee5f4d1f7a50b89842fa1bac6de8ab8bd04 | 63,413 |
import sys
def select_box(runs, gui=False):
"""Selects a box for the experiment, with the correct distribution.
"""
distribution, version = runs[0]['distribution']
distribution = distribution.lower()
architecture = runs[0]['architecture']
record_usage(vagrant_select_box='%s;%s;%s;gui=%s' % (d... | 34ae3c823393bf48cd98839a662c77cc81c096b6 | 63,414 |
def find_between(doc: str, first: str, last: str) -> FoundText:
""" Finds text in doc """
result = FoundText()
try:
result.start = doc.index(first) + len(first)
result.end = doc.index(last, result.start)
result.value = doc[result.start:result.end]
result.found = True
exc... | bf5022658203b6655986150be2f076a0ce89516a | 63,415 |
def clean_pipeline(sentence):
"""Apply cleaning functions in sequential order to an input sentence"""
clean_utils = (remove_hyperlinks, remove_newline, lower, remove_numbers, remove_punctuation, remove_whitespace)
for func in clean_utils:
sentence = func(sentence)
return sentence | 409132ab990ff3ebb659cff675ba63eda2b34b81 | 63,416 |
def tag_repr(tag):
"""String of tag value as (0xgggg, 0xeeee)"""
return "(0x{group:04x}, 0x{elem:04x})".format(group=tag.group,
elem=tag.element) | 058f40824c85b834ce759ae1d01275c718a438c6 | 63,417 |
from datetime import datetime
def _response_letter_handler(request_id, data):
"""
Process letter template for a response.
:param request_id: FOIL Request ID
:param data: data from the frontend AJAX call
:return: the HTML of a rendered template of a response letter.
"""
if not eval_request... | 577cff3ccebde5f86f9287f2e3b9fc369caa8950 | 63,418 |
def create_map(example):
"""Returns a string filled by lexem categories' first symbols."""
_map = ''
for position, symbol in enumerate(example):
_map = _map + lexem_type(symbol)
return _map | 044b821e7389048b00eed8876681f1964d3128f7 | 63,419 |
import json
import urllib
async def post_notification(request):
"""
Create a new notification to run a specific plugin
:Example:
curl -X POST http://localhost:8081/foglamp/notification -d '{"name": "Test Notification", "description":"Test Notification", "rule": "threshold", "channel": "email... | ed1dc8479941db4e1cd21d05011d0a9da3b763aa | 63,420 |
def keyhas(archiveindex_name, key, attr, p5_connection=None):
"""
Syntax: ArchiveIndex <name> keyhas <key> <attr>
Description: Checks whether the <key> has attribute <attr> defined
Return Values:
-On Success: the string "1" if yes, or "0" otherwise
"""
method_name = "keyhas"
return ex... | 7d789d9e84dfe892812acfeb5029f57cabc4022c | 63,421 |
def _stream_split_iterators(stream, n=None):
"""Split stream of samples.
"""
iterators = list(map(Stream, _split_iterators(iter(stream.samples()), n)))
return iterators | 297a2d11b5a94e5d4cd520fb3be643a87c11df7c | 63,422 |
import os
import tqdm
def fetch_mdsa(model, x_train, x_target, target_name, layer_names, args):
"""
@param model: Subject model.
@param x_train: Set of training inputs.
@param x_target: Set of target (test or adversarial) inputs.
@param target_name: name of targeted test inputs
@param layer_na... | f782f609786f228eea20fc4265a1b4bbdc6c0fbf | 63,423 |
def log10(x):
"""log10(x) -> the base 10 logarithm of Decimal x."""
return log(x, D(10)) | 3b2924fdc4045e640a691bd684ee70b910309f13 | 63,424 |
def imo_lookup(request):
"""
Function used to determine if a IMO already exists in the database
"""
data = request.data
imo = data['imo']
try:
vessel = Vessel.objects.get(imo=int(imo))
except Exception as e:
# Some error occurred trying to get query Vessels
return Re... | 300b848ea459a55437fb1be3ef2cc22d6ab10527 | 63,425 |
import locale
def json_categories_to_dict(flat_json):
"""Create a dictionary from the categories in a flat JSON dataframe.
Args:
flat_json (pandas.DataFrame): pandas dataframe which has
been `flattened` by a previous call to
`pandas.io.json.json_normalize`.
Returns:
... | 97306e98f6ff6e8cb0197cd489a7eb428e52a3ab | 63,426 |
def rivers_with_station(stations):
"""rivers_with_station(stations) returns a sorted list of the rivers stations are on without repeats"""
stationRivers = set()
for station in stations:
stationRivers.add(station.river)
stationRivers = sorted(stationRivers)
return stationRivers | d13044fef2a824d0d08e4419a13a2b22f1732175 | 63,427 |
def denormalize(tensor, means=IM_NORM_MEAN, stds=IM_NORM_STD):
"""Reverses the normalisation on a tensor.
Performs a reverse operation on a tensor, so the pixel value range is
between 0 and 1. Useful for when plotting a tensor into an image.
Normalisation: (image - mean) / std
Denormalisation: image... | 8eb0787effdabd9ce7102dd1c920bfcc2a9ecbaf | 63,428 |
def relu(x, out=None):
"""
Rectified linear (unit) transfer function.
Parameters
----------
x : numpy array
Input data.
out : numpy array, optional
Array to hold the output data.
Returns
-------
numpy array
Rectified linear of input data.
"""
return... | 3e7db377b7cc41743bee5c3fc64ed9fa643e980a | 63,429 |
import csv
def read_graph(filepath) -> Graph:
"""Reads a graph from an edge list file and returns a graph_tool Graph object.
Parameters
----------
filepath : str
Path to the edge list file.
Returns
------
Graph
A graph_tool Graph object.
"""
with open(filepath) as... | 8190bb97a12f217e9b704205b04ce89a04b718ae | 63,430 |
from typing import OrderedDict
def make_df_dict(d):
"""Reduce the keys in data, and turn them into the keys need for
the pandas dataframe."""
dout = {}
for key, val in d.items():
data = val['data']
out = val['out']
dout[key] = OrderedDict([
('tp', data['tp']),
... | 31692f96ea6cdfdd51681913d2ede6f1bcf6e5fe | 63,431 |
import textwrap
def get_coin_twitter_timeline(coin_id: str = "eth-ethereum") -> pd.DataFrame:
"""Get twitter timeline for given coin id. Not more than last 50 tweets [Source: CoinPaprika]
Parameters
----------
coin_id: str
id of coin from coinpaprika e.g. Ethereum - > 'eth-ethereum'
Retur... | cf362d5b41c801b9fcaa3ded53bd737b9f32bbe8 | 63,432 |
from io import StringIO
def request_image(**kwargs):
"""
Creates image for OpenLayers overlay.
Returns
-------
StringIO
Image in StringIO.
"""
global vmin
global vmax
global metadata
global cmap
if 'reg' in kwargs:
region = kwargs['reg']
if 'src' in k... | edff59af47282ce770de7197f79b34128c4cb796 | 63,433 |
from datetime import datetime
def get_timestamp():
"""
Obtains current timestamp in standard format with milliseconds
Examples:
>>> get_timestamp()
'2017-08-22 20:34:54,584'
@retval string A consistent-length date and time string
"""
date_format = datetime.strftime(datetime.... | 5b3d1f8098233c09fc485d060b5903d2027df0c9 | 63,434 |
def tab_contents_dimensionality(tab_id):
"""
Callback to switch tabs based on user interaction in the dimensionality
reduction tab of the analysis accordion. Here we make all divs hidden and
then unhide the one we're interested in. This is done to persist the
selection of hyper-parameters when switc... | a645baa342c216d5679d3aeae1cd5e304957c3d8 | 63,435 |
from datetime import datetime
from typing import Literal
def add_agents_and_provenances(your_fn,
g,
lexicon_uri,
PROV,
language,
verbose=0):
"""
:param yo... | 91f6f3e896475b02ac059cd63672b40b7c480255 | 63,436 |
def df2matrix(df, nrows, ncols, column_name="rating"):
"""
Returns a sparse matrix constructed from a dataframe
This code assumes the df has columns: MovieID,UserID,Rating
"""
values = df[column_name].values
ind_movie = df['movieId'].values
ind_user = df['userId'].values
return sparse.cs... | 282f0e95d13b22bdeac1f3c0bc87e5dac4053cc0 | 63,437 |
import torch
def count_acc(logits, labels):
"""Compute the accuracy (after adaptation) of MAML on the test/query points
Parameters
----------
logits : `torch.FloatTensor` instance
Outputs/logits of the model on the query points. This tensor has shape
`(num_examples, num_classes)`.
... | 661c2b0e3580bc1689bb6c1001ac234e866a1162 | 63,438 |
import functools
def check_total_penetration():
"""checks if penetrations for each ST together with which it can
appear totals less than or equal to 1
"""
ds_es = get_bottomup_ds_es()
valid = True
for ds, es in ds_es:
DS_ES_ST_Map = loaders.get_parameter("DS_ES_ST_Map")
STs = [... | 7e244f7d818d32bd4a8d4b051a6ea785e7ce41fe | 63,439 |
import hashlib
import os
def build_json(channel_url):
"""
Returns a final json after uploading the video and formatting the urls.
:param channel_url: Yt channel URL
:return movies_json: Json with all movies
"""
counter = 0
channel_id = str(channel_url.split("/")[-1:][0]) # Getting channel ... | d4cfaa3bd733886213fd6166c7944945cf253e84 | 63,440 |
from typing import Tuple
import scipy
def _cast_matrix_matpool(table_name: str,
real_imag_array,
col_nids_array, col_dofs_array,
row_nids_array, row_dofs_array,
matrix_shape: Tuple[int, int],
d... | 3abe00a1dcb5adfe9cf2f87aea4daa8a2cf5bfff | 63,441 |
def _format_media_type(endpoint, version, suffix):
"""
Formats a value for a cosmos Content-Type or Accept header key.
:param endpoint: a cosmos endpoint, of the form 'x/y',
for example 'package/repo/add', 'service/start', or 'package/error'
:type endpoint: str
:param version: The version of th... | 993e178fc2a91490544936e019342e6ab8f928ce | 63,442 |
def sgl_psf(rho, wavelength, z, r_g=r_g_sun):
"""Returns the gain for a point of the PSF (rho: distance from axis)"""
return 4 * pi**2 / (1-exp(1) ** (-4 * pi**2 * r_g / wavelength)) * r_g / \
wavelength * j0(2*pi*(rho/wavelength)*sqrt((2*r_g)/z))**2 | 970e9ab105684ae367237cad44158490c69a75b8 | 63,443 |
from make_regressors import load_all_regressors
from ML_OOP_stratosphere_gases import regressor_shift
import xarray as xr
def produce_X(regressors=['qbo_cdas', 'anom_nino3p4'],
lag={'qbo_cdas': 5}, add_co2=True, standertize=False,
reg_shift=None, syear=None, eyear=None):
"""reg_shift i... | 10c512eff26c14117518cf1846cbff8e93dda73d | 63,444 |
def homography_warp(image, homography, height=None, width=None, clamp=True):
"""Warp an image according to an inverse homography.
Args:
image: [..., H, W, C] input image
homography: [..., 3, 3] homography mapping output to input
height: desired output height (or None to use input height)
width: des... | 02ace203a976e413ef7a8f62d8176e8d6aa8b2b8 | 63,445 |
def map_transmission_upgrades(
scenario1,
scenario2,
b2b_indices=None,
figsize=(1400, 800),
x_range=None,
y_range=None,
state_borders_kwargs=None,
legend_font_size=20,
legend_location="bottom_left",
**plot_kwargs,
):
"""Plot capacity differences for branches & HVDC lines betw... | 374028c866aba722393e679415add0ea72e45fef | 63,446 |
import os
def vss_create_shadow_copy(windows_volume):
"""
Create a new shadow copy for the specified volume
Windows registry path for vssadmin:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VSS\Settings
MaxShadowCopies
Windows is limited in how many shadow copies can create per volume... | 18ecc2c7a9293658d1931547a9b5a0f452109234 | 63,447 |
def get_dropbox_client(access_key):
"""
Attempts to create the Dropbox Client with the associated
"""
try:
client = Dropbox(access_key)
client.users_get_current_account()
return client
except AuthError as e:
print(f'Failed to authenticate using key {access_key}')
... | 9321d88f70f81087017fc05f090deafe259b823b | 63,448 |
import itertools
def fill_with_virtuals(glycans, libr = None, reducing_end = ['Glc-ol','GlcNAc-ol','Glc3S-ol',
'GlcNAc6S-ol', 'GlcNAc6P-ol', 'GlcNAc1P-ol',
'Glc3P-ol', 'Glc6S-ol', 'GlcOS-ol'],
... | 212e669cac190d8f83159c24ab20091b455039a3 | 63,449 |
def fitsingletile(imshape, alg):
"""Returns whether a given image shape will fit in a single tile or not.
This depends on the algorithm used and the GPU available in the system"""
mx = maxtile(alg)
return mx*mx >= np.prod(imshape) | 44e794462f55bc8e35c91c321e2010f4f656d1f1 | 63,450 |
import math
def approx_rocket_ode(dt, t, x0, y0, vx0, vy0, drag_coef, m):
"""
:param dt: time of sim step
:param t: the start time
:param x0: start x
:param y0: start y
:param v0: start v (size of velocity vector)
:param theta0: start angle (argument of velocity vector)
:param drag_co... | 809786975ab32506d1c012c574f4e8339a4c28b7 | 63,451 |
def fill_result_from_objective_history(result, history):
"""
Overwrite function values in the result object with the values recorded in
the history.
"""
# counters
result.n_fval = history.n_fval
result.n_grad = history.n_grad
result.n_hess = history.n_hess
result.n_res = history.n_r... | a2f1388c5d71a06f45369098039a3fa623a25735 | 63,452 |
import hashlib
import sqlite3
def hash_blocks_until(db,n):
"""Returns combined hash of all block hashes in db until block_height n
"""
sha224 = hashlib.sha224()
with sqlite3.connect(db) as ledger_check:
ledger_check.text_factory = str
h3 = ledger_check.cursor()
for row in h3.execu... | 6bb59b063e9512483783dab70322082247638f46 | 63,453 |
def Armijo_Rule(f_next,f_initial,c1,step_size,pg_initial):
"""
:param f_next: New value of the function to be optimized wrt/ step size
:param f_initial: Value of the function before line search for optimum step size
:param c1: 0<c1<c2<1
:param step_size: step size to be tested
:param pg: inner p... | 90462eda94244c10afdf34e1ad042118d793c4fd | 63,454 |
def rotate_z(vec, theta: float):
"""
Rotate a 3d-vector around the third (z) axis
:param vec: Vector object to rotate
:param theta: Rotation angles (in degrees)
:return: Rotated 3d vector
Dimension of vector is not checked for faster execution
"""
theta = np.pi * theta / 180.
x_ = ve... | 7b02619938a43317c105dce2975973f11bc89471 | 63,455 |
import os
def choose_word():
"""
this function choose the secret word from the words file
:return: the secret word
:rtype: str
"""
all_file, word_list = [], []
if os.path.isfile(SECRET_WORDS_FILE):
with open(SECRET_WORDS_FILE, 'r') as words:
all_file = words.readline... | c4218c77e610679131330065651d9d0476da7897 | 63,456 |
from typing import TextIO
import csv
def process_icp_aes(fh: TextIO, collected_on: str, writer: csv.DictWriter,
args: Args) -> int:
""" Process the file into CSV """
reader = csv.DictReader(fh, delimiter=',')
flds = reader.fieldnames
num_written = 0
# Parse file into values f... | 1f97c2fa09fb7159e4ac15a35db9f0b13efe1d56 | 63,457 |
def ar_or_single(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by one
activator and one repressor with OR logic in the absence of
leakage with single occupancy.
Parameters
----------
x : float or NumPy array
Concentration of activator.
y : float or NumPy array... | c7f3b065cd6ff609e84622e97ebd4bdd43292377 | 63,458 |
def get_version():
"""Return the version."""
return "0.1" | 318c8ee9c5ecfb8b603e7d756879947145fcc242 | 63,459 |
import os
def find_hcp_data():
"""
Returns the freesurfer data path defined in the environment.
"""
try:
dir_hcp_data = os.getenv('HCP_DATA')
except:
dir_hcp_data = None
return dir_hcp_data | 77611b86852523cb117fecee74dd711b22b33463 | 63,460 |
import socket
def connect(host, port):
"""Connect to remote host."""
# Create socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as msg:
return (None, msg)
# Get remote IP
try:
addr = socket.gethostbyname(host)
except socket.gaierr... | ab03e5551f0fbf92c6e2417635bc753d5b77eae2 | 63,461 |
def topics(request):
""""Show all topics."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context) | 195d2c708722cd030ecac55d2bc57254decdb057 | 63,462 |
import argparse
from pathlib import Path
def parse_args():
"""Parse command-line arguments"""
parser = argparse.ArgumentParser(
description='Create a subjective evaluation')
parser.add_argument('config', type=Path, help='The configuration file')
parser.add_argument(
'directory',
... | 45af0c3fb56b153a2d379c23da7251dd84dbc17a | 63,463 |
import warnings
def fitgaussian(x, y, weights=None, guess=None, return_fit=True,
return_uncertainties=False):
"""
Fit a single gaussian to the data "y" at positions "x", points can be
weighted by "weights" and an initial guess for the gaussian parameters
:param x: numpy array (1D), the... | ce0ffe3f5886ca77b48ce1f7dc4edc2b60a92727 | 63,464 |
import requests
def get_last_deploy_for_env(proj_id, env_id):
"""get_last_deploy_for_env will get the information about the last deploy that was run in an enviroment"""
uri = config.OCTOPUS_URI + \
"/api/deployments?environments={0}&projects={1}&take=4".format(
env_id, proj_id)
r = req... | ff0e51e1360c0d3d35c9b5cfc003ff43f5721f65 | 63,465 |
import RFXtrx as rfxtrxmod
def setup(hass, config):
""" Setup the RFXtrx component. """
# Declare the Handle event
def handle_receive(event):
""" Callback all subscribers for RFXtrx gateway. """
# Log RFXCOM event
if not event.device.id_string:
return
entity_i... | 9e4608f20ec5753a4cb23a95d6893aa66e12b1a1 | 63,466 |
import json
def jsonify(data):
"""Dump data as JSON, like like :func:`flask.jsonify`."""
return current_app.response_class(
json.dumps(data, ensure_ascii=False, default=extended_encoder) + "\n",
mimetype=current_app.config["JSONIFY_MIMETYPE"],
) | c088f5d4847ddc3147524054b5c20ec15924f5a4 | 63,467 |
def e2p0(tof,p1,p2,p3,p5,p6):
"""
Background function for TOF spectra
Background function for TOF spectra
Parameters
----------
tof : array-like
The time-of-flight spectrum
p1 : float
constant background
p2 : float
multiplier on 1st exponential
p3 : float
... | bb27e3178cf947d5d1ee7c9ca7fc6a8ae262b066 | 63,468 |
from typing import Dict
def create_task(
config: Dict,
sender: str,
*args,
**kwargs
) -> Dict:
"""Relays task to best TES instance; returns universally unique task id."""
# Validate input data
if not 'body' in kwargs:
raise BadRequest
# TODO (MAYBE): Check service info compati... | 5ade7cd92da514f641ef9eeada0801279709fa29 | 63,469 |
import os
def allowed_to_access_dir(path):
"""
Checks whether we have permission to access the specified directory.
This includes read, write, and execution.
:param path: the path to the directory
:type path: string
:return: whether access is allowed
:rtype: boolean
"""
try:
... | 763fa485d7c35ef5a4d283c1d0362d07c56b2179 | 63,470 |
import pprint
def pfomart(obj):
"""格式化输出某对象
:param obj: obj对象
:return: 格式化出处的字符串
"""
return pprint.pformat(obj) | 2f2c7d7df9de9bb65c72634e8ba9386365408445 | 63,471 |
from typing import Any
from typing import Type
def extend_class(base_cls: Any, cls: Any) -> Type:
"""Apply mixins"""
base_cls_name = base_cls.__name__
return type(base_cls_name, (cls, base_cls), {}) | 5ed297f9115ec3940991b3536c207da3f6b036d0 | 63,472 |
from matplotlib.ticker import MultipleLocator
def plot_rt(
parad, to_cumsum=False,
corners_only=False,
to_add_legend=True,
use_easiest_only=0,
plot_kind='rt_mean',
model_names=('Ser', 'Par'),
to_normalize_max=False,
axs=None,
):
"""
:param parad... | 46bca593c0853483829edf118e6c3f3b88da1b54 | 63,473 |
import struct
def pre_process(
id_: str,
image_paths: dict,
artifact_function = None,
**kwargs) -> struct.BrainImage:
"""Read an image, registrate it, normalize it, remove skull, and add artifact if needed
Args:
id_ (str): image id number/ folder number
image_paths (dict):... | 589cd23c06c7aa5aa0b082ccd0ec7edd87327047 | 63,474 |
import aiohttp
async def retrieve_page(url: str, head=False, call=None, headers=None, **params):
""" Download and return a website with aiohttp.
:param url: Download url as str.
:param head: Whether or not to head the function.
:param call: Any attribute coroutine to call before returning. Eg: "text"... | 5152857e51ac9a65589f123654f2d733854b42e7 | 63,475 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
authn_policy = AuthTktAuthenticationPolicy('sosecreeet', callback=groupfinder, hashalg='sha512')
authz_policy = ACLAuthorizationPolicy()
config = Configurator(settings=settings, root_factory=RootFactory)... | b7948c5f8584c1ab65cf81ea616200b62cd7a46c | 63,476 |
def nx2nx_loader(extractor, stream, transformers, loader_json, graph):
"""
Loader for NetworkX graph.
:returns: networkx.Graph
"""
extractor_json = extractor(graph)
graph = extractor_json["graph"]
node_type_attr = extractor_json["node_type_attr"]
edge_type_attr = extractor_json["edge_ty... | bdf8d904edb80de3a4c91318be9e7dc307155a5f | 63,477 |
def _ts_value_newton(position, counts, bkg, model, C_0_map):
"""
Compute TS value at a given pixel position using the newton
method.
Parameters
----------
position : tuple
Pixel position.
counts : `~numpy.ndarray`
Count map.
bkg : `~numpy.ndarray`
Background ma... | adb27cda1d2c86f6f61d8353d913966cc700c6d3 | 63,478 |
def model_with_redis_field_without_pickling(r):
"""Class with RedisField attribute without pickling."""
class Model(object):
redis_field = RedisTestListField(r, pickling=False)
return Model | bd8f145c823894d0d6c91e2f6308e80f48555e01 | 63,479 |
def journal_info():
"""Create a info dictionary for edit or create later."""
info = {
'title': 'testing',
'body': 'testing_body',
'creation_date': '2017-11-02'
}
return info | e596f42ec158b7635b248558c924e3af56ae33ea | 63,480 |
def get_plugin_aac_definitions() -> str:
"""
Returns the CommandBehaviorType modeling language extension to the plugin infrastructure.
Returns:
string representing yaml extensions and data definitions employed by the plugin
"""
return get_resource_file_contents(__package__, "gen_plant_uml.y... | 04c49fb7546e985b7a230685d98b1eadcd0a4bcf | 63,481 |
def urls_without_scheme(src_list):
"""
Looks for urls/domains without scheme and if it exists, it returns true. otherwise false
"""
result = False
for item in src_list:
if validators.domain(item.replace('*.', '').replace(':*', '').split(':', 1)[0].split('/', 1)[0]):
return Tr... | 310cc42e1f6c4e56a68ef598a8d216cdc5e2daf5 | 63,482 |
from pathlib import Path
import os
def upload_videos_from_folder_to_project(
project,
folder_path,
extensions=common.DEFAULT_VIDEO_EXTENSIONS,
exclude_file_patterns=(),
recursive_subfolders=False,
target_fps=None,
start_time=0.0,
end_time=None,
annotation_status="NotStarted",
i... | 1276dc5ed5013523cb1c8908df7763e7df2d7b49 | 63,483 |
from typing import Type
def make_structured_name(se) -> StructuredName:
"""
Convert tuple form to StructuredName
E.g. make_structured_name(("rev", ("f", Type.Integer)))
"""
if isinstance(se, str):
return StructuredName(se)
if isinstance(se, tuple):
assert len(se) == 2
... | 68977cb2e0f260eb7dad3ff1ec313c501faf431e | 63,484 |
def parse_single_file(content, CRLF=True, LTRB=True, withTranscription=False, withConfidence=False, img_width=0, img_height=0, sort_by_confidences=True):
"""
Returns all points, confindences and transcriptions of a file in lists. Valid line formats:
xmin,ymin,xmax,ymax,[confidence],[transcription]
x1,y1... | 0b3ae4320760198d814bfb3c7a99e164be5d9c90 | 63,485 |
def distance(x1, y1, x2, y2):
"""
The Squared Euclidean Distance is given by the following formula:
round(math.pow((x1-x2), 2) + math.pow((y1-y2), 2))
"""
return pdist(np.array([[x1, y1], [x2, y2]]), metric='sqeuclidean') | 92337d4f434311f807da151321e250f9dfb25813 | 63,486 |
import re
def rle2cells(rle_str: str) -> str:
"""Convert lifeform string in RLE encoding to PlainText
Args:
rle_str (str): single line of RLE commands
Returns:
str: valid PlainText-encoded lifeform
"""
# drop the last part
if "!" in rle_str:
rle_str = rle_str[: rle_st... | e48ea40bd9032445e1aabe4753b7fbdcc62191ed | 63,487 |
from typing import Union
def _condition_counter(true: np.ndarray,
predicted: np.ndarray,
true_condition: Union[bool, int, str, list, tuple, set],
predicted_condition: Union[bool, int, str, list, tuple, set]) -> int:
"""
count the number of i... | 1a107584587875231d77d8b737988b5404aa8534 | 63,488 |
def script_extension(char):
""" Return the script extension property assigned to the Unicode character
'char' as a set of string.
>>> script_extension("a") == {'Latn'}
True
>>> script_extension(unichr(0x060C)) == {'Arab', 'Syrc', 'Thaa'}
True
>>> script_extension(unichr(0x10FFFF)) == {'Zzzz... | bfd6ee27272f3f4ae7014cea919a20abc2e97bf4 | 63,489 |
def format_list_of_floats(float_list, length_per_value=6, digit_after_point=4):
"""Returns a formatted string"""
string = "["
str_format = " {:" + str(length_per_value) + "." + str(digit_after_point) + "f},"
for value in float_list:
string += str_format.format(value)
string += "]"
return... | 622d20132d7e9af19fc3a143306268e8381c457c | 63,490 |
import os
from re import DEBUG
def get_documentation(template, meta, defaults=None, vars=None, extra_paths=[]):
""" return jinja generated file """
def clear_templates_of_git(templates):
return [path for path in templates if ".git/" not in path]
# templated with auto imported macros
template... | 0839b2aa22ac72a98eb7773de24eaa1179b9e809 | 63,491 |
def __apply_text_layer_filter(text_layer, text):
"""Return text with layer properties, applying uppercase,
lowercase or capitalize.
"""
filtered_text = text
char_sequence_case = CharSequenceCase.get_char_sequence_case(
text_layer.text
)
if char_sequence_case:
filtered_text = ... | d140138fb26af25fd68592a681b1b4cf5058fb92 | 63,492 |
def add_metaclass(metaclass):
"""
Class decorator for creating a class with a metaclass.
From `six` package source code: https://bitbucket.org/gutworth/six/overview.
"""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:... | 03cd1bef3ec908f380c2c6ac125ea82570e91587 | 63,493 |
import json
def parse_config():
""" This helper function parses the config in /data/act_overseer_config
:return: tuple (user, pass, log_path) obtained from the config.
"""
with open(filename('data/act_overseer_config'), 'r') as config:
cfg = json.load(config)
user = cfg['user']
... | da4a315f4ee3c217d60ca0343faadb1c7bc2d3e3 | 63,494 |
def distance_matrix(points1, points2, norm=2, max_dist=None):
"""Calculate the distance between each combination of points in two sets.
Parameters
----------
points1 : array_like
2-D array of `n1` points.
points2 : array_like
2-D array of `n2` points.
norm : int, optional
... | 8fa6befb3d937de224cbd91b593a61fd30685291 | 63,495 |
import argparse
def parse_args(args):
"""
Parse script arguments.
:return: Parsed args for assignment
"""
parser = argparse.ArgumentParser()
parser.add_argument('--build-directory',
required=True,
help="Top level directory that stores all the clo... | 808801c29f6059997776222abb340581c1949bec | 63,496 |
def route(url):
"""装饰器工厂函数 接收路径参数"""
def warpped(func):
"""装饰器函数 接收路径对应的函数 func就是被装饰器之前的函数的引用"""
route_list.append((url, func))
def inner():
"""在inner函数内部 才完成了func函数功能的拓展"""
print("正在执行某些拓展功能")
return func()
return inner
return warpped | 69076756542e3077daab1670f0f42d30815163f0 | 63,497 |
from sys import path
def main():
"""Dynamically import modules related to the args and print the ouput"""
path.append('.')
queryobj = utils.getqueryobj()
m = import_module(
'packages.' + queryobj['package'] + '.' + queryobj['module'])
return getattr(m, queryobj['action'])(queryobj['quer... | 719a685d058a84e519617bc928269adf522aba75 | 63,498 |
def check_js_equal(expected=None, actual=None):
"""Minify the JavaScript and compare it"""
with suppress_stderr():
print('Minifying expected JS')
js0 = slimit.minify(expected)
print('Minifying actual JS')
js1 = slimit.minify(actual)
if js0 == js1:
return True
prin... | fcee68200dc38778f019ef5f92be449a517999dd | 63,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.