content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def reindent(str, spaces=''):
"""
Removes any leading empty columns of spaces
"""
lines = str.splitlines()
lspace = [len(l) - len(l.lstrip()) for l in lines if l.lstrip()]
margin = len(lspace) and min(lspace)
return '\n'.join((spaces + l[margin:]) for l in lines) | af46a4440839fb38850d973df0d62abe02213755 | 3,614,200 |
def legal_dissonances(a_list, b_list):
"""
Takes two NoteList objects.
Return format is identical to vertical_intervals() above.
Returned tuples here, however, will only represent intervals that are
illegal in first species counterpoint, but legal in second species.
Second Species Exception:
... | dcec0a759d5f46d3d7d9a4ef1b8606ff15be3516 | 3,614,201 |
def mass2_batch(ts, query, batch_size, top_matches=3, n_jobs=1):
"""
MASS2 batch is a batch version of MASS2 that reduces overall memory usage,
provides parallelization and enables you to find top K number of matches
within the time series. The goal of using this implementation is for very
large tim... | 67de00132a15f0bedfd5ce0145249743a7dcb0a9 | 3,614,202 |
import torch
def getPretrainedModel(loss_module='ArcFace', model_path=CFG.model_path_arcface, device=CFG.device):
"""
Method to get pretrained model from file path
Args:
loss_module (string): loss function Arcface, softmax
model_path (nn.Modiule): Model path
device (torch.devic... | ce617fa49dc9e6ea1ead17cc83efc7e10a88ebd9 | 3,614,203 |
def handle_topic_data(json_data):
"""
- check if user start new topic
- check if user still talk about same topic
"""
intent = json_data['outcomes'][0]['intent']
"""
if session.expected_saying == intent:
#get last topic handler
#handle old topic
msg = handle_intent(se... | 04e610f341ba663841831cb7faa9b4e2d6bfa542 | 3,614,204 |
def get_closest_parameter(driver_name, curve_name, normalize=False):
"""
for nurbs curves only. get the closest parameter value.
:param driver_name: <str> the driving object.
:param curve_name: <str> the mesh object.
:param normalize: <bool> if set True, returns a normalized parameter value.
:r... | 41f71d0a306f0dacb884be79fc5e2893ea75f4d6 | 3,614,205 |
from re import A
def apply_mlp_svd_voting(object_id="M 79", topk=10, return_df=False, ignore_articles=None): # "* sig Ori"
"""
combines both results from above (MLP and SVD) to deliver a final scoring on most probably intersting
papers related to a given object
:param object_id:
:param t... | c6ae7a936a0150f30f7e43f8131dcc9c936c0f74 | 3,614,206 |
import os
import logging
def init_database() -> Database: # pragma: no cover-behave
"""Initialize the database connection and contents."""
database_url = os.environ.get("DATABASE_URL", "mongodb://root:root@localhost:27017")
client = pymongo.MongoClient(database_url)
set_feature_compatibility_version(... | dd652ecf038edbecff3000b94656bc0bd9b2df4e | 3,614,207 |
def income_percentiles(row, percentiles, prefix="total"):
"""
Estimate income percentiles from counts in the census income ranges.
Parameters
==========
row: pandas.Series
A series that contains binned incomes in the ranges given by
CENSUS_INCOME_RANGES.
percentiles: List[float... | ca44ef180f13c730a2eea10c4c4b576e8d54819e | 3,614,208 |
import socket
def process_zabbix(target):
"""Process a Zabbix target
Args:
target: the config file portion for this specific target.
Returns: None
"""
mm = MetricManager(target['name'])
zbxapi = SimpleZabbix(
url=target['api_url'],
user=target['api_user'],
pas... | 61525700697147892a6363e660bb04e6649d9540 | 3,614,209 |
import numpy
def get_column_names(df_object):
"""Get column names for a dataframe ojbect"""
if isinstance(df_object, DataFrame):
columns = list(df_object.columns) # TODO: Update this for numpy arrays etc. later
elif isinstance(df_object, Series):
columns = [df_object.name]
elif isinst... | cdbab7a514e0c3a3eeb4d8fa733c97365434d1df | 3,614,210 |
import urllib
import yaml
def _fetch_global_config(config_url):
"""
Fetch the index_runner_spec configuration file from a URL to a yaml file.
"""
logger.info(f'Fetching config from url: {config_url}')
# Fetch the config directly from config_url
with urllib.request.urlopen(config_url) as res: ... | 5332deff7ad2e96ba4129942912efc775a8d363e | 3,614,211 |
import numpy
def readColorLUT(infile, distance_modulus, mag_1, mag_2, mag_err_1, mag_err_2):
"""
Take in a color look-up table and return the signal color evaluated for each object.
Consider making the argument a Catalog object rather than magnitudes and uncertainties.
"""
reader = pyfits.open(in... | 6bd281bf6434cc14f4a83b7257e24fb165483f90 | 3,614,212 |
def parse_config(conf, env):
"""Get the specific environment, expand any relative paths, and return
a url for create_engine
:param str conf: Name of config file without the file extension
:param str env: Name of the environment within the config file
"""
if env not in conf:
raise Config... | f54398f02a90bbbcc398cbe0cd9b7633ad614650 | 3,614,213 |
def train_model_if_possible(data_df:pd.DataFrame):
"""
add knowledge to skimind
:retrn: bool
"""
if not list(data_df.values):
# aucune nouvelle donnee a apprendre
return True
print(f"preprocessing build")
# train (learning) request object
request_train = preproc... | c89915b2bdd92efd83e51cd8a3bf21880691694f | 3,614,214 |
def eq_xtl(
Cl, D, F,
):
"""
eq_xtl calculates the composition of a trace element in the remaining liquid after a certain amount of
crystallization has occured from a source melt when the crystal remeains in equilibrium with the melt
as described by White (2013) Chapter 7 eq. 7.81. It then calculate... | 298a5557775a953a645aade70f41818e42e761ac | 3,614,215 |
def quantity_label(quantity):
"""Returns formatted string of parameter label
"""
labels = {
'accrate': r'$\dot{m}$',
'alpha': r'$\alpha$',
'd_b': r'$d \sqrt{\xi_\mathrm{b}}$',
'dt': r'$\Delta t$',
'fluence': r'$E_\mathrm{b}$',
'length': 'Burst length',
... | 467baf8f3d2ae72474e6f65e6990779e7cb10034 | 3,614,216 |
def main(inputs: str):
"""Run anagram function as a main method."""
text, check = inputs.split(" ")
return anagram(text=text, check=check) | ff417e95010aed0fd961ec37357af217c3466a23 | 3,614,217 |
def spreadsheet(service, id):
"""Fetch and return spreadsheet meta data with Google sheets API."""
request = service.spreadsheets().get(spreadsheetId=id)
try:
response = request.execute()
except apiclient.errors.HttpError as e:
if e.resp.status == 404:
raise KeyError(id)
... | 17412f8a05c1718bcc6259d3e4809122d6acd2c6 | 3,614,218 |
def fix_labels(mnist_label, add_num):
"""
Args:
label: [[int]] arary, class labels
n: int, number of add data
Returns:
[[int]] array
"""
c_num = len(mnist_label[0])
# add one dimention
fixed_label = np.c_[mnist_label, np.zeros(len(mnist_label))]
assert len(fixed_label[0])... | c721ecb285009f61d4a97b2217ceb97afc6ca717 | 3,614,219 |
from typing import Optional
def get_global_reach_connection(global_reach_connection_name: Optional[str] = None,
private_cloud_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.Inv... | 28ea55e472b98f6333b9bfa38daab51367382bb5 | 3,614,220 |
def parseInertial(link_xml):
"""Parses the URDF xml definition of inertial data.
Args:
link_xml(ElementTree.Element): xml representation of 'inertial' field of URDF link
Returns:
: dict -- of inertial data
"""
inertial_dict = {}
inertial_data = link_xml.find('inertial')
if ine... | 307feba0a36a58c505c2249ef2f2c49ff180d788 | 3,614,221 |
def hexdump(data, start_address=0, compress=True, length=16, sep='.'):
""" Return string array in hex-dump format
:param data: The data array of bytes
:param start_address: Absolute Start Address
:param compress: Compressed output (remove duplicated content, rows)
:param length: ... | 5ea51c95dd297f140c2b96ad1ce10952e3b6e33e | 3,614,222 |
def precipitation():
"""Return the JSON representation of dictionary for the last year."""
# To find the last day:
lastday = list(np.ravel(session.query(Measurement.date).order_by(Measurement.date.desc()).first()))[0]
lastday = lastday.split("-")
year = int(lastday[0])
month = int(lastday[... | 20b92228c7bcc2bc18660b6e0f0545e8ace7ad86 | 3,614,223 |
def get_all_shared_user_info(user, includeCurrentSite=True):
"""Queries all nodes (including local node) for projects and groups the user belongs to.
Returns two lists of dictionaries but does NOT update the local database.
Example of JSON data retrieved from each node:
{
"users": {
... | 2810ce0a67653911aea9c57fd1e339d154073101 | 3,614,224 |
import torch
def binary_accuracy(output: torch.Tensor, target: torch.Tensor) -> float:
"""Computes the accuracy for binary classification"""
# 传入的output是batch x 1的tensor
with torch.no_grad():
batch_size = target.size(0)
pred = (output >= 0.5).float().t().view(-1)
correct = pred.eq(... | 17bfe60acc120c6d3d1578d7d3aff5231a860ff7 | 3,614,225 |
import os
def list_datasets():
"""Get list of available datasets."""
return [
d for d in os.listdir(UEA_UCR_DATA_DIR)
if os.path.isdir(os.path.join(UEA_UCR_DATA_DIR, d))
] | 94df0f6d944c633e61e2ef64a2e3bfd3c0c594b8 | 3,614,226 |
import asyncio
async def healthcheck_task1():
"""A healthcheck representing a database check."""
await asyncio.sleep(0.1)
return ("database is good!", HTTPStatus.OK) | 0e7a968349c26fc28a51781b8dc03c2184981563 | 3,614,227 |
def get_response(request):
"""
Fake view-like callback to use in middleware tests.
"""
return None | 711106895c1aa21847152763bdd05a1f9a367ed6 | 3,614,228 |
def set_proper_dtypes(df):
"""
forgot to save integers as integers. Only the distances feature columns have true floats.
"""
potential_integer_cols = df.columns.difference(list(df.filter(regex='distances.*', axis=1)))
for col in potential_integer_cols:
if str(df[col].dtype) != 'object':
... | 2a7d5f615c666d9a1778dfda1ba427c87541e34b | 3,614,229 |
def has_prefix(sub_s: str) -> bool:
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
if len(sub_s) > 1:
sub_str = sub_s[:2]
else:
sub_str = sub_s[0]
if s... | c873c2a1a03d6a892c1a043c521415f838d60a8c | 3,614,230 |
def stop(syncplan_name, p5_connection=None):
"""
Syntax: SyncPlan <name> stop
Description: Removes the plan <name> from the scheduler
Return Values:
-On Success: the string "1" (the plan was successfully removed)
the string "0" (the plan was not removed or running)
"""
... | 2cec430d9d23079e235c5c0fcfbd94bf1b51d6bb | 3,614,231 |
import torch
def _E_from_XY_batch(X, Y, K, W=None, if_normzliedK=False, normalize=True, show_debug=False): # Ref: https://github.com/marktao99/python/blob/master/CVP/samples/sfm.py#L55
""" Normalized Eight Point Algorithom for E: [Manmohan] In practice, one would transform the data points by K^{-1}, then do a Har... | 07f40fe6275b5b66d21239e18c3cfa7d22e85c2e | 3,614,232 |
import torch
def global_nms(boxes, scores, iou_threshold):
# type: (Tensor, Tensor, float) -> Tensor
"""
Performs non-maximum suppression globally (regardless of category).
Parameters
----------
boxes : Tensor[N, 4]
boxes where NMS will be performed. They
are expected to be in... | 7a2529b16f4b887a3730609aeffeef9f1fc19b81 | 3,614,233 |
import argparse
import sys
def arg_parser():
"""
Parse the command line Arguments and return the values
params: None
returns: data_type - string
returns: train_model - Boolean - Default - Yes
returns: log_level - int - Default - 20 - INFO
returns: console_logging - Boolean - Default - Tru... | 08e2f1409852b4abe2430f760c70eb102e085bd7 | 3,614,234 |
def calculate_stats(answers, predictions, cm):
"""
Prints the Stats for a given class label
:param answers: an array of answers
:param predictions: an array of predictions
:param cm: confusion matrix of form [[TP, FN], [FP, TN]]
"""
# confusion matrix looks like this [[ 23, 63], [ 40, 260]]... | f6c5e2fc54b69aa7bd48bd7e472fdcb64678b5af | 3,614,235 |
def auto_rotate(img):
"""
Automatically rotate the given image to put the eyes on top
:param img: The image to rotate
:type img: 1D numpy array, shape: (1, IMAGE_WIDTH**2)
:returns: The rotated image
:rtype: 2D numpy array, shape: (IMAGE_WIDTH, IMAGE_WIDTH)
"""
#Rotate the image in all ... | 7ef0497d8d6607b2e56ac5e2c51f627b1cc17062 | 3,614,236 |
import time
def calculo_de_tempo_em_execucao(start: float = time()) -> float:
"""Método que irá calcular o tempo de execução a partir de um start
Args:
start (float, optional): tempo decorrido após o start. Defaults to time().
Returns:
float: tempo decorrido de execução.
"""
prin... | 77ef8c01847d5fe86929444677ec83f6d85ff48f | 3,614,237 |
def AddInstanceCommunicationNetworkOp(network):
"""Create an OpCode that adds the instance communication network.
This OpCode contains the configuration necessary for the instance
communication network.
@type network: string
@param network: name or UUID of the instance communication network
@rtype: L{gan... | 52d9b6f76b5f8723cf25db18edb74581c4942503 | 3,614,238 |
import gevent # type: ignore
from gevent.monkey import is_object_patched # type: ignore
from eventlet.patcher import is_monkey_patched # type: ignore
import re
import sys
def _is_contextvars_broken():
# type: () -> bool
"""
Returns whether gevent/eventlet have patched the stdlib in a way where thread l... | 39c298d0fc1cedf7770215b5fe802bdc0dfe4644 | 3,614,239 |
def get_expanding_count(datecol, idcol, targetcol=None):
"""
expanding counts
"""
unq_ids, idcol_inv = np.unique(idcol, return_inverse=True)
unq_dates, date_cnts = np.unique(datecol, return_counts=True)
n = len(idcol)
nunq = len(unq_ids)
learned_dict = np.zeros((nunq, ))
tmp_cnts = ... | 3ae06cca4796aae66db1ebec8273541de2f37927 | 3,614,240 |
from typing import Optional
from typing import List
def text_l(
content: str,
width: Optional[str] = None,
visible: Optional[bool] = None,
tooltip: Optional[str] = None,
commands: Optional[List[Command]] = None,
name: Optional[str] = None,
) -> Component:
"""Create ... | 609b0f7280a6b1aa2999f68d270da3cf5651843c | 3,614,241 |
def null_hurst_measure(measure):
"""Hurst computation parameter from some slope fit.
Parameters
----------
measure: float
the slope of the fit using some method.
Returns
-------
H: float
the Hurst parameter.
"""
# Compute measure
return float(measure) | 5cc8fc8efdf7901ef7af85e4014def95ebee164f | 3,614,242 |
def natSettings(ctx, mach, nicnum, nat, args):
"""This command shows/alters NAT settings.
usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
mtu - set mtu <= 16000
socksndbuf/sockrcvbuf - sets amount of kb for socket sending/receiving buffer
tcpsndwnd/tc... | 2b3e60e68f7c04e8f46b63acf3713297d781d852 | 3,614,243 |
def reduce_loss(loss, reduction):
"""Reduce loss compute.
:param loss: losses
:param reduction: reduce funtion
:return: loss
"""
reduction_function = F._Reduction.get_enum(reduction)
if reduction_function == 0:
return loss
elif reduction_function == 1:
return loss.mean()... | 2e0530b187dd1a59898eb347df7895a6454bbe96 | 3,614,244 |
def cek_filter(data, bound):
""" Check if convergence checks ceke and ceki are within bounds"""
ceke = ceke_filter(data, bound)
ceki = ceki_filter(data, bound)
cek = ceke & ceki
return cek | 2a8d2d8b34e54454c796d1cb50f35e6d75f36493 | 3,614,245 |
import logging
def load_model(dataset):
""" Builds/load a model appropriate for the dataset """
retinanet = RetinaNet(num_classes=dataset.get_num_classes()).train().cuda(DEVICE_IDX)
logging.info('Model loaded')
return retinanet | a20147018c32ba09fb262d1fd69ffa33a57045a1 | 3,614,246 |
def sample(ignition, connection, local_features_path=None):
"""
Pulls in dataframe of relevant observations and columns from PSQL.
Parameters
==========
ignition : yaml with all information necessary
connection : SQLConn connection class
local_features_path : str
Path to locally sto... | 15f0d555bea6b0963f547960beede6224fe7aced | 3,614,247 |
import json
def check_response(response):
"""Check the given HTTP response, returning the result if everything went
fine"""
code, body = response
if code != httplib.OK:
raise Exception('Received http response code %d' % (code))
data = json.loads(body)
if data['error']:
raise E... | a77b1c2e9c714341072c37e69e305529a0825241 | 3,614,248 |
def _strip_value(value, lookup='exact'):
"""
Helper function to remove the branch and version information from the given value,
which could be a single object or a list.
"""
if lookup == 'in':
stripped_value = [_strip_object(el) for el in value]
else:
stripped_value = _strip_obje... | 5dc8c1c02bba50d87bbd15dd89fd3be4ef499c7d | 3,614,249 |
import argparse
def process_command_line(argv=None):
"""
Parse command line arguments
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
Return a Namespace representing the argument list.
"""
# Create the parser
parser = argparse.ArgumentParser(prog='obflow_stat',
... | 6b4a598bc623e7ce19cb3ea85da7db940528b28a | 3,614,250 |
def refactor_levels(
level: Level | list[Level] | None,
obj: Index,
) -> list[int]:
"""
Returns a consistent levels arg for use in ``hide_index`` or ``hide_columns``.
Parameters
----------
level : int, str, list
Original ``level`` arg supplied to above methods.
obj:
Eith... | 699cf16fd3036f6b669da2db758efcd21bdb5eca | 3,614,251 |
def compare_cards(card1, card2):
""" Compare the two given cards and return success if successful """
success = False
if card1.symbol == card2.symbol:
success = True # Success
return success | 27ee184305bd725af2dd1a4a3ef90ef72c815fbf | 3,614,252 |
def get_f_sw_C(washbowl_watersaving_C, Theta_wtr_d):
"""# 洗面水栓の水優先吐水機能における節湯の保温効果係数
Args:
washbowl_watersaving_C(bool): 洗面水栓の水優先吐水機能の有無
Theta_wtr_d(ndarray): 日平均給水温度 (℃)
Returns:
ndarray: 洗面水栓の水優先吐水機能における節湯の効果係数 (-)
"""
f_sw_C_d = np.ones(365)
if washbowl_watersaving_C:
... | 7c51b022c7b0ac3530b7fc2b351d2d9e83f09b5e | 3,614,253 |
def binary(f):
"""Wraps a function of any arity (including nullary) in a function that accepts
exactly 2 parameters. Any extraneous parameters will not be passed to the
supplied function"""
return n_ary(2, f) | 77d14cb4052c0faa1d0fc67e0462d275a0edd234 | 3,614,254 |
import os
import urllib
def downloadMedia(mediaItems: list, isVideo: bool) -> list:
"""
GooglePhotoAPIに接続しphotoもしくはvideoをダウンロードする
Parameters
----------
mediaItems : list
メディア(photo or video)のリスト
isVideo : bool
ビデオであるかどうか
Returns
----------
ids : list
ダウンロー... | f7a1c034097cba29825d8d4f64bf74093510f594 | 3,614,255 |
from typing import Tuple
def get_maxes_and_argmaxes(
data: jnp.array, labels: jnp.array, num_labels: int
) -> Tuple[jnp.ndarray, jnp.ndarray]:
"""
Given a flattened sequence of elements and their corresponding labels,
returns the maxes and argmaxes of each label.
Args:
data: Array of shap... | 9d6fc68e5034e7a89dd0eecf2649a43877a74322 | 3,614,256 |
import os
def sftpUpload(localFile, targetDir):
"""
Just Test connection to host and upload localFile to targetDir
"""
if os.path.isfile(localFile):
print('..Connection to', cinfo['host'])
with pysftp.Connection(**cinfo) as sftp:
print('..Chg to Dir ', targetDir)
... | e51d5382b92e4ae010699181c7162c8d184d66f9 | 3,614,257 |
import platform
import os
import struct
def detect(system_abi=False):
"""Detects host ABI (either process ABI or system ABI, depending on parameters)
:param bool system_abi: specified whether system ABI or process ABI should be detected. The two may differ, e.g.
when a 64-bit system runs 32-bit Pytho... | c5f849bf1e4b694ce0c616f4896e8748eac8e34f | 3,614,258 |
import _uuid
def _uuid_inventory() -> str:
"""Create uuid for inventory."""
return _uuid() | 4acdb6825bba53804d8140f71175777ce0f89adc | 3,614,259 |
def local_overrides_git(install_req, existing_req):
"""Check whether we have a local directory and a Git URL
:param install_req: The requirement to install
:type install_req: pip.req.req_install.InstallRequirement
:param existing_req: An existing requirement or constraint
:type existing_req: pip.re... | 5c031506ddee4d05332421f8470026fbceb0978d | 3,614,260 |
def merge_same_price(df: pd.DataFrame, prec: float=5) -> pd.DataFrame:
"""
Process a collection of bids by merging in each
side (buying or selling) all players with the same
price into a new user with their aggregated quantity
Parameters
----------
df
Collection of bids to process
... | 4d8c841de3759ac3e5775296cbbb97c412d07b1f | 3,614,261 |
def normalize_latents(z, epsilon=1e-8):
"""Pixel norm implementation in NumPy."""
return z / np.sqrt(np.mean(np.square(z), axis=1, keepdims=True) + epsilon) | 39f19136176754824328f05f809e02c327b8efc6 | 3,614,262 |
import os
def _load_saved_model_from_session_bundle_path(export_dir, target, config):
"""Load legacy TF Exporter/SessionBundle checkpoint.
Args:
export_dir: the directory that contains files exported by exporter.
target: The execution engine to connect to. See target in tf.Session()
config: A ConfigP... | c6385e1dd6745e95aec4b8001114955e4884df18 | 3,614,263 |
import os
def get_first_available_file(*paths, file_name):
"""
gets the first path which a file with given name is resided in it.
it returns None if the file is not available in any of given paths.
:param str paths: paths to look for file in them.
all paths must be absolute.
... | 87521324f5d710b8ff0c25761eeb93db3dba2445 | 3,614,264 |
def unite(iterable):
"""Turns a two dimensional array into a one dimensional."""
return list(chain.from_iterable(iterable)) | 10b4445d380061f23f71c66742d0c0312ebd3c97 | 3,614,265 |
import uuid
import os
def reserve_temp_dir(client, bucket, root_dir, empty_file_name='_'):
"""
Reserves a temp dir on Minio.
Normally, Minio does not have directories, only files.
That's why we write an empty file in that reserved directory.
You can customize its name by setting the empty_file_nam... | 2d1fd37f336eec52232bc7d0bf8a4280c702f7c2 | 3,614,266 |
import io
def s3_path_to_bytes_io(path):
"""
Example usage:
bytes_io = s3_path_to_bytes_io("s3://bucket/file.csv")
for line in bytes_io.readlines():
print(line.decode("utf-8"))
"""
bucket, key = s3_path_to_bucket_key(path)
obj = s3_client.get_object(Bucket=bucket, Key=key)
retu... | 9b20e8120781182519a486ec0bb9f3204758215a | 3,614,267 |
def posts_list(request):
"""Logic to handle requests and return responses."""
queryset = Post.objects.all()
context_data = {
"title": "Posts",
"object_list": queryset
}
return render(request, "posts_list.html", context_data)
#return HttpResponse("<h1>List<h1>") | 732dcf5f40f439271c4cfa4db0d5e7e1619bcf45 | 3,614,268 |
def initializeANEOS(in_filename = "std::string",
out_filename = "std::string",
izetl = "std::vector<int>"):
"""Initialize ANEOS with some rather arcane input.
in_filename : The name of the ANEOS input file, initializes the Fortran ANEOS library
out_filename : An optional fi... | eedb4227c13e78a52916f64f7589b9a694f3b28f | 3,614,269 |
def verify_already_exists(username):
""" verify if user already exists """
if User.by_name(username):
return "User already exists" | 57cde28a6fbba6d486d0edaec0eb637570f51398 | 3,614,270 |
from bs4 import BeautifulSoup
def parse(fp_or_str):
"""parse TA98 english web pages into a Python dictionary"""
soup = BeautifulSoup(fp_or_str, "html.parser")
res = soup.find_all(class_=('SectionTitle', 'SectionContent'))
sections = {}
found_current_in_hierarchy = False
ta_hierarchy = []
... | 5f52df040ffbe10c7603ff5a3ad0413c591a3819 | 3,614,271 |
from typing import Any
import torch
def infer_device(x: Any):
"""Infer the device of any object (CPU for any non-torch object)"""
if isinstance(x, torch.Tensor):
return x.device
return torch.device("cpu") | a566c267897ca602e13710a30d928fdc49f856a5 | 3,614,272 |
def test_ps_info():
""" log information for manual testing """
return SkipTest("only used in manual testing")
zones, ps_zones = init_env()
realm = get_realm()
zonegroup = realm.master_zonegroup()
bucket_name = gen_bucket_name()
# create bucket on the first of the rados zones
bucket = zon... | a46619a457663d5281d3a4b74ee8d19561e867b5 | 3,614,273 |
def fertl(rw, rt, phi, a, m, vsh, alpha):
"""Estimate water saturation from Fertl [1]_ equation.
Parameters
----------
rw : int, float
Water resistivity.
rt : array_like
True resistivity.
phi : array_like
Porosity (must be effective).
a : int, float
... | a1bcc19d93d6da56bee35f2e917308d0697ab11a | 3,614,274 |
def mean_agg_func(samples: np.ndarray, num_resamples: int=25_000):
"""
Computes mean.
"""
# Point estimation.
point_estimate = np.mean(samples)
# Confidence interval estimation.
resampled = np.random.choice(samples,
size=(len(samples), num_resamples),
... | d0c8d865a6e314f6a7214160b5d79b96a68722bb | 3,614,275 |
import os
def join_cubes(inputs, output, channels, resume=False, box=None):
"""Join cubes at specific channels
"""
if len(channels)!=len(inputs):
raise ValueError("Length of channels(%i)!=inputs(%i)" %
(len(channels),len(inputs)))
# Concatenated image
imagename = os.path.e... | 71603f989da68dda5e8c17763981f149f4407371 | 3,614,276 |
def factory_membership_model(user_id, org_id, member_type='OWNER'):
"""Produce a Membership model."""
membership = Membership(user_id=user_id,
org_id=org_id,
membership_type_code=member_type)
membership.save()
return membership | 010bde5588acda75a337a529befcacdcf063820e | 3,614,277 |
def from_arrays(x,y,u,v,mask):
"""
from_arrays(x,y,u,v,mask,frame=0)
creates an xArray Dataset from 5 two-dimensional Numpy arrays of x,y,u,v and mask
Input:
x,y,u,v,mask = Numpy floating arrays, all the same size
Output:
data is a xAarray Dataset, see xarray... | c494f421b5cc7e04f69221f3050917dfe969b8f2 | 3,614,278 |
def dup_gf_factor(f, K):
"""Factor univariate polynomials over finite fields. """
f = dup_convert(f, K, K.dom)
coeff, factors = gf_factor(f, K.mod, K.dom)
for i, (f, k) in enumerate(factors):
factors[i] = (dup_convert(f, K.dom, K), k)
return K.convert(coeff, K.dom), factors | 3795623a33998d29285a6fe454049cd6e908a922 | 3,614,279 |
def turns_remaining(turns):
"""returns the number of turns remaining"""
if turns == 0:
return "You ran out of turns."
else:
return "You have {} turns remaining.".format(turns) | 7315f5522c0da660ba37526005c53ba9986d8aa8 | 3,614,280 |
def cross_ratio(A, B, C, D):
"""The cross ration of four _colinear_ points is invariant under projective
transformation. That means that, for any homography H,
cross_ratio(A, B, C, D) == cross_ratio(HA, HB, HC, HD)
which can be useful."""
# (u, v, w) is the line orthogonal to (A-D), that... | 4095d6c448f0d43824ab5b6a05b1921de98388f1 | 3,614,281 |
import random
def find_optimal_route(start_time,
expected_time,
favorite_route='SBS1K',
favorite_option='bus'):
""" Find optimal route for me to go from home to office.
First two inputs should be datetime instances.
"""
# C... | beb64a91e1b5eae4059048c6bf916b8b15dd0be5 | 3,614,282 |
def load_fasta_file(filename, name=None, feature='fasta', unique=True):
"""
Load a fasta file given the filename.
Args:
filename (str): name of the fasta file.
name (str): name for the sequence set
(default: None means use 'filename' as 'name')
feature (str): name for th... | 5071b2c9f625f4cc5e325bdf87a9d92b19ad0285 | 3,614,283 |
from typing import List
from typing import Tuple
def collect_info_masters(
designspace: designspaceLib.DesignSpaceDocument, axis_bounds: AxisBounds
) -> List[Tuple[Location, FontMathObject]]:
"""Return master Info objects wrapped by MathInfo."""
locations_and_masters = []
for source in designspace.sou... | 80fed01b20d59f32493c8fbf7628e5b922d90cdd | 3,614,284 |
def lines_intersect(line1, line2):
""" Returns intersection point between line1 and line2, or None if they dont intersect """
(x1, y1), (x2, y2) = line1
(x3, y3), (x4, y4) = line2
# Compute coeficients for line1
# where a1 x + b1 y + c1 = 0
a1 = y2 - y1
b1 = x1 - x2
c1 = x2 * y1 - x... | 01630c4e056d9c6cca0fd174b71c86ade0ac91c7 | 3,614,285 |
import pathlib
import os
def get_renewal_config(tmp: str, domain: str) -> configobj.ConfigObj:
"""return renewal config of certbot"""
config = {}
tmppath = pathlib.Path(tmp)
cfg = configobj.ConfigObj(os.path.join(tmp, 'config-dir', 'renewal', domain + '.conf'))
for key in ['archive_dir', 'cert', '... | a41a2529691c188da619440efc8de5fed5c6a605 | 3,614,286 |
def _get_project_id():
"""Get project ID from default GCP connection."""
extras = BaseHook.get_connection("google_cloud_default").extra_dejson
key = "extra__google_cloud_platform__project"
if key in extras:
project_id = extras[key]
else:
raise ("Must configure project_id in google_cloud_default "
... | 5dca0b4a9c1e331390e2fa87f891ae63b619ce91 | 3,614,287 |
def get_old_groups():
"""
Get all projects from Firebase which have been created
before we switched to v2.
"""
fb_db = auth.firebaseDB()
ref = fb_db.reference("groups")
projects = ref.get(shallow=True)
logger.info("got old projects from firebase")
return projects | 791a993bfe0b533e3e9826cdfecc05209e234e92 | 3,614,288 |
import json
def get_orders():
"""Return all orders"""
return json.dumps(orders, indent = 4) | f7f72ab387e10a375e86af92fcd0a60470381c6d | 3,614,289 |
def transform_geom(proj, geom):
"""Transform geometry"""
projected_geom = transform(proj, geom)
return projected_geom | fc1f1db121f3925dbc0ce5f062e630ba386868ec | 3,614,290 |
def get_rotation_matrix(init, target):
"""Get rotation matrix that rotates the unit vector init to unit vector target
https://en.wikipedia.org/wiki/Rotation_matrix
Parameters
----------
init : list or numpy array
Initial unit vector
target : list or numpy array
Target unit vecto... | e8dd0f553e96872e5c44b8c1e9150e64c85f5047 | 3,614,291 |
import requests
def make_dcos_request(host_address, relative_url, params=None):
"""Makes a requests that is capable of traversing DCOS EE Strict boundary
:param master: The address for the Mesos master
:type master: `util.host.HostAddress`
:param relative_url: URL path relative to the base address
... | 6075bfc5f5eb935aee835596fc2e6ce4ae530190 | 3,614,292 |
def compute_log_phi(data_intervals, qs, eps, swap):
"""Computes multi-dimensional array log_phi.
Args:
data_intervals: Array of intervals of adjacent points from
compute_intervals.
qs: Increasing array of quantiles in [0,1].
eps: Privacy parameter epsilon.
swap: If true, uses swap dp sensitiv... | a31ba93d85e29f9afb6bf7f005dd0cee25ddcc46 | 3,614,293 |
def get_referencing_foreign_keys(mixed):
"""
Returns referencing foreign keys for given Table object or declarative
class.
:param mixed:
SA Table object or SA declarative class
::
get_referencing_foreign_keys(User) # set([ForeignKey('user.id')])
get_referencing_foreign_k... | 400395d9f8cce763cabdfc74f3c3b9daa6f90966 | 3,614,294 |
import json
import os
def save_environments(workspace, project, env_data):
"""save environments.json file contents.
env_data must be a valid json string.
Returns a string with the error or empty string otherwise"""
error = ''
if len(env_data):
try:
json.loads(env_data)
... | ceff756c8f7ed402c866ead68d66d406f08eb621 | 3,614,295 |
def G1DListMergeEdges(eda, edb):
""" Get the merge between the two individual edges
:param eda: the edges of the first G1DList genome
:param edb: the edges of the second G1DList genome
:rtype: the merged dictionary
"""
edges = {}
for value, near in eda.items():
for adj in near:
if (... | 4393e1d9260a02b20d49afe53e86393f16a4d879 | 3,614,296 |
import operator
def find_corners_of_largest_polygon(img):
"""Finds the 4 extreme corners of the largest contour in the image."""
opencv_version = cv2.__version__.split('.')[0]
if opencv_version == '3':
_, contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Find contours
els... | 3d21c2bfb830b492e3659637640c3a09237eba68 | 3,614,297 |
import tempfile
def hist_k(*args, **kwargs) -> str:
"""Returns the contents of the file created by ISIS hist as a string.
If there is a TO= parameter in the arguments, ``hist_k()`` will
create the file, and return its contents as a string
"""
to_pathlike = None
for (k, v) in kwargs.items():
... | 9154284b6754a74a300b27eaf75d00235efd0442 | 3,614,298 |
def make_rpc_batch_request_entry(rpc_name, params):
"""
Construct an entry for the list of commands that will be passed as a batch
(for `_batch`).
"""
return {
"id": "50",
"version": "1.1",
"method": rpc_name,
"params": params,
} | 603bc7d063f638849a94820af591331f3993c496 | 3,614,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.