content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def imaging_mask(maskbits, bitnamelist=get_default_maskbits(),
bgsmask=False, mwsmask=False):
"""Apply the 'geometric' masks from the Legacy Surveys imaging.
Parameters
----------
maskbits : :class:`~numpy.ndarray` or ``None``
General array of `Legacy Surveys mask`_ bits.
b... | 5,300,500 |
def gen_bbox(lat1_deg,lon1_deg,radius=10):
"""
gen_bbox returns the upper left and lower right coordinates of the bounding box
who's center is at the specified lat/lon
Inputs:
lat1_deg -- Input latitude (degrees)
lon1_deg -- Input longitude (degrees)
radius -- Inputs radius (meters)
... | 5,300,501 |
def get_state(sleep_streak):
"""Returns dict with a state of the bot reported to the server with each poll.
"""
try:
if _in_load_test_mode():
state = os_utilities.get_state()
state['dimensions'] = os_utilities.get_dimensions()
else:
import bot_config
state = bot_config.get_state()
... | 5,300,502 |
def get_connection_probabilities(N,k_over_2,beta):
"""
Return the connection probabilities :math:`p_S` and :math:`p_L`.
"""
assert_parameters(N,k_over_2,beta)
k = float(int(k_over_2 * 2))
pS = k / (k + beta*(N-1.0-k))
pL = k * beta / (k + beta*(N-1.0-k))
return pS, pL | 5,300,503 |
def GetPortagePackage(target, package):
"""Returns a package name for the given target."""
conf = Crossdev.GetConfig(target)
# Portage category:
if target == 'host' or package in Crossdev.MANUAL_PKGS:
category = conf[package + '_category']
else:
category = conf['category']
# Portage package:
pn = ... | 5,300,504 |
def get_new_objective(fields, objective):
"""Checks if the objective given by the user in the --objective flag
differs from the one in the dataset. Returns the new objective or None
if they are the same.
"""
if objective is None:
return None
try:
objective_id = fields.fiel... | 5,300,505 |
def RandomForestClassifier():
"""Wrap a default Random Forest classifier with fixed parameter."""
return sklearn.ensemble.RandomForestClassifier(n_estimators=64) | 5,300,506 |
def get_skew_symmetric(rotational_vector):
"""Get the skew symmetric matrix of a rotational vector.
Parameters
----------
rotational_vector: numpy.ndarray
the rotational vector.
Returns
-------
skew_symmetric:
the skew symmetric matrix of the rotational vector.
"""
... | 5,300,507 |
def get_image(folder, item, filename):
"""画像のレスポンス size で拡大縮小."""
if folder not in ['download', 'face', 'train', 'test']:
abort(404)
filename = os.path.join(DATA_PATH, folder, item, filename)
try:
image = Image.open(filename)
except Exception as err:
pprint.pprint(err)
... | 5,300,508 |
def wrap_phi_to_2pi_torch(x):
"""Shift input angle x to the range of [-pi, pi]
"""
import math
pi = math.pi
x = torch.fmod(2 * pi + torch.fmod(x + pi, 2 * pi), 2 * pi) - pi
return x | 5,300,509 |
def utf16decode(bytes):
""" Take the UTF-16LE encoded strings as bytes from .tbl files and convert
to a UTF-8 string. Jython-compatible. """
bytes = binascii.hexlify(bytes)
bytes = [bytes[i:i+2] for i in range(0, len(bytes), 2)]
bytes = (''.join(filter(lambda a: a !='00', bytes)))
bytes = ... | 5,300,510 |
def FixAbsolutePathInLine(line, relative_paths):
"""Fix absolute paths present in |line| to relative paths."""
absolute_path = line.split(':')[0]
relative_path = relative_paths.get(absolute_path, absolute_path)
if absolute_path == relative_path:
return line
return relative_path + line[len(absolute_path):] | 5,300,511 |
def vgg13_XXS(*args, **kwargs):
"""VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = VGG(make_layers(cfg['BXXS']), final_filter=64, **kwargs)
model.name = "VGG13_XXS"
return model | 5,300,512 |
def read_schema(path):
"""Reads a schema from the provided location.
Args:
path: The location of the file holding a serialized Schema proto.
Returns:
An instance of Schema or None if the input argument is None
"""
result = schema_pb2.Schema()
contents = file_io.read_file_to_string(path)
text_for... | 5,300,513 |
def buildCudaCoreDockerCLI(devices):
"""
Creates the correct device and volume structures to be passed to docker.
"""
cli_devices = []
cli_volumes = {}
libs = []
current_devices = ['/dev/{}'.format(i) for i in os.listdir('/dev/')]
for device in devices:
if device in cu... | 5,300,514 |
def ini_settings(request, test_config_path) -> dict:
"""Load INI settings for test run from py.test command line.
Example:
py.test yourpackage -s --ini=test.ini
:return: A dictionary representing the key/value pairs in an ``app`` section within the file represented by ``config_uri``
"""
... | 5,300,515 |
def is_http_url(url: str) -> bool:
"""判断url是否是http请求的url.
Args:
url (str): 待判断的url字符串
Returns:
bool: 是否是url
"""
try:
result = urlparse(url)
return all([result.scheme, result.netloc]) and result.scheme in ("http", "https")
except ValueError:
return False | 5,300,516 |
def eval_other(setup, nee, i, scoresheet, repeat, nw_outpath):
"""
Experiment to test other embedding methods not integrated in the library.
"""
print('Evaluating Embedding methods...')
lp_coef = dict()
if setup.methods_other is not None:
# Evaluate non OpenNE method
# ---------... | 5,300,517 |
def plot_histogram(series, pdf, title="Histogram"):
"""
Plot histogram of a series.
:param series: Pandas series object
:param pdf: PDF object or PDF filename where the plot will be stored
:param title: Title of the plot
:return:
"""
fig = plt.figure(figsize=[10, 5])
histdata = seri... | 5,300,518 |
def download_tweets_from_s3(path: Path) -> None:
"""Download scraped tweets to `path` from S3 store."""
cmd = " ".join(
[
"aws",
"s3",
"cp",
"s3://nesta-glass/twitter/",
str(path),
"--recursive",
]
)
proc = Popen(
... | 5,300,519 |
def update_maple_invoke_dync_bp(buf, op_enable = True):
"""
update maple::maple_invoke_method breakpoint
when number of enabled maple breakpoints is 0, disable maple::maple_invoke_method
when number of enabled maple breakpoints changes from 0 to non-0, enable maple::maple_invoke_method
... | 5,300,520 |
def setup_persistent_compute_target(workspace, cluster_name, vm_size,
max_nodes):
"""
Set up a persistent compute target on AzureML.
A persistent compute target runs noticeably faster than a
regular compute target for subsequent runs. The benefit
is that AzureML ... | 5,300,521 |
def flatten_tuple(item):
"""
"""
if not is_valid_iterable(item):
return ensure_tuple(item)
if item and is_valid_iterable(item[0]) and len(item) == 1:
item = item[0]
if item and is_valid_iterable(item[0]):
item = (*item[0], item[1])
return tuple(item) | 5,300,522 |
def test_SVDpp_parameters():
"""Ensure that all parameters are taken into account."""
# The baseline against which to compare.
algo = SVDpp(n_factors=1, n_epochs=1)
rmse_default = evaluate(algo, data, measures=['rmse'])['rmse']
# n_factors
algo = SVDpp(n_factors=2, n_epochs=1)
rmse_factors... | 5,300,523 |
def connect_mongodb() -> MongoClient:
"""connect mongodb"""
config = yaml.load(open(SERVER_FILE_PATH, encoding="utf-8"))
config_dct = config.get("mongodb")
client = MongoClient(
"mongodb://{user}:{pwd}@{host}:{port}/{db}"
"?readPreference=primary".format(
user=config_dct.get(... | 5,300,524 |
def parsetepacoc(
stages=(dict(mode='pcfg', split=True, markorigin=True),
dict(mode='plcfrs', prune=True, k=10000),
dict(mode='plcfrs', prune=True, k=5000, dop='doubledop',
estimator='rfe', objective='mpp')),
trainmaxwords=999, trainnumsents=25005, testmaxwords=999,
binarization=parser.DictObj(
me... | 5,300,525 |
def f5(seq, idfun=None):
"""Uniqify a list (remove duplicates).
This is the fast order-preserving uniqifier "f5" from
http://www.peterbe.com/plog/uniqifiers-benchmark
The list does not need to be sorted.
The return value is the uniqified list.
"""
# order preserving
if idfun is None:
... | 5,300,526 |
def do_work(in_queue):
"""
Here the queue which contains dict type obj is read whose NUI which is a unique ID for each unique drug is first read and json data is then requested
for all the roles mentioned in 'diff_rel' of the NUI read.
This data is then added with the key role on to the dict type obj '... | 5,300,527 |
def validate_serial():
"""Validate migrated serials."""
validate_serial_records() | 5,300,528 |
def download_systemplates_sec_storage(server, services):
"""Download System templates on sec storage"""
try:
# Login to management server
ssh = SshClient(
server["ipaddress"],
server["port"],
... | 5,300,529 |
def evaluate(train_data_path, config_path, test_data_path):
"""
Evaluate test data given model derived from Rasa NLU training data and pipeline configuration,
printing f1 scores per entity
Parameters:
train_data_path: relative path of Rasa NLU training data(.json)
config_path: relative ... | 5,300,530 |
def test_diagnostic_option():
"""Ensure that category option properties work."""
tu = get_tu('int f(int i) { return 7; }', all_warnings=True)
assert len(tu.diagnostics) == 1
d = tu.diagnostics[0]
assert d.option == '-Wunused-parameter'
assert d.disable_option == '-Wno-unused-parameter' | 5,300,531 |
def move_brick_to(brick, position):
""" Move brick to given position """
brick.x = position.x
brick.y = position.y
brick.z = position.z | 5,300,532 |
def cvCrossProduct(*args):
"""cvCrossProduct(CvArr src1, CvArr src2, CvArr dst)"""
return _cv.cvCrossProduct(*args) | 5,300,533 |
def compute_oks(points_gt, points_pr, scale=None, stddev=0.025):
"""Computes the object keypoints similarity between sets of points.
Args:
points_gt: Ground truth instances of shape (n_gt, n_nodes, n_ed),
where n_nodes is the number of body parts/keypoint types, and n_ed
is the ... | 5,300,534 |
async def get_member(message, command, example):
"""
getting the user from reply message
"""
try:
member = message.reply_to_message.from_user
logger.info(f"received the user {member}")
except AttributeError:
await message.answer(f"You must <b>send</b> the message "
... | 5,300,535 |
def compute_all_delta_a(old_file: H5File, new_file: H5File, include_cd: bool=False) -> None:
"""Computes the change in absorption for all cases where valid data exists
and stores the results in a new file
Args:
old_file (H5File): The file in which the raw data is stored
new_file (H5File): T... | 5,300,536 |
def test_post_an_oco_order():
"""Tests the API endpoint to post a new oco order"""
client = Client(key, secret)
response = client.new_oco_order(**params)
response.should.equal(mock_item) | 5,300,537 |
def define_output_datastore(datastore=None, template=None):
"""
Sets the `arcgis.env.output_datastore` by providing the datastore and template name
to this method. If datastore is None, the `arcgis.env.output_datastore` will reset
to default.
========================== ===========================... | 5,300,538 |
def file_mode_checker(filename, mode=0o600):
"""Check file mode and update it, if needed.
@param filename: filename path
@type filename: basestring
@param mode: requested file mode
@type mode: int
"""
warn_str = 'File {0} had {1:o} mode; converted to {2:o} mode.'
st_mode = os.stat(file... | 5,300,539 |
def draw_roc(roc_info, prefix='', fnum=1, **kw):
"""
NOTE: There needs to be enough negative examples for using ROC
to make any sense!
Example:
>>> # xdoctest: +REQUIRES(module:kwplot)
>>> # xdoctest: +REQUIRES(module:ndsampler)
>>> from netharn.metrics import DetectionMetrics
... | 5,300,540 |
def verify_recognized(file_path, mkvmerge_path='mkvmerge'):
"""Verify a file is recognized by mkvmerge.
file_path (str):
Path to the file to be verified.
mkvmerge_path (str):
Alternate path to mkvmerge if it is not already in the $PATH variable.
"""
if not verify_mkvmerge(mkvmerge_p... | 5,300,541 |
def padded_gather_nd(params, indices, r, idx_rank):
"""Version of gather_nd that supports gradients and blank indices.
Works like gather_nd, but if an index is given as -1, a 0 will be inserted
in that spot in the output tensor.
Args:
params: tensor from which to gather (see gather_nd).
indices: tenso... | 5,300,542 |
def formatted_bool_eval(token_lst, op_dict):
"""eval a formatted (i.e. of the form 'ToFa(ToF)') string"""
if not token_lst:
return None
if len(token_lst) == 1:
return token_lst[0]
has_parens, l_paren, r_paren = parens(token_lst)
if not has_parens:
return generic_eval(token... | 5,300,543 |
def mapk(actual, predicted, k=10):
"""
Computes the mean average precision at k.
This function computes the mean average prescision at k between two lists
of lists of items.
Parameters
----------
actual : list
A list of lists of elements that are to be predicted
(o... | 5,300,544 |
def loss(_sender_input, _message, _receiver_input, receiver_output, labels, _aux_input):
"""
Accuracy loss - non-differetiable hence cannot be used with GS
"""
acc = (labels == receiver_output).float()
return -acc, {"acc": acc} | 5,300,545 |
def lazyprop(func):
"""Wraps a property so it is lazily evaluated.
Args:
func: The property to wrap.
Returns:
A property that only does computation the first time it is called.
"""
attr_name = '_lazy_' + func.__name__
@property
def _lazyprop(self):
"""A lazily evalu... | 5,300,546 |
def text_to_hitobject(text: str) -> HitObject:
"""
HitObjectの文字列を各情報に変換してHitObjectクラスで出力します
引数
----
text: str
-> HitObject
戻り値
------
HitObject
-> HitObjectクラス
予想される例外
--------------
ValueError
-> おそらくフォーマットが合っていないです、一旦見直しましょう
"""
text_split: list = text.split(',')
if len(text_split) != 6:
rais... | 5,300,547 |
def convert_DateTimeField(model, prop, kwargs):
"""Returns a form field for a DateTimeField."""
return f.DateTimeField(**kwargs) | 5,300,548 |
def extract_range(s):
""" Extract range from string"""
ranges = s.split(',')
if len(ranges) > 1:
return (int(ranges[0]), int(ranges[1]))
else:
return (int(ranges[0]), None) | 5,300,549 |
def test_can_get_project_detail(client, db_setup):
"""If we pass in a project code, we should see the corresponding project
details"""
url = reverse("fn_portal_api:project_list")
response = client.get(url, {"prj_cd": "LHA_IS00_123"})
assert response.status_code == status.HTTP_200_OK
returned =... | 5,300,550 |
def expand_machine_type():
""" get machine type specs from api """
machines = {}
compute = googleapiclient.discovery.build('compute', 'v1',
cache_discovery=False)
for pid, part in cfg.instance_defs.items():
machine = {'cpus': 1, 'memory': 1}
... | 5,300,551 |
def create_output_path(filename, outdir=None):
"""
Given a filename for keypoints and descriptors, create an output
directory with _kps.h5 appended.
Parameters
----------
filename : str
The filename or full path
outdir : str
An optional output path
Returns
... | 5,300,552 |
def _ChooseTest(anomalies):
"""Chooses a test to use for a bisect job.
The particular TestMetadata chosen determines the command and metric name that
is chosen. The test to choose could depend on which of the anomalies has the
largest regression size.
Ideally, the choice of bisect bot to use should be based... | 5,300,553 |
def _make_contrib(superclass, func=None):
"""Backport from django 1.8."""
def contribute_to_class(self, cls, name, **kwargs):
if func:
func(self, cls, name, **kwargs)
else:
super(superclass, self).contribute_to_class(cls, name, **kwargs)
setattr(cls, self.name, _C... | 5,300,554 |
def _get_python_executable() -> str:
"""Returns Python executable.
Returns:
Python executable to use for setuptools packaging.
Raises:
EnvironmentError: If Python executable is not found.
"""
python_executable = sys.executable
if not python_executable:
raise Environmen... | 5,300,555 |
def import_provider_directory():
"""
Imports all files in the [Contrail]/crawler/providers directory to ensure that they are registered.
:return:
"""
for fl in os.listdir(os.path.dirname(__file__)):
if os.path.basename(fl).endswith('.py') and not os.path.basename(fl).startswith('__'):
... | 5,300,556 |
def get_bundle_from_waypoints(
ports1: List[Port],
ports2: List[Port],
waypoints: Coordinates,
straight: Callable = straight,
taper_factory: Callable = taper_function,
bend: Callable = bend_euler,
sort_ports: bool = True,
cross_section: CrossSectionFactory = strip,
separation: Option... | 5,300,557 |
def Gaussian(values, errors, Nsamples=100, weights=None, guess=None, bias=True):
"""
A maximum likelihood estimator that returns the parameters for a Gaussian
that best describes a given data set. Uncertainties on the
best-fitting parameters are calculated using Monte Carlo sampling, but
this c... | 5,300,558 |
def leNetModel():
"""
Creates a LeNet model.
"""
model = createPreProcessingLayers()
model.add(Convolution2D(6,5,5,activation='relu'))
model.add(MaxPooling2D())
model.add(Convolution2D(6,5,5,activation='relu'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(120))
... | 5,300,559 |
def simpleCollision(spriteOne, spriteTwo):
"""
Simple bounding box collision detection.
"""
widthSpriteOne, heightSpriteOne = spriteOne.image.get_size()
rectSpriteOne = spriteOne.image.get_rect().move(
spriteOne.pos.x - widthSpriteOne / 2,
spriteOne.pos.y - heightSpriteOne / 2)
... | 5,300,560 |
def points_in_box(box: 'Box', points: np.ndarray, wlh_factor: float = 1.0):
"""
Checks whether points are inside the box.
Picks one corner as reference (p1) and computes the vector to a target point (v).
Then for each of the 3 axes, project v onto the axis and compare the length.
Inspired by: https... | 5,300,561 |
def random_flip(flip_x_chance, flip_y_chance, prng=DEFAULT_PRNG):
""" Construct a transformation randomly containing X/Y flips (or not).
Args
flip_x_chance: The chance that the result will contain a flip along the X axis.
flip_y_chance: The chance that the result will contain a flip along the Y ... | 5,300,562 |
def compare_image(name,func,options):
"""
Returns comparison information about the function performance on the given image.
This function takes the image with the given name and filters it with the given
function and options. It then compares it to the solution image. If the image
is corrupte... | 5,300,563 |
def load_yaml(filename: str):
"""
Load contents of a yaml file in a dictionary
:param filename: path to the yaml file
:return: a data object contains contents of the yaml file
"""
with open(filename, "r") as f:
data_stream = f.read()
return load(data_stream, Loader=Loader) | 5,300,564 |
def display_email_address(email):
"""Make a formatted address (eg: "User Name <username@somewhere.net>"),
from a tuple (Display name, email address) or a list of tuples.
If the parameter is a string, it is returned.
>>> recipients = [('Joe','joe@smith.com'),'sally@smith.com']
>>> displa... | 5,300,565 |
def create_dataframe(records, cache=False, require_unique=None):
"""Create a spark DataFrame from a list of records.
Parameters
----------
records : list
list of spark.sql.Row
cache : bool
If True, cache the DataFrame in memory.
require_unique : list
list of column names... | 5,300,566 |
def plot_num_features(train_visual_path, output_dir):
"""
Create and save the visuazalition of distribution of numeric features for
the two target variable classes.
Parameters
----------
train_visual_path: string
Path including filename to training data in csv format
output_dir: string
Pat... | 5,300,567 |
def stepinto():
"""
wrapper for stepDebugee, instruction into.
"""
return stepDebugee(True) | 5,300,568 |
def einsum_matmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.B where
the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
M <= N, and identity matrices are impl... | 5,300,569 |
def add_sentence_to_meta(table1, protocol, msg_type, field_name,
bit_cnt, sentence, sentence_id):
""" Add sentence and sentence id to an existing message type and field. """
get_sent_id = -2
meta_db = MetaDB(table1)
msg_meta = meta_db.get_meta_by_proto_msgtype_field(protocol, ms... | 5,300,570 |
def place_review(request, place_id):
"""Create a place review for specified place.
Args:
request: auto-generated by django.
place_id: place identity defined by Google.
POST payloads:
review: review text for this user.
"""
if request.method != 'POST':
return HttpResp... | 5,300,571 |
def eval_classif_cross_val_scores(clf_name, classif, features, labels,
cross_val=10, path_out=None,
scorings=METRIC_SCORING):
""" compute statistic on cross-validation schema
http://scikit-learn.org/stable/modules/generated/sklearn.model_selec... | 5,300,572 |
def part_2_min(guess, list_):
"""finds the position at which minimum fuel is used and returns the fuel amount"""
fuel_for_guess = part_2_fuel(guess, list_)
fuel_guess_up = part_2_fuel(guess + 1, list_)
fuel_guess_down = part_2_fuel(guess - 1, list_)
if (fuel_for_guess < fuel_guess_down) and (f... | 5,300,573 |
def test_filter_env_dict_no_env():
"""
pass through dict elements without ~
"""
yc = YamlConfig(env='xx')
flexmock(yc).should_call('filter_env').with_args({'foo': 'bar'}).once()
flexmock(yc).should_call('filter_env').with_args('bar').once()
result = yc.filter_env({'foo': 'bar'})
assert ... | 5,300,574 |
def fits2dict(fits_file,ext,par_list):
"""
'Converts' a FITS file to a Python dictionary, with a list of the original
FITS table's columns, of the user's choosing. Can use this for ANY FITS file,
but is meant for mkf/orb files in $OBSID_pipe folders from NICER, or event files
(be it from NICER-data ... | 5,300,575 |
def get_matplotlib_data():
""" Return 'mpl-data' folder name for matplotlib.
"""
mpl_data = os.path.join(
os.path.dirname(get_module_file_attribute("matplotlib")), "mpl-data"
)
if not os.path.isdir(mpl_data):
return None
suffix_start = mpl_data.find("matplotlib")
return mpl_d... | 5,300,576 |
def vector_from_skew_matrix(skew_mat):
"""
Compute the skew-symmetric matrix,
known as the cross-product of a vector,
associated to the vector vec.
:param skew_mat: 3x3 skew-symmetric matrix
:return vec: 3d vector
"""
skew_mat = vectorization.expand_dims(skew_mat, to_ndim=3)
n_skew_... | 5,300,577 |
def create_logger(level=logging.DEBUG):
"""Create a logger that emits JSON to stdout"""
logger = logging.getLogger()
logger.setLevel(level)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JSONFormatter())
logger.addHandler(handler)
# Add info_with and friends to logger
... | 5,300,578 |
def mutelist(request):
"""
Edit mutelist entries
"""
mutelist = MuteList.objects.filter(user=request.user)
return _template_values(request,
page_title="edit mute list",
header="mutelist",
navbar='nav_account',
... | 5,300,579 |
def cli(log_level):
"""Manage tmux sessions.
Pass the "--help" argument to any command to see detailed help.
See detailed documentation and examples at:
http://tmuxp.git-pull.com/"""
try:
has_minimum_version()
except TmuxCommandNotFound:
click.echo('tmux not found. tmuxp require... | 5,300,580 |
def test_check_single_qubit_to_decompose_to_rotations(gate, method):
"""Initial matrix and product of final decompositions are same within some
phase."""
gate_list = decompose_one_qubit_gate(gate, method)
circuit = QubitCircuit(num_qubits)
circuit.add_gates(gate_list)
decomposed_gates_final_matr... | 5,300,581 |
def main():
"""Clear a CPAC working directory of all node folders related to pipeline
steps which occur after pre-processing.
This script allows easy clearing of the working directory in order to
re-run a pipeline without re-running registration and segmentation, which
are time-consuming.
"""
... | 5,300,582 |
def parse_block_energy(flines, res_dict, prop):
"""Parse energy block.
Parse block that looks as follows::
Average Adsorbate-Adsorbate energy:
===================================
Block[ 0] -443.23204 Van der Waals: -443.23204 Coulomb: 0.00000 [K]
... | 5,300,583 |
def create_root_and_guest_user() -> None:
"""
APIのテスト用。AdminとGuestロールのユーザを作成する。
"""
container = Container()
db = container.db_provider()
db.create_database()
session_factory = db.session
user = User(
"john", "john@example.com", "ジョン", User.get_hashed_password("plain"), "default"... | 5,300,584 |
def gen_path(base, code):
"""
Generate a path for give base path and code used in data generation
"""
#return os.path.join(base, code[:2], code[:3])
return base | 5,300,585 |
def script_to_bech32(script: bytes, witver: int) -> str:
"""https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program"""
witprog = sha256(script)
return bech32.encode(network('hrp'), witver, witprog) | 5,300,586 |
def compute_ssim(
img0,
img1,
max_val=1.0,
filter_size=11,
filter_sigma=1.5,
k1=0.01,
k2=0.03,
return_map=False,
):
"""Computes SSIM from two images.
This function was modeled after tf.image.ssim, and should produce comparable
output.
Args:
img0: torch.tensor. An ... | 5,300,587 |
def sample_unique_molecules(model: DistributionMatchingGenerator, number_molecules: int, max_tries=10) -> List[str]:
"""
Sample from the given generator until the desired number of unique (distinct) molecules
has been sampled (i.e., ignore duplicate molecules).
Args:
model: model to sample from... | 5,300,588 |
def encode(d):
"""Encode an object in a way that can be transported via Mesos attributes: first to
JSON, then to base64url. The JSON string is padded with spaces so that the base64
string has no = pad characters, which are outside the legal set for Mesos.
"""
if isinstance(d, numbers.Real) and not i... | 5,300,589 |
def export(format, filename, projectpath, verbose):
"""Exports data as jsonl, json, bson or csv file"""
if verbose:
enableVerbose()
if projectpath:
acmd = ProjectBuilder(projectpath)
else:
acmd = ProjectBuilder(projectpath)
acmd.export(format, filename)
pass | 5,300,590 |
async def test_failing_deploy_no_handler(
resource_container, agent, environment, client, clienthelper, async_finalizer, no_agent_backoff
):
"""
dryrun and deploy a configuration model
"""
resource_container.Provider.reset()
version = await clienthelper.get_version()
resources = [
... | 5,300,591 |
def get_detected_head(np_img_set, cascades):
"""Detects a head and returns HeadData depending on input.
Head data is scaled normalized, x, y, and radius go from 0 to 1.
depth is same as raw data"""
potential_boxes = _run_cascades(np_img_set.ir, cascades)
if(len(potential_boxes) == 0):
retu... | 5,300,592 |
def task_default():
"""Default task of set 'test'"""
_logger.warning("No task chosen from set 'tests'") | 5,300,593 |
def create_csv(file_path):
"""
This function will create an index file with image paths and labels in csv format
obtained csv will have two columns path(path to acess the image),label(class of the image)
"""
images=[]
labels=[]
label_file=pd.DataFrame(columns=['path','label'],index=N... | 5,300,594 |
def knn_cond_mutual_information(x, y, z, k, standardize = True, dualtree = True):
"""
Computes conditional mutual information between two time series x and y
conditioned on a third z (which can be multi-dimensional) as
I(x; y | z) = sum( p(x,y,z) * log( p(z)*p(x,y,z) / p(x,z)*p(y,z) ),
wher... | 5,300,595 |
def get_downloader(start_date, end_date, every_min_bar):
"""returns a downloader closure for iex cloud
:param start_date: the first day on which dat are downloaded
:param end_date: the last day on which data are downloaded
:type start_date: str in format YYYY-MM-DD
:type end_date: str in format YYYY... | 5,300,596 |
def kv_kernel(v1, v2, c=3):
""" Updated vertex kernel that multiples the dirac on the node
labels and a brownian bridge on the node attributes """
if isinstance(v1, int):
""" If just an integer, then no attr """
k_dirac = dirac(v1, v2)
k_brownian_bridge = 1
elif isinstance(v1, l... | 5,300,597 |
def _init_caffe(cfg):
"""Initialize pycaffe in a training process.
"""
import caffe
# fix the random seeds (numpy and caffe) for reproducibility
np.random.seed(cfg.RNG_SEED)
caffe.set_random_seed(cfg.RNG_SEED)
# set up caffe
caffe.set_mode_gpu()
caffe.set_device(cfg.GPU_ID) | 5,300,598 |
def view(prefix, tail, start):
"""Show application logs"""
args = [
"awslogs",
"get",
app.log_group,
f"{prefix}.*",
"--no-stream",
"--start",
start,
]
if tail:
args.append("--watch")
with Halo(text="fetching logs", spinner="dots"):
... | 5,300,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.