content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import string
def generate_create_account_key():
"""
Generates a random account creation key. Implementation is very similar to
generate_reset_key().
"""
chars = string.ascii_lowercase + string.digits
return misc_utils.generate_random_string(constants.CREATE_ACCOUNT_KEY_LENGTH,
chars=chars) | e52405a325b787b9473da5530c909bfdcff0d9b4 | 14,800 |
import re
def parse_dblife(file):
"""Parse an DBLife file, returning a tuple:
positions: list of (x,y) co-ordinates
comments: all comments in file, as a list of strings, one per line.
"""
lines = file.split("\n")
comments = []
positions = []
x = 0
y = 0
dblife_patte... | b2d54240280b657c82d8a70da9e9f0ce47a92c7a | 14,801 |
from typing import Any
from typing import Callable
def db_handle_error(logger: Logger, default_return_val: Any) \
-> Any:
"""Handle operational database errors via decorator."""
def decorator(func: Callable) -> Any:
def wrapper(*args, **kwargs): # type: ignore
# Bypass attempt to ... | 1a807bc7a49abc9b50970145c520e823103f3607 | 14,802 |
from typing import Iterable
from typing import Optional
from typing import List
from pathlib import Path
def climb_directory_tree(starting_path: PathOrStr, file_patterns: Iterable[str]) -> Optional[List[Path]]:
"""Climb the directory tree looking for file patterns."""
current_dir: Path = Path(starting_path).a... | 80f036da4cf5564a2b96359ea67db19602333420 | 14,803 |
def serve_file(request, token, require_requester=True, verify_requester=True, signer=None):
"""Basic view to serve a file.
Uses ``evaluate_request`` under the hood. Please refer to that function to view information about exceptions.
:param request: the file request
:type request: bgfiles.models.FileRe... | 98bfae971e141130e94932afb8fdee2a285f2a5a | 14,804 |
def d2_rho_heterodyne(t, rho_vec, A, args):
"""
Need to cythonize, docstrings
"""
M = A[0] + A[3]
e1 = cy_expect_rho_vec(M, rho_vec, 0)
d1 = spmv(M, rho_vec) - e1 * rho_vec
M = A[0] - A[3]
e1 = cy_expect_rho_vec(M, rho_vec, 0)
d2 = spmv(M, rho_vec) - e1 * rho_vec
return [1.0 / np... | 6628c1a7299ee7842a839fd63b00857808bcd3ec | 14,805 |
from pathlib import Path
def get_venv():
"""Return virtual environment path or throw an error if not found"""
env = environ.get("VIRTUAL_ENV", None)
if env:
return Path(env)
else:
raise EnvironmentError("No virtual environment found.") | 44dd4660198a8f5538cbe91ffe52468adc8ee0e8 | 14,806 |
from typing import List
from typing import Dict
from typing import Tuple
from typing import Union
from pathlib import Path
import os
def parse_pascal_voc_anno(
anno_path: str, labels: List[str] = None, keypoint_meta: Dict = None
) -> Tuple[List[AnnotationBbox], Union[str, Path], np.ndarray]:
""" Extract the a... | 5bb8131f359fc3a50db03dd4dad9845e81b3c25c | 14,807 |
def load_user(user_id):
"""Login manager load user method."""
return User.query.get(int(user_id)) | 40d5f35aa88163a6ab69c1da7bad6634225f2cf3 | 14,808 |
def test_interpolate_energy_dispersion():
"""Test of interpolation of energy dispersion matrix using a simple dummy model."""
x = [0.9, 1.1]
y = [8., 11.5]
n_grid = len(x) * len(y)
n_offset = 1
n_en = 30
n_mig = 20
clip_level = 1.e-3
# define simple dummy bias and resolution model u... | 73c60f2b01d20b6e399dfb15da2c3c4b8622a90c | 14,809 |
def _transpose_list_array(x):
"""Transposes a list matrix
"""
n_dims = len(x)
assert n_dims > 0
n_samples = len(x[0])
rows = [None] * n_samples
for i in range(n_samples):
r = [None] * n_dims
for j in range(n_dims):
r[j] = x[j][i]
rows[i] = r
return ro... | 8815526c6485475aeaf791c2b1350449730b94f6 | 14,810 |
def load_businessgroup(request):
""" Business Group Dependent/Chained Dropdown List """
business_type_id = request.GET.get('business_type')
business_group_list = BusinessGroup.objects.filter(
business_type_id=business_type_id).order_by('name')
context = {'business_group_list': business_group_li... | 8801fbd6ae99ed939721d94bd7f3539b5b050d0a | 14,811 |
def seed_normalization(train_X, train_Y, test_X, testY, nor_method=0, merge=0, column=0):
"""
0 for minmax 1 for standard, 2 for nothing
:param nor_method:
:param merge:是否训练集测试集一起归一化
:return:
"""
# imp_mean = SimpleImputer(missing_values=np.nan, strategy="mean")
imp_mean = KNNImputer(n_n... | bae1181b6cca53444f09a69abaa3958e8500f71c | 14,812 |
import pathlib
def combine_matrix_runs(path, runs, pacc_file):
"""Combine a set of transition matrix files.
Args:
path: The base path containing the data to combine.
runs: The list of runs to combine.
pacc_file: The name of the file to combine.
Returns:
A TransitionMatrix... | dee47a3f4bfb6229a5c6aec531a0b50df5275a0b | 14,813 |
import json
def get_pkg_descr(package, version=None, last_modified=None):
"""
Get package description from registry
"""
json_data = fetch_page('http://registry.npmjs.org/%s' % package, last_modified=last_modified)
if json_data is None: # NB: empty string is not None but will fail the check
... | 9be485ee3e63f25da995b6d454a8dd15de4b7a66 | 14,814 |
def has_pattern(str_or_strlist):
"""When passed a string, equivalent to calling looks_like_pattern.
When passed a string list, returns True if any one of the strings looks like a pattern,
False otherwise."""
strlist = [str_or_strlist] if isinstance(str_or_strlist, str) else str_or_strlist
retu... | 902069f01a59b5e42c25635271dc27375732437b | 14,815 |
def update_hidden_area(*args):
"""update_hidden_area(hidden_area_t ha) -> bool"""
return _idaapi.update_hidden_area(*args) | 19739a98283203ece9f29d4fe073633318c0c2a4 | 14,816 |
def after_update_forecast_datasets(msg, config, checklist):
"""Calculate the list of workers to launch after the
update_forecast_datasets worker ends.
:arg msg: Nowcast system message.
:type msg: :py:class:`nemo_nowcast.message.Message`
:arg config: :py:class:`dict`-like object that holds the nowc... | 3ef9a6d37f871900e96f6227fea2f7678843acca | 14,817 |
def index(request):
"""Homepage for this app.
"""
with open('index.html') as fp:
return HttpResponse(fp.read()) | b9ce38f59443e38e5d27ff7f153a834e1c11b429 | 14,818 |
def SECH(*args) -> Function:
"""
The SECH function returns the hyperbolic secant of an angle.
Learn more: https//support.google.com/docs/answer/9116560
"""
return Function("SECH", args) | 594921375aaa7d4fb409e1a4792a6752f81b6bb2 | 14,819 |
def read_ATAC_10x(matrix, cell_names='', var_names='', path_file=''):
"""
Load sparse matrix (including matrices corresponding to 10x data) as AnnData objects.
read the mtx file, tsv file coresponding to cell_names and the bed file containing the variable names
Parameters
----------
matrix: spa... | 9f2073d7582f93db2f714f401fc0fb5e0762a2fc | 14,820 |
def get_html_subsection(name):
"""
Return a subsection as HTML, with the given name
:param name: subsection name
:type name: str
:rtype: str
"""
return "<h2>{}</h2>".format(name) | 2e0f37a7bb9815eda24eba210d8518e64595b9b7 | 14,821 |
def compute_norms(items):
"""
Compute the norms of the item vectors provided.
Arguments:
items -- a hashmap which maps itemIDs to the characteristic vectors
"""
norms = {}
for item in items:
norms[item] = np.sqrt(np.sum(np.square(items[item])))
return... | ff0a805b6a143b7b52c653226b69aed8319eb5ce | 14,822 |
def do_part_1():
"""
Solves part 1
"""
digested_lines = list(map(digest_line, input_lines(2)))
# Poor man's partial
doubles = sum(map(lambda l: contains_nple(l, reps=2), digested_lines))
triples = sum(map(lambda l: contains_nple(l, reps=3), digested_lines))
print(doubles * triples)
r... | 75fa72804d8721b4332d74f00c0bea4d82bcdd02 | 14,823 |
import torch
def create_Rz_batch(a):
"""
Creates a batch of rotation matrices about z of angles a.
Input (batch)
Output (batch, 3, 3)
"""
return torch.stack([
torch.stack([torch.cos(a),
torch.sin(a),
torch.zeros_like(a)],
di... | 7abed1ef608c9985605096679d28c86f5fabab8e | 14,824 |
import torch
def get_upsample_filter(size):
"""Make a 2D bilinear kernel suitable for upsampling"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
filter = (1 - abs(og[0] - center) / factor) * \
... | 8c286e6c20f3400c5206f3f15514a65dc8f3b0b5 | 14,825 |
import math
def lst2gmst(longitude,
hour,
minute=None,
second=None,
longitudeDirection='W',
longitudeUnits='DEGREES'):
"""
Converts Local Sidereal Time to Greenwich Mean Sidereal Time.
Parameters
----------
longitude : float (any nu... | 4e651dde2b5dadb1af5d00bc1813272190f07cdf | 14,826 |
import ast
def filter_funcs(node) -> bool:
"""Filter to get functions names and remove dunder names"""
if not isinstance(node, ast.FunctionDef):
return False
elif node.name.startswith('__') or node.name.endswith('__'):
return False
else:
return True | 022181afa887965af0f2d4c5ec33de07b8a3c089 | 14,827 |
from ptvsd.server import api
def attach(address, log_dir=None, multiprocess=True):
"""Starts a DAP (Debug Adapter Protocol) server in this process,
and connects it to the IDE that is listening for an incoming
connection on a socket with the specified address.
address must be a (host, port) tuple, as ... | aa36e20df5b7d4ad5eb769987ab6e36d368afbb7 | 14,828 |
from typing import Optional
def create_api_token(
creator_id: UserID,
permissions: set[PermissionID],
*,
description: Optional[str] = None,
) -> ApiToken:
"""Create an API token."""
num_bytes = 40
token = token_urlsafe(num_bytes)
db_api_token = DbApiToken(
creator_id, token, p... | 044d041bd013cb5b0ebc9c534b8c0162c3996172 | 14,829 |
import argparse
def parse_arguments():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="Update OCFL inventory sidecar file",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("path", type=str, nargs="*",
... | 4e280ba0471a9bf215871d00e77ae2c4b9f41ebb | 14,830 |
from typing import Tuple
def match_image_widths(
image_i1: Image, image_i2: Image
) -> Tuple[Image, Image, Tuple[float, float], Tuple[float, float]]:
"""Automatically chooses the target width (larger of the two inputs), and
scales both images to that width.
Args:
image_i1: 1st image to match... | 86f043a3069202b2dfc3eb24f9ac10e9077b2237 | 14,831 |
from typing import Optional
from typing import Union
from typing import Any
from typing import Dict
import copy
def get_parameter_value_and_validate_return_type(
domain: Optional[Domain] = None,
parameter_reference: Optional[Union[Any, str]] = None,
expected_return_type: Optional[Union[type, tuple]] = Non... | 9cdd3106a0397a63a13d71b1c0ce5815a41e47ed | 14,832 |
def diff_tags(list_a, list_b):
"""
Return human readable diff string of tags changed between two tag lists
:param list_a: Original tag list
:param list_b: New tag list
:return: Difference string
"""
status_str = text_type("")
tags_added = [tag for tag in list_b if tag not in list_a]
... | e9f69bcdee0e2cb6fd260c56f8bbfe5f568afc63 | 14,833 |
import numpy
def distance_on_great_circle(start_point, direction, distance):
"""compute the location of a point a specified distance along a great circle
NOTE: This assumes a spherical earth. The error introduced in the location
is pretty small (~15 km for a 13000 km path), but it totall screws with
... | e39c62435c208cb2ea4e951b91b641cfbfcd45a8 | 14,834 |
def construct_tree_framework(bracket):
"""Given the tree in bracket form, creates a tree with labeled leaves
and unlabeled inner nodes."""
if type(bracket)==int: #base case, creates leaf
return Node(tree)
else: #recursive step, inner nodes
root = Node(None, construct_tree_framework(brac... | a54651fcc5604f46985b11d0d783c76f4368a9d0 | 14,835 |
def eckart_transform(atommasses, atomcoords):
"""Compute the Eckart transform.
This transform is described in https://gaussian.com/vib/.
Parameters
----------
atommasses : array-like
Atomic masses in atomic mass units (amu).
atomcoords : array-like
Atomic coordinates.
Retu... | 833b18ecdb299d3183da24c3b9d40227e387a385 | 14,836 |
def as_java_array(gateway, java_type, iterable):
"""Creates a Java array from a Python iterable, using the given p4yj gateway"""
java_type = gateway.jvm.__getattr__(java_type)
lst = list(iterable)
arr = gateway.new_array(java_type, len(lst))
for i, e in enumerate(lst):
jobj = as_java_objec... | d8a14a6506a0cbde6f09b4d071f6968da3e4d17d | 14,837 |
import scipy
def match(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Finds the matrix R that minimizes the frobenius norm of RA - B, where
R is orthonormal.
Args:
a (np.ndarray[samples, features]): the first matrix to match
b (np.ndarray[samples, features]): the second matrix to match
... | 461f3f05ab1164bfbac3f9e8f6ccd5622791a6ff | 14,838 |
import time
import requests
import json
def macro_cons_silver_amount():
"""
全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今
:return: pandas.Series
2006-04-29 263651152
2006-05-02 263651152
2006-05-03 445408550
2006-05-04 555123947
2006-05-05 574713264
... | d60bac23a480c056d237dda6b16eb267b2f54ee5 | 14,839 |
import random
def shuffle(answers):
"""
Returns mixed answers and the index of the correct one,
assuming the first answer is the correct one.
"""
indices = list(range(len(answers)))
random.shuffle(indices)
correct = indices.index(0)
answers = [answers[i] for i in indices]
return an... | e597b4aeb65fecf47f4564f2fddb4d76d484707a | 14,840 |
from typing import Union
from pathlib import Path
def annotations_to_xml(annotations_df: pd.DataFrame, image_path: Union[str, Path],
write_file=True) -> str:
"""
Load annotations from dataframe (retinanet output format) and
convert them into xml format (e.g. RectLabel editor / Label... | 68ab235299da7026b77feb715e260f3e1749ec3b | 14,841 |
def depth(sequence, func=max, _depth=0):
"""
Find the nesting depth of a nested sequence
"""
if isinstance(sequence, dict):
sequence = list(sequence.values())
depth_list = [
depth(item, func=func, _depth=_depth + 1)
for item in sequence
if (isinstance(item, dict) or u... | 84b6e7ccaa0f7924fa4a775eca41edf8422222d0 | 14,842 |
def tei_email(elem_text):
"""
create TEI element <email> with given element text
"""
email = etree.Element("email")
email.text = elem_text
return email | cd3d6cf53f7ea5a29c4a02a4ea0d0a2d2144645c | 14,843 |
def rebuild(request):
"""Rebuild ``XPI`` file. It can be provided as POST['location']
:returns: (JSON) contains one field - hashtag it is later used to download
the xpi using :meth:`xpi.views.check_download` and
:meth:`xpi.views.get_download`
"""
# validate entries
secre... | 41d2ca3d73507a99dd790254606d11e743971ba9 | 14,844 |
from typing import List
from pathlib import Path
def get_requirements(req_file: str) -> List[str]:
"""
Extract requirements from provided file.
"""
req_path = Path(req_file)
requirements = req_path.read_text().split("\n") if req_path.exists() else []
return requirements | 3433cd117bbb0ced7ee8238e36f20c69e15c5260 | 14,845 |
from typing import List
import sys
def _generate_ngram_contexts(ngram: str) -> 'List[Acronym]':
"""
Generate a list of contextualized n-grams with a decreasing central n-gram and increasing \
lateral context.
:param ngram:
:return:
"""
tokens = ngram.split(" ")
ngram_size = len(token... | 4beb0fb1f9170191e4118f0c7bb18d0a41e58a63 | 14,846 |
def get_gmail_account(slug):
"""
Return the details of the given account - just pass in the slug
e.g. get_account('testcity')
"""
service = get_gapps_client()
if not service:
return None
try:
return service.users().get(userKey=make_email(slug)).execute()
except HttpError... | 959685e6f40b8333103e47f9ce8c50050ca95961 | 14,847 |
def unisolate_machine_command():
"""Undo isolation of a machine.
Returns:
(str, dict, dict). Human readable, context, raw response
"""
headers = ['ID', 'Type', 'Requestor', 'RequestorComment', 'Status', 'MachineID', 'ComputerDNSName']
machine_id = demisto.args().get('machine_id')
commen... | d981005753030a1be50a3c0ff40022241096ea2f | 14,848 |
def func(*listItems):
"""
1、遍历所有的列表元素
2、遍历所有的列表元素里面的所有元素放进去一个列表里面
3、排序这个列表,返回最大的那个元素
"""
tmp_list=[]
for item in listItems:
if isinstance(item,list):
for i in item:
tmp_list.append(i)
tmp_list=list(filter(lambda k:isinstance(k,int),tmp_list))
tmp... | adbef2744871f1d8f714cbf2a71d4321e3fb72f5 | 14,849 |
def factory(name: str):
"""Factory function to return a processing function for
Part of Speech tagging.
Parameters:
-----------
name : str
Identifier, e.g. 'spacy-de', 'stanza-de', 'flair-de', 'someweta-de',
'someweta-web-de'
Example:
--------
import nlptasks ... | 9166613ba98beeb56dcc5766217d951ff13f9b38 | 14,850 |
def backoff_handler(debug_only=True):
"""Backoff logging handler for when polling occurs.
Args:
details (dict): Backoff context containing the number of tries,
target function currently executing, kwargs, args, value,
and wait time.
"""
def _wrapped(details):
mes... | db76c6d857fd5df000b2bc3ff048d0d180f71a37 | 14,851 |
def align_dataframes(framea, frameb, fill_value = 0.0):
"""Use pandas DataFrame structure to align two-dimensional data
:param framea: First pandas dataframe to align
:param frameb: Other pandas dataframe to align
:param fill_value: default fill value (0.0 float)
return: tuple of aligned frames
... | 86a5e8c399ab47a10715af6c90d0901c2207597c | 14,852 |
def flip_ud(img):
"""
Expects shape to be (num_examples, modalities, depth, width, height)
"""
return np.flip(img.copy(), 3) | f7a14641a89f5a170cb3d19b412acdbcbe3ac2f3 | 14,853 |
def data_context_service_interface_pointuuid_otsi_service_interface_point_spec_otsi_capability_get(uuid): # noqa: E501
"""data_context_service_interface_pointuuid_otsi_service_interface_point_spec_otsi_capability_get
returns tapi.photonic.media.OtsiCapabilityPac # noqa: E501
:param uuid: Id of service-in... | 99b3ed0e843f0dd405cd0d0b618a4da92fbdcf55 | 14,854 |
def _get_trial_event_times(events, units, trial_cond_name):
"""
Get median event start times from all unit-trials from the specified "trial_cond_name" and "units" - aligned to GO CUE
:param events: list of events
"""
events = list(events) + ['go']
event_types, event_times = (psth.TrialCondition... | c7198fdba392d7b5301109175408d3c0d95adbb9 | 14,855 |
import os
def is_path_exists_or_creatable(pathname=None):
"""
`True` if the passed pathname is a valid pathname for the current OS _and_
either currently exists or is hypothetically creatable; `False` otherwise.
This function is guaranteed to _never_ raise exceptions.
"""
try:
# To pr... | ca93215ab86fb9d68d21262a3b941f32bea3c474 | 14,856 |
from typing import Iterable
def select_region(selections, positions, region):
"""
selection in region from selections
"""
if not region:
return selections
region = list(region) + [None, None]
assert all([x is None or isinstance(x, Iterable) and len(x) == 2
for x in regi... | b9efc393b7d60773554130ded49d9dc9e00081e5 | 14,857 |
def summarize_center_and_dispersion(
analysis_layer,
summarize_type=["CentralFeature"],
ellipse_size=None,
weight_field=None,
group_field=None,
output_name=None,
context=None,
gis=None,
estimate=False,
future=False):
"""
.. image::... | a1fc44cb1781bb11f39dda597fe884552ec07a99 | 14,858 |
def length_entropy(r: np.ndarray, minlen: int = 2) -> float:
"""Calculate entropy of diagonal lengths in RQ matrix.
Args:
r (np.ndarray[bool, bool]): Recurrence matrix
minlen (int): Minimum length of a line
Returns:
float: Shannon entropy of distribution of segment lengths
"""
... | fe20e36aade8bae5e8a2fc139ad887495818f336 | 14,859 |
def verify_scholarship_chair(user):
""" Verify user has Scholarship Chair permissions """
user_id = user.brother.id
if Position.objects.filter(title='President')[0].brother.id == user_id or \
Position.objects.filter(title='Scholarship Chair')[0].brother.id == user_id or \
debug:
... | 53b1f0331e9af87cced904b2c26bef7a1d600cf2 | 14,860 |
def rotate(posList, axis, angle):
"""Rotate the points about a given axis by a given angle."""
#normalize axis, turn angle into radians
axis = axis/np.linalg.norm(axis)
angle = np.deg2rad(angle)
#rotation matrix construction
ux, uy, uz = axis
sin, cos = np.sin(angle), np.cos(angle)
rotMa... | 0719bf548f5d952e78f0b2551f2edcd9510b1eca | 14,861 |
def _make_frame_with_filename(tb, idx, filename):
"""Return a copy of an existing stack frame with a new filename."""
frame = tb[idx]
return FrameSummary(
filename,
frame.lineno,
frame.name,
frame.line) | c775b77c3c282ed598adc25996fb418a9b85529e | 14,862 |
def median(X):
"""
Middle value after sorting all values by size, or mean of the two middle values.
Parameters
----------
X : np.array
Dataset. Should be a two-dimensional array.
Returns
-------
a: np.array
One-dimensional array that contains the median for each feature... | 232d1ce560c4030b01b048cb9087d5e8c49b39ec | 14,863 |
def _filter_none_values(d: dict):
"""
Filter out the key-value pairs with `None` as value.
Arguments:
d
dictionary
Returns:
filtered dictionary.
"""
return {key: value for (key, value) in d.items() if value is not None} | bed2629e4fa96a391e15b043aa3a0d64c75d6ed0 | 14,864 |
def new_project(request):
"""
if this is a new project, call crud_project without a slug and
with action set to New
"""
return crud_project(request, slug=None, action="New") | fc224a23fb2ecc39fce20a927c57be0ff74ed9d1 | 14,865 |
def get_Simon_instance(simon_instance):
"""Return an instance of the Simon family as a `Cipher`."""
if simon_instance == SimonInstance.simon_32_64:
default_rounds = 32
n = 16
m = 4
z = "11111010001001010110000111001101111101000100101011000011100110"
elif simon_instance == Sim... | 41ce1cdfdb58b15af8167f5e0d03fcd0beb94c80 | 14,866 |
import os
import struct
def load_mnist(path, kind="train"):
"""
Documentation:
---
Description:
Load MNIST images and labels from unzipped source files.
---
Parameters:
kind : str
Used to identify training data vs. validation data. Pass... | 0e67fe5930e652a7a153dfe9f1c3e1ac1a4eb51c | 14,867 |
def clamp(val: float) -> int:
"""Clamp a number to that expected by a reasonable RGB component
This ensures that we don't have negative values, or values exceeding one byte
Additionally, all number inputs are rounded
Args:
val (float): Raw float value to clamp
Returns:
int: Clamped... | b908afd06f8e5bf9b98f2729424e0b007c62a18a | 14,868 |
import scipy
def componental_mfpt(trans: np.ndarray, **kwargs) -> np.ndarray:
"""Compute Markov mean first passage times per connected component of the chain."""
n_comps, comp_labels = scipy.sparse.csgraph.connected_components(
trans, **kwargs
)
hier_trans = transition_matrix(trans)
absorb... | 76c9ade340668e5f564b874bc808170b2d0903cb | 14,869 |
import os
def get_snippet(path):
"""Get snippet source string"""
current_file_dir = os.path.dirname(__file__)
absolute_path = os.path.join(current_file_dir, path)
with open(absolute_path) as src:
return src.read() | e101a25c61313d0531e0c38e27b120d56fcd8a47 | 14,870 |
def atleast_1d(*arys):
"""
Convert inputs to arrays with at least one dimension.
Scalar inputs are converted to 1-dimensional arrays, whilst
higher-dimensional inputs are preserved.
Parameters
----------
array1, array2, ... : array_like
One or more input arrays.
Returns
--... | 440782c7c5a5b231425cc1c1282110e983dd8dc2 | 14,871 |
def lines2str(lines, sep = "\n"):
"""Merge a list of lines into a single string
Args:
lines (list, str, other): a list of lines or a single object
sep (str, optional): a separator
Returns:
str: a single string which is either a concatenated lines (using
a custom or the ... | a9209bd8eda92f42a287725aaeccfcb35dab24cd | 14,872 |
import os
import subprocess
def tail(fname, n=10, with_tail='tail'):
"""Get the last lines in a file.
Parameters
----------
fname : str
File name.
n : int, optional
Number of lines to get (default is 10).
with_tail : str, optional
The 'tail' command to use (default is ... | 6fe1f0cae399653401dec8226e2e9f3c271bdc16 | 14,873 |
def evaluate(board):
"""
Evaluates chess board
input parameter(s):
board --> The chess board to be evaluated
return parameter(s):
score --> The board evaluation
"""
score = 0
for i in range(len(board)):
for j in range(len(board[i])):
# Add p... | 6b02f085ab47d241f7639143d82570e97891975a | 14,874 |
def get_atom(value):
"""atom = [CFWS] 1*atext [CFWS]
An atom could be an rfc2047 encoded word.
"""
atom = Atom()
if value and value[0] in CFWS_LEADER:
token, value = get_cfws(value)
atom.append(token)
if value and value[0] in ATOM_ENDS:
raise errors.HeaderParseError(
... | f7d93daabfc96138e79443eb2e5c7e7a9b28fbbc | 14,875 |
def create_page():
"""新增页面"""
tags = dbutils.get_tags()
return render_template('edit.html', title='新建', edit=False, tags=tags) | 48c14aabc76ff3c4886b2ff7f1340035936d81ce | 14,876 |
def calculate_class_weights():
"""
:return: class-wise true-label-area / false-label-area as a dictionary
"""
df = collect_stats()
df = df.fillna(0)
df = df.pivot(index = 'Class', columns = 'ImageId', values = 'TotalArea')
df = df.sum(axis=1)
df = df / (2500. - df)
return df.to_dict... | 42d006daee27d1400d76e9233e64e4d09683573c | 14,877 |
def get_data_layer(roidb, num_classes):
"""return a data layer."""
if cfg.TRAIN.HAS_RPN:
if cfg.IS_MULTISCALE:
layer = GtDataLayer(roidb)
else:
layer = RoIDataLayer(roidb, num_classes)
else:
layer = RoIDataLayer(roidb, num_classes)
return layer | 32035fc837b402949a5fb75af0ad5dbe26a2e129 | 14,878 |
def split_on_first_brace(input,begin_brace = "{",end_brace = "}",error_replacement="brace_error"):
"""
input: string with {Something1} Something2
output: tuple (Something1,Something2)
"""
if error_replacement=="chapter_error":
print(input[:20])
input = remove_empty_at_begin(input)
if... | 201f6789f9db65aa98b857c923e3ed0484aaea89 | 14,879 |
import os
import re
def find_files(folder_path: str, pattern: str, maxdepth: int = 1):
"""
Read the absolute path of files under a folder
TODO: make it recursive
"""
assert isinstance(folder_path, str), 'folder path must be a string'
assert maxdepth >= 0
if maxdepth == 0:
return ... | c8c3b59281b183d69b829f164504acc520c89239 | 14,880 |
import warnings
def check_count(value, total_count, dimension_type):
"""check the value for count."""
value = validate(value, "count", int)
if value > total_count:
raise ValueError(
f"Cannot set the count, {value}, more than the number of coordinates, "
f"{total_count}, for... | aed0b31e041c3c8ca791533697c2ad9e292a8fcc | 14,881 |
import json
def request_certificate(request):
"""Request the on-demand creation of a certificate for some user, course.
A request doesn't imply a guarantee that such a creation will take place.
We intentionally use the same machinery as is used for doing certification
at the end of a course run, so th... | 73605a4d02d515656ddbd4cb63e1c810d65f5f2e | 14,882 |
def get_useable_checkers():
"""
列出可用插件列表
:return:
"""
useable_checkers = list()
for (checker_name, checker_instance) in CHECKER_INSTANCE_DICT.items():
if checker_instance.useable:
useable_checkers.append(checker_instance)
return useable_checkers | 9548c4423f2176081e59957a823afb986f134c7a | 14,883 |
def get_training_roidb(imdb):
"""Returns a roidb (Region of Interest database) for use in training."""
if cfg.TRAIN.USE_FLIPPED:
print 'Appending horizontally-flipped training examples...'
imdb.append_flipped_images()
print 'done'
print 'Preparing training data...'
wrdl_roidb.pr... | adec6258d6ffa810aef475ec5257ef92a762f1fa | 14,884 |
def _used_in_calls(schedule_name: str, schedule: ScheduleBlock) -> bool:
"""Recursively find if the schedule calls a schedule with name ``schedule_name``.
Args:
schedule_name: The name of the callee to identify.
schedule: The schedule to parse.
Returns:
True if ``schedule``calls a ... | 9d6ff0b3a415047252ef2148aa6e59e229531ef7 | 14,885 |
def font_size_splitter(font_map):
"""
Split fonts to 4 category (small,medium,large,xlarge) by maximum length of letter in each font.
:param font_map: input fontmap
:type font_map : dict
:return: splitted fonts as dict
"""
small_font = []
medium_font = []
large_font = []
xlarge_... | d047e182df8d9015997c2debd6269012cb779df5 | 14,886 |
from typing import Optional
from typing import Collection
from typing import Union
from typing import List
import pandas
def get_candidate_set_size(
mapped_triples: MappedTriples,
restrict_entities_to: Optional[Collection[int]] = None,
restrict_relations_to: Optional[Collection[int]] = None,
additiona... | ccef15c8dd42e63405bfcaa45231f8efa04e0fd5 | 14,887 |
def dm2skin_normalizeWeightsConstraint(x):
"""Constraint used in optimization that ensures
the weights in the solution sum to 1"""
return sum(x) - 1.0 | 79024cb70fd6cbc3c31b0821baa1bcfb29317043 | 14,888 |
import os
def _load_bitmap(filename):
"""
Load a bitmap file from the backends/images subdirectory in which the
matplotlib library is installed. The filename parameter should not
contain any path information as this is determined automatically.
Returns a wx.Bitmap object
"""
basedir = os... | 9d6d53aa7e370ac064e7db20c7e825f8cc004177 | 14,889 |
import requests
def get_auth():
"""
POST request to users/login, returns auth token
"""
try:
url_user_login = f"https://{url_core_data}/users/login"
json = {
"username": creds_name,
"password": creds_pw
}
headers = {
... | 86aa225a8c856dd46ece14d982a24b32a52a87ef | 14,890 |
def vector_between_points(P, Q):
""" vector between initial point P and terminal point Q """
return vector_subtract(Q, P); | de86c29dfe8c75b31040942d7195b8b92d731106 | 14,891 |
import time
def before_train(loaded_train_model, train_model, train_sess, global_step, hparams, log_f):
"""Misc tasks to do before training."""
stats = init_stats()
info = {"train_ppl": 0.0, "speed": 0.0, "avg_step_time": 0.0,
"avg_grad_norm": 0.0, "avg_train_sel": 0.0,
"learning_r... | d333808bec0771e74d709f859b7423b9e561703f | 14,892 |
import os
def reg_file_comp(ref_file, comp_file):
"""Compare the reference file 'ref_file' with 'comp_file'. The
order of these two files matter. The ref_file MUST be given
first. Only values specified by reg_write() are compared. All
other lines are ignored. Floating point values are compared based
... | 4b3999625880cbf30de5cc4ec062ce700866a539 | 14,893 |
def methodInDB(method_name, dict_link, interface_db_cursor): #checks the database to see if the method exists already
"""
Method used to check the database to see if a method exists in the database
returns a list [Boolean True/False of if the method exists in the db, dictionary link/ID]
"""
crsr = ... | 8dc3ecc256b696a06906e63a461c241ff429e8ae | 14,894 |
def dict_to_image(screen):
""" Takes a dict of room locations and their block type output by RunGame.
Renders the current state of the game screen.
"""
picture = np.zeros((51, 51))
# Color tiles according to what they represent on screen:.
for tile in screen:
pos_x, ... | 5657d3984a035d11854ef2b1f6dff642a00032a1 | 14,895 |
from .model_store import download_model
import os
def get_mobilenet(version,
width_scale,
model_name=None,
pretrained=False,
root=os.path.join('~', '.keras', 'models'),
**kwargs):
"""
Create MobileNet or FD-MobileNet mod... | da4f81d06bc041b63b47f096eed0c41dc7c39390 | 14,896 |
def can_fuse_to(wallet):
"""We can only fuse to wallets that are p2pkh with HD generation. We do
*not* need the private keys."""
return isinstance(wallet, Standard_Wallet) | 1ee8693d7457591a64057a4913d9739f96319e7a | 14,897 |
def _build_context(hps, encoder_outputs):
"""Compute feature representations for attention/copy.
Args:
hps: hyperparameters.
encoder_outputs: outputs by the encoder RNN.
Returns:
Feature representation of [batch_size, seq_len, decoder_dim]
"""
with tf.variable_scope("memory_context"):
contex... | 6ce8a9a7845376f1804610d371d23b32fa9991f7 | 14,898 |
from typing import Union
def rf_local_divide(left_tile_col: Column_type, rhs: Union[float, int, Column_type]) -> Column:
"""Divide two Tiles cell-wise, or divide a Tile's cell values by a scalar"""
if isinstance(rhs, (float, int)):
rhs = lit(rhs)
return _apply_column_function('rf_local_divide', le... | 76740879461e6dea302568d3bebc4dd6d7eb9363 | 14,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.