Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Using the snippet: <|code_start|># You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Methods to visualize latent factors in the data sets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def visualize_dataset(dataset_name, output_path, num_animations=5,
num_frames=20, fps=10):
"""Visualizes the data set by saving images to output_path.
For each latent factor, outputs 16 images where only that latent factor is
varied while all others are kept constant.
Args:
dataset_name: String with name of dataset as defined in named_data.py.
output_path: String with path in which to create the visualizations.
num_animations: Integer with number of distinct animations to create.
num_frames: Integer with number of frames in each animation.
fps: Integer with frame rate for the animation.
"""
<|code_end|>
, determine the next line of code. You have imports:
import os
import numpy as np
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.visualize import visualize_util
from six.moves import range
from tensorflow.compat.v1 import gfile
and context (class names, function names, or code) available:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
. Output only the next line. | data = named_data.get_named_ground_truth_data(dataset_name) |
Given snippet: <|code_start|>
def visualize_dataset(dataset_name, output_path, num_animations=5,
num_frames=20, fps=10):
"""Visualizes the data set by saving images to output_path.
For each latent factor, outputs 16 images where only that latent factor is
varied while all others are kept constant.
Args:
dataset_name: String with name of dataset as defined in named_data.py.
output_path: String with path in which to create the visualizations.
num_animations: Integer with number of distinct animations to create.
num_frames: Integer with number of frames in each animation.
fps: Integer with frame rate for the animation.
"""
data = named_data.get_named_ground_truth_data(dataset_name)
random_state = np.random.RandomState(0)
# Create output folder if necessary.
path = os.path.join(output_path, dataset_name)
if not gfile.IsDirectory(path):
gfile.MakeDirs(path)
# Create still images.
for i in range(data.num_factors):
factors = data.sample_factors(16, random_state)
indices = [j for j in range(data.num_factors) if i != j]
factors[:, indices] = factors[0, indices]
images = data.sample_observations_from_factors(factors, random_state)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import numpy as np
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.visualize import visualize_util
from six.moves import range
from tensorflow.compat.v1 import gfile
and context:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
which might include code, classes, or functions. Output only the next line. | visualize_util.grid_save_images( |
Given the code snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for visualize_dataset.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class VisualizeDatasetTest(absltest.TestCase):
def test_visualize(self):
<|code_end|>
, generate the next line using the imports in this file:
from absl.testing import absltest
from disentanglement_lib.visualize import visualize_dataset
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/visualize/visualize_dataset.py
# def visualize_dataset(dataset_name, output_path, num_animations=5,
# num_frames=20, fps=10):
# """Visualizes the data set by saving images to output_path.
#
# For each latent factor, outputs 16 images where only that latent factor is
# varied while all others are kept constant.
#
# Args:
# dataset_name: String with name of dataset as defined in named_data.py.
# output_path: String with path in which to create the visualizations.
# num_animations: Integer with number of distinct animations to create.
# num_frames: Integer with number of frames in each animation.
# fps: Integer with frame rate for the animation.
# """
# data = named_data.get_named_ground_truth_data(dataset_name)
# random_state = np.random.RandomState(0)
#
# # Create output folder if necessary.
# path = os.path.join(output_path, dataset_name)
# if not gfile.IsDirectory(path):
# gfile.MakeDirs(path)
#
# # Create still images.
# for i in range(data.num_factors):
# factors = data.sample_factors(16, random_state)
# indices = [j for j in range(data.num_factors) if i != j]
# factors[:, indices] = factors[0, indices]
# images = data.sample_observations_from_factors(factors, random_state)
# visualize_util.grid_save_images(
# images, os.path.join(path, "variations_of_factor%s.png" % i))
#
# # Create animations.
# for i in range(num_animations):
# base_factor = data.sample_factors(1, random_state)
# images = []
# for j, num_atoms in enumerate(data.factors_num_values):
# factors = np.repeat(base_factor, num_frames, axis=0)
# factors[:, j] = visualize_util.cycle_factor(base_factor[0, j], num_atoms,
# num_frames)
# images.append(data.sample_observations_from_factors(factors,
# random_state))
# visualize_util.save_animation(np.array(images),
# os.path.join(path, "animation%d.gif" % i),
# fps)
. Output only the next line. | visualize_dataset.visualize_dataset("dummy_data", |
Predict the next line for this snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for util.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
class UtilTest(parameterized.TestCase, tf.test.TestCase):
def test_tfdata(self):
<|code_end|>
with the help of current file imports:
from absl.testing import parameterized
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
import numpy as np
import tensorflow.compat.v1 as tf
and context from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
, which may contain function names, class names, or code. Output only the next line. | ground_truth_data = dummy_data.DummyData() |
Using the snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for util.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
class UtilTest(parameterized.TestCase, tf.test.TestCase):
def test_tfdata(self):
ground_truth_data = dummy_data.DummyData()
<|code_end|>
, determine the next line of code. You have imports:
from absl.testing import parameterized
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
import numpy as np
import tensorflow.compat.v1 as tf
and context (class names, function names, or code) available:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
. Output only the next line. | dataset = util.tf_data_set_from_ground_truth_data(ground_truth_data, 0) |
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for results.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
@gin.configurable("test")
def test_fn(value=gin.REQUIRED):
return value
class ResultsTest(tf.test.TestCase):
def test_namespaced_dict(self):
"""Tests namespacing functionality."""
base_dict = {"!": "!!"}
numbers = {"1": "one"}
chars = {"a": "A"}
<|code_end|>
. Use current file imports:
import os
import tensorflow.compat.v1 as tf
import gin.tf
from disentanglement_lib.utils import results
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
. Output only the next line. | new_dict = results.namespaced_dict(base_dict, numbers=numbers, chars=chars) |
Using the snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for unified_scores.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
def _identity_discretizer(target, num_bins):
del num_bins
return target
class UnifiedScoreTest(absltest.TestCase):
def test_metric_mig(self):
gin.bind_parameter("discretizer.discretizer_fn", _identity_discretizer)
gin.bind_parameter("discretizer.num_bins", 10)
<|code_end|>
, determine the next line of code. You have imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import unified_scores
import numpy as np
import gin.tf
and context (class names, function names, or code) available:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/unified_scores.py
# def unified_scores(mus_train, ys_train, mus_test, ys_test, matrix_fns,
# artifact_dir=None, factor_names=None):
# """Computes unified scores."""
#
# scores = {}
# kws = {}
# for matrix_fn in matrix_fns:
# # Matrix should have shape [num_codes, num_factors].
# matrix = matrix_fn(mus_train, ys_train, mus_test, ys_test)
# matrix_name = matrix_fn.__name__
# if artifact_dir is not None:
# visualize_scores.heat_square(matrix.copy(), artifact_dir, matrix_name,
# "Latent codes", "Factors of Variation",
# factor_names=factor_names)
# visualize_scores.plot_recovery_vs_independent(matrix.copy().T,
# artifact_dir,
# matrix_name+"_pr")
# merge_points = dendrogram.dendrogram_plot(matrix.copy().T, os.path.join(
# artifact_dir, matrix_name+"_dendrogram"), factor_names)
# kws[matrix_name] = merge_points
# results_dict = pr_curves_values(matrix)
# if matrix_name in kws:
# kws[matrix_name].update(results_dict)
# else:
# kws[matrix_name] = results_dict
# for aggregation_fn in AGGREGATION_FN:
# results_dict = aggregation_fn(matrix, ys_train)
# kws[matrix_name].update(results_dict)
# scores = results.namespaced_dict(scores, **kws)
# return scores
. Output only the next line. | ground_truth_data = dummy_data.IdentityObservationsData() |
Given the following code snippet before the placeholder: <|code_start|># Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for unified_scores.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
def _identity_discretizer(target, num_bins):
del num_bins
return target
class UnifiedScoreTest(absltest.TestCase):
def test_metric_mig(self):
gin.bind_parameter("discretizer.discretizer_fn", _identity_discretizer)
gin.bind_parameter("discretizer.num_bins", 10)
ground_truth_data = dummy_data.IdentityObservationsData()
representation_function = lambda x: np.array(x, dtype=np.float64)
random_state = np.random.RandomState(0)
<|code_end|>
, predict the next line using imports from the current file:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import unified_scores
import numpy as np
import gin.tf
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/unified_scores.py
# def unified_scores(mus_train, ys_train, mus_test, ys_test, matrix_fns,
# artifact_dir=None, factor_names=None):
# """Computes unified scores."""
#
# scores = {}
# kws = {}
# for matrix_fn in matrix_fns:
# # Matrix should have shape [num_codes, num_factors].
# matrix = matrix_fn(mus_train, ys_train, mus_test, ys_test)
# matrix_name = matrix_fn.__name__
# if artifact_dir is not None:
# visualize_scores.heat_square(matrix.copy(), artifact_dir, matrix_name,
# "Latent codes", "Factors of Variation",
# factor_names=factor_names)
# visualize_scores.plot_recovery_vs_independent(matrix.copy().T,
# artifact_dir,
# matrix_name+"_pr")
# merge_points = dendrogram.dendrogram_plot(matrix.copy().T, os.path.join(
# artifact_dir, matrix_name+"_dendrogram"), factor_names)
# kws[matrix_name] = merge_points
# results_dict = pr_curves_values(matrix)
# if matrix_name in kws:
# kws[matrix_name].update(results_dict)
# else:
# kws[matrix_name] = results_dict
# for aggregation_fn in AGGREGATION_FN:
# results_dict = aggregation_fn(matrix, ys_train)
# kws[matrix_name].update(results_dict)
# scores = results.namespaced_dict(scores, **kws)
# return scores
. Output only the next line. | scores = unified_scores.compute_unified_scores( |
Based on the snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for sap_score.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class SapScoreTest(absltest.TestCase):
def test_metric(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import sap_score
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/sap_score.py
# def compute_sap(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16,
# continuous_factors=gin.REQUIRED):
# def _compute_sap(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_sap_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED,
# continuous_factors=gin.REQUIRED,
# batch_size=100):
# def compute_score_matrix(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_avg_diff_top_two(matrix):
. Output only the next line. | ground_truth_data = dummy_data.IdentityObservationsData() |
Using the snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for sap_score.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class SapScoreTest(absltest.TestCase):
def test_metric(self):
ground_truth_data = dummy_data.IdentityObservationsData()
representation_function = lambda x: np.array(x, dtype=np.float64)
random_state = np.random.RandomState(0)
<|code_end|>
, determine the next line of code. You have imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import sap_score
import numpy as np
and context (class names, function names, or code) available:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/sap_score.py
# def compute_sap(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16,
# continuous_factors=gin.REQUIRED):
# def _compute_sap(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_sap_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED,
# continuous_factors=gin.REQUIRED,
# batch_size=100):
# def compute_score_matrix(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_avg_diff_top_two(matrix):
. Output only the next line. | scores = sap_score.compute_sap( |
Predict the next line for this snippet: <|code_start|> "loss": loss,
"reconstruction_loss": reconstruction_loss,
"elbo": -elbo
},
every_n_iter=100)
return contrib_tpu.TPUEstimatorSpec(
mode=mode,
loss=loss,
train_op=train_op,
training_hooks=[logging_hook])
elif mode == tf.estimator.ModeKeys.EVAL:
return contrib_tpu.TPUEstimatorSpec(
mode=mode,
loss=loss,
eval_metrics=(make_metric_fn("reconstruction_loss", "elbo",
"regularizer", "kl_loss"),
[reconstruction_loss, -elbo, regularizer, kl_loss]))
else:
raise NotImplementedError("Eval mode not supported.")
def gaussian_encoder(self, input_tensor, is_training):
"""Applies the Gaussian encoder to images.
Args:
input_tensor: Tensor with the observations to be encoded.
is_training: Boolean indicating whether in training mode.
Returns:
Tuple of tensors with the mean and log variance of the Gaussian encoder.
"""
<|code_end|>
with the help of current file imports:
import math
import tensorflow.compat.v1 as tf
import gin.tf
from disentanglement_lib.methods.shared import architectures # pylint: disable=unused-import
from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import gaussian_encoder_model
from six.moves import range
from six.moves import zip
from tensorflow.contrib import tpu as contrib_tpu
and context from other files:
# Path: disentanglement_lib/methods/shared/architectures.py
# def make_gaussian_encoder(input_tensor,
# is_training=True,
# num_latent=gin.REQUIRED,
# encoder_fn=gin.REQUIRED):
# def make_decoder(latent_tensor,
# output_shape,
# is_training=True,
# decoder_fn=gin.REQUIRED):
# def make_discriminator(input_tensor,
# is_training=False,
# discriminator_fn=gin.REQUIRED):
# def fc_encoder(input_tensor, num_latent, is_training=True):
# def conv_encoder(input_tensor, num_latent, is_training=True):
# def fc_decoder(latent_tensor, output_shape, is_training=True):
# def deconv_decoder(latent_tensor, output_shape, is_training=True):
# def fc_discriminator(input_tensor, is_training=True):
# def test_encoder(input_tensor, num_latent, is_training):
# def test_decoder(latent_tensor, output_shape, is_training=False):
#
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
, which may contain function names, class names, or code. Output only the next line. | return architectures.make_gaussian_encoder( |
Continue the code snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Library of losses for disentanglement learning.
Implementation of VAE based models for unsupervised learning of disentangled
representations.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
"""Abstract base class of a basic Gaussian encoder model."""
def model_fn(self, features, labels, mode, params):
"""TPUEstimator compatible model function."""
del labels
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
data_shape = features.get_shape().as_list()[1:]
z_mean, z_logvar = self.gaussian_encoder(features, is_training=is_training)
z_sampled = self.sample_from_latent_distribution(z_mean, z_logvar)
reconstructions = self.decode(z_sampled, data_shape, is_training)
<|code_end|>
. Use current file imports:
import math
import tensorflow.compat.v1 as tf
import gin.tf
from disentanglement_lib.methods.shared import architectures # pylint: disable=unused-import
from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import gaussian_encoder_model
from six.moves import range
from six.moves import zip
from tensorflow.contrib import tpu as contrib_tpu
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/methods/shared/architectures.py
# def make_gaussian_encoder(input_tensor,
# is_training=True,
# num_latent=gin.REQUIRED,
# encoder_fn=gin.REQUIRED):
# def make_decoder(latent_tensor,
# output_shape,
# is_training=True,
# decoder_fn=gin.REQUIRED):
# def make_discriminator(input_tensor,
# is_training=False,
# discriminator_fn=gin.REQUIRED):
# def fc_encoder(input_tensor, num_latent, is_training=True):
# def conv_encoder(input_tensor, num_latent, is_training=True):
# def fc_decoder(latent_tensor, output_shape, is_training=True):
# def deconv_decoder(latent_tensor, output_shape, is_training=True):
# def fc_discriminator(input_tensor, is_training=True):
# def test_encoder(input_tensor, num_latent, is_training):
# def test_decoder(latent_tensor, output_shape, is_training=False):
#
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
. Output only the next line. | per_sample_loss = losses.make_reconstruction_loss(features, reconstructions) |
Given the code snippet: <|code_start|># limitations under the License.
"""Library of losses for disentanglement learning.
Implementation of VAE based models for unsupervised learning of disentangled
representations.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
"""Abstract base class of a basic Gaussian encoder model."""
def model_fn(self, features, labels, mode, params):
"""TPUEstimator compatible model function."""
del labels
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
data_shape = features.get_shape().as_list()[1:]
z_mean, z_logvar = self.gaussian_encoder(features, is_training=is_training)
z_sampled = self.sample_from_latent_distribution(z_mean, z_logvar)
reconstructions = self.decode(z_sampled, data_shape, is_training)
per_sample_loss = losses.make_reconstruction_loss(features, reconstructions)
reconstruction_loss = tf.reduce_mean(per_sample_loss)
kl_loss = compute_gaussian_kl(z_mean, z_logvar)
regularizer = self.regularizer(kl_loss, z_mean, z_logvar, z_sampled)
loss = tf.add(reconstruction_loss, regularizer, name="loss")
elbo = tf.add(reconstruction_loss, kl_loss, name="elbo")
if mode == tf.estimator.ModeKeys.TRAIN:
<|code_end|>
, generate the next line using the imports in this file:
import math
import tensorflow.compat.v1 as tf
import gin.tf
from disentanglement_lib.methods.shared import architectures # pylint: disable=unused-import
from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import gaussian_encoder_model
from six.moves import range
from six.moves import zip
from tensorflow.contrib import tpu as contrib_tpu
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/methods/shared/architectures.py
# def make_gaussian_encoder(input_tensor,
# is_training=True,
# num_latent=gin.REQUIRED,
# encoder_fn=gin.REQUIRED):
# def make_decoder(latent_tensor,
# output_shape,
# is_training=True,
# decoder_fn=gin.REQUIRED):
# def make_discriminator(input_tensor,
# is_training=False,
# discriminator_fn=gin.REQUIRED):
# def fc_encoder(input_tensor, num_latent, is_training=True):
# def conv_encoder(input_tensor, num_latent, is_training=True):
# def fc_decoder(latent_tensor, output_shape, is_training=True):
# def deconv_decoder(latent_tensor, output_shape, is_training=True):
# def fc_discriminator(input_tensor, is_training=True):
# def test_encoder(input_tensor, num_latent, is_training):
# def test_decoder(latent_tensor, output_shape, is_training=False):
#
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
. Output only the next line. | optimizer = optimizers.make_vae_optimizer() |
Predict the next line after this snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Library of losses for disentanglement learning.
Implementation of VAE based models for unsupervised learning of disentangled
representations.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
using the current file's imports:
import math
import tensorflow.compat.v1 as tf
import gin.tf
from disentanglement_lib.methods.shared import architectures # pylint: disable=unused-import
from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import gaussian_encoder_model
from six.moves import range
from six.moves import zip
from tensorflow.contrib import tpu as contrib_tpu
and any relevant context from other files:
# Path: disentanglement_lib/methods/shared/architectures.py
# def make_gaussian_encoder(input_tensor,
# is_training=True,
# num_latent=gin.REQUIRED,
# encoder_fn=gin.REQUIRED):
# def make_decoder(latent_tensor,
# output_shape,
# is_training=True,
# decoder_fn=gin.REQUIRED):
# def make_discriminator(input_tensor,
# is_training=False,
# discriminator_fn=gin.REQUIRED):
# def fc_encoder(input_tensor, num_latent, is_training=True):
# def conv_encoder(input_tensor, num_latent, is_training=True):
# def fc_decoder(latent_tensor, output_shape, is_training=True):
# def deconv_decoder(latent_tensor, output_shape, is_training=True):
# def fc_discriminator(input_tensor, is_training=True):
# def test_encoder(input_tensor, num_latent, is_training):
# def test_decoder(latent_tensor, output_shape, is_training=False):
#
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
. Output only the next line. | class BaseVAE(gaussian_encoder_model.GaussianEncoderModel): |
Based on the snippet: <|code_start|> else:
elt = self.f(self.buf)
if isinstance(elt, t):
return elt
else:
return t._make(elt)
def build_reducer(reducer):
if hasattr(reducer, "begin_group"):
return reducer
else:
return Reducer(reducer)
def group(stream, key, reducer,
assume_sorted=False, typename=None, fields=None):
"""
GroupBy all values for a key.
If reducer is a function, function(t, key, row_group) is called with an array of all rows matching the key value
t is the expected return type
key is the common key for the group.
Otherwise can be a 'Reducer' object.
reducer.begin_group(key) will be called at the beginning of each grou
reducer.row(row) is called on each row
reducer.end_group(t) will be called at the end of each group
and should return the resulting row or a list of rows of type t
"""
reducer = build_reducer(reducer)
if not assume_sorted:
<|code_end|>
, predict the immediate next line with the help of imports:
from base import StreamHeader, BabeBase, StreamFooter
from pybabe.sort import sort
and context (classes, functions, sometimes code) from other files:
# Path: pybabe/sort.py
# def sort(stream, field, reverse=False):
# buf = []
# for elt in stream:
# if isinstance(elt, StreamHeader):
# yield elt
# elif isinstance(elt, StreamFooter):
# buf.sort(key=lambda obj: getattr(obj, field), reverse=reverse)
# for row in buf:
# yield row
# yield elt
# else:
# buf.append(elt)
. Output only the next line. | stream = sort(stream, key) |
Using the snippet: <|code_start|># Copyright 2016-2019 Douglas G. Moore. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestBlockEntropy(unittest.TestCase):
def test_block_entropy_empty(self):
with self.assertRaises(ValueError):
block_entropy([], 1)
def test_block_entropy_dimensions(self):
with self.assertRaises(ValueError):
block_entropy([[[1]]], 1)
def test_block_entropy_short_series(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from pyinform.error import InformError
from pyinform.blockentropy import block_entropy
and context (class names, function names, or code) available:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/blockentropy.py
# def block_entropy(series, k, local=False):
# """
# Compute the (local) block entropy of a time series with block size *k*.
#
# :param series: the time series
# :type series: sequence or `numpy.ndarray`
# :param int k: the block size
# :param bool local: compute the local block entropy
# :returns: the average or local block entropy
# :rtype: float or `numpy.ndarray`
# :raises ValueError: if the time series has no initial conditions
# :raises ValueError: if the time series is greater than 2-D
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# xs = np.ascontiguousarray(series, np.int32)
#
# if xs.ndim == 0:
# raise ValueError("empty timeseries")
# elif xs.ndim > 2:
# raise ValueError("dimension greater than 2")
#
# b = max(2, np.amax(xs) + 1)
#
# data = xs.ctypes.data_as(POINTER(c_int))
# if xs.ndim == 1:
# n, m = 1, xs.shape[0]
# else:
# n, m = xs.shape
#
# e = ErrorCode(0)
#
# if local is True:
# q = max(0, m - k + 1)
# ai = np.empty((n, q), dtype=np.float64)
# out = ai.ctypes.data_as(POINTER(c_double))
# _local_block_entropy(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), out, byref(e))
# else:
# ai = _block_entropy(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), byref(e))
#
# error_guard(e)
#
# return ai
. Output only the next line. | with self.assertRaises(InformError): |
Given the code snippet: <|code_start|># Copyright 2016-2019 Douglas G. Moore. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestBlockEntropy(unittest.TestCase):
def test_block_entropy_empty(self):
with self.assertRaises(ValueError):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from pyinform.error import InformError
from pyinform.blockentropy import block_entropy
and context (functions, classes, or occasionally code) from other files:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/blockentropy.py
# def block_entropy(series, k, local=False):
# """
# Compute the (local) block entropy of a time series with block size *k*.
#
# :param series: the time series
# :type series: sequence or `numpy.ndarray`
# :param int k: the block size
# :param bool local: compute the local block entropy
# :returns: the average or local block entropy
# :rtype: float or `numpy.ndarray`
# :raises ValueError: if the time series has no initial conditions
# :raises ValueError: if the time series is greater than 2-D
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# xs = np.ascontiguousarray(series, np.int32)
#
# if xs.ndim == 0:
# raise ValueError("empty timeseries")
# elif xs.ndim > 2:
# raise ValueError("dimension greater than 2")
#
# b = max(2, np.amax(xs) + 1)
#
# data = xs.ctypes.data_as(POINTER(c_int))
# if xs.ndim == 1:
# n, m = 1, xs.shape[0]
# else:
# n, m = xs.shape
#
# e = ErrorCode(0)
#
# if local is True:
# q = max(0, m - k + 1)
# ai = np.empty((n, q), dtype=np.float64)
# out = ai.ctypes.data_as(POINTER(c_double))
# _local_block_entropy(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), out, byref(e))
# else:
# ai = _block_entropy(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), byref(e))
#
# error_guard(e)
#
# return ai
. Output only the next line. | block_entropy([], 1) |
Given the code snippet: <|code_start|># license that can be found in the LICENSE file.
class TestConditionalEntropy(unittest.TestCase):
def test_conditional_entropy_empty(self):
with self.assertRaises(ValueError):
conditional_entropy([], [])
with self.assertRaises(ValueError):
conditional_entropy([1, 2, 3], [])
with self.assertRaises(ValueError):
conditional_entropy([], [1, 2, 3])
def test_conditional_entropy_dimensions(self):
with self.assertRaises(ValueError):
conditional_entropy([[1]], [1])
with self.assertRaises(ValueError):
conditional_entropy([1], [[1]])
def test_conditional_entropy_size(self):
with self.assertRaises(ValueError):
conditional_entropy([1, 2, 3], [1, 2])
with self.assertRaises(ValueError):
conditional_entropy([1, 2], [1, 2, 3])
def test_conditional_entropy_negative_states(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import numpy as np
from pyinform.error import InformError
from pyinform.conditionalentropy import conditional_entropy
and context (functions, classes, or occasionally code) from other files:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/conditionalentropy.py
# def conditional_entropy(xs, ys, local=False):
# """
# Compute the (local) conditional entropy between two time series.
#
# This function expects the **condition** to be the first argument.
#
# :param xs: the time series drawn from the conditional distribution
# :type xs: a sequence or ``numpy.ndarray``
# :param ys: the time series drawn from the target distribution
# :type ys: a sequence or ``numpy.ndarray``
# :param bool local: compute the local conditional entropy
# :return: the local or average conditional entropy
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series have different shapes
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# us = np.ascontiguousarray(xs, dtype=np.int32)
# vs = np.ascontiguousarray(ys, dtype=np.int32)
# if us.shape != vs.shape:
# raise ValueError("timeseries lengths do not match")
#
# bx = max(2, np.amax(us) + 1)
# by = max(2, np.amax(vs) + 1)
#
# xdata = us.ctypes.data_as(POINTER(c_int))
# ydata = vs.ctypes.data_as(POINTER(c_int))
# n = us.size
#
# e = ErrorCode(0)
#
# if local is True:
# ce = np.empty(us.shape, dtype=np.float64)
# out = ce.ctypes.data_as(POINTER(c_double))
# _local_conditional_entropy(xdata, ydata, c_ulong(n), c_int(bx), c_int(by), out, byref(e))
# else:
# ce = _conditional_entropy(xdata, ydata, c_ulong(n), c_int(bx), c_int(by), byref(e))
#
# error_guard(e)
#
# return ce
. Output only the next line. | with self.assertRaises(InformError): |
Using the snippet: <|code_start|># Copyright 2016-2019 Douglas G. Moore. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestConditionalEntropy(unittest.TestCase):
def test_conditional_entropy_empty(self):
with self.assertRaises(ValueError):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import numpy as np
from pyinform.error import InformError
from pyinform.conditionalentropy import conditional_entropy
and context (class names, function names, or code) available:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/conditionalentropy.py
# def conditional_entropy(xs, ys, local=False):
# """
# Compute the (local) conditional entropy between two time series.
#
# This function expects the **condition** to be the first argument.
#
# :param xs: the time series drawn from the conditional distribution
# :type xs: a sequence or ``numpy.ndarray``
# :param ys: the time series drawn from the target distribution
# :type ys: a sequence or ``numpy.ndarray``
# :param bool local: compute the local conditional entropy
# :return: the local or average conditional entropy
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series have different shapes
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# us = np.ascontiguousarray(xs, dtype=np.int32)
# vs = np.ascontiguousarray(ys, dtype=np.int32)
# if us.shape != vs.shape:
# raise ValueError("timeseries lengths do not match")
#
# bx = max(2, np.amax(us) + 1)
# by = max(2, np.amax(vs) + 1)
#
# xdata = us.ctypes.data_as(POINTER(c_int))
# ydata = vs.ctypes.data_as(POINTER(c_int))
# n = us.size
#
# e = ErrorCode(0)
#
# if local is True:
# ce = np.empty(us.shape, dtype=np.float64)
# out = ce.ctypes.data_as(POINTER(c_double))
# _local_conditional_entropy(xdata, ydata, c_ulong(n), c_int(bx), c_int(by), out, byref(e))
# else:
# ce = _conditional_entropy(xdata, ydata, c_ulong(n), c_int(bx), c_int(by), byref(e))
#
# error_guard(e)
#
# return ce
. Output only the next line. | conditional_entropy([], []) |
Based on the snippet: <|code_start|> elif isinf(x) or isinf(y):
self.fail("unequal infinite values")
else:
self.assertAlmostEqual(x, y, places=places)
def test_relative_entropy_empty(self):
with self.assertRaises(ValueError):
relative_entropy([], [])
with self.assertRaises(ValueError):
relative_entropy([1, 2, 3], [])
with self.assertRaises(ValueError):
relative_entropy([], [1, 2, 3])
def test_relative_entropy_dimensions(self):
with self.assertRaises(ValueError):
relative_entropy([[1]], [1])
with self.assertRaises(ValueError):
relative_entropy([1], [[1]])
def test_relative_entropy_size(self):
with self.assertRaises(ValueError):
relative_entropy([1, 2, 3], [1, 2])
with self.assertRaises(ValueError):
relative_entropy([1, 2], [1, 2, 3])
def test_relative_entropy_negative_states(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import numpy as np
from pyinform.error import InformError
from pyinform.relativeentropy import relative_entropy
from math import isnan, isinf
and context (classes, functions, sometimes code) from other files:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/relativeentropy.py
# def relative_entropy(xs, ys, local=False):
# """
# Compute the local or global relative entropy between two time series
# treating each as observations from a distribution.
#
# :param xs: the time series sampled from the posterior distribution
# :type xs: a sequence or ``numpy.ndarray``
# :param ys: the time series sampled from the prior distribution
# :type ys: a sequence or ``numpy.ndarray``
# :param bool local: compute the local relative entropy
# :return: the local or global relative entropy
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series have different shapes
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# us = np.ascontiguousarray(xs, dtype=np.int32)
# vs = np.ascontiguousarray(ys, dtype=np.int32)
# if us.shape != vs.shape:
# raise ValueError("timeseries lengths do not match")
#
# b = max(2, np.amax(us) + 1, np.amax(vs) + 1)
#
# xdata = us.ctypes.data_as(POINTER(c_int))
# ydata = vs.ctypes.data_as(POINTER(c_int))
# n = us.size
#
# e = ErrorCode(0)
#
# if local is True:
# re = np.empty(b, dtype=np.float64)
# out = re.ctypes.data_as(POINTER(c_double))
# _local_relative_entropy(xdata, ydata, c_ulong(n), c_int(b), out, byref(e))
# else:
# re = _relative_entropy(xdata, ydata, c_ulong(n), c_int(b), byref(e))
#
# error_guard(e)
#
# return re
. Output only the next line. | with self.assertRaises(InformError): |
Predict the next line for this snippet: <|code_start|># Copyright 2016-2019 Douglas G. Moore. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestRelativeEntropy(unittest.TestCase):
def assertQuasiEqual(self, x, y, places=7):
if isnan(x) and isnan(y):
return
elif isinf(x) and isinf(y):
return
elif isnan(x) or isnan(y):
self.fail("unequal NaN values")
elif isinf(x) or isinf(y):
self.fail("unequal infinite values")
else:
self.assertAlmostEqual(x, y, places=places)
def test_relative_entropy_empty(self):
with self.assertRaises(ValueError):
<|code_end|>
with the help of current file imports:
import unittest
import numpy as np
from pyinform.error import InformError
from pyinform.relativeentropy import relative_entropy
from math import isnan, isinf
and context from other files:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/relativeentropy.py
# def relative_entropy(xs, ys, local=False):
# """
# Compute the local or global relative entropy between two time series
# treating each as observations from a distribution.
#
# :param xs: the time series sampled from the posterior distribution
# :type xs: a sequence or ``numpy.ndarray``
# :param ys: the time series sampled from the prior distribution
# :type ys: a sequence or ``numpy.ndarray``
# :param bool local: compute the local relative entropy
# :return: the local or global relative entropy
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series have different shapes
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# us = np.ascontiguousarray(xs, dtype=np.int32)
# vs = np.ascontiguousarray(ys, dtype=np.int32)
# if us.shape != vs.shape:
# raise ValueError("timeseries lengths do not match")
#
# b = max(2, np.amax(us) + 1, np.amax(vs) + 1)
#
# xdata = us.ctypes.data_as(POINTER(c_int))
# ydata = vs.ctypes.data_as(POINTER(c_int))
# n = us.size
#
# e = ErrorCode(0)
#
# if local is True:
# re = np.empty(b, dtype=np.float64)
# out = re.ctypes.data_as(POINTER(c_double))
# _local_relative_entropy(xdata, ydata, c_ulong(n), c_int(b), out, byref(e))
# else:
# re = _relative_entropy(xdata, ydata, c_ulong(n), c_int(b), byref(e))
#
# error_guard(e)
#
# return re
, which may contain function names, class names, or code. Output only the next line. | relative_entropy([], []) |
Given snippet: <|code_start|># Copyright 2016-2019 Douglas G. Moore. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestEntropyRate(unittest.TestCase):
def test_entropy_rate_empty(self):
with self.assertRaises(ValueError):
entropy_rate([], 1)
def test_entropy_rate_dimensions(self):
with self.assertRaises(ValueError):
entropy_rate([[[1]]], 1)
def test_entropy_rate_short_series(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from pyinform.error import InformError
from pyinform.entropyrate import entropy_rate
and context:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/entropyrate.py
# def entropy_rate(series, k, local=False):
# """
# Compute the average or local entropy rate of a time series with history
# length *k*.
#
# :param series: the time series
# :type series: sequence or ``numpy.ndarray``
# :param int k: the history length
# :param bool local: compute the local active information
# :returns: the average or local entropy rate
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series has no initial conditions
# :raises ValueError: if the time series is greater than 2-D
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# xs = np.ascontiguousarray(series, np.int32)
#
# if xs.ndim == 0:
# raise ValueError("empty timeseries")
# elif xs.ndim > 2:
# raise ValueError("dimension greater than 2")
#
# b = max(2, np.amax(xs) + 1)
#
# data = xs.ctypes.data_as(POINTER(c_int))
# if xs.ndim == 1:
# n, m = 1, xs.shape[0]
# else:
# n, m = xs.shape
#
# e = ErrorCode(0)
#
# if local is True:
# q = max(0, m - k)
# er = np.empty((n, q), dtype=np.float64)
# out = er.ctypes.data_as(POINTER(c_double))
# _local_entropy_rate(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), out, byref(e))
# else:
# er = _entropy_rate(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), byref(e))
#
# error_guard(e)
#
# return er
which might include code, classes, or functions. Output only the next line. | with self.assertRaises(InformError): |
Next line prediction: <|code_start|># Copyright 2016-2019 Douglas G. Moore. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestEntropyRate(unittest.TestCase):
def test_entropy_rate_empty(self):
with self.assertRaises(ValueError):
<|code_end|>
. Use current file imports:
(import unittest
from pyinform.error import InformError
from pyinform.entropyrate import entropy_rate)
and context including class names, function names, or small code snippets from other files:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/entropyrate.py
# def entropy_rate(series, k, local=False):
# """
# Compute the average or local entropy rate of a time series with history
# length *k*.
#
# :param series: the time series
# :type series: sequence or ``numpy.ndarray``
# :param int k: the history length
# :param bool local: compute the local active information
# :returns: the average or local entropy rate
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series has no initial conditions
# :raises ValueError: if the time series is greater than 2-D
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# xs = np.ascontiguousarray(series, np.int32)
#
# if xs.ndim == 0:
# raise ValueError("empty timeseries")
# elif xs.ndim > 2:
# raise ValueError("dimension greater than 2")
#
# b = max(2, np.amax(xs) + 1)
#
# data = xs.ctypes.data_as(POINTER(c_int))
# if xs.ndim == 1:
# n, m = 1, xs.shape[0]
# else:
# n, m = xs.shape
#
# e = ErrorCode(0)
#
# if local is True:
# q = max(0, m - k)
# er = np.empty((n, q), dtype=np.float64)
# out = er.ctypes.data_as(POINTER(c_double))
# _local_entropy_rate(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), out, byref(e))
# else:
# er = _entropy_rate(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), byref(e))
#
# error_guard(e)
#
# return er
. Output only the next line. | entropy_rate([], 1) |
Using the snippet: <|code_start|># Copyright 2016-2019 Douglas G. Moore. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestActiveInfo(unittest.TestCase):
def test_active_info_empty(self):
with self.assertRaises(ValueError):
active_info([], 1)
def test_active_info_dimensions(self):
with self.assertRaises(ValueError):
active_info([[[1]]], 1)
def test_active_info_short_series(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from pyinform.error import InformError
from pyinform.activeinfo import active_info
and context (class names, function names, or code) available:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/activeinfo.py
# def active_info(series, k, local=False):
# """
# Compute the average or local active information of a timeseries with history
# length *k*.
#
# :param series: the time series
# :type series: sequence or ``numpy.ndarray``
# :param int k: the history length
# :param bool local: compute the local active information
# :returns: the average or local active information
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series has no initial conditions
# :raises ValueError: if the time series is greater than 2-D
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# xs = np.ascontiguousarray(series, np.int32)
#
# if xs.ndim == 0:
# raise ValueError("empty timeseries")
# elif xs.ndim > 2:
# raise ValueError("dimension greater than 2")
#
# b = max(2, np.amax(xs) + 1)
#
# data = xs.ctypes.data_as(POINTER(c_int))
# if xs.ndim == 1:
# n, m = 1, xs.shape[0]
# else:
# n, m = xs.shape
#
# e = ErrorCode(0)
#
# if local is True:
# q = max(0, m - k)
# ai = np.empty((n, q), dtype=np.float64)
# out = ai.ctypes.data_as(POINTER(c_double))
# _local_active_info(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), out, byref(e))
# else:
# ai = _active_info(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), byref(e))
#
# error_guard(e)
#
# return ai
. Output only the next line. | with self.assertRaises(InformError): |
Here is a snippet: <|code_start|># Copyright 2016-2019 Douglas G. Moore. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestActiveInfo(unittest.TestCase):
def test_active_info_empty(self):
with self.assertRaises(ValueError):
<|code_end|>
. Write the next line using the current file imports:
import unittest
from pyinform.error import InformError
from pyinform.activeinfo import active_info
and context from other files:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/activeinfo.py
# def active_info(series, k, local=False):
# """
# Compute the average or local active information of a timeseries with history
# length *k*.
#
# :param series: the time series
# :type series: sequence or ``numpy.ndarray``
# :param int k: the history length
# :param bool local: compute the local active information
# :returns: the average or local active information
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series has no initial conditions
# :raises ValueError: if the time series is greater than 2-D
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# xs = np.ascontiguousarray(series, np.int32)
#
# if xs.ndim == 0:
# raise ValueError("empty timeseries")
# elif xs.ndim > 2:
# raise ValueError("dimension greater than 2")
#
# b = max(2, np.amax(xs) + 1)
#
# data = xs.ctypes.data_as(POINTER(c_int))
# if xs.ndim == 1:
# n, m = 1, xs.shape[0]
# else:
# n, m = xs.shape
#
# e = ErrorCode(0)
#
# if local is True:
# q = max(0, m - k)
# ai = np.empty((n, q), dtype=np.float64)
# out = ai.ctypes.data_as(POINTER(c_double))
# _local_active_info(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), out, byref(e))
# else:
# ai = _active_info(data, c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), byref(e))
#
# error_guard(e)
#
# return ai
, which may include functions, classes, or code. Output only the next line. | active_info([], 1) |
Given snippet: <|code_start|># Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestMutualInfo(unittest.TestCase):
def test_mutual_info_empty(self):
with self.assertRaises(ValueError):
mutual_info([], [])
with self.assertRaises(ValueError):
mutual_info([1, 2, 3], [])
with self.assertRaises(ValueError):
mutual_info([], [1, 2, 3])
def test_mutual_info_dimensions(self):
with self.assertRaises(ValueError):
mutual_info([[1]], [1])
with self.assertRaises(ValueError):
mutual_info([1], [[1]])
def test_mutual_info_size(self):
with self.assertRaises(ValueError):
mutual_info([1, 2, 3], [1, 2])
with self.assertRaises(ValueError):
mutual_info([1, 2], [1, 2, 3])
def test_mutual_info_negative_states(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import numpy as np
from pyinform.error import InformError
from pyinform.mutualinfo import mutual_info
and context:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/mutualinfo.py
# def mutual_info(xs, ys, local=False):
# """
# Compute the (local) mutual information between two time series.
#
# This function explicitly takes the logarithmic base *b* as an argument.
#
# :param xs: a time series
# :type xs: a sequence or ``numpy.ndarray``
# :param ys: a time series
# :type ys: a sequence or ``numpy.ndarray``
# :param bool local: compute the local mutual information
# :return: the local or average mutual information
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series have different shapes
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# us = np.ascontiguousarray(xs, dtype=np.int32)
# vs = np.ascontiguousarray(ys, dtype=np.int32)
# if us.shape != vs.shape:
# raise ValueError("timeseries lengths do not match")
#
# series = np.ascontiguousarray([us.flatten(), vs.flatten()], dtype=np.int32)
#
# bx = max(2, np.amax(us) + 1)
# by = max(2, np.amax(vs) + 1)
#
# bs = np.ascontiguousarray([bx, by], dtype=np.int32)
#
# seriesdata = series.ctypes.data_as(POINTER(c_int))
# bsdata = bs.ctypes.data_as(POINTER(c_int))
# l, n = series.shape
#
# e = ErrorCode(0)
#
# if local is True:
# mi = np.empty(us.shape, dtype=np.float64)
# out = mi.ctypes.data_as(POINTER(c_double))
# _local_mutual_info(seriesdata, c_ulong(l), c_ulong(n), bsdata, out, byref(e))
# else:
# mi = _mutual_info(seriesdata, c_ulong(l), c_ulong(n), bsdata, byref(e))
#
# error_guard(e)
#
# return mi
which might include code, classes, or functions. Output only the next line. | with self.assertRaises(InformError): |
Here is a snippet: <|code_start|># Copyright 2016-2019 Douglas G. Moore. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestMutualInfo(unittest.TestCase):
def test_mutual_info_empty(self):
with self.assertRaises(ValueError):
<|code_end|>
. Write the next line using the current file imports:
import unittest
import numpy as np
from pyinform.error import InformError
from pyinform.mutualinfo import mutual_info
and context from other files:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/mutualinfo.py
# def mutual_info(xs, ys, local=False):
# """
# Compute the (local) mutual information between two time series.
#
# This function explicitly takes the logarithmic base *b* as an argument.
#
# :param xs: a time series
# :type xs: a sequence or ``numpy.ndarray``
# :param ys: a time series
# :type ys: a sequence or ``numpy.ndarray``
# :param bool local: compute the local mutual information
# :return: the local or average mutual information
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series have different shapes
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# us = np.ascontiguousarray(xs, dtype=np.int32)
# vs = np.ascontiguousarray(ys, dtype=np.int32)
# if us.shape != vs.shape:
# raise ValueError("timeseries lengths do not match")
#
# series = np.ascontiguousarray([us.flatten(), vs.flatten()], dtype=np.int32)
#
# bx = max(2, np.amax(us) + 1)
# by = max(2, np.amax(vs) + 1)
#
# bs = np.ascontiguousarray([bx, by], dtype=np.int32)
#
# seriesdata = series.ctypes.data_as(POINTER(c_int))
# bsdata = bs.ctypes.data_as(POINTER(c_int))
# l, n = series.shape
#
# e = ErrorCode(0)
#
# if local is True:
# mi = np.empty(us.shape, dtype=np.float64)
# out = mi.ctypes.data_as(POINTER(c_double))
# _local_mutual_info(seriesdata, c_ulong(l), c_ulong(n), bsdata, out, byref(e))
# else:
# mi = _mutual_info(seriesdata, c_ulong(l), c_ulong(n), bsdata, byref(e))
#
# error_guard(e)
#
# return mi
, which may include functions, classes, or code. Output only the next line. | mutual_info([], []) |
Given snippet: <|code_start|># Copyright 2016-2019 Douglas G. Moore. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
class TestTransferEntropy(unittest.TestCase):
def test_transfer_entropy_empty(self):
with self.assertRaises(ValueError):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import numpy as np
from pyinform.error import InformError
from pyinform.transferentropy import transfer_entropy
and context:
# Path: pyinform/error.py
# class InformError(Exception):
# """
# InformError signifies an error occurred in a call to inform.
# """
#
# def __init__(self, e=-1, func=None):
# msg = error_string(e)
#
# if func is None:
# msg = "an inform error occurred - \"{}\"".format(msg)
# else:
# msg = "an inform error occurred in `{}` - \"{}\"".format(func, msg)
#
# super(InformError, self).__init__(msg)
#
# self.error_code = e if isinstance(e, ErrorCode) else ErrorCode(e)
#
# Path: pyinform/transferentropy.py
# def transfer_entropy(source, target, k, condition=None, local=False):
# """
# Compute the local or average transfer entropy from one time series to
# another with target history length *k*. Optionally, time series can be
# provided against which to *condition*.
#
# :param source: the source time series
# :type source: sequence or ``numpy.ndarray``
# :param target: the target time series
# :type target: sequence or ``numpy.ndarray``
# :param int k: the history length
# :param condition: time series of any conditions
# :type condition: sequence or ``numpy.ndarray``
# :param bool local: compute the local transfer entropy
# :returns: the average or local transfer entropy
# :rtype: float or ``numpy.ndarray``
# :raises ValueError: if the time series have different shapes
# :raises ValueError: if either time series has no initial conditions
# :raises ValueError: if either time series is greater than 2-D
# :raises InformError: if an error occurs within the ``inform`` C call
# """
# ys = np.ascontiguousarray(source, np.int32)
# xs = np.ascontiguousarray(target, np.int32)
# cs = np.ascontiguousarray(condition, np.int32) if condition is not None else None
#
# if xs.shape != ys.shape:
# raise ValueError("source and target timeseries are different shapes")
# elif xs.ndim > 2:
# raise ValueError("source and target have too great a dimension; must be 2 or less")
#
# if cs is None:
# pass
# elif cs.ndim == 1 and cs.shape != xs.shape:
# raise ValueError("condition has a shape that's inconsistent with the source and target")
# elif cs.ndim == 2 and xs.ndim == 1 and cs.shape[1:] != xs.shape:
# raise ValueError("condition has a shape that's inconsistent with the source and target")
# elif cs.ndim == 2 and xs.ndim == 2 and cs.shape != xs.shape:
# raise ValueError("condition has a shape that's inconsistent with the source and target")
# elif cs.ndim == 3 and cs.shape[1:] != xs.shape:
# raise ValueError("condition has a shape that's inconsistent with the source and target")
# elif cs.ndim > 3:
# raise ValueError("condition has too great a dimension; must be 3 or less")
#
# ydata = ys.ctypes.data_as(POINTER(c_int))
# xdata = xs.ctypes.data_as(POINTER(c_int))
# cdata = cs.ctypes.data_as(POINTER(c_int)) if cs is not None else None
#
# if cs is None:
# b = max(2, max(np.amax(xs), np.amax(ys)) + 1)
# else:
# b = max(2, max(np.amax(xs), np.amax(ys), np.amax(cs)) + 1)
#
# if cs is None:
# z = 0
# elif cs.ndim == 1 or (cs.ndim == 2 and xs.ndim == 2):
# z = 1
# elif cs.ndim == 3 or (cs.ndim == 2 and xs.ndim == 1):
# z = cs.shape[0]
# else:
# raise RuntimeError("unexpected state: condition and source are inconsistent shapes")
#
# if xs.ndim == 1:
# n, m = 1, xs.shape[0]
# else:
# n, m = xs.shape
#
# e = ErrorCode(0)
#
# if local is True:
# q = max(0, m - k)
# te = np.empty((n, q), dtype=np.float64)
# out = te.ctypes.data_as(POINTER(c_double))
# _local_transfer_entropy(ydata, xdata, cdata, c_ulong(z), c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), out, byref(e))
# else:
# te = _transfer_entropy(ydata, xdata, cdata, c_ulong(z), c_ulong(n), c_ulong(m), c_int(b), c_ulong(k), byref(e))
#
# error_guard(e)
#
# return te
which might include code, classes, or functions. Output only the next line. | transfer_entropy([], [], 1) |
Predict the next line after this snippet: <|code_start|>
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
'processor': get_cpu_info(),
'ip_address': get_ip_address(),
'distro': get_distro(),
}
return system_info_dict
def system(self):
system_data_dict = {
'memory': get_memory_info(),
'cpu': get_cpu_utilization(),
'disk': disk_check.check(),
'network': get_network_traffic(),
'loadavg': get_load_average(),
'uptime': get_uptime(),
}
return system_data_dict
def processes(self):
<|code_end|>
using the current file's imports:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and any relevant context from other files:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
. Output only the next line. | return processes_data_collector.collect() |
Based on the snippet: <|code_start|>
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
'processor': get_cpu_info(),
'ip_address': get_ip_address(),
'distro': get_distro(),
}
return system_info_dict
def system(self):
system_data_dict = {
'memory': get_memory_info(),
'cpu': get_cpu_utilization(),
'disk': disk_check.check(),
'network': get_network_traffic(),
'loadavg': get_load_average(),
<|code_end|>
, predict the immediate next line with the help of imports:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and context (classes, functions, sometimes code) from other files:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
. Output only the next line. | 'uptime': get_uptime(), |
Given snippet: <|code_start|>
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
'processor': get_cpu_info(),
'ip_address': get_ip_address(),
'distro': get_distro(),
}
return system_info_dict
def system(self):
system_data_dict = {
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and context:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
which might include code, classes, or functions. Output only the next line. | 'memory': get_memory_info(), |
Based on the snippet: <|code_start|>
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
'processor': get_cpu_info(),
'ip_address': get_ip_address(),
'distro': get_distro(),
}
return system_info_dict
def system(self):
system_data_dict = {
'memory': get_memory_info(),
<|code_end|>
, predict the immediate next line with the help of imports:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and context (classes, functions, sometimes code) from other files:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
. Output only the next line. | 'cpu': get_cpu_utilization(), |
Using the snippet: <|code_start|>
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
'processor': get_cpu_info(),
'ip_address': get_ip_address(),
'distro': get_distro(),
}
return system_info_dict
def system(self):
system_data_dict = {
'memory': get_memory_info(),
'cpu': get_cpu_utilization(),
'disk': disk_check.check(),
'network': get_network_traffic(),
<|code_end|>
, determine the next line of code. You have imports:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and context (class names, function names, or code) available:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
. Output only the next line. | 'loadavg': get_load_average(), |
Given the code snippet: <|code_start|>
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
'processor': get_cpu_info(),
'ip_address': get_ip_address(),
'distro': get_distro(),
}
return system_info_dict
def system(self):
system_data_dict = {
'memory': get_memory_info(),
'cpu': get_cpu_utilization(),
<|code_end|>
, generate the next line using the imports in this file:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and context (functions, classes, or occasionally code) from other files:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
. Output only the next line. | 'disk': disk_check.check(), |
Given the code snippet: <|code_start|>
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
'processor': get_cpu_info(),
'ip_address': get_ip_address(),
'distro': get_distro(),
}
return system_info_dict
def system(self):
system_data_dict = {
'memory': get_memory_info(),
'cpu': get_cpu_utilization(),
'disk': disk_check.check(),
<|code_end|>
, generate the next line using the imports in this file:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and context (functions, classes, or occasionally code) from other files:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
. Output only the next line. | 'network': get_network_traffic(), |
Given snippet: <|code_start|>
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
'processor': get_cpu_info(),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and context:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
which might include code, classes, or functions. Output only the next line. | 'ip_address': get_ip_address(), |
Given the following code snippet before the placeholder: <|code_start|>
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
<|code_end|>
, predict the next line using imports from the current file:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and context including class names, function names, and sometimes code from other files:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
. Output only the next line. | 'processor': get_cpu_info(), |
Given snippet: <|code_start|>
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
self.plugins_list = discover_plugins()
def info(self):
system_info_dict = {
'processor': get_cpu_info(),
'ip_address': get_ip_address(),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and context:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
which might include code, classes, or functions. Output only the next line. | 'distro': get_distro(), |
Given the code snippet: <|code_start|>
log = logging.getLogger(__name__)
class Runner(object):
def __init__(self):
<|code_end|>
, generate the next line using the imports in this file:
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
import logging
and context (functions, classes, or occasionally code) from other files:
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
. Output only the next line. | self.plugins_list = discover_plugins() |
Using the snippet: <|code_start|>
log = logging.getLogger(__name__)
def get_cpu_info():
processor_dict = {}
with open('/proc/cpuinfo', 'r') as l:
lines = l.readlines()
for line in lines:
<|code_end|>
, determine the next line of code. You have imports:
import subprocess
import re
import logging
from amonagent.utils import split_and_slugify, to_float
and context (class names, function names, or code) available:
# Path: amonagent/utils.py
# def split_and_slugify(string, separator=":"):
# _string = string.strip().split(separator)
#
# if len(_string) == 2: # Only key, value
# data = {}
# key = slugify(unicode(_string[0]))
#
# try:
# if len(_string[1]) > 0:
# data[key] = str(_string[1].strip())
# except:
# pass
#
# return data
#
# else:
# return None
#
# def to_float(value):
# result = value
# if not isinstance(value, int):
# result = float(value.replace(",", "."))
#
# return result
. Output only the next line. | parsed_line = split_and_slugify(line) |
Predict the next line for this snippet: <|code_start|>
def check(self):
data = {}
try:
df = subprocess.Popen(['df','-m'], stdout=subprocess.PIPE, close_fds=True).communicate()[0]
dfi = subprocess.Popen(['df','-i'], stdout=subprocess.PIPE, close_fds=True).communicate()[0]
except:
log.exception('Unable to collect disk usage metrics.')
return False
inodes = self.parse_output(dfi)
volumes = self.parse_output(df)
_volume_columns = ('volume', 'total', 'used', 'free', 'percent', 'path')
_inode_columns = ('filesystem', 'inodes', 'iused', 'ifree', 'iuse%', 'mounted_on')
inode_dict = map(lambda x: dict(zip(_inode_columns, x)), inodes)
volumes_dict = map(lambda x: dict(zip(_volume_columns, x)), volumes)
for v in volumes_dict:
if v['volume'].startswith('/'):
if any(i['filesystem'] == v['volume'] for i in inode_dict):
# strip /dev/
name = v['volume'].replace('/dev/', '')
<|code_end|>
with the help of current file imports:
import subprocess
import re
import logging
from amonagent.utils import split_and_slugify, to_float
and context from other files:
# Path: amonagent/utils.py
# def split_and_slugify(string, separator=":"):
# _string = string.strip().split(separator)
#
# if len(_string) == 2: # Only key, value
# data = {}
# key = slugify(unicode(_string[0]))
#
# try:
# if len(_string[1]) > 0:
# data[key] = str(_string[1].strip())
# except:
# pass
#
# return data
#
# else:
# return None
#
# def to_float(value):
# result = value
# if not isinstance(value, int):
# result = float(value.replace(",", "."))
#
# return result
, which may contain function names, class names, or code. Output only the next line. | v['percent'] = to_float(v['percent'].replace("%",'')) # Delete the % sign for easier calculation later |
Given the code snippet: <|code_start|> ### UTILS
### Used in PostgreSQL, Mysql, Mongo
def normalize_row_value(self, value):
if type(value) is Decimal:
value = round(value, 2)
elif type(value) is timedelta:
value = value.total_seconds()
elif type(value) is datetime:
value = str(value)
elif type(value) is dict:
to_str = ', '.join("%s=%r" % (key,val) for (key,val) in value.iteritems())
value = to_str
if value == None or value is False:
value = ""
return value
### UTILS end
def collect(self):
raise NotImplementedError
def error(self, error_msg):
self.result['error'] = str(error_msg)
def find_plugin_path(plugin_name=None):
path = False
<|code_end|>
, generate the next line using the imports in this file:
import imp
import os
import re
import logging
import json
import simplejson as json
from decimal import Decimal
from datetime import timedelta, datetime
from amonagent.settings import settings
and context (functions, classes, or occasionally code) from other files:
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | default_location = "{0}/{1}".format(settings.DEFAULT_PLUGINS_PATH, plugin_name) |
Given the following code snippet before the placeholder: <|code_start|>
class SystemPackages(object):
def __init__(self):
distro = get_distro()
# apt or yum
self.distro_type = distro.get('type')
<|code_end|>
, predict the next line using imports from the current file:
import re
import subprocess
from amonagent.modules.distro import get_distro
from amonagent.utils import unix_utc_now
and context including class names, function names, and sometimes code from other files:
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/utils.py
# def unix_utc_now():
# d = datetime.utcnow()
# _unix = calendar.timegm(d.utctimetuple())
#
# return _unix
. Output only the next line. | self.next_run = unix_utc_now() |
Continue the code snippet: <|code_start|>
log = logging.getLogger(__name__)
class ProcessesDataCollector(object):
def __init__(self):
<|code_end|>
. Use current file imports:
import subprocess
import re
import logging
from amonagent.modules.core import get_memory_info
and context (classes, functions, or code) from other files:
# Path: amonagent/modules/core.py
# def get_memory_info():
#
# memory_dict = {}
# _save_to_dict = ['MemFree', 'MemTotal', 'SwapFree', 'SwapTotal', 'Buffers', 'Cached']
#
# regex = re.compile(r'([0-9]+)')
#
# with open('/proc/meminfo', 'r') as lines:
#
# for line in lines:
# values = line.split(':')
#
# match = re.search(regex, values[1])
# if values[0] in _save_to_dict:
# memory_dict[values[0].lower()] = int(match.group(0)) / 1024 # Convert to MB
#
# # Unix releases buffers and cached when needed
# buffers = memory_dict.get('buffers', 0)
# cached = memory_dict.get('cached', 0)
#
# memory_free = memory_dict['memfree']+buffers+cached
# memory_used = memory_dict['memtotal']-memory_free
#
# memory_percent_used = (float(memory_used)/float(memory_dict['memtotal'])*100)
#
# swap_total = memory_dict.get('swaptotal', 0)
# swap_free = memory_dict.get('swapfree', 0)
# swap_used = swap_total-swap_free
# swap_percent_used = 0
#
# if swap_total > 0:
# swap_percent_used = (float(swap_used)/float(swap_total) * 100)
#
# extracted_data = {
# "total_mb": memory_dict["memtotal"],
# "free_mb": memory_free,
# "used_mb": memory_used,
# "used_percent": memory_percent_used,
# "swap_total_mb":swap_total,
# "swap_free_mb": swap_free,
# "swap_used_mb": swap_used,
# "swap_used_percent": swap_percent_used
# }
#
# # Convert everything to int to avoid float localization problems
# for k,v in extracted_data.items():
# extracted_data[k] = int(v)
#
# return extracted_data
. Output only the next line. | memory = get_memory_info() |
Here is a snippet: <|code_start|> message = 'Fail'
color = FAIL
print "Distro collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_cpu_info()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "CPU Info collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_ip_address()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "IP address collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
<|code_end|>
. Write the next line using the current file imports:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
, which may include functions, classes, or code. Output only the next line. | info = get_uptime() |
Continue the code snippet: <|code_start|> else:
message = 'Fail'
color = FAIL
print "CPU Info collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_ip_address()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "IP address collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_uptime()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Uptime collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
<|code_end|>
. Use current file imports:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context (classes, functions, or code) from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | info = get_memory_info() |
Using the snippet: <|code_start|> else:
message = 'Fail'
color = FAIL
print "Disk usage collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_network_traffic()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Network traffic collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_load_average()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Load collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
<|code_end|>
, determine the next line of code. You have imports:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context (class names, function names, or code) available:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | info = get_cpu_utilization() |
Predict the next line after this snippet: <|code_start|> message = 'Fail'
color = FAIL
print "Memory collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = disk_check.check()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Disk usage collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_network_traffic()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Network traffic collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
<|code_end|>
using the current file's imports:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and any relevant context from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | info = get_load_average() |
Given the following code snippet before the placeholder: <|code_start|> message = 'Fail'
color = FAIL
print "IP address collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_uptime()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Uptime collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_memory_info()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Memory collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
<|code_end|>
, predict the next line using imports from the current file:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context including class names, function names, and sometimes code from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | info = disk_check.check() |
Using the snippet: <|code_start|> color = FAIL
print "Uptime collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_memory_info()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Memory collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = disk_check.check()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Disk usage collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
<|code_end|>
, determine the next line of code. You have imports:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context (class names, function names, or code) available:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | info = get_network_traffic() |
Here is a snippet: <|code_start|> print info
print SEPARATOR
def test_checks():
# Distro information
info = get_distro()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Distro collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_cpu_info()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "CPU Info collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
<|code_end|>
. Write the next line using the current file imports:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
, which may include functions, classes, or code. Output only the next line. | info = get_ip_address() |
Here is a snippet: <|code_start|>
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
SEPARATOR = "\n{color}---------{end}\n".format(color=OKGREEN,end=ENDC)
def print_data(info=None, message=None):
if message == 'OK':
print info
print SEPARATOR
def test_checks():
# Distro information
info = get_distro()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Distro collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
<|code_end|>
. Write the next line using the current file imports:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
, which may include functions, classes, or code. Output only the next line. | info = get_cpu_info() |
Based on the snippet: <|code_start|> color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Network traffic collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_load_average()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Load collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_cpu_utilization()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "CPU collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
<|code_end|>
, predict the immediate next line with the help of imports:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context (classes, functions, sometimes code) from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | info = processes_data_collector.collect() |
Given the following code snippet before the placeholder: <|code_start|>
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
SEPARATOR = "\n{color}---------{end}\n".format(color=OKGREEN,end=ENDC)
def print_data(info=None, message=None):
if message == 'OK':
print info
print SEPARATOR
def test_checks():
# Distro information
<|code_end|>
, predict the next line using imports from the current file:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context including class names, function names, and sometimes code from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | info = get_distro() |
Continue the code snippet: <|code_start|> message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Process collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
url = "{0}/api/test/{1}".format(settings.HOST, settings.SERVER_KEY)
response = requests.post(url)
if response.status_code == 200:
message = 'OK'
color = OKGREEN
else:
message = 'Fail. Please check that you have a valid server key in /etc/amon-agent.conf'
color = FAIL
print "Sending data to {0}".format(url)
print "{color}{message}{end}".format(color=color, message=message, end=ENDC)
def test_plugins(name=None):
print "Enabled plugins: "
start = time.time()
<|code_end|>
. Use current file imports:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context (classes, functions, or code) from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | enabled_plugins = discover_plugins() |
Here is a snippet: <|code_start|> message = 'Fail'
color = FAIL
print "Load collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = get_cpu_utilization()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "CPU collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
info = processes_data_collector.collect()
if len(info) > 0:
message = 'OK'
color = OKGREEN
else:
message = 'Fail'
color = FAIL
print "Process collector: {color}{message}{end}".format(color=color, message=message, end=ENDC)
print_data(info=info, message=message)
<|code_end|>
. Write the next line using the current file imports:
import requests
import time
import sys
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
disk_check,
get_network_traffic,
get_ip_address,
get_cpu_info
)
from amonagent.modules.processes import processes_data_collector
from amonagent.modules.distro import get_distro
from amonagent.modules.plugins import discover_plugins
from amonagent.settings import settings
and context from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
#
# Path: amonagent/modules/processes.py
# class ProcessesDataCollector(object):
# def __init__(self):
# def collect(self):
#
# Path: amonagent/modules/distro.py
# def get_distro():
# distro = {}
# try:
# f = Facts()
# except:
# f = False
#
#
# if f:
# facts_filter = [
# 'distribution_version',
# 'distribution',
# ]
# replaced_names = {
# 'distribution_version': 'version',
# 'distribution' : 'name'
# }
# if type(f.facts) is dict:
#
# for key, fact in f.facts.items():
# if key in facts_filter:
# reported_key = replaced_names[key]
# distro[reported_key] = fact
#
#
# return distro
#
# Path: amonagent/modules/plugins.py
# def discover_plugins(plugin_paths=[]):
# """ Discover the plugin classes contained in Python files, given a
# list of directory names to scan. Return a list of plugin classes.
#
# For now this method will look only in /etc/amonagent/plugins with possible
# future extension which will permit searching for plugins in
# user defined directories
# """
#
# if os.path.exists(ENABLED_PLUGINS_PATH):
# # Find all enabled plugins
# for filename in os.listdir(ENABLED_PLUGINS_PATH):
# plugin_name, ext = os.path.splitext(filename)
# if ext == ".conf":
#
# # Configuration file OK, load the plugin
# plugin_path = find_plugin_path(plugin_name=plugin_name) # path or False
#
# if plugin_path:
# for filename in os.listdir(plugin_path):
# modname, extension = os.path.splitext(filename)
# if extension == '.py':
#
# fp, path, descr = imp.find_module(modname, [plugin_path])
# if fp:
# # Loading the module registers the plugin in
# if modname not in ['base', '__init__']:
# mod = imp.load_module(modname, fp, path, descr)
# fp.close()
#
# return AmonPlugin.plugins
#
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
, which may include functions, classes, or code. Output only the next line. | url = "{0}/api/test/{1}".format(settings.HOST, settings.SERVER_KEY) |
Given the code snippet: <|code_start|>try:
except ImportError:
log = logging.getLogger(__name__)
class ConnectionException(Exception):
" Raised when the Amon Web interface is not responding"
class Remote(object):
def __init__(self):
<|code_end|>
, generate the next line using the imports in this file:
import json
import simplejson as json
import requests
import logging
from amonagent.settings import settings
and context (functions, classes, or occasionally code) from other files:
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | self.server_key = settings.SERVER_KEY |
Based on the snippet: <|code_start|>
def get_log_date_format():
return "%Y-%m-%d %H:%M:%S %Z"
def get_log_format(logger_name):
return '%%(asctime)s | %%(levelname)s | %s | %%(name)s(%%(filename)s:%%(lineno)s) | %%(message)s' % logger_name
def initialize_logging(logger_name):
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import logging.handlers
import os
import sys
import traceback
from amonagent.settings import settings
and context (classes, functions, sometimes code) from other files:
# Path: amonagent/settings.py
# class Settings(object):
# def __init__(self):
. Output only the next line. | log_file = settings.LOGFILE |
Given snippet: <|code_start|>
try:
except ImportError:
try:
config_file = file('/etc/amon-agent.conf').read()
config = json.loads(config_file)
except Exception, e:
print "There was an error in your configuration file (/etc/amon-agent.conf)"
raise e
class Settings(object):
def __init__(self):
# update this dict from the defaults dictionary (but only for ALL_CAPS settings)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from amonagent import defaults
import json
import simplejson as json
and context:
# Path: amonagent/defaults.py
# SYSTEM_CHECK_PERIOD = config.get('system_check_period', 60)
# HOST = config.get('host', 'https://amon.cx')
# SERVER_KEY = config.get('server_key', None)
# PIDFILE = '/var/run/amonagent/amonagent.pid'
# PIDFILE = config.get('pidfile', '/var/run/amonagent.pid')
# LOGFILE = config.get("logfile", '/var/log/amonagent/amonagent.log')
# LOGGING_MAX_BYTES = 5 * 1024 * 1024
# DEFAULT_PLUGINS_PATH = '/etc/amonagent/plugins'
# CUSTOM_PLUGINS_PATH = config.get("custom_plugins_path")
which might include code, classes, or functions. Output only the next line. | for setting in dir(defaults): |
Continue the code snippet: <|code_start|>
class TestSystemCheck(object):
def test_uptime(self):
uptime = get_uptime()
assert isinstance(uptime, str)
def test_ip_address(self):
ip_address = get_ip_address()
valid_ip = False
try:
socket.inet_pton(socket.AF_INET, ip_address)
valid_ip = True
except AttributeError: # no inet_pton here, sorry
try:
socket.inet_aton(ip_address)
valid_ip = True
except socket.error:
pass
except socket.error: # not a valid address
pass
assert valid_ip
def test_memory(self):
<|code_end|>
. Use current file imports:
import sys
import re
import socket
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
get_network_traffic,
get_ip_address,
get_cpu_info,
disk_check
)
and context (classes, functions, or code) from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
. Output only the next line. | memory_dict = get_memory_info() |
Given the following code snippet before the placeholder: <|code_start|> assert 'swap_used_percent' in memory_dict
assert 'swap_total_mb' in memory_dict
assert 'used_percent' > 0
for v in memory_dict.values():
assert isinstance(v, int)
def test_cpu_info(self):
cpu_info = get_cpu_info()
assert isinstance(cpu_info, dict)
assert len(cpu_info.keys()) > 0
def test_disk(self):
disk = disk_check.check()
for k in disk:
_dict = disk[k]
assert 'used' in _dict
assert 'percent' in _dict
assert 'free' in _dict
assert 'volume' in _dict
assert 'total' in _dict
def test_cpu(self):
<|code_end|>
, predict the next line using imports from the current file:
import sys
import re
import socket
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
get_network_traffic,
get_ip_address,
get_cpu_info,
disk_check
)
and context including class names, function names, and sometimes code from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
. Output only the next line. | cpu = get_cpu_utilization() |
Given the following code snippet before the placeholder: <|code_start|>
def test_disk(self):
disk = disk_check.check()
for k in disk:
_dict = disk[k]
assert 'used' in _dict
assert 'percent' in _dict
assert 'free' in _dict
assert 'volume' in _dict
assert 'total' in _dict
def test_cpu(self):
cpu = get_cpu_utilization()
assert 'idle' in cpu
assert 'user' in cpu
assert 'system' in cpu
for v in cpu.values():
# Could be 1.10 - 4, 10.10 - 5, 100.00 - 6
assert len(v) == 4 or len(v) == 5 or len(v) == 6
value_regex = re.compile(r'\d+[\.]\d+')
assert re.match(value_regex, v)
def test_loadavg(self):
<|code_end|>
, predict the next line using imports from the current file:
import sys
import re
import socket
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
get_network_traffic,
get_ip_address,
get_cpu_info,
disk_check
)
and context including class names, function names, and sometimes code from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
. Output only the next line. | loadavg = get_load_average() |
Based on the snippet: <|code_start|>
for v in cpu.values():
# Could be 1.10 - 4, 10.10 - 5, 100.00 - 6
assert len(v) == 4 or len(v) == 5 or len(v) == 6
value_regex = re.compile(r'\d+[\.]\d+')
assert re.match(value_regex, v)
def test_loadavg(self):
loadavg = get_load_average()
assert 'minute' in loadavg
assert 'five_minutes' in loadavg
assert 'fifteen_minutes' in loadavg
assert 'cores' in loadavg
assert isinstance(loadavg['cores'], int)
assert isinstance(loadavg['minute'], str)
assert isinstance(loadavg['five_minutes'], str)
assert isinstance(loadavg['fifteen_minutes'], str)
value_regex = re.compile(r'\d+[\.]\d+')
assert re.match(value_regex, loadavg['minute'])
assert re.match(value_regex, loadavg['five_minutes'])
assert re.match(value_regex, loadavg['fifteen_minutes'])
def test_network(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import re
import socket
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
get_network_traffic,
get_ip_address,
get_cpu_info,
disk_check
)
and context (classes, functions, sometimes code) from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
. Output only the next line. | network_data = get_network_traffic() |
Based on the snippet: <|code_start|>
class TestSystemCheck(object):
def test_uptime(self):
uptime = get_uptime()
assert isinstance(uptime, str)
def test_ip_address(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import re
import socket
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
get_network_traffic,
get_ip_address,
get_cpu_info,
disk_check
)
and context (classes, functions, sometimes code) from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
. Output only the next line. | ip_address = get_ip_address() |
Given the code snippet: <|code_start|> except socket.error:
pass
except socket.error: # not a valid address
pass
assert valid_ip
def test_memory(self):
memory_dict = get_memory_info()
assert 'free_mb' in memory_dict
assert 'total_mb' in memory_dict
assert 'used_mb' in memory_dict
assert 'used_percent' in memory_dict
assert 'swap_free_mb' in memory_dict
assert 'swap_used_mb' in memory_dict
assert 'swap_used_percent' in memory_dict
assert 'swap_total_mb' in memory_dict
assert 'used_percent' > 0
for v in memory_dict.values():
assert isinstance(v, int)
def test_cpu_info(self):
<|code_end|>
, generate the next line using the imports in this file:
import sys
import re
import socket
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
get_network_traffic,
get_ip_address,
get_cpu_info,
disk_check
)
and context (functions, classes, or occasionally code) from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
. Output only the next line. | cpu_info = get_cpu_info() |
Next line prediction: <|code_start|>
def test_memory(self):
memory_dict = get_memory_info()
assert 'free_mb' in memory_dict
assert 'total_mb' in memory_dict
assert 'used_mb' in memory_dict
assert 'used_percent' in memory_dict
assert 'swap_free_mb' in memory_dict
assert 'swap_used_mb' in memory_dict
assert 'swap_used_percent' in memory_dict
assert 'swap_total_mb' in memory_dict
assert 'used_percent' > 0
for v in memory_dict.values():
assert isinstance(v, int)
def test_cpu_info(self):
cpu_info = get_cpu_info()
assert isinstance(cpu_info, dict)
assert len(cpu_info.keys()) > 0
def test_disk(self):
<|code_end|>
. Use current file imports:
(import sys
import re
import socket
from amonagent.modules.core import (
get_uptime,
get_memory_info,
get_cpu_utilization,
get_load_average,
get_network_traffic,
get_ip_address,
get_cpu_info,
disk_check
))
and context including class names, function names, or small code snippets from other files:
# Path: amonagent/modules/core.py
# def get_cpu_info():
# def get_ip_address():
# def get_uptime():
# def get_memory_info():
# def parse_output(self, df_output):
# def keep_device(device):
# def _is_number(self, a_string):
# def _check_blocks(self, blocks):
# def _is_real_device(self, device):
# def _flatten_devices(self, devices):
# def check(self):
# def get_network_traffic():
# def get_load_average():
# def get_cpu_utilization():
# MINUTE = 60
# HOUR = MINUTE * 60
# DAY = HOUR * 24
# class DiskCheck(object):
. Output only the next line. | disk = disk_check.check() |
Here is a snippet: <|code_start|>#
# CommandModule
# Subclass of HalModule that does the heavy lifting of commands for you
#
# Decorator for converting the string stripped of the command to an argument list
def AsArgs(func):
def wrapper(self, string, msg=None):
args = string.split(" ")
func(self, args, msg=msg)
return wrapper
<|code_end|>
. Write the next line using the current file imports:
from . import HalModule
and context from other files:
# Path: halibot/halmodule.py
# class HalModule(HalObject):
#
# def reply(self, msg0=None, **kwargs):
# # Create the reply message
# body = kwargs.get('body', msg0.body)
# mtype = kwargs.get('type', msg0.type)
# author = kwargs.get('author', msg0.author)
# origin = kwargs.get('origin', self.name)
#
# msg = Message(body=body, type=mtype, author=author, origin=origin)
#
# # Synchronous reply?
# if msg0.sync:
# self.sync_replies[msg0.uuid].append(msg)
# else:
# self.send_to(msg, [ msg0.origin ])
#
# def hasPermission(self, msg, perm):
# return self._hal.auth.hasPermission(msg.origin, msg.identity, perm)
, which may include functions, classes, or code. Output only the next line. | class CommandModule(HalModule): |
Given snippet: <|code_start|>
def hasPermission(perm, reply=False, argnum=None, key="msg"):
def real_dec(func):
def wrapper(self, *args, **kwargs):
if argnum != None and argnum < len(args):
msg = args[argnum]
else:
msg = kwargs[key]
# Origin must be set for this to be a valid permission check
if not hasattr(msg, "origin") or not msg.origin:
self.log.error("Probable module bug! -- hasPermission decorator called on a function that doesn't have a valid Message argument!")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import logging
import re
from halibot.message import Message, MalformedMsgException
and context:
# Path: halibot/message.py
# class Message():
#
# def __init__(self, **kwargs):
# self.log = logging.getLogger(self.__class__.__name__)
# self.uuid = uuid.uuid4()
# self.sync = False
#
# self.body = kwargs.get('body', None)
# self.type = kwargs.get('type', 'simple')
# self.author = kwargs.get('author', None)
# self.identity = kwargs.get('identity', None)
# self.origin = kwargs.get('origin', None)
# self.misc = kwargs.get('misc', jsdict())
# self.target = kwargs.get('target', '')
#
# def whom(self):
# return '/'.join(self.target.split('/')[1:])
#
# def __repr__(self):
# return "halibot.Message(body='{}', type='{}', author='{}', identity='{}', origin='{}', misc='{}', target='{}')".format(self.body, self.type, self.author, self.identity, self.origin, self.misc, self.target)
#
# def __str__(self):
# return "body='{}' type='{}' author='{}' origin='{}' target='{}'".format(self.body, self.type, self.author, self.origin, self.target)
#
# class MalformedMsgException(Exception): 'Bad message object'
which might include code, classes, or functions. Output only the next line. | raise MalformedMsgException("Bad or missing origin attribute") |
Given snippet: <|code_start|> r[name] = to.sync_replies.pop(msg.uuid)
return r
async def _receive(self, msg):
try:
fname = 'receive_' + msg.type
if hasattr(self, fname) and callable(getattr(self, fname)):
# Type specific receive function
getattr(self, fname)(msg)
else:
# Generic receive function
self.receive(msg)
except Exception as e:
self.log.error("Exception in message receive", exc_info=True)
def receive(self, msg):
pass
def receive_help(self, msg):
if hasattr(self, 'topics'):
if msg.body == []:
# Retrieve available topics
self.reply(msg, body=list(self.topics.keys()))
else:
# Retrieve help text for topic
key = '/'.join(msg.body)
if key in self.topics:
t = self.topics[key]
self.reply(msg, body=t() if callable(t) else t)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import asyncio
import inspect
import copy
from threading import Thread
from collections import defaultdict
from .halconfigurer import HalConfigurer
from .message import MalformedMsgException
and context:
# Path: halibot/halconfigurer.py
# class HalConfigurer():
#
# def __init__(self, options={}):
# self.options = options
#
# def option(self, option_type, key, **kwargs):
# opt = option_type(key, **kwargs)
#
# # Override the default if the option is already set
# if key in self.options:
# opt.default = self.options[key]
#
# val = opt.configure()
# if val != None:
# self.options[key] = val
#
# def optionString(self, key, **kwargs):
# self.option(Option.String, key, **kwargs)
#
# def optionInt(self, key, **kwargs):
# self.option(Option.Int, key, **kwargs)
#
# def optionNumber(self, key, **kwargs):
# self.option(Option.Number, key, **kwargs)
#
# def optionBoolean(self, key, **kwargs):
# self.option(Option.Boolean, key, **kwargs)
#
# def configure(self):
# pass # pragma: no cover
#
# Path: halibot/message.py
# class MalformedMsgException(Exception): 'Bad message object'
which might include code, classes, or functions. Output only the next line. | class Configurer(HalConfigurer): |
Continue the code snippet: <|code_start|> self.shutdown()
def _queue_msg(self, msg):
fut = asyncio.run_coroutine_threadsafe(self._receive(msg), self.eventloop)
return fut
def init(self):
pass
def shutdown(self):
pass
def apply_filter(self, dest):
fl = self._hal.config.get("filters")
if not fl:
return dest # Filters not enabled/configured
name = dest.split("/")[0]
ib = fl.get("inbound", {})
ob = fl.get("outbound", {})
ret = "/".join(ib.get(name, []) + [dest])
ret = "/".join(ob.get(self.name, []) + [ret])
return ret
def raw_send(self, msg):
if not msg.target:
self.log.warning("Message passed to send without target")
<|code_end|>
. Use current file imports:
import logging
import asyncio
import inspect
import copy
from threading import Thread
from collections import defaultdict
from .halconfigurer import HalConfigurer
from .message import MalformedMsgException
and context (classes, functions, or code) from other files:
# Path: halibot/halconfigurer.py
# class HalConfigurer():
#
# def __init__(self, options={}):
# self.options = options
#
# def option(self, option_type, key, **kwargs):
# opt = option_type(key, **kwargs)
#
# # Override the default if the option is already set
# if key in self.options:
# opt.default = self.options[key]
#
# val = opt.configure()
# if val != None:
# self.options[key] = val
#
# def optionString(self, key, **kwargs):
# self.option(Option.String, key, **kwargs)
#
# def optionInt(self, key, **kwargs):
# self.option(Option.Int, key, **kwargs)
#
# def optionNumber(self, key, **kwargs):
# self.option(Option.Number, key, **kwargs)
#
# def optionBoolean(self, key, **kwargs):
# self.option(Option.Boolean, key, **kwargs)
#
# def configure(self):
# pass # pragma: no cover
#
# Path: halibot/message.py
# class MalformedMsgException(Exception): 'Bad message object'
. Output only the next line. | raise MalformedMsgException("raw_send given empty target") |
Predict the next line for this snippet: <|code_start|>#
# HelpModule
#
class Help(CommandModule):
def init(self):
self.commands = {
'help' : self.command
}
def general_help(self, target):
<|code_end|>
with the help of current file imports:
from halibot import CommandModule, Message
and context from other files:
# Path: halibot/message.py
# class Message():
#
# def __init__(self, **kwargs):
# self.log = logging.getLogger(self.__class__.__name__)
# self.uuid = uuid.uuid4()
# self.sync = False
#
# self.body = kwargs.get('body', None)
# self.type = kwargs.get('type', 'simple')
# self.author = kwargs.get('author', None)
# self.identity = kwargs.get('identity', None)
# self.origin = kwargs.get('origin', None)
# self.misc = kwargs.get('misc', jsdict())
# self.target = kwargs.get('target', '')
#
# def whom(self):
# return '/'.join(self.target.split('/')[1:])
#
# def __repr__(self):
# return "halibot.Message(body='{}', type='{}', author='{}', identity='{}', origin='{}', misc='{}', target='{}')".format(self.body, self.type, self.author, self.identity, self.origin, self.misc, self.target)
#
# def __str__(self):
# return "body='{}' type='{}' author='{}' origin='{}' target='{}'".format(self.body, self.type, self.author, self.origin, self.target)
#
# Path: halibot/commandmodule.py
# class CommandModule(HalModule):
#
# # Subclasses should implement a commands table like the following.
# # Note, the "values" should be methods on the CommandModule-derived class
# # Forgoing this is inadvisable (e.g. loss of _hal reference)
# # "command" -> func(self, string, msg=msg)
# # string: by default, will be the message not split into arguments
# # use the annotation AsArgs above to override this
# # msg: not needed in all commands, the message object as received
#
# def __init__(self, hal, conf={}):
# super().__init__(hal, conf=conf)
#
# self.commands = {}
# # Get the command prefix if defined, otherwise use "!" as default
# self.prefix = self._hal.config.get("command_prefix", "!")
#
# # Override only if you know what you are doing!
# def receive(self, msg):
# self._cmd_receive(msg)
#
# # Actually does the command handling logic. Separate callable so multi-inheritance
# # can work nicely (maybe)
# def _cmd_receive(self, msg):
# body = msg.body.split(" ", 1)
# if body and not body[0].startswith(self.prefix):
# self.default(msg)
# return
#
# # Ugly fix for commands without args
# if len(body) == 1:
# body.append("")
#
# # This maybe should prevent a empty string as a key...
# func = self.commands.get(body[0][1:])
#
# if func:
# func(body[1], msg=msg)
# else:
# self.default(msg)
#
# # Override this to provide some functionality if there is no match in the table
# def default(self, msg):
# pass
, which may contain function names, class names, or code. Output only the next line. | hmsg = Message(body=[], type='help', origin=self.name) |
Using the snippet: <|code_start|>
class MalformedMsgException(Exception): 'Bad message object'
class Message():
def __init__(self, **kwargs):
self.log = logging.getLogger(self.__class__.__name__)
self.uuid = uuid.uuid4()
self.sync = False
self.body = kwargs.get('body', None)
self.type = kwargs.get('type', 'simple')
self.author = kwargs.get('author', None)
self.identity = kwargs.get('identity', None)
self.origin = kwargs.get('origin', None)
<|code_end|>
, determine the next line of code. You have imports:
import logging
import uuid
from .jsdict import jsdict
and context (class names, function names, or code) available:
# Path: halibot/jsdict.py
# class jsdict(dict):
# def __getattr__(self, name):
# return self[name]
#
# def __setattr__(self, name, value):
# self[name] = value
. Output only the next line. | self.misc = kwargs.get('misc', jsdict()) |
Continue the code snippet: <|code_start|>#
# Main bot class
# Handles routing, config, agent/module loading
#
# Avoid appending "." if it i
if "." not in sys.path:
sys.path.append(".")
HALDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
class ObjectDict(dict):
@property
def modules(self):
<|code_end|>
. Use current file imports:
import json
import threading
import os, sys
import importlib
import collections
import halibot.packages
import logging
from distutils.version import StrictVersion as Version
from queue import Queue,Empty
from string import Template
from .halmodule import HalModule
from .halagent import HalAgent
from .halauth import HalAuth
and context (classes, functions, or code) from other files:
# Path: halibot/halmodule.py
# class HalModule(HalObject):
#
# def reply(self, msg0=None, **kwargs):
# # Create the reply message
# body = kwargs.get('body', msg0.body)
# mtype = kwargs.get('type', msg0.type)
# author = kwargs.get('author', msg0.author)
# origin = kwargs.get('origin', self.name)
#
# msg = Message(body=body, type=mtype, author=author, origin=origin)
#
# # Synchronous reply?
# if msg0.sync:
# self.sync_replies[msg0.uuid].append(msg)
# else:
# self.send_to(msg, [ msg0.origin ])
#
# def hasPermission(self, msg, perm):
# return self._hal.auth.hasPermission(msg.origin, msg.identity, perm)
#
# Path: halibot/halagent.py
# class HalAgent(HalObject):
#
# def dispatch(self, msg):
# out = self.config.get('out', self._hal.objects.modules.keys())
# self.send_to(msg, out)
#
# def connect(self, to):
# # FIXME Don't modify the config like this?
# if 'out' in self.config:
# self.config['out'].append(to.name)
# else:
# self.config['out'] = [ to.name ]
#
# Path: halibot/halauth.py
# class HalAuth():
#
# def __init__(self):
# self.perms = []
# self.enabled = False
# self.log = logging.getLogger("Auth")
#
# # Load permission file, and set to enabled
# def load_perms(self, path):
# self.path = path
#
# try:
# with open(self.path, "r") as f:
# temp = json.loads(f.read())
#
# # Roll back into triple, also technically validates format
# self.perms = [(a,b,c) for a,b,c in temp]
#
# except Exception as e:
# self.log.error("Error loading permissions: {}".format(e))
# self.perms = []
# # Return if can't find auth?
#
# self.enabled = True
#
# # Write permissions back to the file that was originally loaded
# def write_perms(self):
# try:
# temp = [list(l) for l in self.perms]
#
# with open(self.path, "w") as f:
# f.write(json.dumps(temp, indent=4))
# except Exception as e: # pragma: no cover
# self.log.error("Error storing permissions: {}".format(e))
#
# def grantPermission(self, ri, identity, perm):
# if not self.enabled:
# return
#
# t = (ri, identity, perm)
# if t not in self.perms:
# self.perms.append(t)
#
# def revokePermission(self, ri, identity, perm):
# if not self.enabled:
# return
#
# try:
# self.perms.remove((ri,identity, perm))
# except Exception as e:
# self.log.error("Revocation failed: {}".format(e))
#
# def hasPermission(self, ri, identity, perm):
# if not self.enabled:
# return True
#
# def tester(x):
# a,b,c = x
# return re.match(a, ri) and b in (identity, "*") and re.match(c, perm)
#
# # Return True on the first successful perm match
# for l in self.perms:
# if tester(l):
# return True
# return False
. Output only the next line. | return dict(filter(lambda x: isinstance(x[1], HalModule), self.items())) |
Continue the code snippet: <|code_start|>#
# Main bot class
# Handles routing, config, agent/module loading
#
# Avoid appending "." if it i
if "." not in sys.path:
sys.path.append(".")
HALDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
class ObjectDict(dict):
@property
def modules(self):
return dict(filter(lambda x: isinstance(x[1], HalModule), self.items()))
@property
def agents(self):
<|code_end|>
. Use current file imports:
import json
import threading
import os, sys
import importlib
import collections
import halibot.packages
import logging
from distutils.version import StrictVersion as Version
from queue import Queue,Empty
from string import Template
from .halmodule import HalModule
from .halagent import HalAgent
from .halauth import HalAuth
and context (classes, functions, or code) from other files:
# Path: halibot/halmodule.py
# class HalModule(HalObject):
#
# def reply(self, msg0=None, **kwargs):
# # Create the reply message
# body = kwargs.get('body', msg0.body)
# mtype = kwargs.get('type', msg0.type)
# author = kwargs.get('author', msg0.author)
# origin = kwargs.get('origin', self.name)
#
# msg = Message(body=body, type=mtype, author=author, origin=origin)
#
# # Synchronous reply?
# if msg0.sync:
# self.sync_replies[msg0.uuid].append(msg)
# else:
# self.send_to(msg, [ msg0.origin ])
#
# def hasPermission(self, msg, perm):
# return self._hal.auth.hasPermission(msg.origin, msg.identity, perm)
#
# Path: halibot/halagent.py
# class HalAgent(HalObject):
#
# def dispatch(self, msg):
# out = self.config.get('out', self._hal.objects.modules.keys())
# self.send_to(msg, out)
#
# def connect(self, to):
# # FIXME Don't modify the config like this?
# if 'out' in self.config:
# self.config['out'].append(to.name)
# else:
# self.config['out'] = [ to.name ]
#
# Path: halibot/halauth.py
# class HalAuth():
#
# def __init__(self):
# self.perms = []
# self.enabled = False
# self.log = logging.getLogger("Auth")
#
# # Load permission file, and set to enabled
# def load_perms(self, path):
# self.path = path
#
# try:
# with open(self.path, "r") as f:
# temp = json.loads(f.read())
#
# # Roll back into triple, also technically validates format
# self.perms = [(a,b,c) for a,b,c in temp]
#
# except Exception as e:
# self.log.error("Error loading permissions: {}".format(e))
# self.perms = []
# # Return if can't find auth?
#
# self.enabled = True
#
# # Write permissions back to the file that was originally loaded
# def write_perms(self):
# try:
# temp = [list(l) for l in self.perms]
#
# with open(self.path, "w") as f:
# f.write(json.dumps(temp, indent=4))
# except Exception as e: # pragma: no cover
# self.log.error("Error storing permissions: {}".format(e))
#
# def grantPermission(self, ri, identity, perm):
# if not self.enabled:
# return
#
# t = (ri, identity, perm)
# if t not in self.perms:
# self.perms.append(t)
#
# def revokePermission(self, ri, identity, perm):
# if not self.enabled:
# return
#
# try:
# self.perms.remove((ri,identity, perm))
# except Exception as e:
# self.log.error("Revocation failed: {}".format(e))
#
# def hasPermission(self, ri, identity, perm):
# if not self.enabled:
# return True
#
# def tester(x):
# a,b,c = x
# return re.match(a, ri) and b in (identity, "*") and re.match(c, perm)
#
# # Return True on the first successful perm match
# for l in self.perms:
# if tester(l):
# return True
# return False
. Output only the next line. | return dict(filter(lambda x: isinstance(x[1], HalAgent), self.items())) |
Given snippet: <|code_start|> return self.system[key]
def __setitem__(self, key, value):
self.local[key] = value
def __delitem__(self, key):
del self.local[value]
def __iter__(self):
return iter(self.local.keys() + self.system.keys())
def __len__(self):
return len(set(self.local.keys()) + set(self.system.keys()))
def __keytransform__(self, key):
return key
class Halibot():
VERSION = "0.2.0"
running = False
log = None
def __init__(self, **kwargs):
self.log = logging.getLogger(self.__class__.__name__)
self.use_config = kwargs.get("use_config", True)
self.workdir = kwargs.get("workdir", ".")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import threading
import os, sys
import importlib
import collections
import halibot.packages
import logging
from distutils.version import StrictVersion as Version
from queue import Queue,Empty
from string import Template
from .halmodule import HalModule
from .halagent import HalAgent
from .halauth import HalAuth
and context:
# Path: halibot/halmodule.py
# class HalModule(HalObject):
#
# def reply(self, msg0=None, **kwargs):
# # Create the reply message
# body = kwargs.get('body', msg0.body)
# mtype = kwargs.get('type', msg0.type)
# author = kwargs.get('author', msg0.author)
# origin = kwargs.get('origin', self.name)
#
# msg = Message(body=body, type=mtype, author=author, origin=origin)
#
# # Synchronous reply?
# if msg0.sync:
# self.sync_replies[msg0.uuid].append(msg)
# else:
# self.send_to(msg, [ msg0.origin ])
#
# def hasPermission(self, msg, perm):
# return self._hal.auth.hasPermission(msg.origin, msg.identity, perm)
#
# Path: halibot/halagent.py
# class HalAgent(HalObject):
#
# def dispatch(self, msg):
# out = self.config.get('out', self._hal.objects.modules.keys())
# self.send_to(msg, out)
#
# def connect(self, to):
# # FIXME Don't modify the config like this?
# if 'out' in self.config:
# self.config['out'].append(to.name)
# else:
# self.config['out'] = [ to.name ]
#
# Path: halibot/halauth.py
# class HalAuth():
#
# def __init__(self):
# self.perms = []
# self.enabled = False
# self.log = logging.getLogger("Auth")
#
# # Load permission file, and set to enabled
# def load_perms(self, path):
# self.path = path
#
# try:
# with open(self.path, "r") as f:
# temp = json.loads(f.read())
#
# # Roll back into triple, also technically validates format
# self.perms = [(a,b,c) for a,b,c in temp]
#
# except Exception as e:
# self.log.error("Error loading permissions: {}".format(e))
# self.perms = []
# # Return if can't find auth?
#
# self.enabled = True
#
# # Write permissions back to the file that was originally loaded
# def write_perms(self):
# try:
# temp = [list(l) for l in self.perms]
#
# with open(self.path, "w") as f:
# f.write(json.dumps(temp, indent=4))
# except Exception as e: # pragma: no cover
# self.log.error("Error storing permissions: {}".format(e))
#
# def grantPermission(self, ri, identity, perm):
# if not self.enabled:
# return
#
# t = (ri, identity, perm)
# if t not in self.perms:
# self.perms.append(t)
#
# def revokePermission(self, ri, identity, perm):
# if not self.enabled:
# return
#
# try:
# self.perms.remove((ri,identity, perm))
# except Exception as e:
# self.log.error("Revocation failed: {}".format(e))
#
# def hasPermission(self, ri, identity, perm):
# if not self.enabled:
# return True
#
# def tester(x):
# a,b,c = x
# return re.match(a, ri) and b in (identity, "*") and re.match(c, perm)
#
# # Return True on the first successful perm match
# for l in self.perms:
# if tester(l):
# return True
# return False
which might include code, classes, or functions. Output only the next line. | self.auth = HalAuth() |
Continue the code snippet: <|code_start|>
class TestBackend(unittest.TestCase):
def test_auto_client(self):
with self.subTest('No arguments are provided'):
expected = {
'server_ip_address': '',
'vni': 0,
}
<|code_end|>
. Use current file imports:
import unittest
from netjsonconfig import VxlanWireguard
and context (classes, functions, or code) from other files:
# Path: netjsonconfig/backends/vxlan/vxlan_wireguard.py
# class VxlanWireguard(Wireguard):
# @classmethod
# def auto_client(cls, vni=0, server_ip_address='', **kwargs):
# """
# Returns a configuration dictionary representing VXLAN configuration
# that is compatible with the passed server configuration.
#
# :param vni: Virtual Network Identifier
# :param server_ip_address: server internal tunnel address
# :returns: dictionary representing VXLAN properties
# """
# config = {
# 'server_ip_address': server_ip_address,
# 'vni': vni,
# }
# return config
. Output only the next line. | self.assertDictEqual(VxlanWireguard.auto_client(), expected) |
Given snippet: <|code_start|>
class OpenWisp(OpenWrt):
"""
OpenWISP 1.x Firmware (legacy) Configuration Backend
"""
schema = schema
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
from jinja2 import Environment, PackageLoader
from ..openwrt.openwrt import OpenWrt
from .renderer import OpenWrtRenderer
from .schema import schema
and context:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/backends/openwisp/renderer.py
# class OpenWrtRenderer(BaseRenderer):
# """
# OpenWRT Renderer for OpenWISP 1.x backend
#
# It uses a slightly different template
# than the default OpenWRT renderer in order
# to provide backward compatibility with the
# format that was generated by OpenWISP Manager.
#
# E.g.:
#
# # OpenWISP Manager:
# config 'system' 'system'
# option 'hostname' 'openwisp-test'
#
# # standard OpenWRT conf generated by netjsonconfig:
# config system 'system'
# option hostname 'openwisp-test'
# """
#
# pass
#
# Path: netjsonconfig/backends/openwisp/schema.py
which might include code, classes, or functions. Output only the next line. | renderer = OpenWrtRenderer |
Continue the code snippet: <|code_start|>
class Switch(OpenWrtConverter):
netjson_key = 'switch'
intermediate_key = 'network'
_uci_types = ['switch', 'switch_vlan']
<|code_end|>
. Use current file imports:
from ..schema import schema
from .base import OpenWrtConverter
and context (classes, functions, or code) from other files:
# Path: netjsonconfig/backends/openwrt/schema.py
. Output only the next line. | _switch_schema = schema['properties']['switch']['items'] |
Here is a snippet: <|code_start|>
class TestBackend(unittest.TestCase, _TabsMixin):
maxDiff = None
def test_config_copy(self):
config = {'interfaces': []}
<|code_end|>
. Write the next line using the current file imports:
import json
import os
import tarfile
import unittest
from hashlib import md5
from time import sleep
from netjsonconfig import OpenWrt
from netjsonconfig.exceptions import ValidationError
from netjsonconfig.utils import _TabsMixin
and context from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
, which may include functions, classes, or code. Output only the next line. | o = OpenWrt(config) |
Based on the snippet: <|code_start|>
class TestRadio(unittest.TestCase, _TabsMixin):
maxDiff = None
def test_render_radio(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.utils import _TabsMixin
and context (classes, functions, sometimes code) from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | o = OpenWrt( |
Continue the code snippet: <|code_start|> option enabled '1'
option engine 'rsax'
option fast_io '1'
option fragment '0'
option group 'nogroup'
option keepalive '20 60'
option key 'key.pem'
option log '/var/log/openvpn.log'
option mode 'server'
option mssfix '1450'
option mtu_disc 'no'
option mtu_test '0'
option mute '0'
option mute_replay_warnings '1'
option persist_key '1'
option persist_tun '1'
option port '1194'
option proto 'udp'
option script_security '0'
option status '/var/log/openvpn.status 10'
option status_version '1'
option tls_server '1'
option tun_ipv6 '0'
option up_delay '0'
option user 'nobody'
option username_as_common_name '0'
option verb '3'
"""
def test_render_server_mode(self):
<|code_end|>
. Use current file imports:
import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.utils import _TabsMixin
and context (classes, functions, or code) from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | c = OpenWrt(self._server_netjson) |
Here is a snippet: <|code_start|>
class Led(OpenWrtConverter):
netjson_key = 'led'
intermediate_key = 'system'
_uci_types = ['led']
<|code_end|>
. Write the next line using the current file imports:
from ..schema import schema
from .base import OpenWrtConverter
and context from other files:
# Path: netjsonconfig/backends/openwrt/schema.py
, which may include functions, classes, or code. Output only the next line. | _schema = schema['properties']['led']['items'] |
Continue the code snippet: <|code_start|> "apn": "apn.vodafone.com",
"pin": "1234",
"device": "/sys/devices/platform/ahb/1b000000.usb/usb1/1-1",
"username": "user123",
"password": "pwd123456",
"metric": 50,
"iptype": "ipv4v6",
"lowpower": False,
"mtu": 1500,
}
]
}
_modemmanager_interface_uci = """package network
config interface 'wwan0'
option apn 'apn.vodafone.com'
option device '/sys/devices/platform/ahb/1b000000.usb/usb1/1-1'
option ifname 'wwan0'
option iptype 'ipv4v6'
option lowpower '0'
option metric '50'
option mtu '1500'
option password 'pwd123456'
option pincode '1234'
option proto 'modemmanager'
option username 'user123'
"""
def test_render_modemmanager_interface(self):
<|code_end|>
. Use current file imports:
import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.utils import _TabsMixin
and context (classes, functions, or code) from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | result = OpenWrt(self._modemmanager_interface_netjson).render() |
Given the following code snippet before the placeholder: <|code_start|>
class TestInterfaces(unittest.TestCase, _TabsMixin):
maxDiff = None
def test_render_loopback(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from copy import deepcopy
from netjsonconfig import OpenWrt
from netjsonconfig.exceptions import ValidationError
from netjsonconfig.utils import _TabsMixin
and context including class names, function names, and sometimes code from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | o = OpenWrt( |
Predict the next line for this snippet: <|code_start|> return self._add_netjson_addresses(interface, proto)
def _add_netjson_addresses(self, interface, proto):
addresses = []
ipv4 = interface.pop('ipaddr', [])
ipv6 = interface.pop('ip6addr', [])
if not isinstance(ipv4, list):
netmask = interface.pop('netmask', 32)
parsed_ip = self.__netjson_parse_ip(ipv4, netmask)
ipv4 = [parsed_ip] if parsed_ip else []
if not isinstance(ipv6, list):
netmask = interface.pop('netmask', 128)
parsed_ip = self.__netjson_parse_ip(ipv6, netmask)
ipv6 = [parsed_ip] if parsed_ip else []
if proto.startswith('dhcp'):
family = 'ipv4' if proto == 'dhcp' else 'ipv6'
addresses.append({'proto': 'dhcp', 'family': family})
for address in ipv4 + ipv6:
address = self.__netjson_parse_ip(address)
if not address:
continue
addresses.append(self.__netjson_address(address, interface))
if addresses:
interface['addresses'] = addresses
return interface
def _netjson_dialup(self, interface):
interface['type'] = 'dialup'
return interface
<|code_end|>
with the help of current file imports:
from collections import OrderedDict
from copy import deepcopy
from ipaddress import ip_address, ip_interface
from ..schema import schema
from .base import OpenWrtConverter
and context from other files:
# Path: netjsonconfig/backends/openwrt/schema.py
, which may contain function names, class names, or code. Output only the next line. | _modem_manager_schema = schema['definitions']['modemmanager_interface']['allOf'][0] |
Based on the snippet: <|code_start|># ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'netjsonconfig'
copyright = u'{0}, OpenWISP.org'.format(datetime.date.today().year)
author = u'Federico Capoano'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import os
import shlex
import sys
from netjsonconfig.version import VERSION, get_version
and context (classes, functions, sometimes code) from other files:
# Path: netjsonconfig/version.py
# VERSION = (0, 9, 1, 'final')
#
# def get_version():
# version = '%s.%s' % (VERSION[0], VERSION[1])
# if VERSION[2]:
# version = '%s.%s' % (version, VERSION[2])
# if VERSION[3:] == ('alpha', 0):
# version = '%s pre-alpha' % version
# else:
# if VERSION[3][0:4] == 'post':
# version = '%s.%s' % (version, VERSION[3])
# elif VERSION[3] != 'final':
# try:
# rev = VERSION[4]
# except IndexError:
# rev = 0
# version = '%s%s%s' % (version, VERSION[3][0:1], rev)
# return version
. Output only the next line. | version = '{0}.{1}'.format(VERSION[0], VERSION[1]) |
Continue the code snippet: <|code_start|> 'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'netjsonconfig'
copyright = u'{0}, OpenWISP.org'.format(datetime.date.today().year)
author = u'Federico Capoano'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '{0}.{1}'.format(VERSION[0], VERSION[1])
# The full version, including alpha/beta/rc tags.
<|code_end|>
. Use current file imports:
import datetime
import os
import shlex
import sys
from netjsonconfig.version import VERSION, get_version
and context (classes, functions, or code) from other files:
# Path: netjsonconfig/version.py
# VERSION = (0, 9, 1, 'final')
#
# def get_version():
# version = '%s.%s' % (VERSION[0], VERSION[1])
# if VERSION[2]:
# version = '%s.%s' % (version, VERSION[2])
# if VERSION[3:] == ('alpha', 0):
# version = '%s pre-alpha' % version
# else:
# if VERSION[3][0:4] == 'post':
# version = '%s.%s' % (version, VERSION[3])
# elif VERSION[3] != 'final':
# try:
# rev = VERSION[4]
# except IndexError:
# rev = 0
# version = '%s%s%s' % (version, VERSION[3][0:1], rev)
# return version
. Output only the next line. | release = get_version() |
Here is a snippet: <|code_start|>
vpn_pattern = re.compile('^# wireguard config:\s', flags=re.MULTILINE)
config_pattern = re.compile('^([^\s]*) ?(.*)$')
config_suffix = '.conf'
<|code_end|>
. Write the next line using the current file imports:
import re
from ..base.parser import BaseParser
and context from other files:
# Path: netjsonconfig/backends/base/parser.py
# class BaseParser(object):
# """
# Base Parser class
# Parsers are used to parse a string or tar.gz
# which represents the router configuration
# """
#
# def __init__(self, config):
# if isinstance(config, str):
# data = self.parse_text(config)
# # presence of read() method
# # indicates a file-like object
# elif hasattr(config, 'read'):
# data = self.parse_tar(config)
# else:
# raise ParseError('Unrecognized format')
# self.intermediate_data = data
#
# def parse_text(self, config):
# raise NotImplementedError()
#
# def parse_tar(self, config):
# raise NotImplementedError()
, which may include functions, classes, or code. Output only the next line. | class WireguardParser(BaseParser): |
Next line prediction: <|code_start|>
class TestNetwork(unittest.TestCase, _TabsMixin):
maxDiff = None
_ula_netjson = {"general": {"ula_prefix": "fd8e:f40a:6701::/48"}}
_ula_uci = """package network
config globals 'globals'
option ula_prefix 'fd8e:f40a:6701::/48'
"""
_ula_netjson_id = {
"general": {"ula_prefix": "fd8e:f40a:6701::/48", "globals_id": "arbitrary_id"}
}
_ula_uci_id = """package network
config globals 'arbitrary_id'
option ula_prefix 'fd8e:f40a:6701::/48'
"""
def test_render_ula_prefix(self):
<|code_end|>
. Use current file imports:
(import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.exceptions import ValidationError
from netjsonconfig.utils import _TabsMixin)
and context including class names, function names, or small code snippets from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | o = OpenWrt(self._ula_netjson) |
Predict the next line after this snippet: <|code_start|> "mode": "access_point",
"ssid": "wpa2-personal",
"encryption": {
"protocol": "wpa2_personal",
"cipher": "tkip+ccmp",
"key": "passphrase012345",
},
},
}
]
}
_wpa2_personal_uci = """package network
config interface 'wlan0'
option ifname 'wlan0'
option proto 'none'
package wireless
config wifi-iface 'wifi_wlan0'
option device 'radio0'
option encryption 'psk2+tkip+ccmp'
option ifname 'wlan0'
option key 'passphrase012345'
option mode 'ap'
option network 'wlan0'
option ssid 'wpa2-personal'
"""
def test_render_wpa2_personal(self):
<|code_end|>
using the current file's imports:
import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.utils import _TabsMixin
and any relevant context from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | o = OpenWrt(self._wpa2_personal_netjson) |
Next line prediction: <|code_start|> )
command = (
"netjsonconfig --config '{0}' -b openwrt -m render -a files=False".format(
config
)
)
output = subprocess.check_output(command, shell=True).decode()
self.assertNotIn('test.txt', output)
self.assertNotIn('test_valid_arg', output)
def test_generate_redirection(self):
config = """'{"general": { "hostname": "example" }}'"""
command = (
"""netjsonconfig -c %s -b openwrt -m generate > test.tar.gz""" % config
)
subprocess.check_output(command, shell=True)
tar = tarfile.open(self._test_file, 'r')
self.assertEqual(len(tar.getmembers()), 1)
tar.close()
def test_context(self):
config = json.dumps({'general': {'description': '{{ DESC }}'}})
command = "export DESC=testdesc; netjsonconfig --config '{0}' -b openwrt -m render".format(
config
)
output = subprocess.check_output(command, shell=True).decode()
self.assertNotIn('{{ DESC }}', output)
self.assertIn('testdesc', output)
def test_parse(self):
<|code_end|>
. Use current file imports:
(import json
import os
import subprocess
import tarfile
import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.utils import _TabsMixin)
and context including class names, function names, or small code snippets from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | o = OpenWrt( |
Given the code snippet: <|code_start|> },
"country": {
"type": "string",
"maxLength": 2,
"default": "00",
"enum": list(countries.values()),
"options": {"enum_titles": list(countries.keys())},
"propertyOrder": 7,
},
"disabled": {
"type": "boolean",
"default": False,
"format": "checkbox",
"propertyOrder": 9,
},
},
},
"radio_2ghz_channels": {
"properties": {
"channel": {"enum": channels_2ghz, "options": {"enum_titles": ['auto']}}
}
},
"radio_5ghz_channels": {
"properties": {
"channel": {"enum": channels_5ghz, "options": {"enum_titles": ['auto']}}
}
},
"radio_2and5_channels": {
"properties": {
"channel": {
<|code_end|>
, generate the next line using the imports in this file:
from .channels import channels_2and5, channels_2ghz, channels_5ghz
from .countries import countries
and context (functions, classes, or occasionally code) from other files:
# Path: netjsonconfig/channels.py
#
# Path: netjsonconfig/countries.py
. Output only the next line. | "enum": channels_2and5, |
Here is a snippet: <|code_start|> "phy": {"type": "string", "propertyOrder": 3},
"channel": {"type": "integer", "propertyOrder": 4},
"channel_width": {
"type": "integer",
"title": "channel width (mhz)",
"propertyOrder": 5,
},
"tx_power": {
"type": "integer",
"title": "transmit power (dbm)",
"propertyOrder": 6,
},
"country": {
"type": "string",
"maxLength": 2,
"default": "00",
"enum": list(countries.values()),
"options": {"enum_titles": list(countries.keys())},
"propertyOrder": 7,
},
"disabled": {
"type": "boolean",
"default": False,
"format": "checkbox",
"propertyOrder": 9,
},
},
},
"radio_2ghz_channels": {
"properties": {
<|code_end|>
. Write the next line using the current file imports:
from .channels import channels_2and5, channels_2ghz, channels_5ghz
from .countries import countries
and context from other files:
# Path: netjsonconfig/channels.py
#
# Path: netjsonconfig/countries.py
, which may include functions, classes, or code. Output only the next line. | "channel": {"enum": channels_2ghz, "options": {"enum_titles": ['auto']}} |
Based on the snippet: <|code_start|> "propertyOrder": 5,
},
"tx_power": {
"type": "integer",
"title": "transmit power (dbm)",
"propertyOrder": 6,
},
"country": {
"type": "string",
"maxLength": 2,
"default": "00",
"enum": list(countries.values()),
"options": {"enum_titles": list(countries.keys())},
"propertyOrder": 7,
},
"disabled": {
"type": "boolean",
"default": False,
"format": "checkbox",
"propertyOrder": 9,
},
},
},
"radio_2ghz_channels": {
"properties": {
"channel": {"enum": channels_2ghz, "options": {"enum_titles": ['auto']}}
}
},
"radio_5ghz_channels": {
"properties": {
<|code_end|>
, predict the immediate next line with the help of imports:
from .channels import channels_2and5, channels_2ghz, channels_5ghz
from .countries import countries
and context (classes, functions, sometimes code) from other files:
# Path: netjsonconfig/channels.py
#
# Path: netjsonconfig/countries.py
. Output only the next line. | "channel": {"enum": channels_5ghz, "options": {"enum_titles": ['auto']}} |
Given the following code snippet before the placeholder: <|code_start|> }
},
{"$ref": "#/definitions/base_wireless_settings"},
{"$ref": "#/definitions/mesh_id_wireless_property"},
{"$ref": "#/definitions/encryption_wireless_property_mesh"},
],
},
"base_radio_settings": {
"type": "object",
"additionalProperties": True,
"required": ["protocol", "name", "channel", "channel_width"],
"properties": {
"name": {"type": "string", "propertyOrder": 1, "minLength": 3},
"protocol": {"type": "string", "propertyOrder": 2},
"phy": {"type": "string", "propertyOrder": 3},
"channel": {"type": "integer", "propertyOrder": 4},
"channel_width": {
"type": "integer",
"title": "channel width (mhz)",
"propertyOrder": 5,
},
"tx_power": {
"type": "integer",
"title": "transmit power (dbm)",
"propertyOrder": 6,
},
"country": {
"type": "string",
"maxLength": 2,
"default": "00",
<|code_end|>
, predict the next line using imports from the current file:
from .channels import channels_2and5, channels_2ghz, channels_5ghz
from .countries import countries
and context including class names, function names, and sometimes code from other files:
# Path: netjsonconfig/channels.py
#
# Path: netjsonconfig/countries.py
. Output only the next line. | "enum": list(countries.values()), |
Given the following code snippet before the placeholder: <|code_start|>"""
OpenWrt specific JSON-Schema definition
"""
default_radio_driver = "mac80211"
wireguard = base_wireguard_schema["properties"]["wireguard"]["items"]["properties"]
wireguard_peers = wireguard["peers"]["items"]["properties"]
<|code_end|>
, predict the next line using imports from the current file:
from ...schema import schema as default_schema
from ...utils import merge_config
from ..openvpn.schema import base_openvpn_schema
from ..wireguard.schema import base_wireguard_schema
from .timezones import timezones
and context including class names, function names, and sometimes code from other files:
# Path: netjsonconfig/schema.py
# DEFAULT_FILE_MODE = '0644'
# X509_FILE_MODE = '0600'
# MAC_PATTERN = '([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})'
# MAC_PATTERN_BLANK = '^({0}|)$'.format(MAC_PATTERN)
#
# Path: netjsonconfig/utils.py
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
#
# Path: netjsonconfig/backends/openvpn/schema.py
#
# Path: netjsonconfig/backends/openwrt/timezones.py
. Output only the next line. | interface_settings = default_schema["definitions"]["interface_settings"]["properties"] |
Given the following code snippet before the placeholder: <|code_start|>"""
OpenWrt specific JSON-Schema definition
"""
default_radio_driver = "mac80211"
wireguard = base_wireguard_schema["properties"]["wireguard"]["items"]["properties"]
wireguard_peers = wireguard["peers"]["items"]["properties"]
interface_settings = default_schema["definitions"]["interface_settings"]["properties"]
<|code_end|>
, predict the next line using imports from the current file:
from ...schema import schema as default_schema
from ...utils import merge_config
from ..openvpn.schema import base_openvpn_schema
from ..wireguard.schema import base_wireguard_schema
from .timezones import timezones
and context including class names, function names, and sometimes code from other files:
# Path: netjsonconfig/schema.py
# DEFAULT_FILE_MODE = '0644'
# X509_FILE_MODE = '0600'
# MAC_PATTERN = '([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})'
# MAC_PATTERN_BLANK = '^({0}|)$'.format(MAC_PATTERN)
#
# Path: netjsonconfig/utils.py
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
#
# Path: netjsonconfig/backends/openvpn/schema.py
#
# Path: netjsonconfig/backends/openwrt/timezones.py
. Output only the next line. | schema = merge_config( |
Here is a snippet: <|code_start|> "preshared_key": wireguard_peers["preshared_key"],
"persistent_keepalive": {
"type": "integer",
"title": "keep alive",
"description": (
"Number of second between keepalive "
"messages, 0 means disabled"
),
"default": 0,
"propertyOrder": 6,
},
"route_allowed_ips": {
"type": "boolean",
"format": "checkbox",
"title": "route allowed IPs",
"description": (
"Automatically create a route for "
"each Allowed IPs for this peer"
),
"default": False,
"propertyOrder": 7,
},
},
},
},
},
},
)
# add OpenVPN schema
<|code_end|>
. Write the next line using the current file imports:
from ...schema import schema as default_schema
from ...utils import merge_config
from ..openvpn.schema import base_openvpn_schema
from ..wireguard.schema import base_wireguard_schema
from .timezones import timezones
and context from other files:
# Path: netjsonconfig/schema.py
# DEFAULT_FILE_MODE = '0644'
# X509_FILE_MODE = '0600'
# MAC_PATTERN = '([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})'
# MAC_PATTERN_BLANK = '^({0}|)$'.format(MAC_PATTERN)
#
# Path: netjsonconfig/utils.py
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
#
# Path: netjsonconfig/backends/openvpn/schema.py
#
# Path: netjsonconfig/backends/openwrt/timezones.py
, which may include functions, classes, or code. Output only the next line. | schema = merge_config(schema, base_openvpn_schema) |
Based on the snippet: <|code_start|> "properties": {
"hwmode": {
"type": "string",
"title": "hardware mode",
"readOnly": True,
"propertyOrder": 8,
"default": "11a",
"enum": ["11a"],
}
}
},
"radio_80211gn_settings": {
"allOf": [{"$ref": "#/definitions/radio_hwmode_11g"}]
},
"radio_80211an_settings": {
"allOf": [{"$ref": "#/definitions/radio_hwmode_11a"}]
},
"radio_80211ac_5ghz_settings": {
"allOf": [{"$ref": "#/definitions/radio_hwmode_11a"}]
},
"radio_80211ax_2ghz_settings": {
"allOf": [{"$ref": "#/definitions/radio_hwmode_11g"}]
},
"radio_80211ax_5ghz_settings": {
"allOf": [{"$ref": "#/definitions/radio_hwmode_11a"}]
},
},
"properties": {
"general": {
"properties": {
<|code_end|>
, predict the immediate next line with the help of imports:
from ...schema import schema as default_schema
from ...utils import merge_config
from ..openvpn.schema import base_openvpn_schema
from ..wireguard.schema import base_wireguard_schema
from .timezones import timezones
and context (classes, functions, sometimes code) from other files:
# Path: netjsonconfig/schema.py
# DEFAULT_FILE_MODE = '0644'
# X509_FILE_MODE = '0600'
# MAC_PATTERN = '([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})'
# MAC_PATTERN_BLANK = '^({0}|)$'.format(MAC_PATTERN)
#
# Path: netjsonconfig/utils.py
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
#
# Path: netjsonconfig/backends/openvpn/schema.py
#
# Path: netjsonconfig/backends/openwrt/timezones.py
. Output only the next line. | "timezone": {"enum": list(timezones.keys()), "default": "UTC"} |
Next line prediction: <|code_start|>
class TestFormats(unittest.TestCase, _TabsMixin):
maxDiff = None
def test_general_hostname(self):
<|code_end|>
. Use current file imports:
(import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.exceptions import ValidationError
from netjsonconfig.utils import _TabsMixin)
and context including class names, function names, or small code snippets from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | o = OpenWrt({"general": {"hostname": "invalid hostname"}}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.