content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def validate_abi_type(abi_type: TypeStr) -> None:
"""
Helper function for validating an abi_type
"""
if not is_recognized_type(abi_type):
raise ValueError(f"Unrecognized abi_type: {abi_type}") | 5,314,700 |
def batch_norm1d ( input # in_minibatch x 1 x in_size
, running_mean # 1 x in_size (not no minibatch)
, running_var # 1 x in_size (not no minibatch)
, weight=None # 1 x in_size
, bias=None # 1 x in_size
, eps=1E-5
, ... | 5,314,701 |
def disco(version, co, out=None, is_pypy=False):
"""
diassembles and deparses a given code block 'co'
"""
assert iscode(co)
# store final output stream for case of error
real_out = out or sys.stdout
print('# Python %s' % version, file=real_out)
if co.co_filename:
print('# Embed... | 5,314,702 |
def isolated_margin_account(self, **kwargs):
"""Query Isolated Margin Account Info (USER_DATA)
GET /sapi/v1/margin/isolated/account
https://binance-docs.github.io/apidocs/spot/en/#query-isolated-margin-account-info-user_data
Keyword Args:
symbols (str, optional): Max 5 symbols can be sent; se... | 5,314,703 |
def multiplex_erdos_renyi(mg, seed=None, include_all=True):
"""Return a Multinet such that each layer is an Erdos-Renyi network with
same p as the original Multinet given.
Parameters
----------
mg : Multinet
Multiplex network to be configured.
seed : object
Seed for the model.
... | 5,314,704 |
def analysis_file_inclusion(node, vul_function, back_node, vul_lineno, function_params=None, file_path=None):
"""
处理include/require类型节点-->判断节点类型-->不同If分支回溯判断参数是否可控-->输出结果
:param file_path:
:param node:
:param vul_function:
:param back_node:
:param vul_lineno:
:param function_params:
... | 5,314,705 |
def load_model(model_dir,
model_file=None,
model_name=None,
serialize_model=True):
"""Loads the model from the catalog or a definition file.
Args:
model_dir: The model directory.
model_file: An optional model configuration.
Mutually exclusive with :obj:`mo... | 5,314,706 |
def homography(points1, points1_indices, points2, points2_indices, num_points=4, min_num_points=4):
"""
Computes homography matrix for given two sets of points
:param points1: First point set
:param points1_indices: First point set indices
:param points2: Second point set
:param points2_indices... | 5,314,707 |
def get_sid_trid_combination_score(site_id, tr_ids_list, idfilt2best_trids_dic):
"""
Get site ID - transcript ID combination score, based on selected
transcripts for each of the 10 different filter settings.
10 transcript quality filter settings:
EIR
EXB
TSC
ISRN
ISR
ISRFC
S... | 5,314,708 |
def extract_address_from_dnb_company(dnb_company, prefix, ignore_when_missing=()):
"""
Extract address from dnb company data. This takes a `prefix` string to
extract address fields that start with a certain prefix.
"""
country = Country.objects.filter(
iso_alpha2_code=dnb_company[f'{prefix}... | 5,314,709 |
def prepare_inverse_operator(orig, nave, lambda2, dSPM):
"""Prepare an inverse operator for actually computing the inverse
Parameters
----------
orig: dict
The inverse operator structure read from a file
nave: int
Number of averages (scales the noise covariance)
lambda2: float
... | 5,314,710 |
def showCommandHeader(command_name, ctx):
"""Displays basic information to user.
Args:
command_name: The name of the command which started method.
Returns:
Noting
"""
if ctx.obj['DEBUG']:
click.echo('')
click.echo('*' * 60)
click.echo('Executing command: %s... | 5,314,711 |
def filter_non_primary_chromosomes(df):
"""Filter out all variants that do not reside on the primary chromosomes
(i.e. 1-22, X, Y, MT)."""
# Print excluded variants for debugging/logging purpose.
exclude_indices = df.index[~df['Chromosome'].isin(["%s" % chrom for chrom in range(1, 23)] + ['X', 'Y', 'MT... | 5,314,712 |
def float_convert(d, include_keys=None, exclude_keys=None):
"""Convert elements in a document to floats.
By default, traverse all keys
If include_keys is specified, only convert the list from include_keys a.b, a.b.c
If exclude_keys is specified, only exclude the list from exclude_keys
:param d: a ... | 5,314,713 |
def bin_downsample(Ain, dsfac):
"""
Downsample an array by binning.
Parameters
----------
Ain : 2-D array
The matrix to be downsampled
dsfac : int
Downsampling factor for the matrix
Returns
-------
Aout : 2-D array
Downsampled array
"""
# Err... | 5,314,714 |
def testComPolValidity(compol):
"""
The P3P header syntax must be one of the followings:
* P3P: CP="...", policyref="..."
* P3P: policyref="...", CP="..."
* P3P: CP="..."
* P3P: policyref="..."
---
'policyref="..."' contains ONE Link to a Policy Reference file
'CP="..."' contains spe... | 5,314,715 |
def test_chgid_gid_int():
"""
Tests if gid is an integer or not
"""
pytest.raises(SaltInvocationError, mac_group.chgid, "foo", "foo") | 5,314,716 |
def test_StripComments_only_comment():
"""Test StripComments on an input containing only comments."""
assert cxx.StripComments("// Just a comment") == " "
assert cxx.StripComments("/* Just a comment */") == " " | 5,314,717 |
def sentry_event_filter( # noqa: WPS231
event, hint, ignored_types: List[str] = None, ignored_messages: List[str] = None
) -> Optional[Dict[str, Any]]:
"""Avoid sending events to Sentry that match the specified types or regexes.
In order to avoid flooding Sentry with events that are not useful and prevent... | 5,314,718 |
def make_case(unicode_domain, unicode_allowed=True, case_name=None):
"""Generates a C++ test case for an IDN domain test.
This is designed specifically for the IDNTestCase struct in the file
components/url_formatter/url_formatter_unittest.cc. It generates a row of
the idn_cases array, specifying a test f... | 5,314,719 |
def map_dymola_and_json(results, case, res_fin, case_dict):
"""
This function couples the .mat file variable with the final .json variable
:param results: Result obtained from the _extract_data function
:param case: Dictionary that specifies the BESTEST case
:param res_fin: Dictionary with the same... | 5,314,720 |
def check_include_directive(facts, report_func):
"""
Checks if the data model tells include directives are used
and produces a report.
:param obj facts: model object containing info about CUPS configuration
:param func report_func: creates report
"""
title = ('CUPS no longer supports usage ... | 5,314,721 |
def main():
"""Parse CLI arguments and launches main program."""
args = docopt(__doc__, version=VERSION)
config = ConfigParser(interpolation=ExtendedInterpolation())
# Set defaults for all sections
config.read_dict(copy.copy(DEFAULT_OPTIONS))
try:
config.read(args['--file'])
except ... | 5,314,722 |
def upload_word_book(request):
"""
处理上传单词本
"""
username = request.POST.get("username")
# 获取上传的文件,如果没有文件,则默认为None
word_book = request.FILES.get("word_book", None)
# 没有上传文件,没有上传txt文件
book_name = str(word_book.name)
# 错误需要重新渲染html
user = request.session['user']
# 获取数据
book_... | 5,314,723 |
def statusName(dictname):
"""Return the underlying key used for access to the status of the
dictlist named dictname.
"""
return (dictname, "S") | 5,314,724 |
def test_normalize():
"""Test normalize"""
assert normalize(None) == ''
assert normalize('') == ''
assert normalize('FOO') == 'foo'
assert normalize('FOO BAR') == 'foo_bar'
assert normalize('foo-b*!a,r') == 'foobar'
assert normalize('Foo Bar') == 'foo_bar'
assert normalize('Foo / Bar')... | 5,314,725 |
async def async_remove_entry(hass, config_entry):
"""Handle removal of an entry."""
await hass.config_entries.async_forward_entry_unload(config_entry, "binary_sensor")
Logger("custom_components.healthchecksio").info(
"Successfully removed the healthchecksio integration"
) | 5,314,726 |
def stydiffstat(dataNameList, SELECT_RANGE, dateStart, dateEnd):
"""
Return the place name of input places
Parameters
----------
dataNameList : list - list of strings of all participant id with shared data
SELECT_RANGE: var - flag to define if select certain period
dateStart: str - the s... | 5,314,727 |
def ergsperSecondtoLsun(ergss):
"""
Converts ergs per second to solar luminosity in L_sun.
:param ergss: ergs per second
:type ergss: float or ndarray
:return: luminosity in L_sun
:rtype: float or ndarray
"""
return ergss / 3.839e33 | 5,314,728 |
def check_print_wrong_pair_object(object_a, object_b, relationship_type):
"""
Prints specific user messages for wrong object(s) pair (Object_a, Object_b) relationship
Args:
object_a: (input_string, object_or_none, object_type_string)
e.g. (exposes_str[0], fun_elem, 'Functional Element')
... | 5,314,729 |
def test_updating_payment_token_fails(session):
"""Assert that a payment token cannot be updated."""
filing = Filing()
filing.payment_token = 'payment token'
filing.save()
with pytest.raises(BusinessException) as excinfo:
filing.payment_token = 'payment token'
assert excinfo.value.stat... | 5,314,730 |
def svd(A, maxiter=30):
"""
Given a matrix A, this routine computes its SVD A = U.W.VT
- The matrix U is output mxm matrix. This mean
matrix U will have same size of matrix A.
- The matrix W is ouput as the diagonal mxn matrix that contains
the singular values
- The matrix V ... | 5,314,731 |
def sys_unlink(kernel: Kernel, pathname_addr: Uint):
"""
int sys_unlink(const char * pathname)
"""
pathname = kernel.kernel_read_string(pathname_addr).decode()
logger.info('sys_unlink(const char * pathname = %r)', pathname)
try:
os.unlink(pathname)
except OSError:
ret = -1... | 5,314,732 |
def make(merger, toc, default_folder, parent, bookmarks, evenpages):
"""Join several pdf files to target."""
for title, pdf, childs in toc:
if pdf.startswith(FOLDER):
pdf = os.path.join(
default_folder,
pdf.replace(FOLDER, '')
)
new_parent = bo... | 5,314,733 |
def reconnect(module_session, request_id):
"""Reconnects the SQL Editor Session
Args:
module_session (object): The session where the session will be reconnected
request_id (str): ID of the request for reconnection.
Returns:
A dict holding the result message and the connection infor... | 5,314,734 |
def directory_for_model(args):
"""
:param args:
:return:
"""
model_dir = os.path.join(args.models_folder, args.model)
model_img_dir = os.path.join(model_dir, 'images')
check_dir(model_img_dir)
model_video_dir = os.path.join(model_dir, 'videos')
check_dir(model_video_dir)
metr... | 5,314,735 |
def _publish_test_model_local(
dataset: VersionedDataset, model: Model, training_config: TrainingConfig
) -> None:
"""Publishes the versioned model to the local filesystem.
:param dataset: The versioned dataset.
:param model: The model.
:param training_config: The training configuration.
"""
... | 5,314,736 |
def send_email(**kwargs):
""" Utility method for sending an email"""
logger = kwargs.get('logger', logging)
from_address = kwargs.get('from_email_address', 'ensembl-production@ebi.ac.uk')
msg = MIMEText(kwargs['body'])
msg['Subject'] = kwargs['subject']
msg['From'] = from_address
msg['To'] =... | 5,314,737 |
def createdb():
""" Make the database. """
db.create_all() | 5,314,738 |
def produces_record(obj: Any) -> bool:
"""Check if `obj` is annotated to generate records."""
if hasattr(obj, 'get_data_specs'):
return True
else:
return False | 5,314,739 |
def readJson(fname):
""" Read json file and load it line-by-line into data
"""
data = []
line_num = 0
with open(fname, encoding="utf-8") as f:
for line in f:
line_num += 1
try:
data.append(json.loads(line))
except:
print("er... | 5,314,740 |
def parse_address(address):
"""Parse an address and return it as an Integer."""
if is_hex(address):
return int(address, 16)
return to_unsigned_long(gdb.parse_and_eval(address)) | 5,314,741 |
def index(request):
"""Index page for upload images"""
form = ImageForm(request.POST or None, files=request.FILES or None)
context = {
"form": form
}
if not form.is_valid():
return render(request, "index.html", context)
image = form.save()
pixel_count_add(image.id)
return... | 5,314,742 |
def binary_search(arr, val):
"""
Summary of binary_search function: searches an input array for a value and
returns the index to matching element in array or -1 if not found.
Parameters:
array (array): An array of values
val (integer): An integer value
Returns:
index (integer): Re... | 5,314,743 |
def get_authorized_http():
"""Create an httplib2.Http wrapped with OAuth credentials.
This checks the user's configuration directory for stored
credentials. If found, it uses them. If not found, this opens a
browser window to prompt the user to sign in and authorize access
to the user's email add... | 5,314,744 |
def update_resource(resource, incoming_request):
"""Replace the contents of a resource with *data* and return an appropriate
*Response*.
:param resource: :class:`sandman.model.Model` to be updated
:param data: New values for the fields in *resource*
"""
resource.from_dict(get_resource_data(inc... | 5,314,745 |
def step_plots(X, labs, steps_vec, perplexity = 30, ncols = 3, \
verbose = False, cdict = {1: 'red', 2: 'mediumspringgreen', 3: 'royalblue'}):
"""Plots t-SNE output for given dataset and perplexity values
Required inputs:
X ~ NxM data matrix
steps_vec ~ A list of step numbers
... | 5,314,746 |
def flash_image(image_in, port=1):
"""Main function to flash an .srec image to the fuel gauge
Args:
image_in (str): Path to the image file
port (int, optional): The i2c port to open
Returns:
None. Script will fail if there is a failure
"""
print("Starting flashing process..... | 5,314,747 |
def new_object_graph(
modules=finding.ALL_IMPORTED_MODULES, classes=None, binding_specs=None,
only_use_explicit_bindings=False, allow_injecting_none=False,
configure_method_name='configure',
dependencies_method_name='dependencies',
get_arg_names_from_class_name=(
bind... | 5,314,748 |
def test__saveActivity__has_id(syn):
"""
Testing saveActivity method works properly
"""
with patch.object(syn, 'restPUT') as mock_restPUT:
put_result = {'name': 'test_activity', 'description': 'test_description', 'id': 123}
syn._saveActivity(put_result)
mock_restPUT.assert_call... | 5,314,749 |
def telegram_settings():
"""set telegram client configuration.
"""
return {
'result': []
} | 5,314,750 |
def find_pointing_documents(path, index):
"""
Returns the Metadata of the documents that use a given block as a pointer.
Args:
path(str): Path to the file
index(int): Index of the block in the file
Returns:
list(Metadata): List of documents that used the block as a pointer
""... | 5,314,751 |
def make_shell_context():
"""注册了程序,数据库实例,以及模型,使得这些对象可直接导入shell"""
return dict(app=app, db=db, User=User, Post=Post, Category=Category,
Tag=Tag, Role=Role, Permission=Permission) | 5,314,752 |
def test_event_unpublished_with_auth_not_organizer(user, client, hidden_event):
""" Test that an unpublished page can not be accessed if the user
is not an organizer"""
client.force_login(user)
url = '/' + hidden_event.page_url + '/'
resp = client.get(url)
assert resp.status_code == 200
as... | 5,314,753 |
async def amain(args):
"""Async main to run the event loop and related functionality"""
# Initialize queues for communication between pipeline stages
manager = aioprocessing.managers.AioSyncManager()
manager.start()
queues = datastructures.Queues(
manager.AioQueue(maxsize=MAX_CONCURRENT_ITE... | 5,314,754 |
def compute_jacobian(x, y, structured_tensor=False,
retain_graph=False):
"""Compute the Jacobian matrix of output with respect to input.
If input and/or output have more than one dimension, the Jacobian of the
flattened output with respect to the flattened input is returned if
`str... | 5,314,755 |
def unwarp_chunk_slices_backward(mat3D, xcenter, ycenter, list_fact,
start_index, stop_index):
"""
Generate a chunk of unwarped slices [:,start_index: stop_index, :] used
for tomographic data.
Parameters
----------
mat3D : array_like
3D array. Corre... | 5,314,756 |
def load_data(database_filepath):
"""
Function to load data from a database
Inputs:
database_filepath (path): location of the database
Returns:
X (pandas dataframe): messages (features)
Y (pandas dataframe): categories (targets)
category_name... | 5,314,757 |
def ndarray_duplicate_element_by_array(arr1,arr2):
"""
Duplicate each element in arr1[i] by the corresponding value of
arr2[i], if arr2[i]==0, then arr1[i] will be dropped in final
output, if all elements of arr2 is zero, then a None value
will be returned.
Parameters:
---------... | 5,314,758 |
def namedtuple(typename, field_names, default_value=None, default_values=()):
"""namedtuple with default value.
Args:
typename (str): type name of this namedtuple
field_names (list[str]): name of each field
default_value (Any): the default value for all fields
default_values (li... | 5,314,759 |
def _create_molecule_images(chosen_smiles, directory):
"""Creates a PNG image of the 2D representation of each
molecule represented in a list of smiles patterns.
Parameters
----------
chosen_smiles: list of str
The list of molecule smiles representations.
directory: str
The dire... | 5,314,760 |
def log_quaternion_loss_batch(predictions, labels, params):
"""A helper function to compute the error between quaternions.
Args:
predictions: A Tensor of size [batch_size, 4].
labels: A Tensor of size [batch_size, 4].
params: A dictionary of parameters. Expecting 'use_logging', 'batch_size'.
Returns... | 5,314,761 |
def scrape_users(basic_users: List[BasicUser]) -> List[User]:
"""Scrape user pages for list of User objects.
"""
def major_delay(base: int, offset: int) -> None:
delay = getdelay(base, offset)
print(f"\nDelaying server request for {delay} seconds...")
countdown(delay)
print()... | 5,314,762 |
def angle_section(
d: float,
b: float,
t: float,
r_r: float,
r_t: float,
n_r: int,
material: pre.Material = pre.DEFAULT_MATERIAL,
) -> geometry.Geometry:
"""Constructs an angle section with the bottom left corner at the origin *(0, 0)*, with depth
*d*, width *b*, thickness *t*, root ... | 5,314,763 |
def summary_parameters(model):
"""
Summary Parameters of Model
:param model: torch.nn.module_name
:param logger: logger
:return: None
"""
print('>> Trainable Parameters:')
trainable_paramters = [(str(n), str(v.dtype), str(tuple(v.shape)), str(v.numel()))
for n... | 5,314,764 |
async def test_get_status_no_data(aresponses):
"""Test PVOutput status without data is handled."""
aresponses.add(
"pvoutput.org",
"/service/r2/getstatus.jsp",
"GET",
aresponses.Response(text="Bad Request!", status=400),
)
async with aiohttp.ClientSession() as session:
... | 5,314,765 |
def default_rule_template(alert_list, file_name):
"""
Build a default rules template
:param alert_list: list of alert set names
:param file_name: output file name
:return: None
"""
default_rule_dict = {
"MW": [0, 500],
"LogP": [-5, 5],
"HBD": [0, 5],
"HBA": [0... | 5,314,766 |
def main(all_images):
"""
Find a connected iPhone, and print the paths to images on it.
:param all_images: Whether or not to list all images on the phone, or
only those newer than those found on disk.
"""
start_time = time.time()
localdir = os.path.abspath(os.path.d... | 5,314,767 |
def plot_and_save_data():
"""
Generates samples from each model and saves their plots in a 2d-Euclidean space.
:return:
"""
for model_id in Model.__members__.values():
_, means, covariances = get_parameters(model_id)
samples, samples_per_component = get_data(model_id, NUM_SAMPLES)
... | 5,314,768 |
def download_thread(thread_name):
"""
持续从下载任务队列获取任务并下载文件,直到stop_sing为True
:param thread_name: 线程名称,用于输出
:return:
"""
msg = ' '.join(['Thread', str(thread_name), '{}: {}'])
global queue_down, down_stop, temp_dir, cli_args
while not down_stop:
# 从下载任务队列中获取一个任务
if queue_down... | 5,314,769 |
def normalize_adj(adj, type='sym'):
"""Symmetrically normalize adjacency matrix."""
if type == 'sym':
adj = sp.coo_matrix(adj)
rowsum = np.array(adj.sum(1))
# d_inv_sqrt = np.power(rowsum, -0.5)
# d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
# return adj*d_inv_sqrt*d_inv_sqrt.fl... | 5,314,770 |
def get_mb(
num):
"""get_mb
convert a the number of bytes (as an ``integer``)
to megabytes with 2 decimal points of precision
:param num: integer - number of bytes
"""
return to_f(num / NUM_BYTES_IN_AN_MB) | 5,314,771 |
def GetComments(node, layers='core') :
"""Get the rdfs:comment(s) we find on this node within any of the specified layers."""
return GetTargets(Unit.GetUnit("rdfs:comment", True), node, layers=layers ) | 5,314,772 |
def _ValidateObbFileList(arg_internal_name, arg_value):
"""Validates that 'obb-files' contains at most 2 entries."""
arg_value = ValidateStringList(arg_internal_name, arg_value)
if len(arg_value) > 2:
raise test_exceptions.InvalidArgException(
arg_internal_name, 'At most two OBB files may be specified... | 5,314,773 |
def _depol_error_value_one_qubit(gate_error, gate_time=0, t1=inf, t2=inf):
"""Return 2-qubit depolarizing channel probability for device model"""
# Check trivial case where there is no gate error
if gate_error is None:
return None
if gate_error == 0:
return 0
# Check t1 and t2 are v... | 5,314,774 |
def test_isfinite() -> None:
"""Test :meth:`AssertionManager.isfinite`."""
assertion.isfinite(0)
assertion.isfinite(0.0)
assertion.isfinite(98)
assertion.isfinite(nan, invert=True)
assertion.isfinite(inf, invert=True)
assertion.isfinite(-inf, invert=True)
assertion.isfinite(1, 1, 1, exce... | 5,314,775 |
def meh(text):
"""
>>> meh(EXAMPLE_INPUT)
[3, 8, 9, 1, 2, 5, 4, 6, 7]
"""
return [int(c) for c in text] | 5,314,776 |
def get_latest_dataset():
""" Return latest dataset that was created """
return getattr(qcodes.DataSet._latest, None) | 5,314,777 |
def insert_newlines(text, line_length):
"""
Given text and a desired line length, wrap the text as a typewriter would.
Insert a newline character ("\n") after each word that reaches or exceeds
the desired line length.
text: a string containing the text to wrap.
line_length: the number of charac... | 5,314,778 |
def pprint(dicts):
"""
Print dictionary using json format.
"""
try:
s = json.dumps(dicts, indent=2)
print(s, flush=True)
except:
print(dicts, flush=True) | 5,314,779 |
def gen_annular_fpm(inputs):
"""
Generate an annular FPM using PROPER.
Outside the outer ring is opaque.If rhoOuter = infinity, then the outer
ring is omitted and the mask is cropped down to the size of the inner spot.
The inner spot has a specifyable amplitude value. The output array is the
sm... | 5,314,780 |
def _get_time_ts(string: str) -> float:
"""
通过传入的字符串获取时间戳
"""
year = time.localtime().tm_year
month = re.search(r"(\d+)月", string).group(1)
day = re.search(r"(\d+)日", string).group(1)
return time.mktime(time.strptime(f"{year}-{month:>02}-{day:>02}", "%Y-%m-%d")) | 5,314,781 |
def octresnet10_ad2(**kwargs):
"""
Oct-ResNet-10 (alpha=1/2) model from 'Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks
with Octave Convolution,' https://arxiv.org/abs/1904.05049.
Parameters:
----------
pretrained : bool, default False
Whether to load the p... | 5,314,782 |
def create_standalone_plot(fig, fname, backend=None):
"""
Create a script which can be executed to plot the given figure.
Pickles the figure and stores it as string in the script.
Parameter
---------
fig : matplotlib.figure.Figure
Matplotlib figure to store.
fname : str
Fil... | 5,314,783 |
def getdict_userid_username():
"""
Make a dictionary to map from Moodle user IDs to user names
"""
dict_userid_username = {}
userxml = os.path.join("backup","users.xml")
docs = parse(userxml)
users = docs.getElementsByTagName("user")
for user in users:
userid = int(user.getAttrib... | 5,314,784 |
def generate_template(global_entity, sentence, sent_ent, kb_arr, domain):
"""
code from GLMP: https://github.com/jasonwu0731/GLMP/blob/master/utils/utils_Ent_kvr.py
Based on the system response and the provided entity table, the output is the sketch response.
"""
sketch_response = []
if sent_ent... | 5,314,785 |
def project_file_read(request):
"""
get content of project file
:param request: request object
:return: file content
"""
if request.method == 'POST':
data = json.loads(request.body)
path = join(data['path'], data['label'])
# binary file
with open(path, 'rb') as f:... | 5,314,786 |
def check_remove_filepath(path: Path, log: Logger, force: bool):
"""Checks the path does not point to a file, if it does will raise an error or remove it."""
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists():
if not path.is_file():
log.error("%s exists and is not a file, ab... | 5,314,787 |
def add_password():
""" Add password to the Password Entry & also copy it to clipboard """
pass_entry.delete(0, tkinter.END) # Clear the existing password or data in password entry
random_password = generate_password() # Calls the function to generate a password
pass_entry.insert(0, random_password) ... | 5,314,788 |
def ast_to_graph(root: Node) -> nx.DiGraph:
"""
You will create your regular expression with a specific syntax which is
transformed into an AST, however the regular expression engine expects
to navigate in a graph. As it is too complicated to navigate inside the
AST directly, this function transform... | 5,314,789 |
def transform(record):
"""
Transforms (maps) a record.
Parameters
----------
record : dict
The record to transform.
Returns
-------
dict
The transformed record.
"""
return {
record["stakeholder_approach"]: {
record["stakeholder_id"]: {
... | 5,314,790 |
def easeInQuart(n):
"""A quartic tween function that begins slow and then accelerates.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
"""
_checkRange... | 5,314,791 |
def apply(dataframe, parameters=None, variant=CLASSIC):
"""
Discover a StarStar model from an ad-hoc built dataframe
Parameters
-------------
df
Dataframe
parameters
Possible parameters of the algorithm
variant
Variant of the algorithm, possible values: classic
... | 5,314,792 |
def create_win_scite(folders):
"""
create a batch file to start scite
@param folders see @see fn create_win_batches
@return operations (list of what was done)
"""
text = ['@echo off',
'set CURRENT2=%~dp0',
'call "%CURRENT2%env.bat"',
... | 5,314,793 |
def invoke_cli(cli_runner):
""" invoking cli commands with options"""
return partial(cli_runner.invoke, cli) | 5,314,794 |
def create_launch_template(client, name, image_ami_id,
iam_instance_profile_arn, user_data):
"""Create a launch template for provisioning instances
Args:
client (EC2.Client): boto3 ec2 client
name (str): the name of the launch template
image_ami_id (str): the ... | 5,314,795 |
def extract_contents(args, path, output_dir):
"""
:type args: any
:type path: str
:type output_dir: str
"""
if not args.test:
if not os.path.exists(path):
return
with open(path, 'r') as json_fd:
items = json.load(json_fd)
for item in items:
... | 5,314,796 |
def FlowGradedComplex(complex, discrete_flow):
"""
Overview:
Given a complex and a graph on its top dimensional cells,
produce a GradedComplex such that the preimage of a down set
is the collection of cells in the closure of all the
associated top cells
Inputs:
complex : a complex
flow... | 5,314,797 |
def mock_documents(number_of_documents: int = 100, vector_length=5):
"""
Utility function to mock documents. Aimed at helping users reproduce errors
if required.
The schema for the documents is as follows:
.. code-block::
{'_chunk_': 'chunks',
'_chunk_.label': 'text',
... | 5,314,798 |
def _run_threads(rank,
world_size,
env_spawner,
model,
optimizer,
flags):
"""Initializes RPC clients.
Intended use as target function for :py:func:`torch.multiprocessing.spawn()`.
* Spawns a :py:class:`~pytorch_seed_rl.ag... | 5,314,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.