content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_calculate_distance():
""" Test that calculate_distance calculates what we expect"""
r1 = np.array([0,0,0])
r2 = np.array([0,1,0])
expected_distance = 1
calculated_distance = molecool.calculate_distance(r1,r2)
assert expected_distance == calculated_distance | 5,313,000 |
def translate_marker_and_linestyle_to_Plotly_mode(marker, linestyle):
"""<marker> and <linestyle> are each one and only one of the valid
options for each object."""
if marker is None and linestyle != 'none':
mode = 'lines'
elif marker is not None and linestyle != 'none':
mode = 'lines+markers'
elif marker is n... | 5,313,001 |
def handle_exception(err):
"""for better error handling"""
# start with the correct headers and status code from the error
response = err.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": err.code,
"name": err.name,
"description": err.descripti... | 5,313,002 |
def strRT(R, T):
"""Returns a string for a rotation/translation pair in a readable form.
"""
x = "[%6.3f %6.3f %6.3f %6.3f]\n" % (
R[0,0], R[0,1], R[0,2], T[0])
x += "[%6.3f %6.3f %6.3f %6.3f]\n" % (
R[1,0], R[1,1], R[1,2], T[1])
x += "[%6.3f %6.3f %6.3f %6.3f]\n" % (
R[2,0]... | 5,313,003 |
def video_duration_shrink(fullVideoPath, tStart, tEnd, writeFlie=False):
"""
This function serves to shrink the video duration and
cuts the clip between two times.
Inputs:
fullVideoPath: The corresponding path of the desired video
tStart: The starting time to cut the video from that (d... | 5,313,004 |
def _send_message(project, msg, topic):
"""Sends the message to the topic in project.
Args:
project: A string representing the GCP project to use for pub/sub
msg: A JSON object representing the message to be sent
topic: A string representing the topic name
"""
publisher = pubsub_v1.PublisherClient(... | 5,313,005 |
def update_plant_dropdowns(window, garden):
"""Sort, filter, and update plant tab dropdowns."""
plant_names = sorted([""] + list(garden.plants))
types = {p.org_type for p in garden.plants.values() if p.org_type}
plant_types = sorted([""] + list(types))
window["-PLANT NAME-"].update(values=plant_name... | 5,313,006 |
def _scale_log_and_divide(train, val, scaler="log_and_divide_20"):
"""First apply a log transform, then divide by the value specified in
scaler to sequences train and val.
Parameters
----------
train : np.ndarray
Training dataset
val : np.ndarray
Validation dataset
scaler: s... | 5,313,007 |
def write_error(error):
"""
Writes the error message into S3.
"""
data = {
'result':'error',
'error':unicode(error),
}
key = _get_key()
key.set_contents_from_string(json.dumps(data)) | 5,313,008 |
def retrain(seg_instance: Seg):
"""重新使用内置词典训练 seg_instance。
比如在增加自定义词语信息后需要调用这个模块重新训练分词器
:type seg_instance: Seg
"""
seg_instance.train(PHRASES_DICT.keys()) | 5,313,009 |
def extract_classes(document):
""" document = "545,32 8:1 18:2"
extract_classes(document) => returns "545,32"
"""
return document.split()[0] | 5,313,010 |
def general_value(value):
"""Checks if value is generally valid
Returns:
200 if ok,
700 if ',' in value,
701 if '\n' in value"""
if ',' in value:
return 700
elif '\n' in value:
return 701
else:
return 200 | 5,313,011 |
def _install_dials_autocompletion():
"""generate bash.sh and SConscript file in /build/dials/autocomplete"""
import libtbx.load_env
import os # required due to cctbx weirdness
# Find the dials source directory
dist_path = libtbx.env.dist_path("dials")
# Set the location of the output director... | 5,313,012 |
def test_utc_timestamp():
"""
Test that the resulting timestamp's timezone attribute is pytz.UTC
"""
from geotoys.datetime import utc_timestamp
import pandas
import pytz
ts = pandas.Timestamp(2012,1,5,8,42)
ts_utc = utc_timestamp(ts)
assert ts_utc.tz is pytz.UTC | 5,313,013 |
def test_nesting_pipelines():
"""Test that nesting of pipelines works."""
from sktime.forecasting.ets import AutoETS
from sktime.transformations.series.boxcox import LogTransformer
from sktime.transformations.series.compose import OptionalPassthrough
from sktime.transformations.series.detrend import... | 5,313,014 |
def _cast_to(matrix, dtype):
""" Make a copy of the array as double precision floats or return the reference if it already is"""
return matrix.astype(dtype) if matrix.dtype != dtype else matrix | 5,313,015 |
def wire_mask(arr: np.ndarray, invert: bool = False) -> np.ndarray:
"""
Function
----------
Given an 2D boolean array, returns those pixels on the surface
Parameters
----------
arr : numpy.ndarray
A 2D array corresponding to the segmentation mask
invert : boolean (Default = Fals... | 5,313,016 |
def reverse_str(string):
"""
Base case: length of string
Modification: str slice
"""
if len(string) == 1:
return string
return reverse_str(string[1:]) + string[0] | 5,313,017 |
def check_drf_token(request, format=None):
"""
Return `{"status": true}` if the Django Rest Framework API Token is valid.
<!--
:param request:
:type request:
:param format:
:type format:
:return:
:rtype:
-->
"""
token_exists = Token.objects.filter(key=request.data["token... | 5,313,018 |
def print_available_models():
"""
Print the list of models supported by tsaugur with additional information.
:return: None
"""
print(
"\n"
"Model Description Exogeneous variables\n"
"---------------------------------------... | 5,313,019 |
def iter_chunk_and_save(phase, examples, feat_spec, tokenizer, args: RunConfiguration):
"""Convert Examples to DataRows, optionally truncate sequences if possible, stream to disk.
Args:
phase (str): string identifying the data subset (e.g., train, val or test).
examples (list[Example]): list of... | 5,313,020 |
def run_rsfa(dynamic_copies=2, expansion_order=1, cut_off=55,
num_whitened_signals=99, num_features=99,
sample_weight_parameter=2, epochs=1, conv_tol=0,
plot_last_epoch=True):
"""Recursive Slow Feature Analysis
Runs the recursive slow feature analysis algorithm on the Ten... | 5,313,021 |
def main():
""" runs as a basic version of Amazon Echo """
with io.open(_CONFIG_PATH, 'r') as cfile:
config = yaml.load(cfile)
echo = tabitha.VoiceClient()
avs = AlexaVoiceService(config)
def _terminate(dummy1, dummy2):
print('Quitting...')
avs.terminate()
echo.ter... | 5,313,022 |
def test_jdbc_producer_ordering(sdc_builder, sdc_executor, multi_row, database):
"""Ensure that variously intertwined operations won't be executed out of order in harmful way."""
if isinstance(database, OracleDatabase) and multi_row:
pytest.skip('multi_row is not supported on oracle databases')
ta... | 5,313,023 |
def load_instance(alfacase_content: DescriptionDocument, class_: Type[T]) -> T:
"""
Create an instance of class_ with the attributes found in alfacase_content.
"""
alfacase_to_case_description = get_case_description_attribute_loader_dict(class_)
case_values = to_case_values(alfacase_content, alfacas... | 5,313,024 |
def build_pair_output_path(indices: list, save_dir: str) -> (str, str):
"""
Create directory for saving the paired data
:param indices: indices of the pair, the last one is for label
:param save_dir: directory of output
:return: - save_dir, str, directory for saving the moving/fixed image
... | 5,313,025 |
def create_mg_db_and_user(context, admin="admin", passwd=None, config_types=[]):
"""
根据配置新建mongodb数据库以及用户
"""
if len(config_types) == 0:
config_types = ["development", "testing"]
for config_type in config_types:
command = f"mongo -u {admin} -p{passwd} < cmds/{config_type}_mongodb.txt... | 5,313,026 |
def restart_service(node: CephNode) -> None:
"""
restart HAproxy service.
Args:
node : The node on which service need to restart.
Returns:
None
Raises:
CommandFailed
"""
node.exec_command(sudo=True, cmd="systemctl restart haproxy")
LOG.info("HAproxy Service re... | 5,313,027 |
def number_scenarios(scenes):
"""
Add a 'scenario_number' and 'scenario_name' variable to each scenario.
The hash table for each scenario is altered!
"""
count = 0
for scene in scenes:
scene[1]['scenario_name'] = scene[0]
scene[1]['scenario_number'] = count
count += 1
... | 5,313,028 |
def test_indented_code_blocks_084():
"""
Test case 084: However, any non-blank line with fewer than four leading spaces ends the code block immediately. So a paragraph may occur immediately after indented code:
"""
# Arrange
source_markdown = """ foo
bar"""
expected_tokens = [
"[ico... | 5,313,029 |
async def purge(client, message):
"""
purge
Deletes a selection of messages
Will delete all messages posted after a given message id
>>purge #MESSAGE_ID#
"""
maximumDelete = 250
#Start by stripping off the command
#messageContent will contain the message_id we need for delete
mes... | 5,313,030 |
def trimscan_corner_plot(det, element, ranges, chips=range(16)):
"""
"""
pixels = det.get_pixels()
labels = [r'$a_0$', r'$a_1$', r'$a_2$', r'$a_3$', r'$a_4$', r'$a_5$']
data = []
# Loop over pixels and do the analysis
for index in range(len(labels)):
fit_data = []
... | 5,313,031 |
def find_key_value_in_list(listing, key, value):
"""
look for key with value in list and return dict
:param listing:
:param key:
:param value:
:return: dict_found
"""
# for l in listing:
# if key in l.keys():
# if l[key] == value:
# print("l[key = ", v... | 5,313,032 |
def run_from_cli():
"""Called from the command-line, prints the specified Fibonacci number."""
n = int(sys.argv[1])
print(fibo_number(n)) | 5,313,033 |
def request_test_suite_started(etos, activity_id):
"""Request test suite started from graphql.
:param etos: Etos Library instance for communicating with ETOS.
:type etos: :obj:`etos_lib.etos.ETOS`
:param activity_id: ID of activity in which the test suites started
:type activity_id: str
:return... | 5,313,034 |
def doctest_PJContainer_setitem_with_no_key_IdNamesPJContainer():
"""IdNamesPJContainer: __setitem__(None, obj)
Whenever an item is added with no key, the OID is used.
>>> dm.root['people'] = container.IdNamesPJContainer('person')
>>> dm.root['people'][None] = Person('Stephan')
Let's now sear... | 5,313,035 |
def cast_env(env):
"""Encode all the environment values as the appropriate type.
This assumes that all the data is or can be represented as UTF8"""
return {six.ensure_str(key): six.ensure_str(value) for key, value in env.items()} | 5,313,036 |
def contingency_table(seg, gt, ignore_seg=[0], ignore_gt=[0], norm=True):
"""Return the contingency table for all regions in matched segmentations.
Parameters
----------
seg : np.ndarray, int type, arbitrary shape
A candidate segmentation.
gt : np.ndarray, int type, same shape as `seg`
... | 5,313,037 |
def create_object_detection_training(
train_object_detection_model_request: TrainImageModel,
):
"""[Train a Object Detection Model in AutoML GCP]
Args:
train_object_detection_model_request (TrainImageModel): [Based on Input Schema]
Raises:
error: [Error]
Returns:
[type]: [... | 5,313,038 |
def jwt_authentication(secret, exc=exceptions.PermissionDenied()):
"""
Provide authentication for a view that must have a valid JWT token for the provided secret key
:param secret: The secret key that validates the jwt token provided in the request headers
:param exc: The exception to throw if the token... | 5,313,039 |
def strategy_regret(meta_games, subgame_index, ne=None, subgame_ne=None):
"""
Calculate the strategy regret based on a complete payoff matrix for PSRO.
strategy_regret of player equals to nash_payoff in meta_game - fix opponent nash strategy, player deviates to subgame_nash
Assume all player... | 5,313,040 |
def run():
"""Run app."""
device = os.getenv('DEVICE', 'Samsung S8')
logger.info('Device: {device}'.format(device=device))
avd_name = '{device}_{version}'.format(device=device.replace(' ', '_').lower(), version=ANDROID_VERSION)
logger.info('AVD name: {avd}'.format(avd=avd_name))
if os.getenv('... | 5,313,041 |
def convert_int_to_form(num: int, form_num: int) -> int:
"""Converts decimal integer to specified form number.
Supports conversion to octal and binary forms.
"""
output = 0
bin_digits = []
while num > 0:
num, r = divmod(num , form_num)
bin_digits.insert(0, r)
num_digits =... | 5,313,042 |
def test_valid(__init__, schema, value, expected_value):
"""
GIVEN class that derives from UtilityBase with a schema and the expected value
WHEN to_dict is called
THEN the expected value is returned.
"""
model = type(
"model", (utility_base.UtilityBase,), {"_schema": schema, "__init__": ... | 5,313,043 |
def create_transformation(path_to_importfolder, path_to_exportfolder, start_number, repeat_variable):
"""
Main definition to create the transformations and store them.
Keyword arguments:
path_to_importfolder -- path to the import folder
path_to_exportfolder -- path to the export folder
start_nu... | 5,313,044 |
def less_equal(x, y, cond=None):
"""
This OP returns the truth value of :math:`x <= y` elementwise,
which is equivalent function to the overloaded operator `<=`.
"""
helper = MpcLayerHelper("less_equal", **locals())
if cond is None:
cond = helper.create_variable_for_type_inference(dtype... | 5,313,045 |
def test_cpu_ins_stx_zpy(reg_y: int, memory_location: int) -> None:
"""
Store X Register, Zero Page, Y.
The Zero Page address may not exceed beyond 0xFF:
- 0x80 + 0x0F => 0x8F
- 0x80 + 0xFF => 0x7F (0x017F)
return: None
"""
memory = m6502.Memory()
cpu = m6502.Processor(memory)
... | 5,313,046 |
def test_skip_tags(skip_tags_option, expected):
"""
:param tags_option:
:param expected:
:return:
"""
args = [__prog__] + skip_tags_option + ['playbook.yml']
cli = PlaybookGrapherCLI(args)
cli.parse()
# Ansible uses a set to construct the tags list. It may happen that the order o... | 5,313,047 |
def _expiration(timeout, time_format=None):
"""
Return an expiration time
:param timeout: When
:param time_format: The format of the returned value
:return: A timeout date
"""
if timeout == "now":
return time_util.instant(time_format)
else:
# validity time should match l... | 5,313,048 |
def test_likelihood_fitting_bivariate_gaussian():
"""
Fit using the likelihood method.
"""
# Make variables and parameters
x = Variable('x')
y = Variable('y')
x0 = Parameter('x0', value=0.6, min=0.5, max=0.7)
sig_x = Parameter('sig_x', value=0.1, max=1.0)
y0 = Parameter('y0', value=0... | 5,313,049 |
def get_default_opts(project_name, **aux_opts):
"""
Creates default options using auxiliary options as keyword argument
Use this function if you want to use PyScaffold from another application
in order to generate an option dictionary that can than be passed to
:obj:`create_project`.
:param pr... | 5,313,050 |
async def test_create_race_allready_exist(
event_loop: Any,
mocker: MockFixture,
new_raceplan: Raceplan,
raceplan_mock: Dict,
) -> None:
"""Should raise IllegalValueException."""
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
re... | 5,313,051 |
def prep(config):
""" Generates a csv file compatible with retinanet training script
outputs it in the OPENEM_WORK area for subsequent commands to use
"""
work_dir = config.work_dir()
retinanet_dir = os.path.join(work_dir, "retinanet")
species_csv = os.path.join(retinanet_dir, "species.csv"... | 5,313,052 |
def get_vgg_model(image_size, num_classes):
"""Get VGG16 model"""
inputs = Input(shape=[*image_size, 3])
model = VGG16(
include_top=False,
weights="imagenet",
classes=num_classes,
input_tensor=inputs,
classifier_activation=None,
)
model.trainable = False
... | 5,313,053 |
def redraw_gameWindow(win, p1, p2, color):
""" Displays up the Chess Board Window
includes time """
win.blit(board_img, (0, 0))
formatTime1 = str(int(p1//60)) + ":" + str(int(p1%60))
formatTime2 = str(int(p2 // 60)) + ":" + str(int(p2 % 60))
i... | 5,313,054 |
def random_weights(n_i: int, n_j: int, axis: int = 0, seed: int | None = None) -> ndarray:
"""Generate random weights for producer-injector gains.
Args
----
n_i : int
n_j : int
axis : int, default is 0
seed : int, default is None
Returns
-------
gains_guess: ndarray
"""
... | 5,313,055 |
def spatiotemporal_split(
segments=4,
nan_lims=[np.nan, np.nan],
# usebounds=False,
# order=['minx', 'miny', 'maxx', 'maxy'],
**kwargs
):
"""
Creates spatiotemporal grid using piecewise function and arbitrary
ranges for individial kw-parameters (e.g. age=(0., 450.)), and
sequentially... | 5,313,056 |
def ensure_session(session=None):
"""If session is None, create a default session and return it. Otherwise return the session passed in"""
if session is None:
session = boto3.session.Session()
return session | 5,313,057 |
def relator_terms_to_codes(field):
"""Replace $$e with a MARC relator term with a $$4 with the corresponding code."""
if field["e"]:
existing_codes = [code for code in field.get_subfields("4")]
relator_term = field["e"].strip().lower()
if relator_term in relators_by_name.keys():
... | 5,313,058 |
def reset(label):
"""
@api {delete} /:label Reset counter
@apiName ResetCounter
@apiGroup Counter
@apiParam {String} label Counter label.
@apiSuccess {Number} counter Zero value.
"""
store.delete(label)
return jsonify(counter=0) | 5,313,059 |
def remove_duplicates(df, by=["full_text"]):
"""
Remove duplicates from raw data file by specific columns and save results in file with name given.
"""
boolean_mask = df.duplicated(subset=by, keep="first")
df = df[~boolean_mask]
return df | 5,313,060 |
def read_ecmwf_corrections(base_dir, LMAX, months, MMAX=None):
"""
Read atmospheric jump corrections from Fagiolini et al. (2015)
Arguments
---------
base_dir: Working data directory for GRACE/GRACE-FO data
LMAX: Upper bound of Spherical Harmonic Degrees
months: list of GRACE/GRACE-FO month... | 5,313,061 |
def tex_parenthesis(obj):
"""Return obj with parenthesis if there is a plus or minus sign."""
result = str(obj)
return f"({result})" if "+" in result or "-" in result else result | 5,313,062 |
def main():
"""Repopulate the incident context with the attachments metadata.
Returns:
Demisto entry.
"""
entries = demisto.executeCommand(
'getEntries',
{
'filter': {
'categories': ['attachments']
}
}
)
if is_error(entries... | 5,313,063 |
def add_spec_patch(region, services):
""" Go through spec and determine patching """
LOGGER.info('Create 06_ssm_service_removal patch for region %s', region)
spec = json.loads(get_url_content(SPEC_REGIONS.get(region)))
patches = []
for spec_type in ['ResourceTypes', 'PropertyTypes']:
for r... | 5,313,064 |
def swap_target_nonterminals(target):
"""
Swap non-terminal tokens.
:param target: List of target tokens
:return: List of target tokens
"""
return ['X_1' if token == 'X_0' else 'X_0' if token == 'X_1' else token for token in target] | 5,313,065 |
def validate_nd_array(x):
"""Casts x as a numpy array of the original input shape."""
# Get shape and cast as 1d
x, shape = _get_shape_and_return_1d_array(x)
# Return to original shape
x = x.reshape(shape)
return x | 5,313,066 |
def _expandaliases(aliases, tree, expanding, cache):
"""Expand aliases in tree, recursively.
'aliases' is a dictionary mapping user defined aliases to
revsetalias objects.
"""
if not isinstance(tree, tuple):
# Do not expand raw strings
return tree
alias = _getalias(aliases, tree... | 5,313,067 |
def monitor_status():
""" Reports the wifi status to the extension """
laststatus = ''
while True:
status = wifi_status()
if status != laststatus:
alog().info(f'WiFi status has changed to "{status}"')
postmessage(status)
laststatus = status
time.sleep(... | 5,313,068 |
def is_executable_file(path):
"""Checks that path is an executable regular file (or a symlink to a file).
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``, but
on some platforms :func:`os.access` gives us the wrong answer, so this
checks permission bits directly.
Note
----... | 5,313,069 |
def to_svd_numpy(numpy_array, compress_rate):
"""
We transform an image to its SVD representation: U x D x V^T.
We return as output for each channel X, 2 channels with values: U x D, and V^T.
The initial size is n^2, the final size is: 2np
:param numpy_array: the input image
:param compress_rat... | 5,313,070 |
def _get_login_player_name(html):
"""
指定されたHTMLからログインユーザー名を抽出する。
:param html: 投票ページのHTML
:type html: str
:return: ログインユーザー名
:rtype: str
"""
# ログインユーザー名を返却する
soup = bs4.BeautifulSoup(html, 'html.parser')
player_name_box = soup.find('div', {'class': 'player_name_box'})
if play... | 5,313,071 |
def execute(ctx):
"""Execute this module with the configured options"""
error = MODULE.check_options()
if error:
return
msg = f'Attempting to generate a one-time token to reset the password for user ID {MODULE_OPTIONS["id"]["value"]}'
LOGGER.info(msg)
index_event(ctx.obj.es, module=__... | 5,313,072 |
def my_lovely_hat(file):
"""Everyone loves to wear a nice hat on they head, so articles does too."""
error = None
n = 0
while True:
line = yield error
error = None
if not line:
break
line = line.strip()
if not line:
continue
if l... | 5,313,073 |
def get_max_streak(submissions):
"""
Get the maximum of all streaks
@param submissions (List of tuples): [(DateTime object, count)...]
@return (Tuple): Returns streaks of the user
"""
streak = 0
max_streak = 0
prev = curr = None
total_submissions = 0
for i in submi... | 5,313,074 |
def check_node_reachable(context):
"""
Returns whether the specified node IP is reachable and informs user
"""
chat_id = context.job.context['chat_id']
user_data = context.job.context['user_data']
if 'is_node_reachable' not in user_data:
user_data['is_node_reachable'] = True
respo... | 5,313,075 |
def padZeros(numberString, numZeros, insertSide):
"""Return a string padded with zeros on the left or right side."""
if insertSide == 'left':
return '0' * numZeros + numberString
elif insertSide == 'right':
return numberString + '0' * numZeros | 5,313,076 |
def stations():
""" Return a JSON list of stations from the dataset."""
# Create our session (link) from Python to the DB
session = Session(engine)
station_list = session.query(Measurement.station, Station.name, func.count(Measurement.station)).\
filter(Measurement.station == St... | 5,313,077 |
def eval_sot_accuracy_robustness(results,
annotations,
burnin=10,
ignore_unknown=True,
videos_wh=None):
"""Calculate accuracy and robustness over all tracking sequences.
Args:
... | 5,313,078 |
def load_geo_targets(project_id: str, dataset_id: str) -> None:
"""Loads geo targets."""
client = bigquery.Client(project=project_id)
fully_qualified_table_id = f'{project_id}.{dataset_id}.geo_targets'
job_config = bigquery.LoadJobConfig(
source_format=bigquery.SourceFormat.CSV,
skip_leading_rows=1,... | 5,313,079 |
def spares_kdt_compute_mean_std_v2(res_dicts, spaces, arch_key='eval_arch', perf_key='eval_perf', use_hash=False, sort_best_model_fn=None):
""" Just compute the average sKdT
Parameters
----------
res_dicts : list
dict of running, multiple seed run contains inside
arch_key : str, optional
... | 5,313,080 |
def test_create_bokeh_plot(mocked_run):
"""Ensures that wandb.Bokeh constructor accepts a bokeh plot"""
bp = dummy_data.bokeh_plot()
bp = wandb.data_types.Bokeh(bp)
bp.bind_to_run(mocked_run, "bokeh", 0) | 5,313,081 |
def _write_test_data_files(tempdir):
"""
Write the temporary data files used by the oldtests.
:param str tempdir: path to oldtests' primary temporary directory,
within which temp data files may be placed directly or within
subdirectory/ies.
"""
data_files_subdir = os.path.join(tempd... | 5,313,082 |
def roi_proposal(rpn_cls_prob_reshape, rpn_bbox_pred, H, W, ANCHOR_PER_GRID, ANCHOR_BOX, TOP_N_DETECTION, NMS_THRESH, IM_H, IM_W):
"""
clip the predict results fron rpn output
appply nms
proposal topN results as final layer output, no backward operation need here
"""
box_probs = np.reshape(rpn_c... | 5,313,083 |
def mi_gg(x, y, biascorrect=True, demeaned=False):
"""Mutual information (MI) between two Gaussian variables in bits
I = mi_gg(x,y) returns the MI between two (possibly multidimensional)
Gassian variables, x and y, with bias correction.
If x and/or y are multivariate columns must correspond to sampl... | 5,313,084 |
def dgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info):
"""LAPACK routine (version 3.0)
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
March 31, 1993
Python replacement by K. KISHIMOTO (korry@users.sourceforge.net)
Purpose
=======
dge... | 5,313,085 |
def reverse_path(dict_, root, child_to_parents):
"""
CommandLine:
python -m utool.util_graph --exec-reverse_path --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> child_to_parents = {
>>> 'chip': ['... | 5,313,086 |
def build_lifegame_model(n, **kwargs):
""" build a MIP model for a stable game of life configuration
chessboard is (n+1) x (n+1)
:param n:
:return:
"""
assert n >= 2
assert Model.supports_logical_constraints(), "This model requires logical constraints cplex.version must be 12.80 or higher... | 5,313,087 |
def get_wofs_values(landsat_dataset):
"""classifies a landsat scene using the wofs algorithm
:param landsat_dataset: xarray with dims 'latitude','longitude' containing data from a landsat scene
:return: xarray dataset containing wofs classification values
"""
# landsat dataset needs dim 'time' for w... | 5,313,088 |
def readdirs(DIR):
"""Implementation of perl readdir in list context"""
result = (DIR[0])[DIR[1]:]
DIR[1] = len(DIR[0])
return result | 5,313,089 |
def expandChunk(layout, typesize, shape_json,
chunk_min=CHUNK_MIN, layout_class='H5D_CHUNKED'):
""" Extend the chunk shape until it is above the MIN target.
"""
if shape_json is None or shape_json["class"] == 'H5S_NULL':
return None
if shape_json["class"] == 'H5S_SCALAR':
... | 5,313,090 |
def remove_domestic(images: pd.DataFrame, reset_index: bool = True) -> pd.DataFrame:
"""
Removes images where the identification corresponds to a domestic
species. See wiutils/_domestic for a list of the genera considered
as domestic.
Parameters
----------
images : DataFrame
DataFra... | 5,313,091 |
def compute_cyclepoints(sig, fs, f_range, **find_extrema_kwargs):
"""Compute sample indices of cyclepoints.
Parameters
----------
sig : 1d array
Time series.
fs : float
Sampling rate, in Hz.
f_range : tuple of (float, float)
Frequency range, in Hz, to narrowband filter t... | 5,313,092 |
def behav_data_inverted(df):
"""
Flips the dimensions that need inverting
Faster than using is_inverted_dim
"""
# Apparently groupby with categorical dtype is broken
# See https://github.com/pandas-dev/pandas/issues/22512#issuecomment-422422573
df["class_"] = df["class_"].astype(str)
inv... | 5,313,093 |
def _resample_event_obs(obs, fx, obs_data):
"""
Resample the event observation.
Parameters
----------
obs : datamodel.Observation
The Observation being resampled.
fx : datamodel.EventForecast
The corresponding Forecast.
obs_data : pd.Series
Timeseries data of the eve... | 5,313,094 |
def downloader(inegi_csv,folder):
"""This prorgram reads a csv generated by INEGI's GIS data search, and downloads all files in it to the target folder"""
df=pandas.read_csv(inegi_csv,
na_values=[""],
usecols=["upc", "titulo","formatos","escala","url"])
df=... | 5,313,095 |
def project_raw_gw(
raw_waveforms,
sample_params,
waveform_generator,
ifo,
get_snr=False,
noise_psd=None,
):
"""Project a raw gravitational wave onto an intterferometer
Args:
raw_waveforms: the plus and cross polarizations of a list of GWs
sample_params: dictionary of GW... | 5,313,096 |
def make_subreads_bam_of_zmws2(in_subreads_fn_or_obj, zmws, out_bam_fn, out_fa_fn=None):
"""Make subreads bam of zmws
in_subreads_fn --- subreads.bam or suberadset.xml
# movie2bams --- {movie: bam_file}, e.g., {'movie1': 'path-to-movie1', 'movie2': 'path-to-movie2'}
zmws --- a list of zmws or reads, e.g... | 5,313,097 |
def threshold(weights, delta_size):
""" Sample for threshold minimizing pixel changes. """
return min((abs(added_pixel_count(weights,i) + delta_size), i)
for i in np.linspace(10**-2,10**-7,40))[1] | 5,313,098 |
def davenport_matrix(B = None,
covariance_analysis = False,
**attitude_profile_kwargs):
"""Compute the Davenport matrix for a given attitude profile.
Accepts either an attitude profile matrix or the arguments
for the attitude_profile_matrix() funct... | 5,313,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.