content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def findStars_old(imgData,apertureType='radius',maxima_size=5,maxima_sigma=2,maxima_footprint=None,aperture_radii=[],threshold=None,
saturate=None,margin=None,binStruct=None,fit_method='elliptical moffat',id=None):
"""
Detect possible sources in an image and attempt to fit them to a specified pr... | 5,302,900 |
def run(factory, method: str, **kwargs):
"""hook to call event list factory
call any function
Args:
factory: :obj:`design_db_manager.events.EventManager` or :obj:`str`
method (str): 取得の仕方. 'get' or 'get_all'
kwargs (dict): kwargs for method selected by args
date or (yea... | 5,302,901 |
def label_unlabeled_plain(file_in, file_out_prefix='data/up/plain/'):
"""Get all unlabeled pairs from `file_in` and save those predicted as positives in `file_out`.
Sort by predictions."""
table = []
headers = ['Algorithm', 'UP']
df = pd.read_csv(file_in, index_col=0, na_filter=False)
X = list(... | 5,302,902 |
def arr_2_tio_image(arr):
"""
ScalarImage(shape: (c, w, h, d))
dtype: torch.DoubleTensor
"""
arr = arr.swapaxes(0,3)
return tio.ScalarImage(tensor=arr) | 5,302,903 |
def test_parse_redirect_inside_terminator(parser):
"""The terminator designates the end of the commmand/arguments portion.
If a redirector occurs before a terminator, then it will be treated as
part of the arguments and not as a redirector."""
line = 'has > inside;'
statement = parser.parse(line)
... | 5,302,904 |
def create_table_of_contents_github_or_gitlab():
"""
Read from file and returns list of (Original Text, Table of Contents List).
"""
md_text_toc_pairs = []
valid_filepaths = []
for filepath in params['name']:
name, ext = path.splitext(filepath)
if ext.lower() != '.md':
... | 5,302,905 |
def parse():
"""Parse the command line inputs and execute the subcommand."""
# Build the list of subcommand modules
modnames = [mod for (_, mod, _)
in pkgutil.iter_modules(payu.subcommands.__path__,
prefix=payu.subcommands.__name__ + '.')
... | 5,302,906 |
def get_data_type(name):
"""Extract the data type name from an ABC(...) type name."""
return name.split('(', 1)[0] | 5,302,907 |
def rytz_axis_construction(d1: Vec3, d2: Vec3) -> Tuple[Vec3, Vec3, float]:
"""The Rytz’s axis construction is a basic method of descriptive Geometry
to find the axes, the semi-major axis and semi-minor axis, starting from two
conjugated half-diameters.
Source: `Wikipedia <https://en.m.wikipedia.org/wi... | 5,302,908 |
def test_get_var_units(initialized_bmi, var_name):
"""Test the units of the variables."""
units = initialized_bmi.get_var_units(var_name)
assert isinstance(units, str)
assert check_unit_is_valid(units) | 5,302,909 |
def assert_is_image(img, color=True, check_range=True):
"""Checks if an image satisfies image format.
This function checks if a given image satisfies image format or not.
If the image does not satifiy the format, this function raises an
:class:`AssertionError`.
Args:
img (~numpy.ndarray): ... | 5,302,910 |
def clear_resources():
"""Removes all resource instances from your db and elasticsearch resource index"""
se = SearchEngineFactory().create()
match_all_query = Query(se)
match_all_query.delete(index=TERMS_INDEX)
match_all_query.delete(index=RESOURCES_INDEX)
match_all_query.delete(index=RESOURCE_... | 5,302,911 |
def moving_average(time_series, window_size=20, fwd_fill_to_end=0):
"""
Computes a Simple Moving Average (SMA) function on a time series
:param time_series: a pandas time series input containing numerical values
:param window_size: a window size used to compute the SMA
:param fwd_fill_to_end: index ... | 5,302,912 |
def format_timestamp(df):
"""
Reformat timestamps to ISO 8601
Args:
df: input dataframe
Return:
input dataframe with timestamps formatted as ISO 8601
"""
return df.withColumn(
"timestamp",
F.date_format(
F.to_timestamp("timestamp"), "yyyy-MM-dd'T'HH:m... | 5,302,913 |
def FE(obs, mod, axis=None):
""" Fractional Error (%)"""
return (old_div(np.ma.abs(mod - obs), (mod + obs))).mean(axis=axis) * 2. * 100. | 5,302,914 |
def clean_up(self):
"""
Cleans model solutions
"""
self._indiv_spectra = None | 5,302,915 |
def run_query(db_config_file, query, columns, **kwargs):
"""
General function to run a query against MLWH.
Parameters
----------
db_config_file : str
Path to MySQL config file.
query : str
SQL query.
columns : list of str
Column names for output.
**kwargs
... | 5,302,916 |
def compute_distribution_shift(index, df_wgt, Y, X, method, hist_len, freq=None, tic=0):
""" Y:target (unobserved), X:data (observed) """
N = Y.shape[1]
p = _normalize_distribution(Y)
q = _normalize_distribution(X)
if method.lower() in ['kl', 'kl-divergence']:
eps_ratio = (1-EPS_GREEDY) / ... | 5,302,917 |
def load_input(path: Path) -> Sequence[int]:
"""Loads the input data for the puzzle."""
with open(path, "r") as f:
depths = tuple(int(d) for d in f.readlines())
return depths | 5,302,918 |
def build_receive_plot():
"""
Function to build or rebuild our receive_plot.sh script.
:return:
"""
f = open(receive_script, 'w+')
f.write('#! /bin/bash \n')
f.write(f'nc -l -q5 -p 4040 > "{get_plot_drive_to_use()[0]}/$1" < /dev/null')
f.close()
os.chmod(receive_script, 0o755)
ch... | 5,302,919 |
def create_user(email, password):
"""Create and return a new user."""
user = User(email=email, password=password)
db.session.add(user)
db.session.commit()
return user | 5,302,920 |
def forgiving_state_copy(target_net, source_net):
"""
Handle partial loading when some tensors don't match up in size.
Because we want to use models that were trained off a different
number of classes.
"""
net_state_dict = target_net.state_dict()
loaded_dict = source_net.state_dict()
new... | 5,302,921 |
def _get_query_results(job, splunk_client, limit):
""" Get results from a complete Splunk query """
# Get the results and display them
response = splunk_client.get_results(job, limit)
# Replace "null" with ""
if response:
response = remove_nulls(response)
return response | 5,302,922 |
def patched_auth_failed_open_connection(auth_failed_prepared_stream_reader, event_loop):
"""Return a tuple of patched stream_reader and stream_writer."""
stream_writer = MagicMock()
if asyncio.iscoroutinefunction(stream_writer):
# Python 3.8.2 and later
return_value = (auth_failed_prepared_s... | 5,302,923 |
def has_permissions(**perms):
"""
A decorator that checks if the author has the required permissions.
Examples
--------
::
@has_permissions(administrator=True)
async def setup(ctx):
print("Success")
"""
async def predicate(ctx):
"""
Parameters
... | 5,302,924 |
def run_qc_checks(project_dirs, machine_type):
"""main function"""
qcfails = []
assert len(project_dirs) >= 1
# determine all all/all/all/lane.html in project subdirs of given demux_dir
#
demux_html_files = []
for d in project_dirs:
g = os.path.join(d, 'html/*/all/all/all/lane.html'... | 5,302,925 |
def warning(text, render=1):
""" display a warning
Args:
text (str): warning message
render (bool, optional): Defaults to True. render or return settings
Returns:
str: setting value if render=False, None otherwise
"""
color = 'yellow'
s = "[Warning] %s" % text
writ... | 5,302,926 |
def test_all_of():
"""
GIVEN schemas with schema that has allOf and the referenced schema
WHEN model_factory is called with the name of the schema
THEN a model with the property and tablename is returned.
"""
model = model_factory.model_factory(
name="Schema",
base=mock.MagicMock... | 5,302,927 |
def _ratio_enum(anchor, ratios):
""" Enumerate a set of anchors for each aspect ratio wrt an anchor."""
w, h, x_ctr, y_ctr = _whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = np.round(np.sqrt(size_ratios))
hw = np.round(ws * ratios)
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
... | 5,302,928 |
def test_user_validation_ownership(shared_zone_test_context):
"""
Confirm that test users cannot add/edit/delete records in non-test zones (via zone admin group)
"""
client = shared_zone_test_context.shared_zone_vinyldns_client
batch_change_input = {
"changes": [
get_change_A_AAA... | 5,302,929 |
def dummy_filefield_as_sequence(toformat_name):
"""Simple helper method to fill a models.FileField"""
return factory.Sequence(lambda n: get_dummy_uploaded_image(toformat_name % n)) | 5,302,930 |
def send_script(script, ip, port=30002):
"""Send the script to the UR"""
try:
s = socket.create_connection((ip, port), timeout=2)
except socket.timeout:
print("UR with ip {} not available on port {}".format(ip, port))
finally:
enc_script = script.encode('utf-8') # encoding allows... | 5,302,931 |
def intersect(bed, truth, chromosome, prefix):
"""
Perform bed intersection at chromosome level
:param bed: str
Bed file path
:param truth: str
Truth vcf path
:param chromosome: str
Chromosome
:param prefix: str
Prefix of the output file
:return: tuple
... | 5,302,932 |
def pytest_generate_tests(metafunc):
""" Test case generation and parameterization for this module """
if "ordwrap" in metafunc.fixturenames:
metafunc.parametrize("ordwrap", [tuple, OrderedDict]) | 5,302,933 |
def read_model(hdf5_file_name):
"""Reads model from HDF5 file.
:param hdf5_file_name: Path to input file.
"""
return keras.models.load_model(hdf5_file_name) | 5,302,934 |
def image(server, hash_string):
"""Handle image, use redis to cache image."""
image_url = 'https://{0}.zhimg.com/{1}'.format(server, hash_string)
cached = Config.redis_server.get(image_url)
if cached:
buffer_image = StringIO(cached)
buffer_image.seek(0)
else:
r = Crawler().se... | 5,302,935 |
def address(interface):
"""
Get the IPv4 address assigned to an interface.
Example::
import fabtools
# Print all configured IP addresses
for interface in fabtools.network.interfaces():
print(fabtools.network.address(interface))
"""
with settings(hide('running'... | 5,302,936 |
def nearest_griddata(x, y, z, xi, yi):
"""
Nearest Neighbor Interpolation Method.
Nearest-neighbor interpolation (also known as proximal interpolation or, in some contexts, point sampling) is a simple method of multivariate interpolation in one or more dimensions.<br/>
Interpolation is the problem of ... | 5,302,937 |
def path_to_label(path, pkgroot):
"""Substitute one pkgroot for another relative one to obtain a label."""
if path.find("${pkgroot}") != -1:
return os.path.normpath(path.strip("\"").replace("${pkgroot}", topdir)).replace('\\', '/')
topdir_relative_path = path.replace(pkgroot, "$topdir")
if topd... | 5,302,938 |
async def test_form_username(opp):
"""Test we get the username data back."""
result = await opp.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {}
with patch(
"openpeer... | 5,302,939 |
def clean_invite_embed(line):
"""Makes invites not embed"""
return line.replace("discord.gg/", "discord.gg/\u200b") | 5,302,940 |
def invalid_name(statement):
"""Identifies invalid identifiers when a name begins with a number"""
first = statement.prev_token
second = statement.bad_token
# New in Python 3.10
if (
statement.highlighted_tokens is not None
and len(statement.highlighted_tokens) > 1
):
fir... | 5,302,941 |
def bbox_iou(bboxes1, bboxes2):
"""
@param bboxes1: (a, b, ..., 4)
@param bboxes2: (A, B, ..., 4)
x:X is 1:n or n:n or n:1
@return (max(a,A), max(b,B), ...)
ex) (4,):(3,4) -> (3,)
(2,1,4):(2,3,4) -> (2,3)
"""
bboxes1_area = bboxes1[..., 2] * bboxes1[..., 3]
bboxes2_area =... | 5,302,942 |
def get_album_audio_analysis(sp, album_name, album_name_dict, album_info_path):
"""Get audio analysis data for all albums for the given artists and pickle the data-frames
:param sp: Spotify object
:type sp: object
:param album_name: List of album names
:type album_name: list
:param album_name_d... | 5,302,943 |
def fit_and_sample(lagged_zvalues:[[float]],num:int, copula=None, fig_file=None, labels=None ):
""" Example of fitting a copula function, and sampling
lagged_zvalues: [ [z1,z2,z3] ] Data with roughly N(0,1) margins
copula :
returns: [ [z1, z2, z3] ] representative sample
... | 5,302,944 |
async def test_climate_hvac_action_pi_demand(hass, device_climate):
"""Test hvac action based on pi_heating/cooling_demand attrs."""
thrm_cluster = device_climate.device.endpoints[1].thermostat
entity_id = await find_entity_id(DOMAIN, device_climate, hass)
state = hass.states.get(entity_id)
assert... | 5,302,945 |
def set_errors_to_event(event_uuid: str, errors: Dict[str, List[str]]) -> bool:
"""Adds the list of errors provided into the event.
Arguments:
event_uuid {str} -- The UUID for the event to add errors to.
errors {List[str]} -- Dict with the error messages for each event property
Returns:
... | 5,302,946 |
def createQueryFilters(filters):
"""
Takes in filters from the frontend and creates a query that elasticsearch can use
Args: filters with the fields below
verified - if the user is verified
topics - list of topics we want to see
pov - point of view
lang - the langauge the tw... | 5,302,947 |
def compute_dual_subgradient(weights, dual_vars, lbs, ubs, l_preacts, u_preacts):
"""
Given the network layers, post- and pre-activation bounds as lists of
tensors, and dual variables (and functions thereof) as DualVars, compute the subgradient of the dual objective.
:return: DualVars instance represent... | 5,302,948 |
def generate_dir_rst(dir, fhindex, example_dir, root_dir, plot_gallery):
""" Generate the rst file for an example directory.
"""
if not dir == '.':
target_dir = os.path.join(root_dir, dir)
src_dir = os.path.join(example_dir, dir)
else:
target_dir = root_dir
src_dir = exam... | 5,302,949 |
def test_lbfgs_optimizer(caplog):
"""Unit test of LBFGS optimizer."""
caplog.set_level(logging.INFO)
optimizer = "lbfgs"
dirpath = "temp_test_optimizer"
model = nn.Linear(1, 1)
emmental_learner = EmmentalLearner()
Meta.reset()
emmental.init(dirpath)
# Test default LBFGS setting
... | 5,302,950 |
def plot_surface_density_profile(model: astro_dynamo.model.DynamicalModel,
ax: SubplotBase = None,
target_values: torch.Tensor = None) -> SubplotBase:
"""Plots the azimuthally averaged surface density of a model.
The model must contain a SurfaceD... | 5,302,951 |
def prepare_monthly_donations():
"""
Prepare MonthlyOrders.
"""
ten_days_ago = timezone.now() + timezone.timedelta(days=-10)
recent_batches = MonthlyBatch.objects.filter(date__gt=ten_days_ago)
if recent_batches.count() > 0:
recent_batch = recent_batches.all()[0]
message = "Found... | 5,302,952 |
def calc_hash_crc(filename):
"""Calculate hash and crc32 of selected file"""
data = open(filename, 'rb').read()
fhash = hashlib.sha256(data).hexdigest()
fcrc = zlib.crc32(data)
return {'sha256': fhash, 'crc32' : fcrc} | 5,302,953 |
def deny_request(request, cast: Cast, username: str):
"""
Denies a cast membership request
"""
user = get_object_or_404(User, username=username)
try:
cast.remove_member_request(user.profile)
except ValueError as exc:
messages.error(request, str(exc))
else:
notify.send... | 5,302,954 |
async def create_user_service_call(request: web.Request) -> web.Response:
""" Register User """
user_host = request.app["config"].user_service.host
user_port = request.app["config"].user_service.port
user_path = request.app["config"].user_service.path
user_url = URL(f"http://{user_host}:{user_port}... | 5,302,955 |
def cli():
"""Shipped Brain cli - Upload your models to app.shippedbrain.com"""
pass | 5,302,956 |
def compareDocDecorator(f):
"""Decorator that updates doc strings for comparison methods.
Similar to :func:`serpentTools.plot.magicPlotDocDecorator`
but for comparison functions
"""
f.__doc__ = compareDocReplacer(f.__doc__)
return f | 5,302,957 |
def unet2D(input_tensor, use_upsampling=False,
n_out=1, dropout=0.2, print_summary = False, return_model=False):
"""
2D U-Net
"""
print("2D U-Net Segmentation")
inputs = K.layers.Input(shape=input_tensor, name="Images")
# Convolution parameters
params = dict(kernel_size=(3, 3),... | 5,302,958 |
def sanitise_data(filename):
"""
Make sure that the data are in the primary hdu.
Otherwise some astromatic softs are not working properly.
Other solution would be to check astromatic soft config.
"""
# Make sure to use only the Primary hdu.
# sextractor, scamp seems to crash otherwise.
h... | 5,302,959 |
def extract_addresses_from_txlist(tx_hashes_tx, _getrawtransaction_batch):
"""
helper for extract_addresses, seperated so we can pass in a mocked _getrawtransaction_batch for test purposes
"""
logger.debug('extract_addresses_from_txlist, txs: %d' % (len(tx_hashes_tx.keys()), ))
tx_hashes_addresses ... | 5,302,960 |
def main():
"""Shows basic usage of the Sheets API.
Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
credentials = get_credentials()
http = cr... | 5,302,961 |
def test_pred_loc_inv(
col_min_valid,
row_min_valid,
col_max_valid,
row_max_valid,
valid_offset_lon,
valid_offset_lat,
valid_offset_row,
valid_offset_col,
):
"""
Test inverse localization
"""
# init predictors
___, gri = prepare_loc()
gri.estimate_inverse_loc_pred... | 5,302,962 |
def set_accuracy_83(num):
"""Reduce floating point accuracy to 8.3 (xxxxx.xxx).
:param float num: input number
:returns: float with specified accuracy
"""
return float("{:8.3f}".format(num)) | 5,302,963 |
def abort_if_not_from_a_chat(chat_id: int, message: Message):
"""Makes an abort if the message is not from the chat with the given id"""
if message.chat_id != chat_id:
logger.info("Abort because message is not from a chat")
abort(403, message=f'Message {message.message_id} is not from the chat ... | 5,302,964 |
def get_hexes_at_radius(centre_col, centre_row, radius):
"""
Function that get a list of all hexes at a certain radius from
a centre hex
"""
if radius == 0:
hex_list = [[centre_col, centre_row]]
return hex_list
if radius == 1:
hex_list = [[centre_col, centre_row - 2],
... | 5,302,965 |
def get_dependency_network(filepath):
"""
Given a directory, collects all Python and IPython files and
uses the Python AST to create a dictionary of dependencies from them.
Returns the dependencies converted into a NetworkX graph.
"""
files = get_files(filepath)
dependencies = {}
for fil... | 5,302,966 |
def red(message, prefix=None, suffix=None):
"""Print the message in red text.
:param message: The message to be printed.
:type message: str
:param prefix: A string to print before the message. A space is automatically added to the end.
:type prefix: str
:param suffix: A string to print after ... | 5,302,967 |
def get_user(user_name):
"""
Fetches a github developer (user). Receives an username/login. E.g.
'h3nnn4n'
"""
auth = get_auth()
result = requests.get(
f'https://api.github.com/users/{user_name}',
auth=auth
)
rate_limit_update(result.headers)
check_for_errors(result... | 5,302,968 |
def show_available_simulators():
""" """
print("{:15} | {:10} | {:10} | {:10} | {:10}".format("backend", "wfn", "sampling", "noise", "installed"))
print("--------------------------------------------------------------------")
for k in SUPPORTED_BACKENDS:
print("{:15} | {:10} | {:10} | {:10} | {:1... | 5,302,969 |
def sift(*args):
"""Filters rows of the data that meet input criteria.
Giving multiple arguments to sift is equivalent to a logical "and".
In: df >> sift(X.carat > 4, X.cut == "Premium")
# Out:
# carat cut color clarity depth table price x ...
# 4.01 Premium I I1 61.0 61 152... | 5,302,970 |
def ellipsecoords(pars,npoints=100):
""" Create coordinates of an ellipse."""
# [x,y,asemi,bsemi,theta]
# copied from ellipsecoords.pro
xc = pars[0]
yc = pars[1]
asemi = pars[2]
bsemi = pars[3]
pos_ang = pars[4]
phi = 2*np.pi*(np.arange(npoints,dtype=float)/(npoints-1)) # Divide ci... | 5,302,971 |
def crop_images_scan_manual(images: Tuple[Image], ids: Union[list, DF],
x_sizes: Union[list, DF], y_sizes: Union[list, DF]) -> Tuple[Image]:
""" Read data from dataframe ids, series x_sizes and y_sizes and crop images """
x_sizes = x_sizes.to_list()
y_sizes = y_sizes.to_list()
... | 5,302,972 |
def number_vars(expr):
"""
returns the number of variables in expr
"""
m = PBA.get_var_map(expr)
return len(m) | 5,302,973 |
def test_list_decimal_length_nistxml_sv_iv_list_decimal_length_1_2(mode, save_output, output_format):
"""
Type list/decimal is restricted by facet length with value 5.
"""
assert_bindings(
schema="nistData/list/decimal/Schema+Instance/NISTSchema-SV-IV-list-decimal-length-1.xsd",
instance... | 5,302,974 |
def get_staticmethod_func(cm):
"""
Returns the function wrapped by the #staticmethod *cm*.
"""
if hasattr(cm, '__func__'):
return cm.__func__
else:
return cm.__get__(int) | 5,302,975 |
def like_hood_data_individual(l_values, decision_mat, state_mat):
"""
generates the individual likelihood contribution based on the model.
Parameters
----------
l_values : np.array
the raw log likelihood per state.
decision_mat : numpy.array
see :ref:`decision_mat`
state_mat... | 5,302,976 |
def new_extractor_obj():
"""
Gera um objeto News_extractor novo para cada teste.
"""
return News_extractor() | 5,302,977 |
def write_strs(strs: Iterable[str], dest: str) -> None:
"""Writes strings out to a file."""
with open(dest, 'w') as out:
for elem in strs:
out.write(elem)
out.write('\n') | 5,302,978 |
def render_jinja2_template(
template_path: Path,
package: Optional[Package] = None,
service_name: Optional[ServiceName] = None,
) -> str:
"""
Render Jinja2 template to a string.
Arguments:
template_path -- Relative path to template in `TEMPLATES_PATH`
module -- Module record.
... | 5,302,979 |
def main_cli(session: nox.Session) -> None:
"""Install all dependencies then run package main cli with arg '--version'.
nox -s main_cli
"""
install_dependencies(session, "dev", "test", "doc", "sciops")
session.run("{{cookiecutter.__pkg_import_name}}", "--version") | 5,302,980 |
def fault_wtd_avg_params(slipmodel):
"""
###
# fault_wtd_avg_params: Generate default format for fault parameters from a given slip model for RW
###
"""
num_faults = int(np.max(slipmodel[:, 0]) + 1)
faults = np.zeros((num_faults, 6))
sub_fault_pot = np.zeros((len(slipmodel), 2))
... | 5,302,981 |
def call_me_back(*args):
"""accepts and prints as when argument as possible"""
print('Hello and welcome to Python\'s world oof programming')
print('Welcome to the programming world, where we eat python (not the snake!!!) as food')
print(args[1], args) | 5,302,982 |
async def get_task(request):
"""
Returns a task
:Example: curl -X GET http://localhost:8082/foglamp/task/{task_id}?name=xxx&state=xxx
"""
try:
task_id = request.match_info.get('task_id', None)
if not task_id:
raise web.HTTPBadRequest(reason='Task ID is required.')
... | 5,302,983 |
def test_alternate_rule(db_cls):
"""Testing that both recursion and alternation work."""
d = read(
"""
edge(a, b).
edge(b, c).
edge(c, d).
edge(d, e).
edge(e, f).
path(A, B) :-
edge(A, B).
path(A, B) :-
edge(A, C),
path(C, B).
""",
db_cls=db_cls,
)
# Should be able to recurse t... | 5,302,984 |
def endtext(update, context):
"""Returns `ConversationHandler.END`, which tells the
ConversationHandler that the conversation is over"""
try:
BOT.delete_message(
chat_id=update.message.chat.id,
message_id=context.user_data['message_id']
)
except:
pass
... | 5,302,985 |
def taq_initial_data():
"""Takes the initial values for the analysis
:return: None -- The function prints the message and does not return a
value.
"""
print()
print('#################################################')
print('Average Response Functions Physical Time Analysis')
print('#... | 5,302,986 |
def make_series_filter(
user: str = None, sys_name: str = None, newer_than: dt.datetime = None,
older_than: dt.datetime = None, complete: bool = False,
incomplete: bool = False) -> Callable[[SeriesInfo], bool]:
"""Generate a filter for using with dir_db functions to filter series. This
i... | 5,302,987 |
def users(*logins):
""" Decorate a method to execute it once for each given user. """
@decorator
def wrapper(func, *args, **kwargs):
self = args[0]
old_uid = self.uid
try:
# retrieve users
Users = self.env['res.users'].with_context(active_test=False)
... | 5,302,988 |
def laplace_mech(eps, delta, k=1, prob=1.0):
"""
Calibrate the scale parameter b of the Laplace mechanism
:param eps: prescribed eps
:param delta: prescribed delta
:param k: (optional) number of times to run this mechanism.
:return: the parameter structure for this randomized algorithm
"""
... | 5,302,989 |
def is_mac():
"""
Checks if we are running on Mac OSX.
:returns: **bool** to indicate if we're on a Mac
"""
return platform.system() == 'Darwin' | 5,302,990 |
def log(x, base=None):
""" log(x, base=e)
Logarithmic function.
"""
_math = infer_math(x)
if base is None:
return _math.log(x)
elif _math == math:
return _math.log(x, base)
else:
# numpy has no option to set a base
return _math.log(x) / _math.log(base) | 5,302,991 |
def service_delete(context, service_id, session=None):
"""Deletes both a Service and the Storage Node from the Database."""
if not session:
session = cinder_db.get_session()
with session.begin():
#First we want to cleanup the actual Service entry from the DB
query = model_query(
... | 5,302,992 |
def air_to_vacuum(wair, units):
"""Convert wavelengths in air to wavelengths in vacuum.
**Algorithm:** Convert input air wavelengths to Angstroms. Convert
air wavelengths greater than 1999.3520267833621 Angstroms to vacuum
wavelengths using the following formulae, which is used by VALD3:
.. math::... | 5,302,993 |
def project_test(config, server, project):
"""プロジェクトの全てのボットをテストする"""
server_, entity_bucket = build_entity_bucket(config, server)
repos_factory = build_repository_factory(server_, auth=False)
results = []
for bot_name, _ in entity_bucket.iter_bots(project=project):
res = _bot_test(entity_buc... | 5,302,994 |
def tf_spost(A):
"""Superoperator on the right of matrix A."""
Id = Id_like(A)
return tf_kron(Id, tf.linalg.matrix_transpose(A)) | 5,302,995 |
def element_to_toc_item(element):
"""Convert an element to a TOC item, recursively converting children.
Args:
element (dict) - tree element represented as a dict.
"""
sub_items = []
if "members" in element:
# Group members by type, then alphabetically.
element["members"].sort... | 5,302,996 |
def read_ground_truth(img_path):
"""
Summary.
Read ground truth from txt path corresponding to image path
Args:
img_path(string): image path.
Returns:
list, [YAW,PITCH,ROLL], key point list, bool value(is ground truth valid).
"""
txt_path = ""
if img_path.endswith('jpg... | 5,302,997 |
def check_file_access(file_path, file_label, file_rwx='r', use_logger=False,
warn_only=False, exit_val=exitvals['startup']['num']):
"""
Check if a file is accessible.
For purposes of this function, 'file' includes directories,
symlinks, etc.
If the file doesn't exist, the ch... | 5,302,998 |
def display_sustainability(ticker: str):
"""Yahoo Finance ticker sustainability
Parameters
----------
other_args : List[str]
argparse other args
ticker : str
Fundamental analysis ticker symbol
"""
df_sustainability = yahoo_finance_model.get_sustainability(ticker)
if df_... | 5,302,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.