Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|> "Number of Object Storage storage zones; this number "
"MUST be no larger than the number of configured "
"storage devices.",
"CONFIG_SWIFT_STORAGE_ZONES",
'1',
validators=[validators.digit]),
Argument("swift-storage-replicas",
"Number of Object Storage storage replicas; this number "
"MUST be no larger than the number of configured "
"storage zones.",
"CONFIG_SWIFT_STORAGE_REPLICAS",
'1',
validators=[validators.digit]),
Argument("swift-hash",
"Custom seed number to use for swift_hash_path_suffix in"
" /etc/swift/swift.conf. If you do not provide a value, "
"a seed number is automatically generated.",
"CONFIG_SWIFT_HASH",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("swift-storage-size",
"Size of the Object Storage loopback file storage "
"device in GB",
"CONFIG_SWIFT_STORAGE_SIZE",
"2",
validators=[validators.digit]),
]
}
for group in conf:
<|code_end|>
. Use current file imports:
import os
import stat
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context (classes, functions, or code) from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Given the code snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
#
# 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.
#
def init_config():
conf = {
"SWIFT": [
<|code_end|>
, generate the next line using the imports in this file:
import os
import stat
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context (functions, classes, or occasionally code) from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | Argument("swift-ks-pw", |
Predict the next line for this snippet: <|code_start|> Argument("swift-storage-replicas",
"Number of Object Storage storage replicas; this number "
"MUST be no larger than the number of configured "
"storage zones.",
"CONFIG_SWIFT_STORAGE_REPLICAS",
'1',
validators=[validators.digit]),
Argument("swift-hash",
"Custom seed number to use for swift_hash_path_suffix in"
" /etc/swift/swift.conf. If you do not provide a value, "
"a seed number is automatically generated.",
"CONFIG_SWIFT_HASH",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("swift-storage-size",
"Size of the Object Storage loopback file storage "
"device in GB",
"CONFIG_SWIFT_STORAGE_SIZE",
"2",
validators=[validators.digit]),
]
}
for group in conf:
Controller.get().add_group(group, conf[group])
def init_sequences():
controller = Controller.get()
conf = controller.CONF
<|code_end|>
with the help of current file imports:
import os
import stat
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
, which may contain function names, class names, or code. Output only the next line. | if util.str2bool(conf['CONFIG_SWIFT_INSTALL']): |
Predict the next line for this snippet: <|code_start|># Copyright (c) 2015 Intel Corporation
#
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"AMQP": [
Argument("amqp-auth-user",
"User for amqp authentication",
"CONFIG_AMQP_AUTH_USER",
"amqp_user",
validators=[validators.not_empty]),
Argument("amqp-auth-pw",
"Password for amqp user authentication",
"CONFIG_AMQP_AUTH_PASSWORD",
<|code_end|>
with the help of current file imports:
from clearstack import utils
from clearstack import validators
from clearstack.argument import Argument
from clearstack.controller import Controller
from clearstack.common import util
and context from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
, which may contain function names, class names, or code. Output only the next line. | utils.generate_random_pw(), |
Based on the snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"AMQP": [
Argument("amqp-auth-user",
"User for amqp authentication",
"CONFIG_AMQP_AUTH_USER",
"amqp_user",
<|code_end|>
, predict the immediate next line with the help of imports:
from clearstack import utils
from clearstack import validators
from clearstack.argument import Argument
from clearstack.controller import Controller
from clearstack.common import util
and context (classes, functions, sometimes code) from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | validators=[validators.not_empty]), |
Given snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"AMQP": [
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clearstack import utils
from clearstack import validators
from clearstack.argument import Argument
from clearstack.controller import Controller
from clearstack.common import util
and context:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
which might include code, classes, or functions. Output only the next line. | Argument("amqp-auth-user", |
Given snippet: <|code_start|># 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.
#
def init_config():
conf = {
"AMQP": [
Argument("amqp-auth-user",
"User for amqp authentication",
"CONFIG_AMQP_AUTH_USER",
"amqp_user",
validators=[validators.not_empty]),
Argument("amqp-auth-pw",
"Password for amqp user authentication",
"CONFIG_AMQP_AUTH_PASSWORD",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("amqp-host",
"The IP address or hostname of the server on which"
" to install the AMQP service",
"CONFIG_AMQP_HOST",
util.get_ip(),
validators=[validators.ip_or_hostname])
]
}
for group in conf:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clearstack import utils
from clearstack import validators
from clearstack.argument import Argument
from clearstack.controller import Controller
from clearstack.common import util
and context:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
which might include code, classes, or functions. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Predict the next line after this 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.
#
def init_config():
conf = {
"AMQP": [
Argument("amqp-auth-user",
"User for amqp authentication",
"CONFIG_AMQP_AUTH_USER",
"amqp_user",
validators=[validators.not_empty]),
Argument("amqp-auth-pw",
"Password for amqp user authentication",
"CONFIG_AMQP_AUTH_PASSWORD",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("amqp-host",
"The IP address or hostname of the server on which"
" to install the AMQP service",
"CONFIG_AMQP_HOST",
<|code_end|>
using the current file's imports:
from clearstack import utils
from clearstack import validators
from clearstack.argument import Argument
from clearstack.controller import Controller
from clearstack.common import util
and any relevant context from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | util.get_ip(), |
Predict the next line after this snippet: <|code_start|> "cirros",
validators=[validators.not_empty]),
Argument("provision-image-url",
'A URL or local file location for an image to download'
'and provision in Glance (defaults to a URL for a '
'recent "cirros" image).',
"CONFIG_PROVISION_IMAGE_URL",
'http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-'
'x86_64-disk.img',
validators=[validators.not_empty])
]
}
for group in conf:
Controller.get().add_group(group, conf[group])
def init_sequences():
controller = Controller.get()
conf = controller.CONF
if util.str2bool(conf['CONFIG_PROVISION_DEMO']):
controller.add_sequence("Running provisioning",
setup_controller)
def setup_controller():
conf = Controller.get().CONF
templates = ['provision']
recipe = ""
for template in templates:
<|code_end|>
using the current file's imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and any relevant context from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | recipe += utils.get_template(template) |
Next line prediction: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Victor Morales <victor.morales@intel.com>
#
# 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.
#
def init_config():
conf = {
"PROVISION_INIT": [
Argument("provision-demo",
"Specify 'y' to provision for demo usage and testing."
" ['y', 'n']",
"CONFIG_PROVISION_DEMO",
"n",
options=['y', 'n'],
<|code_end|>
. Use current file imports:
(from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util)
and context including class names, function names, or small code snippets from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | validators=[validators.y_or_n]) |
Here is a snippet: <|code_start|> ],
"PROVISION_DEMO": [
Argument("provision-demo-floatrange",
"CIDR network address for the floating IP subnet.",
"CONFIG_PROVISION_DEMO_FLOATRANGE",
"172.24.4.224/28",
validators=[validators.cidr]),
Argument("privision-image-format",
'Format for the demo image (default "qcow2").',
"CONFIG_PROVISION_IMAGE_FORMAT",
"qcow2",
validators=[validators.not_empty]),
Argument("provision-image-name",
'The name to be assigned to the demo image in Glance '
'(default "cirros")',
"CONFIG_PROVISION_IMAGE_NAME",
"cirros",
validators=[validators.not_empty]),
Argument("provision-image-url",
'A URL or local file location for an image to download'
'and provision in Glance (defaults to a URL for a '
'recent "cirros" image).',
"CONFIG_PROVISION_IMAGE_URL",
'http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-'
'x86_64-disk.img',
validators=[validators.not_empty])
]
}
for group in conf:
<|code_end|>
. Write the next line using the current file imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
, which may include functions, classes, or code. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Predict the next line for this snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Victor Morales <victor.morales@intel.com>
#
# 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.
#
def init_config():
conf = {
"PROVISION_INIT": [
<|code_end|>
with the help of current file imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
, which may contain function names, class names, or code. Output only the next line. | Argument("provision-demo", |
Given the following code snippet before the placeholder: <|code_start|> validators=[validators.cidr]),
Argument("privision-image-format",
'Format for the demo image (default "qcow2").',
"CONFIG_PROVISION_IMAGE_FORMAT",
"qcow2",
validators=[validators.not_empty]),
Argument("provision-image-name",
'The name to be assigned to the demo image in Glance '
'(default "cirros")',
"CONFIG_PROVISION_IMAGE_NAME",
"cirros",
validators=[validators.not_empty]),
Argument("provision-image-url",
'A URL or local file location for an image to download'
'and provision in Glance (defaults to a URL for a '
'recent "cirros" image).',
"CONFIG_PROVISION_IMAGE_URL",
'http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-'
'x86_64-disk.img',
validators=[validators.not_empty])
]
}
for group in conf:
Controller.get().add_group(group, conf[group])
def init_sequences():
controller = Controller.get()
conf = controller.CONF
<|code_end|>
, predict the next line using imports from the current file:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context including class names, function names, and sometimes code from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | if util.str2bool(conf['CONFIG_PROVISION_DEMO']): |
Given snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Julio Montes <julio.montes@intel.com>
# Author: Victor Morales <victor.morales@intel.com>
#
# 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.
#
class Sequence:
def __init__(self, desc, function, args=None):
self.description = desc
self.function = function
self.function_args = args
def run(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clearstack.common.util import LOG
and context:
# Path: clearstack/common/util.py
# LOG = logging.getLogger("Clearstack")
which might include code, classes, or functions. Output only the next line. | LOG.info(self.description) |
Predict the next line after this snippet: <|code_start|> "KEYSTONE": [
Argument("keystone-db-pw",
"Password for keystone to access DB",
"CONFIG_KEYSTONE_DB_PW",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("keystone-admin-token",
"The token to use for the Keystone service api",
"CONFIG_KEYSTONE_ADMIN_TOKEN",
uuid.uuid4().hex,
validators=[validators.not_empty]),
Argument("keystone-admin-pw",
"The password to use for the Keystone admin user",
"CONFIG_KEYSTONE_ADMIN_PW",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("keystone-demo-pw",
"The password to use for the Keystone demo user",
"CONFIG_KEYSTONE_DEMO_PW",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("keystone-region",
"Region name",
"CONFIG_KEYSTONE_REGION",
"RegionOne",
validators=[validators.not_empty])
]
}
for group in conf:
<|code_end|>
using the current file's imports:
import uuid
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
and any relevant context from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Based on the snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"KEYSTONE": [
<|code_end|>
, predict the immediate next line with the help of imports:
import uuid
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
and context (classes, functions, sometimes code) from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
. Output only the next line. | Argument("keystone-db-pw", |
Given the code snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"KEYSTONE": [
Argument("keystone-db-pw",
"Password for keystone to access DB",
"CONFIG_KEYSTONE_DB_PW",
<|code_end|>
, generate the next line using the imports in this file:
import uuid
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
and context (functions, classes, or occasionally code) from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
. Output only the next line. | utils.generate_random_pw(), |
Given the following code snippet before the placeholder: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"KEYSTONE": [
Argument("keystone-db-pw",
"Password for keystone to access DB",
"CONFIG_KEYSTONE_DB_PW",
utils.generate_random_pw(),
<|code_end|>
, predict the next line using imports from the current file:
import uuid
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
and context including class names, function names, and sometimes code from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
. Output only the next line. | validators=[validators.not_empty]), |
Here is a snippet: <|code_start|># 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.
#
def init_config():
conf = {
"MARIADB": [
Argument("mariadb-host",
"The IP address or hostname of the MariaDB server",
"CONFIG_MARIADB_HOST",
util.get_ip(),
validators=[validators.ip_or_hostname]),
Argument("mariadb-user",
"User for mariadb authentication",
"CONFIG_MARIADB_USER",
"root",
validators=[validators.not_empty]),
Argument("mariadb-pw",
"Password for mariadb user",
"CONFIG_MARIADB_PW",
utils.generate_random_pw(),
validators=[validators.not_empty])
]
}
for group in conf:
<|code_end|>
. Write the next line using the current file imports:
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
from clearstack.common import util
and context from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
, which may include functions, classes, or code. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Predict the next line after this snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"MARIADB": [
<|code_end|>
using the current file's imports:
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
from clearstack.common import util
and any relevant context from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | Argument("mariadb-host", |
Predict the next line after this snippet: <|code_start|># 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.
#
def init_config():
conf = {
"MARIADB": [
Argument("mariadb-host",
"The IP address or hostname of the MariaDB server",
"CONFIG_MARIADB_HOST",
util.get_ip(),
validators=[validators.ip_or_hostname]),
Argument("mariadb-user",
"User for mariadb authentication",
"CONFIG_MARIADB_USER",
"root",
validators=[validators.not_empty]),
Argument("mariadb-pw",
"Password for mariadb user",
"CONFIG_MARIADB_PW",
<|code_end|>
using the current file's imports:
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
from clearstack.common import util
and any relevant context from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | utils.generate_random_pw(), |
Given snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"MARIADB": [
Argument("mariadb-host",
"The IP address or hostname of the MariaDB server",
"CONFIG_MARIADB_HOST",
util.get_ip(),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
from clearstack.common import util
and context:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
which might include code, classes, or functions. Output only the next line. | validators=[validators.ip_or_hostname]), |
Continue the code snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"MARIADB": [
Argument("mariadb-host",
"The IP address or hostname of the MariaDB server",
"CONFIG_MARIADB_HOST",
<|code_end|>
. Use current file imports:
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
from clearstack.common import util
and context (classes, functions, or code) from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | util.get_ip(), |
Given the code snippet: <|code_start|> except AttributeError:
LOG.debug("missing attribute: init_config in %s",
plugin.__file__)
def add_arguments(parser):
load_plugins()
for group in Controller.get().get_all_groups():
for argument in group.get_all_arguments():
parser.add_argument("--{0}".format(argument.cmd_option),
action="store",
dest=argument.conf_name,
help=argument.description,
choices=argument.option_list)
def load_sequences():
load_plugins()
for plugin in Controller.get().get_all_plugins():
try:
getattr(plugin, "init_sequences")()
except AttributeError:
LOG.debug("missing attribute: init_sequences in %s",
plugin.__file__)
def run_all_sequences():
load_sequences()
try:
<|code_end|>
, generate the next line using the imports in this file:
import re
import os
from importlib import import_module
from clearstack import utils
from clearstack.controller import Controller
from clearstack.common.util import LOG
and context (functions, classes, or occasionally code) from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/common/util.py
# LOG = logging.getLogger("Clearstack")
. Output only the next line. | utils.copy_resources() |
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.
#
def load_plugins():
""" return if plugins already are loaded """
if Controller.get().get_all_plugins():
return
path = "plugins"
base_module = "clearstack.{0}".format(path)
directory = "{0}/{1}".format(os.path.dirname(
os.path.realpath(__file__)), path)
rx_val = r'^[a-zA-Z]+_[0-9]{3}\.py$'
files = [fd for fd in os.listdir(directory) if re.match(rx_val, fd)]
for fd in sorted(files, key=_get_weight):
plugin = import_module("{0}.{1}".format(base_module, fd.split(".")[0]))
Controller.get().add_plugin(plugin)
try:
getattr(plugin, "init_config")()
except AttributeError:
<|code_end|>
. Use current file imports:
import re
import os
from importlib import import_module
from clearstack import utils
from clearstack.controller import Controller
from clearstack.common.util import LOG
and context (classes, functions, or code) from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/common/util.py
# LOG = logging.getLogger("Clearstack")
. Output only the next line. | LOG.debug("missing attribute: init_config in %s", |
Given the following code snippet before the placeholder: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Julio Montes <julio.montes@intel.com>
# Author: Victor Morales <victor.morales@intel.com>
#
# 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.
#
@Singleton
class AnswerFile:
def generate(self, file, variables_cmd):
with open(file, "w") as f:
f.write("[general]\n\n")
<|code_end|>
, predict the next line using imports from the current file:
import os
import configparser
from clearstack.controller import Controller
from clearstack.common.util import LOG
from clearstack.common.singleton import Singleton
and context including class names, function names, and sometimes code from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/common/util.py
# LOG = logging.getLogger("Clearstack")
#
# Path: clearstack/common/singleton.py
# class Singleton:
# def __init__(self, decorated):
# self._decorated = decorated
#
# def get(self):
# try:
# return self._instance
# except AttributeError:
# self._instance = self._decorated()
# return self._instance
#
# def __call__(self):
# raise TypeError('Singletons must be accessed through `Get()`.')
#
# def __instancecheck__(self, inst):
# return isinstance(inst, self._decorated)
. Output only the next line. | for group in Controller.get().get_all_groups(): |
Predict the next line for this snippet: <|code_start|> for group in Controller.get().get_all_groups():
for argument in group.get_all_arguments():
f.write("# {0}\n".format(argument.description))
value = variables_cmd.get(argument.conf_name,
argument.default_value)
f.write("{0}={1}\n\n".format(argument.conf_name, value))
def read(self, file, variables_cmd):
conf = Controller.get().CONF
config = configparser.RawConfigParser()
config.optionxform = str
if not os.path.isfile(file):
raise IOError("file {0} not found".format(file))
""" Validate option in answer file"""
config.read(file)
if not config.has_section('general'):
raise KeyError("answer file {0} doesn't have general"
" section".format(file))
conf_file = dict(config['general'])
conf_file.update(variables_cmd) # override variables
conf.update(conf_file)
try:
Controller.get().validate_groups(conf_file)
except Exception as e:
raise e
all_args = Controller.get().get_all_arguments()
for non_supported in (set(conf_file) - set(all_args)):
<|code_end|>
with the help of current file imports:
import os
import configparser
from clearstack.controller import Controller
from clearstack.common.util import LOG
from clearstack.common.singleton import Singleton
and context from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/common/util.py
# LOG = logging.getLogger("Clearstack")
#
# Path: clearstack/common/singleton.py
# class Singleton:
# def __init__(self, decorated):
# self._decorated = decorated
#
# def get(self):
# try:
# return self._instance
# except AttributeError:
# self._instance = self._decorated()
# return self._instance
#
# def __call__(self):
# raise TypeError('Singletons must be accessed through `Get()`.')
#
# def __instancecheck__(self, inst):
# return isinstance(inst, self._decorated)
, which may contain function names, class names, or code. Output only the next line. | LOG.warn("clearstack: variable {0} is not" |
Continue the code snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"GLANCE": [
Argument("glance-db-pw",
"Password for glance to access DB",
"CONFIG_GLANCE_DB_PW",
<|code_end|>
. Use current file imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context (classes, functions, or code) from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | utils.generate_random_pw(), |
Given the following code snippet before the placeholder: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"GLANCE": [
Argument("glance-db-pw",
"Password for glance to access DB",
"CONFIG_GLANCE_DB_PW",
utils.generate_random_pw(),
<|code_end|>
, predict the next line using imports from the current file:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context including class names, function names, and sometimes code from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | validators=[validators.not_empty]), |
Given the following code snippet before the placeholder: <|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.
#
def init_config():
conf = {
"GLANCE": [
Argument("glance-db-pw",
"Password for glance to access DB",
"CONFIG_GLANCE_DB_PW",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("glance-ks-pw",
"Password to use for Glance to"
" authenticate with Keystone",
"CONFIG_GLANCE_KS_PW",
utils.generate_random_pw(),
validators=[validators.not_empty])
]
}
for group in conf:
<|code_end|>
, predict the next line using imports from the current file:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context including class names, function names, and sometimes code from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Based on the snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"GLANCE": [
<|code_end|>
, predict the immediate next line with the help of imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context (classes, functions, sometimes code) from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | Argument("glance-db-pw", |
Here is a snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
#
def init_config():
conf = {
"GLANCE": [
Argument("glance-db-pw",
"Password for glance to access DB",
"CONFIG_GLANCE_DB_PW",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("glance-ks-pw",
"Password to use for Glance to"
" authenticate with Keystone",
"CONFIG_GLANCE_KS_PW",
utils.generate_random_pw(),
validators=[validators.not_empty])
]
}
for group in conf:
Controller.get().add_group(group, conf[group])
def init_sequences():
controller = Controller.get()
conf = controller.CONF
<|code_end|>
. Write the next line using the current file imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
, which may include functions, classes, or code. Output only the next line. | if util.str2bool(conf['CONFIG_GLANCE_INSTALL']): |
Here is a 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.
#
conf = {'COMPONENT': [Argument('argument',
'description',
'CONFIG_ARGUMET',
'secure')]}
for group in conf:
Controller.get().add_group(group, conf[group])
class AnswerFileTest(testtools.TestCase):
def setUp(self):
super(AnswerFileTest, self).setUp()
def test_generate_file(self):
m = mock.mock_open()
filename = '/tmp/clearstack.answerfile'
with mock.patch('clearstack.answer_file.open', m, create=True):
<|code_end|>
. Write the next line using the current file imports:
import mock
import testtools
from clearstack.answer_file import AnswerFile
from clearstack.argument import Argument
from clearstack.controller import Controller
and context from other files:
# Path: clearstack/answer_file.py
# class AnswerFile:
# def generate(self, file, variables_cmd):
# with open(file, "w") as f:
# f.write("[general]\n\n")
# for group in Controller.get().get_all_groups():
# for argument in group.get_all_arguments():
# f.write("# {0}\n".format(argument.description))
# value = variables_cmd.get(argument.conf_name,
# argument.default_value)
# f.write("{0}={1}\n\n".format(argument.conf_name, value))
#
# def read(self, file, variables_cmd):
# conf = Controller.get().CONF
# config = configparser.RawConfigParser()
# config.optionxform = str
# if not os.path.isfile(file):
# raise IOError("file {0} not found".format(file))
#
# """ Validate option in answer file"""
# config.read(file)
# if not config.has_section('general'):
# raise KeyError("answer file {0} doesn't have general"
# " section".format(file))
# conf_file = dict(config['general'])
# conf_file.update(variables_cmd) # override variables
# conf.update(conf_file)
#
# try:
# Controller.get().validate_groups(conf_file)
# except Exception as e:
# raise e
#
# all_args = Controller.get().get_all_arguments()
# for non_supported in (set(conf_file) - set(all_args)):
# LOG.warn("clearstack: variable {0} is not"
# " supported yet".format(non_supported))
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
, which may include functions, classes, or code. Output only the next line. | AnswerFile.get().generate(filename, {}) |
Based on the snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Julio Montes <julio.montes@intel.com>
# Author: Victor Morales <victor.morales@intel.com>
#
# 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.
#
conf = {'COMPONENT': [Argument('argument',
'description',
'CONFIG_ARGUMET',
'secure')]}
for group in conf:
<|code_end|>
, predict the immediate next line with the help of imports:
import mock
import testtools
from clearstack.answer_file import AnswerFile
from clearstack.argument import Argument
from clearstack.controller import Controller
and context (classes, functions, sometimes code) from other files:
# Path: clearstack/answer_file.py
# class AnswerFile:
# def generate(self, file, variables_cmd):
# with open(file, "w") as f:
# f.write("[general]\n\n")
# for group in Controller.get().get_all_groups():
# for argument in group.get_all_arguments():
# f.write("# {0}\n".format(argument.description))
# value = variables_cmd.get(argument.conf_name,
# argument.default_value)
# f.write("{0}={1}\n\n".format(argument.conf_name, value))
#
# def read(self, file, variables_cmd):
# conf = Controller.get().CONF
# config = configparser.RawConfigParser()
# config.optionxform = str
# if not os.path.isfile(file):
# raise IOError("file {0} not found".format(file))
#
# """ Validate option in answer file"""
# config.read(file)
# if not config.has_section('general'):
# raise KeyError("answer file {0} doesn't have general"
# " section".format(file))
# conf_file = dict(config['general'])
# conf_file.update(variables_cmd) # override variables
# conf.update(conf_file)
#
# try:
# Controller.get().validate_groups(conf_file)
# except Exception as e:
# raise e
#
# all_args = Controller.get().get_all_arguments()
# for non_supported in (set(conf_file) - set(all_args)):
# LOG.warn("clearstack: variable {0} is not"
# " supported yet".format(non_supported))
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Given the following code snippet before the placeholder: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Julio Montes <julio.montes@intel.com>
# Author: Victor Morales <victor.morales@intel.com>
#
# 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.
#
class ShellTest(testtools.TestCase):
def setUp(self):
super(ShellTest, self).setUp()
def test_help(self):
required = 'usage:'
<|code_end|>
, predict the next line using imports from the current file:
import testtools
from testtools import matchers
from clearstack.tests import utils
and context including class names, function names, and sometimes code from other files:
# Path: clearstack/tests/utils.py
# def shell(argstr):
. Output only the next line. | help_text = utils.shell('--help') |
Continue the code snippet: <|code_start|>#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
#
# 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.
#
def init_config():
conf = {
"MONGODB": [
Argument("mongodb-host",
"The IP address or hostname of the MongoDB server",
"CONFIG_MONGODB_HOST",
util.get_ip(),
validators=[validators.ip_or_hostname])
]
}
for group in conf:
<|code_end|>
. Use current file imports:
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
from clearstack.common import util
and context (classes, functions, or code) from other files:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Given snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
#
# 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.
#
def init_config():
conf = {
"MONGODB": [
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
from clearstack.common import util
and context:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
which might include code, classes, or functions. Output only the next line. | Argument("mongodb-host", |
Given snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
#
def init_config():
conf = {
"MONGODB": [
Argument("mongodb-host",
"The IP address or hostname of the MongoDB server",
"CONFIG_MONGODB_HOST",
util.get_ip(),
validators=[validators.ip_or_hostname])
]
}
for group in conf:
Controller.get().add_group(group, conf[group])
def init_sequences():
controller = Controller.get()
conf = controller.CONF
if util.str2bool(conf['CONFIG_CEILOMETER_INSTALL']):
controller.add_sequence("Setting up MongoDB", setup_mongodb)
def setup_mongodb():
conf = Controller.get().CONF
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
from clearstack.common import util
and context:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
which might include code, classes, or functions. Output only the next line. | recipe = utils.get_template('mongodb') |
Given snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
#
# 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.
#
def init_config():
conf = {
"MONGODB": [
Argument("mongodb-host",
"The IP address or hostname of the MongoDB server",
"CONFIG_MONGODB_HOST",
util.get_ip(),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
from clearstack.common import util
and context:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
which might include code, classes, or functions. Output only the next line. | validators=[validators.ip_or_hostname]) |
Given snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
#
# 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.
#
def init_config():
conf = {
"MONGODB": [
Argument("mongodb-host",
"The IP address or hostname of the MongoDB server",
"CONFIG_MONGODB_HOST",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack import utils
from clearstack import validators
from clearstack.common import util
and context:
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
which might include code, classes, or functions. Output only the next line. | util.get_ip(), |
Given the following code snippet before the placeholder: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def shell(argstr):
orig = sys.stdout
clean_env = {}
_old_env, os.environ = os.environ, clean_env.copy()
try:
sys.stdout = io.StringIO()
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import io
from clearstack import shell as clearstack_shell
and context including class names, function names, and sometimes code from other files:
# Path: clearstack/shell.py
# class ClearstackConfiguratorShell(object):
# def get_base_parser(self):
# def main(self, argv):
# def do_help(self, args):
# def main():
. Output only the next line. | _shell = clearstack_shell.ClearstackConfiguratorShell() |
Given the following code snippet before the placeholder: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"NOVA": [
Argument("nova-db-pw",
"Password for nova to access DB",
"CONFIG_NOVA_DB_PW",
<|code_end|>
, predict the next line using imports from the current file:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context including class names, function names, and sometimes code from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | utils.generate_random_pw(), |
Predict the next line after this snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"NOVA": [
Argument("nova-db-pw",
"Password for nova to access DB",
"CONFIG_NOVA_DB_PW",
utils.generate_random_pw(),
<|code_end|>
using the current file's imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and any relevant context from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | validators=[validators.not_empty]), |
Given the following code snippet before the placeholder: <|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.
#
def init_config():
conf = {
"NOVA": [
Argument("nova-db-pw",
"Password for nova to access DB",
"CONFIG_NOVA_DB_PW",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("nova-ks-pw",
"Password to use for the Nova to"
" authenticate with Keystone",
"CONFIG_NOVA_KS_PW",
utils.generate_random_pw(),
validators=[validators.not_empty])
]
}
for group in conf:
<|code_end|>
, predict the next line using imports from the current file:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context including class names, function names, and sometimes code from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Based on the snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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.
#
def init_config():
conf = {
"NOVA": [
<|code_end|>
, predict the immediate next line with the help of imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context (classes, functions, sometimes code) from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | Argument("nova-db-pw", |
Predict the next line for this snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
#
def init_config():
conf = {
"NOVA": [
Argument("nova-db-pw",
"Password for nova to access DB",
"CONFIG_NOVA_DB_PW",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("nova-ks-pw",
"Password to use for the Nova to"
" authenticate with Keystone",
"CONFIG_NOVA_KS_PW",
utils.generate_random_pw(),
validators=[validators.not_empty])
]
}
for group in conf:
Controller.get().add_group(group, conf[group])
def init_sequences():
controller = Controller.get()
conf = controller.CONF
<|code_end|>
with the help of current file imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
, which may contain function names, class names, or code. Output only the next line. | if util.str2bool(conf['CONFIG_NOVA_INSTALL']): |
Based on the snippet: <|code_start|>
return parser
def main(self, argv):
self.parser = self.get_base_parser()
run_setup.add_arguments(self.parser)
(options, args) = self.parser.parse_known_args(argv)
utils.setup_debugging(options.debug)
LOG.debug('Starting clearstack')
if not argv or options.help:
self.do_help(options)
return 0
if options.gen_keys:
LOG.debug('generating ssh keys')
utils.generate_ssh_keys(options.gen_keys)
# todo: fix
# if options.allinone:
# LOG.debug('testing root access')
# if os.geteuid() != 0:
# LOG.error("clearstack: error: you need to have root access")
# sys.exit(1)
""" Save user's variables, used to read/write answerfile """
variables_cmd = {k: v for (k, v) in options.__dict__.items()
if v is not None and k.startswith("CONFIG_")}
<|code_end|>
, predict the immediate next line with the help of imports:
import argparse
import sys
import clearstack
from clearstack.answer_file import AnswerFile
from clearstack import run_setup
from clearstack import utils
from clearstack.common.util import LOG
and context (classes, functions, sometimes code) from other files:
# Path: clearstack/answer_file.py
# class AnswerFile:
# def generate(self, file, variables_cmd):
# with open(file, "w") as f:
# f.write("[general]\n\n")
# for group in Controller.get().get_all_groups():
# for argument in group.get_all_arguments():
# f.write("# {0}\n".format(argument.description))
# value = variables_cmd.get(argument.conf_name,
# argument.default_value)
# f.write("{0}={1}\n\n".format(argument.conf_name, value))
#
# def read(self, file, variables_cmd):
# conf = Controller.get().CONF
# config = configparser.RawConfigParser()
# config.optionxform = str
# if not os.path.isfile(file):
# raise IOError("file {0} not found".format(file))
#
# """ Validate option in answer file"""
# config.read(file)
# if not config.has_section('general'):
# raise KeyError("answer file {0} doesn't have general"
# " section".format(file))
# conf_file = dict(config['general'])
# conf_file.update(variables_cmd) # override variables
# conf.update(conf_file)
#
# try:
# Controller.get().validate_groups(conf_file)
# except Exception as e:
# raise e
#
# all_args = Controller.get().get_all_arguments()
# for non_supported in (set(conf_file) - set(all_args)):
# LOG.warn("clearstack: variable {0} is not"
# " supported yet".format(non_supported))
#
# Path: clearstack/run_setup.py
# def load_plugins():
# def add_arguments(parser):
# def load_sequences():
# def run_all_sequences():
# def generate_admin_openrc():
# def _get_weight(item):
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/common/util.py
# LOG = logging.getLogger("Clearstack")
. Output only the next line. | ansfile = AnswerFile.get() |
Here is a snippet: <|code_start|>
parser.add_argument('--version',
action='version',
version=clearstack.__version__,
help="Shows the client version and exits.")
parser.add_argument('-d',
'--debug',
action='store_true',
help="Enable debug mode in clearstack")
parser.add_argument('--gen-answer-file',
action='store',
dest='gen_answer_file',
help='Generate an answer file')
parser.add_argument('--answer-file',
action='store',
dest='answer_file',
help='Read answer file')
parser.add_argument('--gen-keys',
action='store',
dest='gen_keys',
help='Generate ssh keys')
return parser
def main(self, argv):
self.parser = self.get_base_parser()
<|code_end|>
. Write the next line using the current file imports:
import argparse
import sys
import clearstack
from clearstack.answer_file import AnswerFile
from clearstack import run_setup
from clearstack import utils
from clearstack.common.util import LOG
and context from other files:
# Path: clearstack/answer_file.py
# class AnswerFile:
# def generate(self, file, variables_cmd):
# with open(file, "w") as f:
# f.write("[general]\n\n")
# for group in Controller.get().get_all_groups():
# for argument in group.get_all_arguments():
# f.write("# {0}\n".format(argument.description))
# value = variables_cmd.get(argument.conf_name,
# argument.default_value)
# f.write("{0}={1}\n\n".format(argument.conf_name, value))
#
# def read(self, file, variables_cmd):
# conf = Controller.get().CONF
# config = configparser.RawConfigParser()
# config.optionxform = str
# if not os.path.isfile(file):
# raise IOError("file {0} not found".format(file))
#
# """ Validate option in answer file"""
# config.read(file)
# if not config.has_section('general'):
# raise KeyError("answer file {0} doesn't have general"
# " section".format(file))
# conf_file = dict(config['general'])
# conf_file.update(variables_cmd) # override variables
# conf.update(conf_file)
#
# try:
# Controller.get().validate_groups(conf_file)
# except Exception as e:
# raise e
#
# all_args = Controller.get().get_all_arguments()
# for non_supported in (set(conf_file) - set(all_args)):
# LOG.warn("clearstack: variable {0} is not"
# " supported yet".format(non_supported))
#
# Path: clearstack/run_setup.py
# def load_plugins():
# def add_arguments(parser):
# def load_sequences():
# def run_all_sequences():
# def generate_admin_openrc():
# def _get_weight(item):
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/common/util.py
# LOG = logging.getLogger("Clearstack")
, which may include functions, classes, or code. Output only the next line. | run_setup.add_arguments(self.parser) |
Predict the next line after this snippet: <|code_start|> action='version',
version=clearstack.__version__,
help="Shows the client version and exits.")
parser.add_argument('-d',
'--debug',
action='store_true',
help="Enable debug mode in clearstack")
parser.add_argument('--gen-answer-file',
action='store',
dest='gen_answer_file',
help='Generate an answer file')
parser.add_argument('--answer-file',
action='store',
dest='answer_file',
help='Read answer file')
parser.add_argument('--gen-keys',
action='store',
dest='gen_keys',
help='Generate ssh keys')
return parser
def main(self, argv):
self.parser = self.get_base_parser()
run_setup.add_arguments(self.parser)
(options, args) = self.parser.parse_known_args(argv)
<|code_end|>
using the current file's imports:
import argparse
import sys
import clearstack
from clearstack.answer_file import AnswerFile
from clearstack import run_setup
from clearstack import utils
from clearstack.common.util import LOG
and any relevant context from other files:
# Path: clearstack/answer_file.py
# class AnswerFile:
# def generate(self, file, variables_cmd):
# with open(file, "w") as f:
# f.write("[general]\n\n")
# for group in Controller.get().get_all_groups():
# for argument in group.get_all_arguments():
# f.write("# {0}\n".format(argument.description))
# value = variables_cmd.get(argument.conf_name,
# argument.default_value)
# f.write("{0}={1}\n\n".format(argument.conf_name, value))
#
# def read(self, file, variables_cmd):
# conf = Controller.get().CONF
# config = configparser.RawConfigParser()
# config.optionxform = str
# if not os.path.isfile(file):
# raise IOError("file {0} not found".format(file))
#
# """ Validate option in answer file"""
# config.read(file)
# if not config.has_section('general'):
# raise KeyError("answer file {0} doesn't have general"
# " section".format(file))
# conf_file = dict(config['general'])
# conf_file.update(variables_cmd) # override variables
# conf.update(conf_file)
#
# try:
# Controller.get().validate_groups(conf_file)
# except Exception as e:
# raise e
#
# all_args = Controller.get().get_all_arguments()
# for non_supported in (set(conf_file) - set(all_args)):
# LOG.warn("clearstack: variable {0} is not"
# " supported yet".format(non_supported))
#
# Path: clearstack/run_setup.py
# def load_plugins():
# def add_arguments(parser):
# def load_sequences():
# def run_all_sequences():
# def generate_admin_openrc():
# def _get_weight(item):
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/common/util.py
# LOG = logging.getLogger("Clearstack")
. Output only the next line. | utils.setup_debugging(options.debug) |
Predict the next line after this snippet: <|code_start|> help="Shows the client version and exits.")
parser.add_argument('-d',
'--debug',
action='store_true',
help="Enable debug mode in clearstack")
parser.add_argument('--gen-answer-file',
action='store',
dest='gen_answer_file',
help='Generate an answer file')
parser.add_argument('--answer-file',
action='store',
dest='answer_file',
help='Read answer file')
parser.add_argument('--gen-keys',
action='store',
dest='gen_keys',
help='Generate ssh keys')
return parser
def main(self, argv):
self.parser = self.get_base_parser()
run_setup.add_arguments(self.parser)
(options, args) = self.parser.parse_known_args(argv)
utils.setup_debugging(options.debug)
<|code_end|>
using the current file's imports:
import argparse
import sys
import clearstack
from clearstack.answer_file import AnswerFile
from clearstack import run_setup
from clearstack import utils
from clearstack.common.util import LOG
and any relevant context from other files:
# Path: clearstack/answer_file.py
# class AnswerFile:
# def generate(self, file, variables_cmd):
# with open(file, "w") as f:
# f.write("[general]\n\n")
# for group in Controller.get().get_all_groups():
# for argument in group.get_all_arguments():
# f.write("# {0}\n".format(argument.description))
# value = variables_cmd.get(argument.conf_name,
# argument.default_value)
# f.write("{0}={1}\n\n".format(argument.conf_name, value))
#
# def read(self, file, variables_cmd):
# conf = Controller.get().CONF
# config = configparser.RawConfigParser()
# config.optionxform = str
# if not os.path.isfile(file):
# raise IOError("file {0} not found".format(file))
#
# """ Validate option in answer file"""
# config.read(file)
# if not config.has_section('general'):
# raise KeyError("answer file {0} doesn't have general"
# " section".format(file))
# conf_file = dict(config['general'])
# conf_file.update(variables_cmd) # override variables
# conf.update(conf_file)
#
# try:
# Controller.get().validate_groups(conf_file)
# except Exception as e:
# raise e
#
# all_args = Controller.get().get_all_arguments()
# for non_supported in (set(conf_file) - set(all_args)):
# LOG.warn("clearstack: variable {0} is not"
# " supported yet".format(non_supported))
#
# Path: clearstack/run_setup.py
# def load_plugins():
# def add_arguments(parser):
# def load_sequences():
# def run_all_sequences():
# def generate_admin_openrc():
# def _get_weight(item):
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/common/util.py
# LOG = logging.getLogger("Clearstack")
. Output only the next line. | LOG.debug('Starting clearstack') |
Predict the next line after this snippet: <|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.
#
class ModulesUtilTest(testtools.TestCase):
def setUp(self):
super(ModulesUtilTest, self).setUp()
# # Test if run_command is hidden debug logs
# def test_0000_run_command(self):
# util.setup_debugging(True, False)
# util.run_command("echo", debug=False)
# logging.StreamHandler().close()
# self.assertEqual("echo" in open(self.log_file).read(), False)
# # Test if run_command is showing debug logs
# def test_0001_run_command(self):
# util.setup_debugging(True, False)
# util.run_command("echo")
# logging.StreamHandler().close()
# self.assertEqual("echo" in open(self.log_file).read(), True)
# Test command not found
def test_0002_run_command(self):
<|code_end|>
using the current file's imports:
import testtools
from clearstack.common import util
and any relevant context from other files:
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | self.assertRaises(Exception, util.run_command, "inexistente") |
Given snippet: <|code_start|>#
DEBUG = False
@Singleton
class Controller:
CONF = {}
_plugins = []
_groups = []
_sequences = []
def add_sequence(self, desc, function, args=None):
self._sequences.append(Sequence(desc, function, args))
def run_all_sequences(self):
for seq in self._sequences:
try:
seq.run()
except Exception as e:
raise e
def add_plugin(self, plugin):
self._plugins.append(plugin)
def get_all_plugins(self):
return self._plugins
def add_group(self, name, args):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from clearstack.group import Group
from clearstack.sequence import Sequence
from clearstack.common.singleton import Singleton
and context:
# Path: clearstack/group.py
# class Group(object):
# def __init__(self, group_name, arguments):
# self.group_name = group_name
# self.arguments = arguments
#
# def get_group_name(self):
# return self.group_name
#
# def get_all_arguments(self):
# return self.arguments
#
# Path: clearstack/sequence.py
# class Sequence:
# def __init__(self, desc, function, args=None):
# self.description = desc
# self.function = function
# self.function_args = args
#
# def run(self):
# LOG.info(self.description)
# if self.function_args:
# if not self.function(*self.function_args):
# raise Exception("error running {0}({1})"
# .format(self.function.__name__,
# self.function_args))
# else:
# if not self.function():
# raise Exception("error running {0}"
# .format(self.function.__name__))
#
# Path: clearstack/common/singleton.py
# class Singleton:
# def __init__(self, decorated):
# self._decorated = decorated
#
# def get(self):
# try:
# return self._instance
# except AttributeError:
# self._instance = self._decorated()
# return self._instance
#
# def __call__(self):
# raise TypeError('Singletons must be accessed through `Get()`.')
#
# def __instancecheck__(self, inst):
# return isinstance(inst, self._decorated)
which might include code, classes, or functions. Output only the next line. | self._groups.append(Group(name, args)) |
Next line prediction: <|code_start|># Copyright (c) 2015 Intel Corporation
#
# Author: Julio Montes <julio.montes@intel.com>
# Author: Victor Morales <victor.morales@intel.com>
#
# 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.
#
DEBUG = False
@Singleton
class Controller:
CONF = {}
_plugins = []
_groups = []
_sequences = []
def add_sequence(self, desc, function, args=None):
<|code_end|>
. Use current file imports:
(from clearstack.group import Group
from clearstack.sequence import Sequence
from clearstack.common.singleton import Singleton)
and context including class names, function names, or small code snippets from other files:
# Path: clearstack/group.py
# class Group(object):
# def __init__(self, group_name, arguments):
# self.group_name = group_name
# self.arguments = arguments
#
# def get_group_name(self):
# return self.group_name
#
# def get_all_arguments(self):
# return self.arguments
#
# Path: clearstack/sequence.py
# class Sequence:
# def __init__(self, desc, function, args=None):
# self.description = desc
# self.function = function
# self.function_args = args
#
# def run(self):
# LOG.info(self.description)
# if self.function_args:
# if not self.function(*self.function_args):
# raise Exception("error running {0}({1})"
# .format(self.function.__name__,
# self.function_args))
# else:
# if not self.function():
# raise Exception("error running {0}"
# .format(self.function.__name__))
#
# Path: clearstack/common/singleton.py
# class Singleton:
# def __init__(self, decorated):
# self._decorated = decorated
#
# def get(self):
# try:
# return self._instance
# except AttributeError:
# self._instance = self._decorated()
# return self._instance
#
# def __call__(self):
# raise TypeError('Singletons must be accessed through `Get()`.')
#
# def __instancecheck__(self, inst):
# return isinstance(inst, self._decorated)
. Output only the next line. | self._sequences.append(Sequence(desc, function, args)) |
Next line prediction: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
#
# 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.
#
def init_config():
conf = {
"HEAT": [
Argument("heat-db-pw",
"Password for heat to access DB",
"CONFIG_HEAT_DB_PW",
<|code_end|>
. Use current file imports:
(from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util)
and context including class names, function names, or small code snippets from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | utils.generate_random_pw(), |
Using the snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
#
# 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.
#
def init_config():
conf = {
"HEAT": [
Argument("heat-db-pw",
"Password for heat to access DB",
"CONFIG_HEAT_DB_PW",
utils.generate_random_pw(),
<|code_end|>
, determine the next line of code. You have imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context (class names, function names, or code) available:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | validators=[validators.not_empty]), |
Here is a snippet: <|code_start|> "CONFIG_HEAT_DB_PW",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("heat-ks-pw",
"Password to use for Heat to"
" authenticate with Keystone",
"CONFIG_HEAT_KS_PW",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("heat-domain",
"Name of the Identity domain for Orchestration.",
"CONFIG_HEAT_DOMAIN",
"heat",
validators=[validators.not_empty]),
Argument("heat-domain-admin",
"Name of the Identity domain administrative user for "
"Orchestration.",
"CONFIG_HEAT_DOMAIN_ADMIN",
"heat_domain_admin",
validators=[validators.not_empty]),
Argument("heat-domain-password",
"Password for the Identity domain administrative user "
"for Orchestration",
"CONFIG_HEAT_DOMAIN_PASSWORD",
utils.generate_random_pw(),
validators=[validators.not_empty])
]
}
for group in conf:
<|code_end|>
. Write the next line using the current file imports:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
, which may include functions, classes, or code. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Next line prediction: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
#
# 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.
#
def init_config():
conf = {
"HEAT": [
<|code_end|>
. Use current file imports:
(from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util)
and context including class names, function names, or small code snippets from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | Argument("heat-db-pw", |
Given the code snippet: <|code_start|> "CONFIG_HEAT_KS_PW",
utils.generate_random_pw(),
validators=[validators.not_empty]),
Argument("heat-domain",
"Name of the Identity domain for Orchestration.",
"CONFIG_HEAT_DOMAIN",
"heat",
validators=[validators.not_empty]),
Argument("heat-domain-admin",
"Name of the Identity domain administrative user for "
"Orchestration.",
"CONFIG_HEAT_DOMAIN_ADMIN",
"heat_domain_admin",
validators=[validators.not_empty]),
Argument("heat-domain-password",
"Password for the Identity domain administrative user "
"for Orchestration",
"CONFIG_HEAT_DOMAIN_PASSWORD",
utils.generate_random_pw(),
validators=[validators.not_empty])
]
}
for group in conf:
Controller.get().add_group(group, conf[group])
def init_sequences():
controller = Controller.get()
conf = controller.CONF
<|code_end|>
, generate the next line using the imports in this file:
from clearstack import utils
from clearstack import validators
from clearstack.controller import Controller
from clearstack.argument import Argument
from clearstack.common import util
and context (functions, classes, or occasionally code) from other files:
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | if util.str2bool(conf['CONFIG_HEAT_INSTALL']): |
Using the 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.
#
def validate_ssh_key(ssh_key):
hosts = utils.get_all_hosts()
util.remove_localhost(hosts)
if len(hosts) != 0:
validators.file(ssh_key)
def init_config():
home = os.getenv('HOME')
if home is None:
home = "/root"
conf = {
"GENERAL": [
<|code_end|>
, determine the next line of code. You have imports:
import os
from clearstack.argument import Argument
from clearstack.controller import Controller
from clearstack import validators
from clearstack import utils
from clearstack.common import util
and context (class names, function names, or code) available:
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | Argument("debug-mode", |
Given snippet: <|code_start|> " OpenStack Networking (neutron)",
"CONFIG_NEUTRON_INSTALL",
"y",
options=['y', 'n'],
validators=[validators.y_or_n]),
Argument("ceilometer-install",
"Set 'y' if you would like Clearstack to install"
" OpenStack Telemetry (ceilometer)",
"CONFIG_CEILOMETER_INSTALL",
"y",
options=['y', 'n'],
validators=[validators.y_or_n]),
Argument("heat-install",
"Set 'y' if you would like Clearstack to install"
" OpenStack Orchestration (heat)",
"CONFIG_HEAT_INSTALL",
"n",
options=['y', 'n'],
validators=[validators.y_or_n]),
Argument("swift-install",
"Set 'y' if you would like Clearstack to install"
" OpenStack Object Storage (swift)",
"CONFIG_SWIFT_INSTALL",
"n",
options=['y', 'n'],
validators=[validators.y_or_n])
]
}
for group in conf:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from clearstack.argument import Argument
from clearstack.controller import Controller
from clearstack import validators
from clearstack import utils
from clearstack.common import util
and context:
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
which might include code, classes, or functions. Output only the next line. | Controller.get().add_group(group, conf[group]) |
Predict the next line after this snippet: <|code_start|>#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
# Author: Obed Munoz <obed.n.munoz@intel.com>
#
# 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.
#
def validate_ssh_key(ssh_key):
hosts = utils.get_all_hosts()
util.remove_localhost(hosts)
if len(hosts) != 0:
<|code_end|>
using the current file's imports:
import os
from clearstack.argument import Argument
from clearstack.controller import Controller
from clearstack import validators
from clearstack import utils
from clearstack.common import util
and any relevant context from other files:
# Path: clearstack/argument.py
# class Argument(object):
# def __init__(self, cmd_option, description,
# conf_name, default_value, validators=[],
# options=None):
# self.cmd_option = cmd_option
# self.description = description
# self.conf_name = conf_name
# self.default_value = default_value
# self.validators = validators
# self.option_list = options
#
# def validate(self, option):
# for validator in self.validators:
# try:
# validator(option)
# except ValueError as e:
# raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
#
# Path: clearstack/controller.py
# class Controller:
# CONF = {}
# _plugins = []
# _groups = []
# _sequences = []
#
# def add_sequence(self, desc, function, args=None):
# self._sequences.append(Sequence(desc, function, args))
#
# def run_all_sequences(self):
# for seq in self._sequences:
# try:
# seq.run()
# except Exception as e:
# raise e
#
# def add_plugin(self, plugin):
# self._plugins.append(plugin)
#
# def get_all_plugins(self):
# return self._plugins
#
# def add_group(self, name, args):
# self._groups.append(Group(name, args))
#
# def get_all_groups(self):
# return self._groups
#
# def get_all_arguments(self):
# """Get a list of the configuration argument loaded"""
# arguments = []
# for group in self._groups:
# arguments.extend([argument.conf_name
# for argument in group.get_all_arguments()])
# return arguments
#
# def validate_groups(self, conf_values):
# """ Load validation functions, in order to check
# the values in the answer file """
# arguments = {}
# for group in self._groups:
# for arg in group.get_all_arguments():
# try:
# arg.validate(conf_values[arg.conf_name])
# except Exception as e:
# raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
# return arguments
#
# Path: clearstack/validators.py
# def y_or_n(value):
# def ip_or_hostname(value):
# def cidr(value):
# def file(value):
# def not_empty(value):
# def digit(value):
#
# Path: clearstack/utils.py
# def arg(*args, **kwargs):
# def _decorator(func):
# def run_recipe(recipe_file, recipe_src, hosts):
# def _run_recipe_local(recipe_file):
# def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts):
# def get_all_hosts():
# def generate_conf_file(conf_file):
# def copy_resources():
# def _copy_resources_local():
# def _copy_resources_to_hosts(_hosts):
# def get_logs():
# def get_template(template):
# def generate_random_pw():
# def generate_ssh_keys(output):
# def setup_debugging(debug):
#
# Path: clearstack/common/util.py
# HOST_LOG_DIR = '/var/log/clearstack'
# HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR)
# LOG_DIR = '/var/log/clearstack'
# LOG_DIR = '/tmp/log/clearstack'
# LOG_FILE = "{0}/clearstack.log".format(LOG_DIR)
# LOG = logging.getLogger("Clearstack")
# def _print_error_message(self, e, file_name):
# def port_open(port):
# def service_status(service):
# def service_enabled(service):
# def setup_debugging(debug, is_remote_host=True):
# def run_command(command, stdin=None, environ=None, debug=True):
# def str2bool(value):
# def write_config(file, data):
# def write_properties(file, data):
# def get_option(file, section, option):
# def delete_option(file, section, option=None):
# def write_in_file_ine(file, data):
# def get_dns():
# def get_netmask():
# def get_gateway():
# def get_net_interface():
# def get_ips():
# def get_nic(ip):
# def get_ip():
# def find_my_ip_from_config(config_ips):
# def is_localhost(host):
# def has_localhost(hosts):
# def remove_localhost(hosts):
# def ensure_directory(dir):
# def link_file(source, target):
. Output only the next line. | validators.file(ssh_key) |
Predict the next line after this snippet: <|code_start|># Command line entry point for cancat2candump
def main():
argv = sys.argv[1:]
parser = argparse.ArgumentParser(
prog='cancat2candump',
description='Utility to convert a CanCat session into a candump log')
parser.add_argument('session', help='input CanCat session')
parser.add_argument('output', help='output candump file')
args = parser.parse_args(argv)
<|code_end|>
using the current file's imports:
import sys
import argparse
from cancat.utils import convert
and any relevant context from other files:
# Path: cancat/utils/convert.py
# def cancat2candump(session, output):
# def cancat2pcap(session, output):
# def _import_candump(filename):
# def _import_pcap(filename):
# def candump2cancat(candumplog, output):
# def pcap2cancat(pcapfile, output):
. Output only the next line. | convert.cancat2candump(args.session, args.output) |
Given the code snippet: <|code_start|># Command line entry point for cancat2pcap
# This requires scapy to be installed
def main():
argv = sys.argv[1:]
parser = argparse.ArgumentParser(
prog='cancat2pcap',
description='Utility to convert a CanCat session into a pcap')
parser.add_argument('session', type=argparse.FileType('rb'),
help='input CanCat session')
parser.add_argument('output', type=str,
help='output pcap file')
args = parser.parse_args(argv)
<|code_end|>
, generate the next line using the imports in this file:
import sys
import argparse
from cancat.utils import convert
and context (functions, classes, or occasionally code) from other files:
# Path: cancat/utils/convert.py
# def cancat2candump(session, output):
# def cancat2pcap(session, output):
# def _import_candump(filename):
# def _import_pcap(filename):
# def candump2cancat(candumplog, output):
# def pcap2cancat(pcapfile, output):
. Output only the next line. | convert.cancat2pcap(args.session, args.output) |
Given the following code snippet before the placeholder: <|code_start|># Command line entry point for candump2cancat
def main():
argv = sys.argv[1:]
parser = argparse.ArgumentParser(
prog='candump2cancat',
description='Utility to convert a candump log into a CanCat session')
parser.add_argument('log', help='input candump log')
parser.add_argument('output', help='output cancat session')
args = parser.parse_args(argv)
<|code_end|>
, predict the next line using imports from the current file:
import sys
import argparse
from cancat.utils import convert
and context including class names, function names, and sometimes code from other files:
# Path: cancat/utils/convert.py
# def cancat2candump(session, output):
# def cancat2pcap(session, output):
# def _import_candump(filename):
# def _import_pcap(filename):
# def candump2cancat(candumplog, output):
# def pcap2cancat(pcapfile, output):
. Output only the next line. | convert.candump2cancat(args.log, args.output) |
Next line prediction: <|code_start|># Command line entry point for candump2cancat
# This requires scapy to be installed
def main():
argv = sys.argv[1:]
parser = argparse.ArgumentParser(
prog='pcap2cancat',
description='Utility to convert a pcap with CAN messages into a CanCat session')
parser.add_argument('pcap', help='input pcap')
parser.add_argument('output', help='output cancat session')
args = parser.parse_args(argv)
<|code_end|>
. Use current file imports:
(import sys
import argparse
from cancat.utils import convert)
and context including class names, function names, or small code snippets from other files:
# Path: cancat/utils/convert.py
# def cancat2candump(session, output):
# def cancat2pcap(session, output):
# def _import_candump(filename):
# def _import_pcap(filename):
# def candump2cancat(candumplog, output):
# def pcap2cancat(pcapfile, output):
. Output only the next line. | convert.pcap2cancat(args.pcap, args.output) |
Continue the code snippet: <|code_start|> def __iter__(self):
return self
def __len__(self):
if hasattr(self, 'count'):
return self.count
elif self.values is not None:
return len(self.values)
else:
return 0
def __next__(self):
return self.next()
class ZendeskResultGenerator(BaseResultGenerator):
""" Generic result generator. """
def __init__(self,
response_handler,
response_json,
response_objects=None,
object_type=None):
super(ZendeskResultGenerator, self).__init__(response_handler,
response_json)
self.object_type = object_type or self.response_handler.api.object_type
self.values = response_objects or None
def process_page(self):
response_objects = self.response_handler.deserialize(
self._response_json)
<|code_end|>
. Use current file imports:
import re
import six
import logging
from abc import abstractmethod
from datetime import datetime, timedelta
from zenpy.lib.util import as_plural
from zenpy.lib.exception import SearchResponseLimitExceeded
from collections.abc import Iterable
from collections import Iterable
from math import ceil
and context (classes, functions, or code) from other files:
# Path: zenpy/lib/util.py
# def as_plural(result_key):
# """
# Given a result key, return in the plural form.
# """
# # Not at all guaranteed to work in all cases...
# if result_key.endswith('y'):
# return re.sub("y$", "ies", result_key)
# elif result_key.endswith('address'):
# return result_key + 'es'
# elif result_key.endswith('us'):
# return re.sub("us$", "uses", result_key)
# elif not result_key.endswith('s'):
# return result_key + 's'
# else:
# return result_key
#
# Path: zenpy/lib/exception.py
# class SearchResponseLimitExceeded(APIException):
# """
# A ``SearchResponseLimitExceeded`` is raised when a search has too many results
#
# See https://develop.zendesk.com/hc/en-us/articles/360022563994--BREAKING-New-Search-API-Result-Limits
# """
. Output only the next line. | return response_objects[as_plural(self.object_type)] |
Based on the snippet: <|code_start|> end_time = self._response_json.get('end_time', None)
# If we are calling an incremental API, make sure to honour the restrictions
if end_time:
# We can't request updates from an incremental api if the
# start_time value is less than 5 minutes in the future.
if (datetime.fromtimestamp(int(end_time)) +
timedelta(minutes=5)) > datetime.now():
raise StopIteration
# No more pages to request
if self._response_json.get("end_of_stream") is True:
raise StopIteration
return super(ZendeskResultGenerator,
self).get_next_page(page_num, page_size)
class SearchResultGenerator(BaseResultGenerator):
""" Result generator for search queries. """
def process_page(self):
search_results = list()
for object_json in self._response_json['results']:
object_type = object_json.pop('result_type')
search_results.append(
self.response_handler.api._object_mapping.object_from_json(
object_type, object_json))
return search_results
def get_next_page(self, page_num, page_size):
try:
return super(SearchResultGenerator,
self).get_next_page(page_num, page_size)
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import six
import logging
from abc import abstractmethod
from datetime import datetime, timedelta
from zenpy.lib.util import as_plural
from zenpy.lib.exception import SearchResponseLimitExceeded
from collections.abc import Iterable
from collections import Iterable
from math import ceil
and context (classes, functions, sometimes code) from other files:
# Path: zenpy/lib/util.py
# def as_plural(result_key):
# """
# Given a result key, return in the plural form.
# """
# # Not at all guaranteed to work in all cases...
# if result_key.endswith('y'):
# return re.sub("y$", "ies", result_key)
# elif result_key.endswith('address'):
# return result_key + 'es'
# elif result_key.endswith('us'):
# return re.sub("us$", "uses", result_key)
# elif not result_key.endswith('s'):
# return result_key + 's'
# else:
# return result_key
#
# Path: zenpy/lib/exception.py
# class SearchResponseLimitExceeded(APIException):
# """
# A ``SearchResponseLimitExceeded`` is raised when a search has too many results
#
# See https://develop.zendesk.com/hc/en-us/articles/360022563994--BREAKING-New-Search-API-Result-Limits
# """
. Output only the next line. | except SearchResponseLimitExceeded: |
Predict the next line after this snippet: <|code_start|> elif value:
parameters[key] = value
elif key in ('since_id', 'ticket_id',
'issue_id'): # Jira integration
parameters[key] = value
# this is a bit of a hack
elif key == 'role':
if isinstance(value, basestring) or len(value) == 1:
parameters['role[]'] = value
else:
parameters['role[]'] = value[0] + '&' + "&".join(
('role[]={}'.format(role) for role in value[1:]))
elif key.endswith('ids'):
# if it looks like a type of unknown id, send it through as such
parameters[key] = ",".join(map(str, value))
if path == self.endpoint and not path.endswith('.json'):
path += '.json'
return Url(path=path, params=parameters)
class SecondaryEndpoint(BaseEndpoint):
def __call__(self, id, **kwargs):
return Url(self.endpoint % dict(id=id), params=kwargs)
class MultipleIDEndpoint(BaseEndpoint):
def __call__(self, *args):
if not args or len(args) < 2:
<|code_end|>
using the current file's imports:
import logging
from datetime import date
from datetime import datetime
from requests.utils import quote
from zenpy.lib.exception import ZenpyException
from zenpy.lib.util import is_iterable_but_not_string, to_unix_ts
from urllib import urlencode
from urlparse import urlunsplit, SplitResult
from urllib.parse import urlencode
from urllib.parse import urlunsplit, SplitResult
and any relevant context from other files:
# Path: zenpy/lib/exception.py
# class ZenpyException(Exception):
# """
# A ``ZenpyException`` is raised for internal errors.
# """
#
# Path: zenpy/lib/util.py
# def is_iterable_but_not_string(obj):
# """
# Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).
# """
# return hasattr(obj, '__iter__') and not isinstance(
# obj, str) and not isinstance(obj, bytes)
#
# def to_unix_ts(start_time):
# """Given a datetime object, returns its value as a unix timestamp"""
# if isinstance(start_time, datetime):
# if is_timezone_aware(start_time):
# start_time = start_time.astimezone(pytz.utc)
# else:
# log.warning(
# "Non timezone-aware datetime object passed to IncrementalEndpoint. "
# "The Zendesk API expects UTC time, if this is not the case results will be incorrect!"
# )
# unix_time = calendar.timegm(start_time.timetuple())
# else:
# unix_time = start_time
#
# return int(unix_time)
. Output only the next line. | raise ZenpyException( |
Predict the next line after this snippet: <|code_start|> """
def __call__(self, **kwargs):
parameters = {}
path = self.endpoint
for key, value in kwargs.items():
if key == 'id':
path += "/{}.json".format(value)
elif key == 'ids':
path += '/show_many.json'
parameters[key] = ",".join(map(str, value))
elif key == 'destroy_ids':
path += '/destroy_many.json'
parameters['ids'] = ",".join(map(str, value))
elif key == 'create_many':
path += '/create_many.json'
elif key == '/create_or_update_many':
path = self.endpoint
elif key == 'recover_ids':
path += '/recover_many.json'
parameters[key] = ",".join(map(str, value))
elif key == 'update_many':
path += '/update_many.json'
elif key == 'count_many':
path += '/count_many.json'
parameters[key] = ",".join(map(str, value))
elif key == 'external_id' and path == 'tickets':
parameters[key] = value
elif key in ('external_id', 'external_ids'):
external_ids = [
value
<|code_end|>
using the current file's imports:
import logging
from datetime import date
from datetime import datetime
from requests.utils import quote
from zenpy.lib.exception import ZenpyException
from zenpy.lib.util import is_iterable_but_not_string, to_unix_ts
from urllib import urlencode
from urlparse import urlunsplit, SplitResult
from urllib.parse import urlencode
from urllib.parse import urlunsplit, SplitResult
and any relevant context from other files:
# Path: zenpy/lib/exception.py
# class ZenpyException(Exception):
# """
# A ``ZenpyException`` is raised for internal errors.
# """
#
# Path: zenpy/lib/util.py
# def is_iterable_but_not_string(obj):
# """
# Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).
# """
# return hasattr(obj, '__iter__') and not isinstance(
# obj, str) and not isinstance(obj, bytes)
#
# def to_unix_ts(start_time):
# """Given a datetime object, returns its value as a unix timestamp"""
# if isinstance(start_time, datetime):
# if is_timezone_aware(start_time):
# start_time = start_time.astimezone(pytz.utc)
# else:
# log.warning(
# "Non timezone-aware datetime object passed to IncrementalEndpoint. "
# "The Zendesk API expects UTC time, if this is not the case results will be incorrect!"
# )
# unix_time = calendar.timegm(start_time.timetuple())
# else:
# unix_time = start_time
#
# return int(unix_time)
. Output only the next line. | ] if not is_iterable_but_not_string(value) else value |
Given the following code snippet before the placeholder: <|code_start|> return Url(self.endpoint % dict(id=id), params=kwargs)
class MultipleIDEndpoint(BaseEndpoint):
def __call__(self, *args):
if not args or len(args) < 2:
raise ZenpyException(
"This endpoint requires at least two arguments!")
return Url(self.endpoint.format(*args))
class IncrementalEndpoint(BaseEndpoint):
"""
An IncrementalEndpoint takes a start_time parameter
for querying the incremental api endpoint.
Note: The Zendesk API expects UTC time. If a timezone aware datetime object is passed
Zenpy will convert it to UTC, however if a naive object or unix timestamp is passed there is nothing
Zenpy can do. It is recommended to always pass timezone aware objects to this endpoint.
:param start_time: unix timestamp or datetime object
:param include: list of items to sideload
"""
def __call__(self, start_time=None, include=None, per_page=None):
if start_time is None:
raise ZenpyException(
"Incremental Endpoint requires a start_time parameter!")
elif isinstance(start_time, datetime):
<|code_end|>
, predict the next line using imports from the current file:
import logging
from datetime import date
from datetime import datetime
from requests.utils import quote
from zenpy.lib.exception import ZenpyException
from zenpy.lib.util import is_iterable_but_not_string, to_unix_ts
from urllib import urlencode
from urlparse import urlunsplit, SplitResult
from urllib.parse import urlencode
from urllib.parse import urlunsplit, SplitResult
and context including class names, function names, and sometimes code from other files:
# Path: zenpy/lib/exception.py
# class ZenpyException(Exception):
# """
# A ``ZenpyException`` is raised for internal errors.
# """
#
# Path: zenpy/lib/util.py
# def is_iterable_but_not_string(obj):
# """
# Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).
# """
# return hasattr(obj, '__iter__') and not isinstance(
# obj, str) and not isinstance(obj, bytes)
#
# def to_unix_ts(start_time):
# """Given a datetime object, returns its value as a unix timestamp"""
# if isinstance(start_time, datetime):
# if is_timezone_aware(start_time):
# start_time = start_time.astimezone(pytz.utc)
# else:
# log.warning(
# "Non timezone-aware datetime object passed to IncrementalEndpoint. "
# "The Zendesk API expects UTC time, if this is not the case results will be incorrect!"
# )
# unix_time = calendar.timegm(start_time.timetuple())
# else:
# unix_time = start_time
#
# return int(unix_time)
. Output only the next line. | unix_time = to_unix_ts(start_time) |
Continue the code snippet: <|code_start|>
class TestCategoryCreateUpdateDelete(
SingleUpdateApiTestCase, SingleCreateApiTestCase, SingleDeleteApiTestCase
):
__test__ = True
<|code_end|>
. Use current file imports:
from zenpy.lib.api_objects.help_centre_objects import Category
from test_api.fixtures import (
SingleUpdateApiTestCase,
SingleCreateApiTestCase,
SingleDeleteApiTestCase,
)
and context (classes, functions, or code) from other files:
# Path: zenpy/lib/api_objects/help_centre_objects.py
# class Category(BaseObject):
# """
# ######################################################################
# # Do not modify, this class is autogenerated by gen_classes.py #
# ######################################################################
# """
# def __init__(self,
# api=None,
# created_at=None,
# description=None,
# html_url=None,
# id=None,
# locale=None,
# name=None,
# outdated=None,
# position=None,
# source_locale=None,
# updated_at=None,
# url=None,
# **kwargs):
#
# self.api = api
# self.created_at = created_at
# self.description = description
# self.html_url = html_url
# self.id = id
# self.locale = locale
# self.name = name
# self.outdated = outdated
# self.position = position
# self.source_locale = source_locale
# self.updated_at = updated_at
# self.url = url
#
# for key, value in kwargs.items():
# setattr(self, key, value)
#
# for key in self.to_dict():
# if getattr(self, key) is None:
# try:
# self._dirty_attributes.remove(key)
# except KeyError:
# continue
#
# @property
# def created(self):
#
# if self.created_at:
# return dateutil.parser.parse(self.created_at)
#
# @created.setter
# def created(self, created):
# if created:
# self.created_at = created
#
# @property
# def updated(self):
#
# if self.updated_at:
# return dateutil.parser.parse(self.updated_at)
#
# @updated.setter
# def updated(self, updated):
# if updated:
# self.updated_at = updated
. Output only the next line. | ZenpyType = Category |
Here is a snippet: <|code_start|> self.stream = environment._tokenize(source, name, filename, state)
self.name = name
self.filename = filename
self.closed = False
self.extensions = {}
for extension in environment.extensions.itervalues():
for tag in extension.tags:
self.extensions[tag] = extension.parse
self._last_identifier = 0
def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
"""Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename.
"""
if lineno is None:
lineno = self.stream.current.lineno
raise exc(msg, lineno, self.name, self.filename)
def is_tuple_end(self, extra_end_rules=None):
"""Are we at the end of a tuple?"""
if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):
return True
elif extra_end_rules is not None:
return self.stream.current.test_any(extra_end_rules)
return False
def free_identifier(self, lineno=None):
"""Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
self._last_identifier += 1
<|code_end|>
. Write the next line using the current file imports:
from jinja2 import nodes
from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError
and context from other files:
# Path: jinja2/nodes.py
# class Impossible(Exception):
# class NodeType(type):
# class Node(object):
# class Stmt(Node):
# class Helper(Node):
# class Template(Node):
# class Output(Stmt):
# class Extends(Stmt):
# class For(Stmt):
# class If(Stmt):
# class Macro(Stmt):
# class CallBlock(Stmt):
# class FilterBlock(Stmt):
# class Block(Stmt):
# class Include(Stmt):
# class Import(Stmt):
# class FromImport(Stmt):
# class ExprStmt(Stmt):
# class Assign(Stmt):
# class Expr(Node):
# class BinExpr(Expr):
# class UnaryExpr(Expr):
# class Name(Expr):
# class Literal(Expr):
# class Const(Literal):
# class TemplateData(Literal):
# class Tuple(Literal):
# class List(Literal):
# class Dict(Literal):
# class Pair(Helper):
# class Keyword(Helper):
# class CondExpr(Expr):
# class Filter(Expr):
# class Test(Expr):
# class Call(Expr):
# class Getitem(Expr):
# class Getattr(Expr):
# class Slice(Expr):
# class Concat(Expr):
# class Compare(Expr):
# class Operand(Helper):
# class Mul(BinExpr):
# class Div(BinExpr):
# class FloorDiv(BinExpr):
# class Add(BinExpr):
# class Sub(BinExpr):
# class Mod(BinExpr):
# class Pow(BinExpr):
# class And(BinExpr):
# class Or(BinExpr):
# class Not(UnaryExpr):
# class Neg(UnaryExpr):
# class Pos(UnaryExpr):
# class EnvironmentAttribute(Expr):
# class ExtensionAttribute(Expr):
# class ImportedName(Expr):
# class InternalName(Expr):
# class MarkSafe(Expr):
# class ContextReference(Expr):
# class Continue(Stmt):
# class Break(Stmt):
# def __new__(cls, name, bases, d):
# def __init__(self, *fields, **attributes):
# def iter_fields(self, exclude=None, only=None):
# def iter_child_nodes(self, exclude=None, only=None):
# def find(self, node_type):
# def find_all(self, node_type):
# def set_ctx(self, ctx):
# def set_lineno(self, lineno, override=False):
# def set_environment(self, environment):
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def from_untrusted(cls, value, lineno=None, environment=None):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self, obj=None):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def const(obj):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def __init__(self):
# def as_const(self):
# def _failing_new(*args, **kwargs):
#
# Path: jinja2/exceptions.py
# class TemplateSyntaxError(TemplateError):
# """Raised to tell the user that there is a problem with the template."""
#
# def __init__(self, message, lineno, name=None, filename=None):
# if not isinstance(message, unicode):
# message = message.decode('utf-8', 'replace')
# TemplateError.__init__(self, message.encode('utf-8'))
# self.lineno = lineno
# self.name = name
# self.filename = filename
# self.source = None
# self.message = message
#
# def __unicode__(self):
# location = 'line %d' % self.lineno
# name = self.filename or self.name
# if name:
# location = 'File "%s", %s' % (name, location)
# lines = [self.message, ' ' + location]
#
# # if the source is set, add the line to the output
# if self.source is not None:
# try:
# line = self.source.splitlines()[self.lineno - 1]
# except IndexError:
# line = None
# if line:
# lines.append(' ' + line.strip())
#
# return u'\n'.join(lines)
#
# def __str__(self):
# return unicode(self).encode('utf-8')
#
# class TemplateAssertionError(TemplateSyntaxError):
# """Like a template syntax error, but covers cases where something in the
# template caused an error at compile time that wasn't necessarily caused
# by a syntax error. However it's a direct subclass of
# :exc:`TemplateSyntaxError` and has the same attributes.
# """
, which may include functions, classes, or code. Output only the next line. | rv = object.__new__(nodes.InternalName) |
Given the following code snippet before the placeholder: <|code_start|>
:copyright: 2008 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',
'macro', 'include', 'from', 'import',
'set'])
_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])
class Parser(object):
"""This is the central parsing class Jinja2 uses. It's passed to
extensions and can be used to parse expressions or statements.
"""
def __init__(self, environment, source, name=None, filename=None,
state=None):
self.environment = environment
self.stream = environment._tokenize(source, name, filename, state)
self.name = name
self.filename = filename
self.closed = False
self.extensions = {}
for extension in environment.extensions.itervalues():
for tag in extension.tags:
self.extensions[tag] = extension.parse
self._last_identifier = 0
<|code_end|>
, predict the next line using imports from the current file:
from jinja2 import nodes
from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError
and context including class names, function names, and sometimes code from other files:
# Path: jinja2/nodes.py
# class Impossible(Exception):
# class NodeType(type):
# class Node(object):
# class Stmt(Node):
# class Helper(Node):
# class Template(Node):
# class Output(Stmt):
# class Extends(Stmt):
# class For(Stmt):
# class If(Stmt):
# class Macro(Stmt):
# class CallBlock(Stmt):
# class FilterBlock(Stmt):
# class Block(Stmt):
# class Include(Stmt):
# class Import(Stmt):
# class FromImport(Stmt):
# class ExprStmt(Stmt):
# class Assign(Stmt):
# class Expr(Node):
# class BinExpr(Expr):
# class UnaryExpr(Expr):
# class Name(Expr):
# class Literal(Expr):
# class Const(Literal):
# class TemplateData(Literal):
# class Tuple(Literal):
# class List(Literal):
# class Dict(Literal):
# class Pair(Helper):
# class Keyword(Helper):
# class CondExpr(Expr):
# class Filter(Expr):
# class Test(Expr):
# class Call(Expr):
# class Getitem(Expr):
# class Getattr(Expr):
# class Slice(Expr):
# class Concat(Expr):
# class Compare(Expr):
# class Operand(Helper):
# class Mul(BinExpr):
# class Div(BinExpr):
# class FloorDiv(BinExpr):
# class Add(BinExpr):
# class Sub(BinExpr):
# class Mod(BinExpr):
# class Pow(BinExpr):
# class And(BinExpr):
# class Or(BinExpr):
# class Not(UnaryExpr):
# class Neg(UnaryExpr):
# class Pos(UnaryExpr):
# class EnvironmentAttribute(Expr):
# class ExtensionAttribute(Expr):
# class ImportedName(Expr):
# class InternalName(Expr):
# class MarkSafe(Expr):
# class ContextReference(Expr):
# class Continue(Stmt):
# class Break(Stmt):
# def __new__(cls, name, bases, d):
# def __init__(self, *fields, **attributes):
# def iter_fields(self, exclude=None, only=None):
# def iter_child_nodes(self, exclude=None, only=None):
# def find(self, node_type):
# def find_all(self, node_type):
# def set_ctx(self, ctx):
# def set_lineno(self, lineno, override=False):
# def set_environment(self, environment):
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def from_untrusted(cls, value, lineno=None, environment=None):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self, obj=None):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def const(obj):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def __init__(self):
# def as_const(self):
# def _failing_new(*args, **kwargs):
#
# Path: jinja2/exceptions.py
# class TemplateSyntaxError(TemplateError):
# """Raised to tell the user that there is a problem with the template."""
#
# def __init__(self, message, lineno, name=None, filename=None):
# if not isinstance(message, unicode):
# message = message.decode('utf-8', 'replace')
# TemplateError.__init__(self, message.encode('utf-8'))
# self.lineno = lineno
# self.name = name
# self.filename = filename
# self.source = None
# self.message = message
#
# def __unicode__(self):
# location = 'line %d' % self.lineno
# name = self.filename or self.name
# if name:
# location = 'File "%s", %s' % (name, location)
# lines = [self.message, ' ' + location]
#
# # if the source is set, add the line to the output
# if self.source is not None:
# try:
# line = self.source.splitlines()[self.lineno - 1]
# except IndexError:
# line = None
# if line:
# lines.append(' ' + line.strip())
#
# return u'\n'.join(lines)
#
# def __str__(self):
# return unicode(self).encode('utf-8')
#
# class TemplateAssertionError(TemplateSyntaxError):
# """Like a template syntax error, but covers cases where something in the
# template caused an error at compile time that wasn't necessarily caused
# by a syntax error. However it's a direct subclass of
# :exc:`TemplateSyntaxError` and has the same attributes.
# """
. Output only the next line. | def fail(self, msg, lineno=None, exc=TemplateSyntaxError): |
Using the snippet: <|code_start|> node = nodes.Import(lineno=self.stream.next().lineno)
node.template = self.parse_expression()
self.stream.expect('name:as')
node.target = self.parse_assign_target(name_only=True).name
return self.parse_import_context(node, False)
def parse_from(self):
node = nodes.FromImport(lineno=self.stream.next().lineno)
node.template = self.parse_expression()
self.stream.expect('name:import')
node.names = []
def parse_context():
if self.stream.current.value in ('with', 'without') and \
self.stream.look().test('name:context'):
node.with_context = self.stream.next().value == 'with'
self.stream.skip()
return True
return False
while 1:
if node.names:
self.stream.expect('comma')
if self.stream.current.type is 'name':
if parse_context():
break
target = self.parse_assign_target(name_only=True)
if target.name.startswith('_'):
self.fail('names starting with an underline can not '
'be imported', target.lineno,
<|code_end|>
, determine the next line of code. You have imports:
from jinja2 import nodes
from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError
and context (class names, function names, or code) available:
# Path: jinja2/nodes.py
# class Impossible(Exception):
# class NodeType(type):
# class Node(object):
# class Stmt(Node):
# class Helper(Node):
# class Template(Node):
# class Output(Stmt):
# class Extends(Stmt):
# class For(Stmt):
# class If(Stmt):
# class Macro(Stmt):
# class CallBlock(Stmt):
# class FilterBlock(Stmt):
# class Block(Stmt):
# class Include(Stmt):
# class Import(Stmt):
# class FromImport(Stmt):
# class ExprStmt(Stmt):
# class Assign(Stmt):
# class Expr(Node):
# class BinExpr(Expr):
# class UnaryExpr(Expr):
# class Name(Expr):
# class Literal(Expr):
# class Const(Literal):
# class TemplateData(Literal):
# class Tuple(Literal):
# class List(Literal):
# class Dict(Literal):
# class Pair(Helper):
# class Keyword(Helper):
# class CondExpr(Expr):
# class Filter(Expr):
# class Test(Expr):
# class Call(Expr):
# class Getitem(Expr):
# class Getattr(Expr):
# class Slice(Expr):
# class Concat(Expr):
# class Compare(Expr):
# class Operand(Helper):
# class Mul(BinExpr):
# class Div(BinExpr):
# class FloorDiv(BinExpr):
# class Add(BinExpr):
# class Sub(BinExpr):
# class Mod(BinExpr):
# class Pow(BinExpr):
# class And(BinExpr):
# class Or(BinExpr):
# class Not(UnaryExpr):
# class Neg(UnaryExpr):
# class Pos(UnaryExpr):
# class EnvironmentAttribute(Expr):
# class ExtensionAttribute(Expr):
# class ImportedName(Expr):
# class InternalName(Expr):
# class MarkSafe(Expr):
# class ContextReference(Expr):
# class Continue(Stmt):
# class Break(Stmt):
# def __new__(cls, name, bases, d):
# def __init__(self, *fields, **attributes):
# def iter_fields(self, exclude=None, only=None):
# def iter_child_nodes(self, exclude=None, only=None):
# def find(self, node_type):
# def find_all(self, node_type):
# def set_ctx(self, ctx):
# def set_lineno(self, lineno, override=False):
# def set_environment(self, environment):
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def from_untrusted(cls, value, lineno=None, environment=None):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self, obj=None):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def const(obj):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def __init__(self):
# def as_const(self):
# def _failing_new(*args, **kwargs):
#
# Path: jinja2/exceptions.py
# class TemplateSyntaxError(TemplateError):
# """Raised to tell the user that there is a problem with the template."""
#
# def __init__(self, message, lineno, name=None, filename=None):
# if not isinstance(message, unicode):
# message = message.decode('utf-8', 'replace')
# TemplateError.__init__(self, message.encode('utf-8'))
# self.lineno = lineno
# self.name = name
# self.filename = filename
# self.source = None
# self.message = message
#
# def __unicode__(self):
# location = 'line %d' % self.lineno
# name = self.filename or self.name
# if name:
# location = 'File "%s", %s' % (name, location)
# lines = [self.message, ' ' + location]
#
# # if the source is set, add the line to the output
# if self.source is not None:
# try:
# line = self.source.splitlines()[self.lineno - 1]
# except IndexError:
# line = None
# if line:
# lines.append(' ' + line.strip())
#
# return u'\n'.join(lines)
#
# def __str__(self):
# return unicode(self).encode('utf-8')
#
# class TemplateAssertionError(TemplateSyntaxError):
# """Like a template syntax error, but covers cases where something in the
# template caused an error at compile time that wasn't necessarily caused
# by a syntax error. However it's a direct subclass of
# :exc:`TemplateSyntaxError` and has the same attributes.
# """
. Output only the next line. | exc=TemplateAssertionError) |
Given the code snippet: <|code_start|> locals = {}
for name, value in real_locals.iteritems():
if name.startswith('l_'):
locals[name[2:]] = value
# if there is a local called __jinja_exception__, we get
# rid of it to not break the debug functionality.
locals.pop('__jinja_exception__', None)
# assamble fake globals we need
globals = {
'__name__': filename,
'__file__': filename,
'__jinja_exception__': exc_info[:2]
}
# and fake the exception
code = compile('\n' * (lineno - 1) + 'raise __jinja_exception__[0], ' +
'__jinja_exception__[1]', filename, 'exec')
# if it's possible, change the name of the code. This won't work
# on some python environments such as google appengine
try:
function = tb.tb_frame.f_code.co_name
if function == 'root':
location = 'top-level template code'
elif function.startswith('block_'):
location = 'block "%s"' % function[6:]
else:
location = 'template'
<|code_end|>
, generate the next line using the imports in this file:
import sys
import ctypes
from jinja2.utils import CodeType
from types import TracebackType
from jinja2._speedups import tb_set_next
and context (functions, classes, or occasionally code) from other files:
# Path: jinja2/utils.py
# def _test_gen_bug():
# def concat(gen):
# def is_python_keyword(name):
# def method(self): pass
# def _func():
# def contextfunction(f):
# def environmentfunction(f):
# def is_undefined(obj):
# def consume(iterable):
# def clear_caches():
# def import_string(import_name, silent=False):
# def open_if_exists(filename, mode='r'):
# def pformat(obj, verbose=False):
# def urlize(text, trim_url_limit=None, nofollow=False):
# def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
# def __new__(cls, base=u'', encoding=None, errors='strict'):
# def __html__(self):
# def __add__(self, other):
# def __radd__(self, other):
# def __mul__(self, num):
# def __mod__(self, arg):
# def __repr__(self):
# def join(self, seq):
# def split(self, *args, **kwargs):
# def rsplit(self, *args, **kwargs):
# def splitlines(self, *args, **kwargs):
# def unescape(self):
# def handle_match(m):
# def striptags(self):
# def escape(cls, s):
# def make_wrapper(name):
# def func(self, *args, **kwargs):
# def _escape_argspec(obj, iterable):
# def __init__(self, obj):
# def __init__(self, capacity):
# def _postinit(self):
# def _remove(self, obj):
# def __getstate__(self):
# def __setstate__(self, d):
# def __getnewargs__(self):
# def copy(self):
# def get(self, key, default=None):
# def setdefault(self, key, default=None):
# def clear(self):
# def __contains__(self, key):
# def __len__(self):
# def __repr__(self):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def __delitem__(self, key):
# def items(self):
# def iteritems(self):
# def values(self):
# def itervalue(self):
# def keys(self):
# def iterkeys(self):
# def __reversed__(self):
# def __init__(self, *items):
# def reset(self):
# def current(self):
# def next(self):
# def __init__(self, sep=u', '):
# def __call__(self):
# def escape(s):
# def soft_unicode(s):
# def __init__(self, _func, *args, **kwargs):
# def __call__(self, *args, **kwargs):
# class _C(object):
# class Markup(unicode):
# class _MarkupEscapeHelper(object):
# class LRUCache(object):
# class Cycler(object):
# class Joiner(object):
# class partial(object):
. Output only the next line. | code = CodeType(0, code.co_nlocals, code.co_stacksize, |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
jinja2.defaults
~~~~~~~~~~~~~~~
Jinja default filters and tags.
:copyright: 2007-2008 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
# defaults for the parser / lexer
BLOCK_START_STRING = '{%'
BLOCK_END_STRING = '%}'
VARIABLE_START_STRING = '{{'
VARIABLE_END_STRING = '}}'
COMMENT_START_STRING = '{#'
COMMENT_END_STRING = '#}'
LINE_STATEMENT_PREFIX = None
TRIM_BLOCKS = False
NEWLINE_SEQUENCE = '\n'
# default filters, tests and namespace
DEFAULT_NAMESPACE = {
'range': xrange,
'dict': lambda **kw: kw,
<|code_end|>
using the current file's imports:
from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner
from jinja2.filters import FILTERS as DEFAULT_FILTERS
from jinja2.tests import TESTS as DEFAULT_TESTS
and any relevant context from other files:
# Path: jinja2/utils.py
# def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
# """Generate some lorem impsum for the template."""
# from jinja2.constants import LOREM_IPSUM_WORDS
# from random import choice, random, randrange
# words = LOREM_IPSUM_WORDS.split()
# result = []
#
# for _ in xrange(n):
# next_capitalized = True
# last_comma = last_fullstop = 0
# word = None
# last = None
# p = []
#
# # each paragraph contains out of 20 to 100 words.
# for idx, _ in enumerate(xrange(randrange(min, max))):
# while True:
# word = choice(words)
# if word != last:
# last = word
# break
# if next_capitalized:
# word = word.capitalize()
# next_capitalized = False
# # add commas
# if idx - randrange(3, 8) > last_comma:
# last_comma = idx
# last_fullstop += 2
# word += ','
# # add end of sentences
# if idx - randrange(10, 20) > last_fullstop:
# last_comma = last_fullstop = idx
# word += '.'
# next_capitalized = True
# p.append(word)
#
# # ensure that the paragraph ends with a dot.
# p = u' '.join(p)
# if p.endswith(','):
# p = p[:-1] + '.'
# elif not p.endswith('.'):
# p += '.'
# result.append(p)
#
# if not html:
# return u'\n\n'.join(result)
# return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))
#
# class Cycler(object):
# """A cycle helper for templates."""
#
# def __init__(self, *items):
# if not items:
# raise RuntimeError('at least one item has to be provided')
# self.items = items
# self.reset()
#
# def reset(self):
# """Resets the cycle."""
# self.pos = 0
#
# @property
# def current(self):
# """Returns the current item."""
# return self.items[self.pos]
#
# def next(self):
# """Goes one item ahead and returns it."""
# rv = self.current
# self.pos = (self.pos + 1) % len(self.items)
# return rv
#
# class Joiner(object):
# """A joining helper for templates."""
#
# def __init__(self, sep=u', '):
# self.sep = sep
# self.used = False
#
# def __call__(self):
# if not self.used:
# self.used = True
# return u''
# return self.sep
#
# Path: jinja2/filters.py
# FILTERS = {
# 'attr': do_attr,
# 'replace': do_replace,
# 'upper': do_upper,
# 'lower': do_lower,
# 'escape': escape,
# 'e': escape,
# 'forceescape': do_forceescape,
# 'capitalize': do_capitalize,
# 'title': do_title,
# 'default': do_default,
# 'd': do_default,
# 'join': do_join,
# 'count': len,
# 'dictsort': do_dictsort,
# 'sort': do_sort,
# 'length': len,
# 'reverse': do_reverse,
# 'center': do_center,
# 'indent': do_indent,
# 'title': do_title,
# 'capitalize': do_capitalize,
# 'first': do_first,
# 'last': do_last,
# 'random': do_random,
# 'filesizeformat': do_filesizeformat,
# 'pprint': do_pprint,
# 'truncate': do_truncate,
# 'wordwrap': do_wordwrap,
# 'wordcount': do_wordcount,
# 'int': do_int,
# 'float': do_float,
# 'string': soft_unicode,
# 'list': do_list,
# 'urlize': do_urlize,
# 'format': do_format,
# 'trim': do_trim,
# 'striptags': do_striptags,
# 'slice': do_slice,
# 'batch': do_batch,
# 'sum': sum,
# 'abs': abs,
# 'round': do_round,
# 'sort': do_sort,
# 'groupby': do_groupby,
# 'safe': do_mark_safe,
# 'xmlattr': do_xmlattr
# }
#
# Path: jinja2/tests.py
# TESTS = {
# 'odd': test_odd,
# 'even': test_even,
# 'divisibleby': test_divisibleby,
# 'defined': test_defined,
# 'undefined': test_undefined,
# 'none': test_none,
# 'lower': test_lower,
# 'upper': test_upper,
# 'string': test_string,
# 'number': test_number,
# 'sequence': test_sequence,
# 'iterable': test_iterable,
# 'callable': callable,
# 'sameas': test_sameas,
# 'escaped': test_escaped
# }
. Output only the next line. | 'lipsum': generate_lorem_ipsum, |
Given the code snippet: <|code_start|> and modify the AST in place so that it should be easier to evaluate it.
Because the AST does not contain all the scoping information and the
compiler has to find that out, we cannot do all the optimizations we
want. For example loop unrolling doesn't work because unrolled loops would
have a different scoping.
The solution would be a second syntax tree that has the scoping rules stored.
:copyright: Copyright 2008 by Christoph Hack, Armin Ronacher.
:license: BSD.
"""
def optimize(node, environment):
"""The context hint can be used to perform an static optimization
based on the context given."""
optimizer = Optimizer(environment)
return optimizer.visit(node)
class Optimizer(NodeTransformer):
def __init__(self, environment):
self.environment = environment
def visit_If(self, node):
"""Eliminate dead code."""
# do not optimize ifs that have a block inside so that it doesn't
# break super().
<|code_end|>
, generate the next line using the imports in this file:
from jinja2 import nodes
from jinja2.visitor import NodeTransformer
and context (functions, classes, or occasionally code) from other files:
# Path: jinja2/nodes.py
# class Impossible(Exception):
# class NodeType(type):
# class Node(object):
# class Stmt(Node):
# class Helper(Node):
# class Template(Node):
# class Output(Stmt):
# class Extends(Stmt):
# class For(Stmt):
# class If(Stmt):
# class Macro(Stmt):
# class CallBlock(Stmt):
# class FilterBlock(Stmt):
# class Block(Stmt):
# class Include(Stmt):
# class Import(Stmt):
# class FromImport(Stmt):
# class ExprStmt(Stmt):
# class Assign(Stmt):
# class Expr(Node):
# class BinExpr(Expr):
# class UnaryExpr(Expr):
# class Name(Expr):
# class Literal(Expr):
# class Const(Literal):
# class TemplateData(Literal):
# class Tuple(Literal):
# class List(Literal):
# class Dict(Literal):
# class Pair(Helper):
# class Keyword(Helper):
# class CondExpr(Expr):
# class Filter(Expr):
# class Test(Expr):
# class Call(Expr):
# class Getitem(Expr):
# class Getattr(Expr):
# class Slice(Expr):
# class Concat(Expr):
# class Compare(Expr):
# class Operand(Helper):
# class Mul(BinExpr):
# class Div(BinExpr):
# class FloorDiv(BinExpr):
# class Add(BinExpr):
# class Sub(BinExpr):
# class Mod(BinExpr):
# class Pow(BinExpr):
# class And(BinExpr):
# class Or(BinExpr):
# class Not(UnaryExpr):
# class Neg(UnaryExpr):
# class Pos(UnaryExpr):
# class EnvironmentAttribute(Expr):
# class ExtensionAttribute(Expr):
# class ImportedName(Expr):
# class InternalName(Expr):
# class MarkSafe(Expr):
# class ContextReference(Expr):
# class Continue(Stmt):
# class Break(Stmt):
# def __new__(cls, name, bases, d):
# def __init__(self, *fields, **attributes):
# def iter_fields(self, exclude=None, only=None):
# def iter_child_nodes(self, exclude=None, only=None):
# def find(self, node_type):
# def find_all(self, node_type):
# def set_ctx(self, ctx):
# def set_lineno(self, lineno, override=False):
# def set_environment(self, environment):
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def from_untrusted(cls, value, lineno=None, environment=None):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self, obj=None):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def const(obj):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def __init__(self):
# def as_const(self):
# def _failing_new(*args, **kwargs):
#
# Path: jinja2/visitor.py
# class NodeTransformer(NodeVisitor):
# """Walks the abstract syntax tree and allows modifications of nodes.
#
# The `NodeTransformer` will walk the AST and use the return value of the
# visitor functions to replace or remove the old node. If the return
# value of the visitor function is `None` the node will be removed
# from the previous location otherwise it's replaced with the return
# value. The return value may be the original node in which case no
# replacement takes place.
# """
#
# def generic_visit(self, node, *args, **kwargs):
# for field, old_value in node.iter_fields():
# if isinstance(old_value, list):
# new_values = []
# for value in old_value:
# if isinstance(value, Node):
# value = self.visit(value, *args, **kwargs)
# if value is None:
# continue
# elif not isinstance(value, Node):
# new_values.extend(value)
# continue
# new_values.append(value)
# old_value[:] = new_values
# elif isinstance(old_value, Node):
# new_node = self.visit(old_value, *args, **kwargs)
# if new_node is None:
# delattr(node, field)
# else:
# setattr(node, field, new_node)
# return node
#
# def visit_list(self, node, *args, **kwargs):
# """As transformers may return lists in some places this method
# can be used to enforce a list as return value.
# """
# rv = self.visit(node, *args, **kwargs)
# if not isinstance(rv, list):
# rv = [rv]
# return rv
. Output only the next line. | if node.find(nodes.Block) is not None: |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
jinja2.optimizer
~~~~~~~~~~~~~~~~
The jinja optimizer is currently trying to constant fold a few expressions
and modify the AST in place so that it should be easier to evaluate it.
Because the AST does not contain all the scoping information and the
compiler has to find that out, we cannot do all the optimizations we
want. For example loop unrolling doesn't work because unrolled loops would
have a different scoping.
The solution would be a second syntax tree that has the scoping rules stored.
:copyright: Copyright 2008 by Christoph Hack, Armin Ronacher.
:license: BSD.
"""
def optimize(node, environment):
"""The context hint can be used to perform an static optimization
based on the context given."""
optimizer = Optimizer(environment)
return optimizer.visit(node)
<|code_end|>
. Use current file imports:
from jinja2 import nodes
from jinja2.visitor import NodeTransformer
and context (classes, functions, or code) from other files:
# Path: jinja2/nodes.py
# class Impossible(Exception):
# class NodeType(type):
# class Node(object):
# class Stmt(Node):
# class Helper(Node):
# class Template(Node):
# class Output(Stmt):
# class Extends(Stmt):
# class For(Stmt):
# class If(Stmt):
# class Macro(Stmt):
# class CallBlock(Stmt):
# class FilterBlock(Stmt):
# class Block(Stmt):
# class Include(Stmt):
# class Import(Stmt):
# class FromImport(Stmt):
# class ExprStmt(Stmt):
# class Assign(Stmt):
# class Expr(Node):
# class BinExpr(Expr):
# class UnaryExpr(Expr):
# class Name(Expr):
# class Literal(Expr):
# class Const(Literal):
# class TemplateData(Literal):
# class Tuple(Literal):
# class List(Literal):
# class Dict(Literal):
# class Pair(Helper):
# class Keyword(Helper):
# class CondExpr(Expr):
# class Filter(Expr):
# class Test(Expr):
# class Call(Expr):
# class Getitem(Expr):
# class Getattr(Expr):
# class Slice(Expr):
# class Concat(Expr):
# class Compare(Expr):
# class Operand(Helper):
# class Mul(BinExpr):
# class Div(BinExpr):
# class FloorDiv(BinExpr):
# class Add(BinExpr):
# class Sub(BinExpr):
# class Mod(BinExpr):
# class Pow(BinExpr):
# class And(BinExpr):
# class Or(BinExpr):
# class Not(UnaryExpr):
# class Neg(UnaryExpr):
# class Pos(UnaryExpr):
# class EnvironmentAttribute(Expr):
# class ExtensionAttribute(Expr):
# class ImportedName(Expr):
# class InternalName(Expr):
# class MarkSafe(Expr):
# class ContextReference(Expr):
# class Continue(Stmt):
# class Break(Stmt):
# def __new__(cls, name, bases, d):
# def __init__(self, *fields, **attributes):
# def iter_fields(self, exclude=None, only=None):
# def iter_child_nodes(self, exclude=None, only=None):
# def find(self, node_type):
# def find_all(self, node_type):
# def set_ctx(self, ctx):
# def set_lineno(self, lineno, override=False):
# def set_environment(self, environment):
# def __eq__(self, other):
# def __ne__(self, other):
# def __repr__(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def from_untrusted(cls, value, lineno=None, environment=None):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self, obj=None):
# def as_const(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def can_assign(self):
# def as_const(self):
# def const(obj):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def as_const(self):
# def __init__(self):
# def as_const(self):
# def _failing_new(*args, **kwargs):
#
# Path: jinja2/visitor.py
# class NodeTransformer(NodeVisitor):
# """Walks the abstract syntax tree and allows modifications of nodes.
#
# The `NodeTransformer` will walk the AST and use the return value of the
# visitor functions to replace or remove the old node. If the return
# value of the visitor function is `None` the node will be removed
# from the previous location otherwise it's replaced with the return
# value. The return value may be the original node in which case no
# replacement takes place.
# """
#
# def generic_visit(self, node, *args, **kwargs):
# for field, old_value in node.iter_fields():
# if isinstance(old_value, list):
# new_values = []
# for value in old_value:
# if isinstance(value, Node):
# value = self.visit(value, *args, **kwargs)
# if value is None:
# continue
# elif not isinstance(value, Node):
# new_values.extend(value)
# continue
# new_values.append(value)
# old_value[:] = new_values
# elif isinstance(old_value, Node):
# new_node = self.visit(old_value, *args, **kwargs)
# if new_node is None:
# delattr(node, field)
# else:
# setattr(node, field, new_node)
# return node
#
# def visit_list(self, node, *args, **kwargs):
# """As transformers may return lists in some places this method
# can be used to enforce a list as return value.
# """
# rv = self.visit(node, *args, **kwargs)
# if not isinstance(rv, list):
# rv = [rv]
# return rv
. Output only the next line. | class Optimizer(NodeTransformer): |
Here is a snippet: <|code_start|> """Put the bucket into the cache."""
self.dump_bytecode(bucket)
class FileSystemBytecodeCache(BytecodeCache):
"""A bytecode cache that stores bytecode on the filesystem. It accepts
two arguments: The directory where the cache items are stored and a
pattern string that is used to build the filename.
If no directory is specified the system temporary items folder is used.
The pattern can be used to have multiple separate caches operate on the
same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``
is replaced with the cache key.
>>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')
This bytecode cache supports clearing of the cache using the clear method.
"""
def __init__(self, directory=None, pattern='__jinja2_%s.cache'):
if directory is None:
directory = tempfile.gettempdir()
self.directory = directory
self.pattern = pattern
def _get_cache_filename(self, bucket):
return path.join(self.directory, self.pattern % bucket.key)
def load_bytecode(self, bucket):
<|code_end|>
. Write the next line using the current file imports:
from os import path, listdir
from cStringIO import StringIO
from hashlib import sha1
from sha import new as sha1
from jinja2.utils import open_if_exists
from os import remove
import marshal
import tempfile
import cPickle as pickle
import fnmatch
and context from other files:
# Path: jinja2/utils.py
# def open_if_exists(filename, mode='r'):
# """Returns a file descriptor for the filename if that file exists,
# otherwise `None`.
# """
# try:
# return file(filename, mode)
# except IOError, e:
# if e.errno not in (errno.ENOENT, errno.EISDIR):
# raise
, which may include functions, classes, or code. Output only the next line. | f = open_if_exists(self._get_cache_filename(bucket), 'rb') |
Here is a snippet: <|code_start|>
def test_odd(value):
"""Return true if the variable is odd."""
return value % 2 == 1
def test_even(value):
"""Return true if the variable is even."""
return value % 2 == 0
def test_divisibleby(value, num):
"""Check if a variable is divisible by a number."""
return value % num == 0
def test_defined(value):
"""Return true if the variable is defined:
.. sourcecode:: jinja
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
See the :func:`default` filter for a simple way to set undefined
variables.
"""
<|code_end|>
. Write the next line using the current file imports:
import re
from jinja2.runtime import Undefined
and context from other files:
# Path: jinja2/runtime.py
# class Undefined(object):
# """The default undefined type. This undefined type can be printed and
# iterated over, but every other access will raise an :exc:`UndefinedError`:
#
# >>> foo = Undefined(name='foo')
# >>> str(foo)
# ''
# >>> not foo
# True
# >>> foo + 42
# Traceback (most recent call last):
# ...
# UndefinedError: 'foo' is undefined
# """
# __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
# '_undefined_exception')
#
# def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):
# self._undefined_hint = hint
# self._undefined_obj = obj
# self._undefined_name = name
# self._undefined_exception = exc
#
# def _fail_with_undefined_error(self, *args, **kwargs):
# """Regular callback function for undefined objects that raises an
# `UndefinedError` on call.
# """
# if self._undefined_hint is None:
# if self._undefined_obj is None:
# hint = '%r is undefined' % self._undefined_name
# elif not isinstance(self._undefined_name, basestring):
# hint = '%r object has no element %r' % (
# self._undefined_obj.__class__.__name__,
# self._undefined_name
# )
# else:
# hint = '%r object has no attribute %r' % (
# self._undefined_obj.__class__.__name__,
# self._undefined_name
# )
# else:
# hint = self._undefined_hint
# raise self._undefined_exception(hint)
#
# __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
# __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
# __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
# __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
# __int__ = __float__ = __complex__ = __pow__ = __rpow__ = \
# _fail_with_undefined_error
#
# def __str__(self):
# return unicode(self).encode('utf-8')
#
# def __unicode__(self):
# return u''
#
# def __len__(self):
# return 0
#
# def __iter__(self):
# if 0:
# yield None
#
# def __nonzero__(self):
# return False
#
# def __repr__(self):
# return 'Undefined'
, which may include functions, classes, or code. Output only the next line. | return not isinstance(value, Undefined) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
jinja2.runtime
~~~~~~~~~~~~~~
Runtime helpers.
:copyright: Copyright 2008 by Armin Ronacher.
:license: BSD.
"""
# these variables are exported to the template runtime
__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',
'TemplateRuntimeError', 'missing', 'concat', 'escape',
'markup_join', 'unicode_join']
#: the types we support for context functions
_context_function_types = (FunctionType, MethodType)
def markup_join(seq):
"""Concatenation that escapes if necessary and converts to unicode."""
buf = []
iterator = imap(soft_unicode, seq)
for arg in iterator:
buf.append(arg)
if hasattr(arg, '__html__'):
<|code_end|>
, generate the next line using the imports in this file:
import sys
from itertools import chain, imap
from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
concat, MethodType, FunctionType
from jinja2.exceptions import UndefinedError, TemplateRuntimeError
from collections import Mapping
and context (functions, classes, or occasionally code) from other files:
# Path: jinja2/utils.py
# def _test_gen_bug():
# def concat(gen):
# def is_python_keyword(name):
# def method(self): pass
# def _func():
# def contextfunction(f):
# def environmentfunction(f):
# def is_undefined(obj):
# def consume(iterable):
# def clear_caches():
# def import_string(import_name, silent=False):
# def open_if_exists(filename, mode='r'):
# def pformat(obj, verbose=False):
# def urlize(text, trim_url_limit=None, nofollow=False):
# def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
# def __new__(cls, base=u'', encoding=None, errors='strict'):
# def __html__(self):
# def __add__(self, other):
# def __radd__(self, other):
# def __mul__(self, num):
# def __mod__(self, arg):
# def __repr__(self):
# def join(self, seq):
# def split(self, *args, **kwargs):
# def rsplit(self, *args, **kwargs):
# def splitlines(self, *args, **kwargs):
# def unescape(self):
# def handle_match(m):
# def striptags(self):
# def escape(cls, s):
# def make_wrapper(name):
# def func(self, *args, **kwargs):
# def _escape_argspec(obj, iterable):
# def __init__(self, obj):
# def __init__(self, capacity):
# def _postinit(self):
# def _remove(self, obj):
# def __getstate__(self):
# def __setstate__(self, d):
# def __getnewargs__(self):
# def copy(self):
# def get(self, key, default=None):
# def setdefault(self, key, default=None):
# def clear(self):
# def __contains__(self, key):
# def __len__(self):
# def __repr__(self):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def __delitem__(self, key):
# def items(self):
# def iteritems(self):
# def values(self):
# def itervalue(self):
# def keys(self):
# def iterkeys(self):
# def __reversed__(self):
# def __init__(self, *items):
# def reset(self):
# def current(self):
# def next(self):
# def __init__(self, sep=u', '):
# def __call__(self):
# def escape(s):
# def soft_unicode(s):
# def __init__(self, _func, *args, **kwargs):
# def __call__(self, *args, **kwargs):
# class _C(object):
# class Markup(unicode):
# class _MarkupEscapeHelper(object):
# class LRUCache(object):
# class Cycler(object):
# class Joiner(object):
# class partial(object):
#
# Path: jinja2/exceptions.py
# class UndefinedError(TemplateRuntimeError):
# """Raised if a template tries to operate on :class:`Undefined`."""
#
# class TemplateRuntimeError(TemplateError):
# """A generic runtime error in the template engine. Under some situations
# Jinja may raise this exception.
# """
. Output only the next line. | return Markup(u'').join(chain(buf, iterator)) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
jinja2.runtime
~~~~~~~~~~~~~~
Runtime helpers.
:copyright: Copyright 2008 by Armin Ronacher.
:license: BSD.
"""
# these variables are exported to the template runtime
__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',
'TemplateRuntimeError', 'missing', 'concat', 'escape',
'markup_join', 'unicode_join']
#: the types we support for context functions
_context_function_types = (FunctionType, MethodType)
def markup_join(seq):
"""Concatenation that escapes if necessary and converts to unicode."""
buf = []
<|code_end|>
, generate the next line using the imports in this file:
import sys
from itertools import chain, imap
from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
concat, MethodType, FunctionType
from jinja2.exceptions import UndefinedError, TemplateRuntimeError
from collections import Mapping
and context (functions, classes, or occasionally code) from other files:
# Path: jinja2/utils.py
# def _test_gen_bug():
# def concat(gen):
# def is_python_keyword(name):
# def method(self): pass
# def _func():
# def contextfunction(f):
# def environmentfunction(f):
# def is_undefined(obj):
# def consume(iterable):
# def clear_caches():
# def import_string(import_name, silent=False):
# def open_if_exists(filename, mode='r'):
# def pformat(obj, verbose=False):
# def urlize(text, trim_url_limit=None, nofollow=False):
# def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
# def __new__(cls, base=u'', encoding=None, errors='strict'):
# def __html__(self):
# def __add__(self, other):
# def __radd__(self, other):
# def __mul__(self, num):
# def __mod__(self, arg):
# def __repr__(self):
# def join(self, seq):
# def split(self, *args, **kwargs):
# def rsplit(self, *args, **kwargs):
# def splitlines(self, *args, **kwargs):
# def unescape(self):
# def handle_match(m):
# def striptags(self):
# def escape(cls, s):
# def make_wrapper(name):
# def func(self, *args, **kwargs):
# def _escape_argspec(obj, iterable):
# def __init__(self, obj):
# def __init__(self, capacity):
# def _postinit(self):
# def _remove(self, obj):
# def __getstate__(self):
# def __setstate__(self, d):
# def __getnewargs__(self):
# def copy(self):
# def get(self, key, default=None):
# def setdefault(self, key, default=None):
# def clear(self):
# def __contains__(self, key):
# def __len__(self):
# def __repr__(self):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def __delitem__(self, key):
# def items(self):
# def iteritems(self):
# def values(self):
# def itervalue(self):
# def keys(self):
# def iterkeys(self):
# def __reversed__(self):
# def __init__(self, *items):
# def reset(self):
# def current(self):
# def next(self):
# def __init__(self, sep=u', '):
# def __call__(self):
# def escape(s):
# def soft_unicode(s):
# def __init__(self, _func, *args, **kwargs):
# def __call__(self, *args, **kwargs):
# class _C(object):
# class Markup(unicode):
# class _MarkupEscapeHelper(object):
# class LRUCache(object):
# class Cycler(object):
# class Joiner(object):
# class partial(object):
#
# Path: jinja2/exceptions.py
# class UndefinedError(TemplateRuntimeError):
# """Raised if a template tries to operate on :class:`Undefined`."""
#
# class TemplateRuntimeError(TemplateError):
# """A generic runtime error in the template engine. Under some situations
# Jinja may raise this exception.
# """
. Output only the next line. | iterator = imap(soft_unicode, seq) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
jinja2.runtime
~~~~~~~~~~~~~~
Runtime helpers.
:copyright: Copyright 2008 by Armin Ronacher.
:license: BSD.
"""
# these variables are exported to the template runtime
__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',
'TemplateRuntimeError', 'missing', 'concat', 'escape',
'markup_join', 'unicode_join']
#: the types we support for context functions
_context_function_types = (FunctionType, MethodType)
def markup_join(seq):
"""Concatenation that escapes if necessary and converts to unicode."""
buf = []
iterator = imap(soft_unicode, seq)
for arg in iterator:
buf.append(arg)
if hasattr(arg, '__html__'):
return Markup(u'').join(chain(buf, iterator))
<|code_end|>
. Use current file imports:
(import sys
from itertools import chain, imap
from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
concat, MethodType, FunctionType
from jinja2.exceptions import UndefinedError, TemplateRuntimeError
from collections import Mapping)
and context including class names, function names, or small code snippets from other files:
# Path: jinja2/utils.py
# def _test_gen_bug():
# def concat(gen):
# def is_python_keyword(name):
# def method(self): pass
# def _func():
# def contextfunction(f):
# def environmentfunction(f):
# def is_undefined(obj):
# def consume(iterable):
# def clear_caches():
# def import_string(import_name, silent=False):
# def open_if_exists(filename, mode='r'):
# def pformat(obj, verbose=False):
# def urlize(text, trim_url_limit=None, nofollow=False):
# def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
# def __new__(cls, base=u'', encoding=None, errors='strict'):
# def __html__(self):
# def __add__(self, other):
# def __radd__(self, other):
# def __mul__(self, num):
# def __mod__(self, arg):
# def __repr__(self):
# def join(self, seq):
# def split(self, *args, **kwargs):
# def rsplit(self, *args, **kwargs):
# def splitlines(self, *args, **kwargs):
# def unescape(self):
# def handle_match(m):
# def striptags(self):
# def escape(cls, s):
# def make_wrapper(name):
# def func(self, *args, **kwargs):
# def _escape_argspec(obj, iterable):
# def __init__(self, obj):
# def __init__(self, capacity):
# def _postinit(self):
# def _remove(self, obj):
# def __getstate__(self):
# def __setstate__(self, d):
# def __getnewargs__(self):
# def copy(self):
# def get(self, key, default=None):
# def setdefault(self, key, default=None):
# def clear(self):
# def __contains__(self, key):
# def __len__(self):
# def __repr__(self):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def __delitem__(self, key):
# def items(self):
# def iteritems(self):
# def values(self):
# def itervalue(self):
# def keys(self):
# def iterkeys(self):
# def __reversed__(self):
# def __init__(self, *items):
# def reset(self):
# def current(self):
# def next(self):
# def __init__(self, sep=u', '):
# def __call__(self):
# def escape(s):
# def soft_unicode(s):
# def __init__(self, _func, *args, **kwargs):
# def __call__(self, *args, **kwargs):
# class _C(object):
# class Markup(unicode):
# class _MarkupEscapeHelper(object):
# class LRUCache(object):
# class Cycler(object):
# class Joiner(object):
# class partial(object):
#
# Path: jinja2/exceptions.py
# class UndefinedError(TemplateRuntimeError):
# """Raised if a template tries to operate on :class:`Undefined`."""
#
# class TemplateRuntimeError(TemplateError):
# """A generic runtime error in the template engine. Under some situations
# Jinja may raise this exception.
# """
. Output only the next line. | return concat(buf) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
"""
jinja2.runtime
~~~~~~~~~~~~~~
Runtime helpers.
:copyright: Copyright 2008 by Armin Ronacher.
:license: BSD.
"""
# these variables are exported to the template runtime
__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',
'TemplateRuntimeError', 'missing', 'concat', 'escape',
'markup_join', 'unicode_join']
#: the types we support for context functions
<|code_end|>
, predict the next line using imports from the current file:
import sys
from itertools import chain, imap
from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
concat, MethodType, FunctionType
from jinja2.exceptions import UndefinedError, TemplateRuntimeError
from collections import Mapping
and context including class names, function names, and sometimes code from other files:
# Path: jinja2/utils.py
# def _test_gen_bug():
# def concat(gen):
# def is_python_keyword(name):
# def method(self): pass
# def _func():
# def contextfunction(f):
# def environmentfunction(f):
# def is_undefined(obj):
# def consume(iterable):
# def clear_caches():
# def import_string(import_name, silent=False):
# def open_if_exists(filename, mode='r'):
# def pformat(obj, verbose=False):
# def urlize(text, trim_url_limit=None, nofollow=False):
# def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
# def __new__(cls, base=u'', encoding=None, errors='strict'):
# def __html__(self):
# def __add__(self, other):
# def __radd__(self, other):
# def __mul__(self, num):
# def __mod__(self, arg):
# def __repr__(self):
# def join(self, seq):
# def split(self, *args, **kwargs):
# def rsplit(self, *args, **kwargs):
# def splitlines(self, *args, **kwargs):
# def unescape(self):
# def handle_match(m):
# def striptags(self):
# def escape(cls, s):
# def make_wrapper(name):
# def func(self, *args, **kwargs):
# def _escape_argspec(obj, iterable):
# def __init__(self, obj):
# def __init__(self, capacity):
# def _postinit(self):
# def _remove(self, obj):
# def __getstate__(self):
# def __setstate__(self, d):
# def __getnewargs__(self):
# def copy(self):
# def get(self, key, default=None):
# def setdefault(self, key, default=None):
# def clear(self):
# def __contains__(self, key):
# def __len__(self):
# def __repr__(self):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def __delitem__(self, key):
# def items(self):
# def iteritems(self):
# def values(self):
# def itervalue(self):
# def keys(self):
# def iterkeys(self):
# def __reversed__(self):
# def __init__(self, *items):
# def reset(self):
# def current(self):
# def next(self):
# def __init__(self, sep=u', '):
# def __call__(self):
# def escape(s):
# def soft_unicode(s):
# def __init__(self, _func, *args, **kwargs):
# def __call__(self, *args, **kwargs):
# class _C(object):
# class Markup(unicode):
# class _MarkupEscapeHelper(object):
# class LRUCache(object):
# class Cycler(object):
# class Joiner(object):
# class partial(object):
#
# Path: jinja2/exceptions.py
# class UndefinedError(TemplateRuntimeError):
# """Raised if a template tries to operate on :class:`Undefined`."""
#
# class TemplateRuntimeError(TemplateError):
# """A generic runtime error in the template engine. Under some situations
# Jinja may raise this exception.
# """
. Output only the next line. | _context_function_types = (FunctionType, MethodType) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
"""
jinja2.runtime
~~~~~~~~~~~~~~
Runtime helpers.
:copyright: Copyright 2008 by Armin Ronacher.
:license: BSD.
"""
# these variables are exported to the template runtime
__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',
'TemplateRuntimeError', 'missing', 'concat', 'escape',
'markup_join', 'unicode_join']
#: the types we support for context functions
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
from itertools import chain, imap
from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
concat, MethodType, FunctionType
from jinja2.exceptions import UndefinedError, TemplateRuntimeError
from collections import Mapping
and context:
# Path: jinja2/utils.py
# def _test_gen_bug():
# def concat(gen):
# def is_python_keyword(name):
# def method(self): pass
# def _func():
# def contextfunction(f):
# def environmentfunction(f):
# def is_undefined(obj):
# def consume(iterable):
# def clear_caches():
# def import_string(import_name, silent=False):
# def open_if_exists(filename, mode='r'):
# def pformat(obj, verbose=False):
# def urlize(text, trim_url_limit=None, nofollow=False):
# def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
# def __new__(cls, base=u'', encoding=None, errors='strict'):
# def __html__(self):
# def __add__(self, other):
# def __radd__(self, other):
# def __mul__(self, num):
# def __mod__(self, arg):
# def __repr__(self):
# def join(self, seq):
# def split(self, *args, **kwargs):
# def rsplit(self, *args, **kwargs):
# def splitlines(self, *args, **kwargs):
# def unescape(self):
# def handle_match(m):
# def striptags(self):
# def escape(cls, s):
# def make_wrapper(name):
# def func(self, *args, **kwargs):
# def _escape_argspec(obj, iterable):
# def __init__(self, obj):
# def __init__(self, capacity):
# def _postinit(self):
# def _remove(self, obj):
# def __getstate__(self):
# def __setstate__(self, d):
# def __getnewargs__(self):
# def copy(self):
# def get(self, key, default=None):
# def setdefault(self, key, default=None):
# def clear(self):
# def __contains__(self, key):
# def __len__(self):
# def __repr__(self):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def __delitem__(self, key):
# def items(self):
# def iteritems(self):
# def values(self):
# def itervalue(self):
# def keys(self):
# def iterkeys(self):
# def __reversed__(self):
# def __init__(self, *items):
# def reset(self):
# def current(self):
# def next(self):
# def __init__(self, sep=u', '):
# def __call__(self):
# def escape(s):
# def soft_unicode(s):
# def __init__(self, _func, *args, **kwargs):
# def __call__(self, *args, **kwargs):
# class _C(object):
# class Markup(unicode):
# class _MarkupEscapeHelper(object):
# class LRUCache(object):
# class Cycler(object):
# class Joiner(object):
# class partial(object):
#
# Path: jinja2/exceptions.py
# class UndefinedError(TemplateRuntimeError):
# """Raised if a template tries to operate on :class:`Undefined`."""
#
# class TemplateRuntimeError(TemplateError):
# """A generic runtime error in the template engine. Under some situations
# Jinja may raise this exception.
# """
which might include code, classes, or functions. Output only the next line. | _context_function_types = (FunctionType, MethodType) |
Predict the next line for this snippet: <|code_start|> arguments.append(args[self._argument_count:])
elif len(args) > self._argument_count:
raise TypeError('macro %r takes not more than %d argument(s)' %
(self.name, len(self.arguments)))
return self._func(*arguments)
def __repr__(self):
return '<%s %s>' % (
self.__class__.__name__,
self.name is None and 'anonymous' or repr(self.name)
)
class Undefined(object):
"""The default undefined type. This undefined type can be printed and
iterated over, but every other access will raise an :exc:`UndefinedError`:
>>> foo = Undefined(name='foo')
>>> str(foo)
''
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
"""
__slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
'_undefined_exception')
<|code_end|>
with the help of current file imports:
import sys
from itertools import chain, imap
from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
concat, MethodType, FunctionType
from jinja2.exceptions import UndefinedError, TemplateRuntimeError
from collections import Mapping
and context from other files:
# Path: jinja2/utils.py
# def _test_gen_bug():
# def concat(gen):
# def is_python_keyword(name):
# def method(self): pass
# def _func():
# def contextfunction(f):
# def environmentfunction(f):
# def is_undefined(obj):
# def consume(iterable):
# def clear_caches():
# def import_string(import_name, silent=False):
# def open_if_exists(filename, mode='r'):
# def pformat(obj, verbose=False):
# def urlize(text, trim_url_limit=None, nofollow=False):
# def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
# def __new__(cls, base=u'', encoding=None, errors='strict'):
# def __html__(self):
# def __add__(self, other):
# def __radd__(self, other):
# def __mul__(self, num):
# def __mod__(self, arg):
# def __repr__(self):
# def join(self, seq):
# def split(self, *args, **kwargs):
# def rsplit(self, *args, **kwargs):
# def splitlines(self, *args, **kwargs):
# def unescape(self):
# def handle_match(m):
# def striptags(self):
# def escape(cls, s):
# def make_wrapper(name):
# def func(self, *args, **kwargs):
# def _escape_argspec(obj, iterable):
# def __init__(self, obj):
# def __init__(self, capacity):
# def _postinit(self):
# def _remove(self, obj):
# def __getstate__(self):
# def __setstate__(self, d):
# def __getnewargs__(self):
# def copy(self):
# def get(self, key, default=None):
# def setdefault(self, key, default=None):
# def clear(self):
# def __contains__(self, key):
# def __len__(self):
# def __repr__(self):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def __delitem__(self, key):
# def items(self):
# def iteritems(self):
# def values(self):
# def itervalue(self):
# def keys(self):
# def iterkeys(self):
# def __reversed__(self):
# def __init__(self, *items):
# def reset(self):
# def current(self):
# def next(self):
# def __init__(self, sep=u', '):
# def __call__(self):
# def escape(s):
# def soft_unicode(s):
# def __init__(self, _func, *args, **kwargs):
# def __call__(self, *args, **kwargs):
# class _C(object):
# class Markup(unicode):
# class _MarkupEscapeHelper(object):
# class LRUCache(object):
# class Cycler(object):
# class Joiner(object):
# class partial(object):
#
# Path: jinja2/exceptions.py
# class UndefinedError(TemplateRuntimeError):
# """Raised if a template tries to operate on :class:`Undefined`."""
#
# class TemplateRuntimeError(TemplateError):
# """A generic runtime error in the template engine. Under some situations
# Jinja may raise this exception.
# """
, which may contain function names, class names, or code. Output only the next line. | def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError): |
Given the code snippet: <|code_start|>
def visit(self, node, *args, **kwargs):
"""Visit a node."""
f = self.get_visitor(node)
if f is not None:
return f(node, *args, **kwargs)
return self.generic_visit(node, *args, **kwargs)
def generic_visit(self, node, *args, **kwargs):
"""Called if no explicit visitor function exists for a node."""
for node in node.iter_child_nodes():
self.visit(node, *args, **kwargs)
class NodeTransformer(NodeVisitor):
"""Walks the abstract syntax tree and allows modifications of nodes.
The `NodeTransformer` will walk the AST and use the return value of the
visitor functions to replace or remove the old node. If the return
value of the visitor function is `None` the node will be removed
from the previous location otherwise it's replaced with the return
value. The return value may be the original node in which case no
replacement takes place.
"""
def generic_visit(self, node, *args, **kwargs):
for field, old_value in node.iter_fields():
if isinstance(old_value, list):
new_values = []
for value in old_value:
<|code_end|>
, generate the next line using the imports in this file:
from jinja2.nodes import Node
and context (functions, classes, or occasionally code) from other files:
# Path: jinja2/nodes.py
# class Node(object):
# """Baseclass for all Jinja2 nodes. There are a number of nodes available
# of different types. There are three major types:
#
# - :class:`Stmt`: statements
# - :class:`Expr`: expressions
# - :class:`Helper`: helper nodes
# - :class:`Template`: the outermost wrapper node
#
# All nodes have fields and attributes. Fields may be other nodes, lists,
# or arbitrary values. Fields are passed to the constructor as regular
# positional arguments, attributes as keyword arguments. Each node has
# two attributes: `lineno` (the line number of the node) and `environment`.
# The `environment` attribute is set at the end of the parsing process for
# all nodes automatically.
# """
# __metaclass__ = NodeType
# fields = ()
# attributes = ('lineno', 'environment')
# abstract = True
#
# def __init__(self, *fields, **attributes):
# if self.abstract:
# raise TypeError('abstract nodes are not instanciable')
# if fields:
# if len(fields) != len(self.fields):
# if not self.fields:
# raise TypeError('%r takes 0 arguments' %
# self.__class__.__name__)
# raise TypeError('%r takes 0 or %d argument%s' % (
# self.__class__.__name__,
# len(self.fields),
# len(self.fields) != 1 and 's' or ''
# ))
# for name, arg in izip(self.fields, fields):
# setattr(self, name, arg)
# for attr in self.attributes:
# setattr(self, attr, attributes.pop(attr, None))
# if attributes:
# raise TypeError('unknown attribute %r' %
# iter(attributes).next())
#
# def iter_fields(self, exclude=None, only=None):
# """This method iterates over all fields that are defined and yields
# ``(key, value)`` tuples. Per default all fields are returned, but
# it's possible to limit that to some fields by providing the `only`
# parameter or to exclude some using the `exclude` parameter. Both
# should be sets or tuples of field names.
# """
# for name in self.fields:
# if (exclude is only is None) or \
# (exclude is not None and name not in exclude) or \
# (only is not None and name in only):
# try:
# yield name, getattr(self, name)
# except AttributeError:
# pass
#
# def iter_child_nodes(self, exclude=None, only=None):
# """Iterates over all direct child nodes of the node. This iterates
# over all fields and yields the values of they are nodes. If the value
# of a field is a list all the nodes in that list are returned.
# """
# for field, item in self.iter_fields(exclude, only):
# if isinstance(item, list):
# for n in item:
# if isinstance(n, Node):
# yield n
# elif isinstance(item, Node):
# yield item
#
# def find(self, node_type):
# """Find the first node of a given type. If no such node exists the
# return value is `None`.
# """
# for result in self.find_all(node_type):
# return result
#
# def find_all(self, node_type):
# """Find all the nodes of a given type."""
# for child in self.iter_child_nodes():
# if isinstance(child, node_type):
# yield child
# for result in child.find_all(node_type):
# yield result
#
# def set_ctx(self, ctx):
# """Reset the context of a node and all child nodes. Per default the
# parser will all generate nodes that have a 'load' context as it's the
# most common one. This method is used in the parser to set assignment
# targets and other nodes to a store context.
# """
# todo = deque([self])
# while todo:
# node = todo.popleft()
# if 'ctx' in node.fields:
# node.ctx = ctx
# todo.extend(node.iter_child_nodes())
# return self
#
# def set_lineno(self, lineno, override=False):
# """Set the line numbers of the node and children."""
# todo = deque([self])
# while todo:
# node = todo.popleft()
# if 'lineno' in node.attributes:
# if node.lineno is None or override:
# node.lineno = lineno
# todo.extend(node.iter_child_nodes())
# return self
#
# def set_environment(self, environment):
# """Set the environment for all nodes."""
# todo = deque([self])
# while todo:
# node = todo.popleft()
# node.environment = environment
# todo.extend(node.iter_child_nodes())
# return self
#
# def __eq__(self, other):
# return type(self) is type(other) and \
# tuple(self.iter_fields()) == tuple(other.iter_fields())
#
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __repr__(self):
# return '%s(%s)' % (
# self.__class__.__name__,
# ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
# arg in self.fields)
# )
. Output only the next line. | if isinstance(value, Node): |
Next line prediction: <|code_start|>#!/usr/bin/python
if __name__ == '__main__':
if not os.path.exists("logs"):
os.makedirs("logs")
redis = Redis(host=os.environ['REDIS_HOST'], port=int(os.environ['REDIS_PORT']), db=int(os.environ['REDIS_DB']))
<|code_end|>
. Use current file imports:
(from redis import Redis
from lib.model import sm
from lib.export import export_chat
import time
import datetime
import os)
and context including class names, function names, or small code snippets from other files:
# Path: lib/model.py
# def now():
# def init_db():
# class Log(Base):
# class LogPage(Base):
#
# Path: lib/export.py
# def export_chat(redis, sql, url):
# log = sql.query(Log).filter(Log.url == url).scalar()
#
# if not log:
# return
#
# # Create temp directory.
# if not os.path.exists('tmp/' + log.url):
# os.makedirs('tmp/' + log.url)
#
# # Create export pages.
# for page in log.pages:
# with codecs.open('tmp/' + log.url + '/' + str(page.number) + '.html', 'w', 'utf8') as f:
# paginator = paginate.Page([], page=page.number, items_per_page=1, item_count=log.page_count, url=PageURL(log.url))
#
# lines = page.content.split('\n')[0:-1]
# lines = filter(lambda x: x is not None, map(lambda _: parse_line(_, 0), lines))
#
# for line in lines:
# line['datetime'] = datetime.datetime.fromtimestamp(line['timestamp']/1000.0)
#
# f.write(log_template.render(
# lines=lines,
# paginator=paginator
# ))
#
# # Copy static assets
# shutil.copyfile('static/js/bbcode.js', 'tmp/' + log.url + '/bbcode.js')
# shutil.copyfile('static/js/jquery.min.js', 'tmp/' + log.url + '/jquery.min.js')
# shutil.copyfile('static/css/msparp.css', 'tmp/' + log.url + '/msparp.css')
# shutil.copyfile('static/css/chat.css', 'tmp/' + log.url + '/chat.css')
#
# # Create export zip.
# with zipfile.ZipFile('logs/' + log.url + ".zip", 'w', zipfile.ZIP_DEFLATED) as logzip:
# zipdir('tmp/'+log.url, logzip, log.url)
#
# # Cleanup the temporary files.
# shutil.rmtree('tmp/' + log.url, ignore_errors=True)
. Output only the next line. | sql = sm() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python
if __name__ == '__main__':
if not os.path.exists("logs"):
os.makedirs("logs")
redis = Redis(host=os.environ['REDIS_HOST'], port=int(os.environ['REDIS_PORT']), db=int(os.environ['REDIS_DB']))
sql = sm()
current_time = datetime.datetime.now()
while True:
if datetime.datetime.now().minute != current_time.minute:
# Export chats.
for chat in redis.smembers('export-queue'):
<|code_end|>
with the help of current file imports:
from redis import Redis
from lib.model import sm
from lib.export import export_chat
import time
import datetime
import os
and context from other files:
# Path: lib/model.py
# def now():
# def init_db():
# class Log(Base):
# class LogPage(Base):
#
# Path: lib/export.py
# def export_chat(redis, sql, url):
# log = sql.query(Log).filter(Log.url == url).scalar()
#
# if not log:
# return
#
# # Create temp directory.
# if not os.path.exists('tmp/' + log.url):
# os.makedirs('tmp/' + log.url)
#
# # Create export pages.
# for page in log.pages:
# with codecs.open('tmp/' + log.url + '/' + str(page.number) + '.html', 'w', 'utf8') as f:
# paginator = paginate.Page([], page=page.number, items_per_page=1, item_count=log.page_count, url=PageURL(log.url))
#
# lines = page.content.split('\n')[0:-1]
# lines = filter(lambda x: x is not None, map(lambda _: parse_line(_, 0), lines))
#
# for line in lines:
# line['datetime'] = datetime.datetime.fromtimestamp(line['timestamp']/1000.0)
#
# f.write(log_template.render(
# lines=lines,
# paginator=paginator
# ))
#
# # Copy static assets
# shutil.copyfile('static/js/bbcode.js', 'tmp/' + log.url + '/bbcode.js')
# shutil.copyfile('static/js/jquery.min.js', 'tmp/' + log.url + '/jquery.min.js')
# shutil.copyfile('static/css/msparp.css', 'tmp/' + log.url + '/msparp.css')
# shutil.copyfile('static/css/chat.css', 'tmp/' + log.url + '/chat.css')
#
# # Create export zip.
# with zipfile.ZipFile('logs/' + log.url + ".zip", 'w', zipfile.ZIP_DEFLATED) as logzip:
# zipdir('tmp/'+log.url, logzip, log.url)
#
# # Cleanup the temporary files.
# shutil.rmtree('tmp/' + log.url, ignore_errors=True)
, which may contain function names, class names, or code. Output only the next line. | export_chat(redis, sql, chat) |
Next line prediction: <|code_start|> abort(404)
if log.url is not None:
return redirect(url_for('view_log', chat=log.url))
abort(404)
@app.route('/chat/<chat>/log')
def view_log(chat=None):
try:
log = g.mysql.query(Log).filter(Log.url==chat).one()
except NoResultFound:
abort(404)
current_page = request.args.get('page') or log.page_count
mode = request.args.get('mode') or 'normal'
try:
log_page = g.mysql.query(LogPage).filter(and_(LogPage.log_id==log.id, LogPage.number==current_page)).one()
except NoResultFound:
abort(404)
url_generator = paginate.PageURL(url_for('view_log', chat=chat), {'page': current_page})
# It's only one row per page and we want to fetch them via both log id and
# page number rather than slicing, so we'll just give it an empty list and
# override the count.
paginator = paginate.Page([], page=current_page, items_per_page=1, item_count=log.page_count, url=url_generator)
# Pages end with a line break, so the last line is blank.
lines = log_page.content.split('\n')[0:-1]
<|code_end|>
. Use current file imports:
(import datetime
import os
from flask import Flask, g, request, render_template, redirect, url_for, abort
from sqlalchemy import and_
from sqlalchemy.orm.exc import NoResultFound
from webhelpers import paginate
from lib.messages import parse_line
from lib.model import Log, LogPage
from lib.requests import connect_mysql, disconnect_mysql
from werkzeug.contrib.fixers import ProxyFix)
and context including class names, function names, or small code snippets from other files:
# Path: lib/messages.py
# def parse_line(line, id):
# # Lines consist of comma separated fields.
# parts = line.split(',', 4)
#
# try:
# if not isinstance(parts[4], unicode):
# parts[4] = unicode(parts[4], encoding='utf-8')
#
# timestamp = int(parts[0])
# counter = int(parts[1])
# except (ValueError, IndexError):
# return None
#
# return {
# 'id': id,
# 'timestamp': timestamp,
# 'counter': counter,
# 'type': parts[2],
# 'color': parts[3],
# 'line': parts[4]
# }
#
# Path: lib/model.py
# class Log(Base):
# __tablename__ = 'logs'
# id = Column(Integer, primary_key=True)
# url = Column(String(100), unique=True)
# page_count = Column(Integer, default=1)
# time_created = Column(DateTime(), nullable=False, default=now)
# time_saved = Column(DateTime(), nullable=False, default=now)
#
# class LogPage(Base):
# __tablename__ = 'log_pages'
# log_id = Column(Integer, ForeignKey('logs.id'), primary_key=True, autoincrement=False)
# number = Column(Integer, primary_key=True)
# content = Column(UnicodeText, nullable=False)
#
# Path: lib/requests.py
# def connect_mysql():
# g.mysql = sm()
#
# def disconnect_mysql(response=None):
# g.mysql.close()
# del g.mysql
# return response
. Output only the next line. | lines = filter(lambda x: x is not None, map(lambda _: parse_line(_, 0), lines)) |
Continue the code snippet: <|code_start|># Export config
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config['EXPORT_URL'] = os.environ.get("EXPORT_URL", "http://unsupportedlogs.msparp.com")
app.wsgi_app = ProxyFix(app.wsgi_app, 2)
# Pre and post request stuff
app.before_request(connect_mysql)
app.teardown_request(disconnect_mysql)
# Chat
@app.route('/chat')
@app.route('/chat/<chat>')
def chat(chat=None):
if chat is None:
return redirect(url_for("configure"))
return redirect(url_for("view_log", chat=chat))
@app.route('/logs/group/<chat>')
def old_view_log(chat):
return redirect(url_for('view_log', chat=chat))
@app.route('/logs/<log_id>')
def view_log_by_id(log_id=None):
try:
log_id = int(log_id)
except ValueError:
abort(400)
try:
<|code_end|>
. Use current file imports:
import datetime
import os
from flask import Flask, g, request, render_template, redirect, url_for, abort
from sqlalchemy import and_
from sqlalchemy.orm.exc import NoResultFound
from webhelpers import paginate
from lib.messages import parse_line
from lib.model import Log, LogPage
from lib.requests import connect_mysql, disconnect_mysql
from werkzeug.contrib.fixers import ProxyFix
and context (classes, functions, or code) from other files:
# Path: lib/messages.py
# def parse_line(line, id):
# # Lines consist of comma separated fields.
# parts = line.split(',', 4)
#
# try:
# if not isinstance(parts[4], unicode):
# parts[4] = unicode(parts[4], encoding='utf-8')
#
# timestamp = int(parts[0])
# counter = int(parts[1])
# except (ValueError, IndexError):
# return None
#
# return {
# 'id': id,
# 'timestamp': timestamp,
# 'counter': counter,
# 'type': parts[2],
# 'color': parts[3],
# 'line': parts[4]
# }
#
# Path: lib/model.py
# class Log(Base):
# __tablename__ = 'logs'
# id = Column(Integer, primary_key=True)
# url = Column(String(100), unique=True)
# page_count = Column(Integer, default=1)
# time_created = Column(DateTime(), nullable=False, default=now)
# time_saved = Column(DateTime(), nullable=False, default=now)
#
# class LogPage(Base):
# __tablename__ = 'log_pages'
# log_id = Column(Integer, ForeignKey('logs.id'), primary_key=True, autoincrement=False)
# number = Column(Integer, primary_key=True)
# content = Column(UnicodeText, nullable=False)
#
# Path: lib/requests.py
# def connect_mysql():
# g.mysql = sm()
#
# def disconnect_mysql(response=None):
# g.mysql.close()
# del g.mysql
# return response
. Output only the next line. | log = g.mysql.query(Log).filter(Log.id==log_id).one() |
Next line prediction: <|code_start|>@app.route('/logs/group/<chat>')
def old_view_log(chat):
return redirect(url_for('view_log', chat=chat))
@app.route('/logs/<log_id>')
def view_log_by_id(log_id=None):
try:
log_id = int(log_id)
except ValueError:
abort(400)
try:
log = g.mysql.query(Log).filter(Log.id==log_id).one()
except NoResultFound:
abort(404)
if log.url is not None:
return redirect(url_for('view_log', chat=log.url))
abort(404)
@app.route('/chat/<chat>/log')
def view_log(chat=None):
try:
log = g.mysql.query(Log).filter(Log.url==chat).one()
except NoResultFound:
abort(404)
current_page = request.args.get('page') or log.page_count
mode = request.args.get('mode') or 'normal'
try:
<|code_end|>
. Use current file imports:
(import datetime
import os
from flask import Flask, g, request, render_template, redirect, url_for, abort
from sqlalchemy import and_
from sqlalchemy.orm.exc import NoResultFound
from webhelpers import paginate
from lib.messages import parse_line
from lib.model import Log, LogPage
from lib.requests import connect_mysql, disconnect_mysql
from werkzeug.contrib.fixers import ProxyFix)
and context including class names, function names, or small code snippets from other files:
# Path: lib/messages.py
# def parse_line(line, id):
# # Lines consist of comma separated fields.
# parts = line.split(',', 4)
#
# try:
# if not isinstance(parts[4], unicode):
# parts[4] = unicode(parts[4], encoding='utf-8')
#
# timestamp = int(parts[0])
# counter = int(parts[1])
# except (ValueError, IndexError):
# return None
#
# return {
# 'id': id,
# 'timestamp': timestamp,
# 'counter': counter,
# 'type': parts[2],
# 'color': parts[3],
# 'line': parts[4]
# }
#
# Path: lib/model.py
# class Log(Base):
# __tablename__ = 'logs'
# id = Column(Integer, primary_key=True)
# url = Column(String(100), unique=True)
# page_count = Column(Integer, default=1)
# time_created = Column(DateTime(), nullable=False, default=now)
# time_saved = Column(DateTime(), nullable=False, default=now)
#
# class LogPage(Base):
# __tablename__ = 'log_pages'
# log_id = Column(Integer, ForeignKey('logs.id'), primary_key=True, autoincrement=False)
# number = Column(Integer, primary_key=True)
# content = Column(UnicodeText, nullable=False)
#
# Path: lib/requests.py
# def connect_mysql():
# g.mysql = sm()
#
# def disconnect_mysql(response=None):
# g.mysql.close()
# del g.mysql
# return response
. Output only the next line. | log_page = g.mysql.query(LogPage).filter(and_(LogPage.log_id==log.id, LogPage.number==current_page)).one() |
Given the code snippet: <|code_start|>
app = Flask(__name__)
# Export config
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config['EXPORT_URL'] = os.environ.get("EXPORT_URL", "http://unsupportedlogs.msparp.com")
app.wsgi_app = ProxyFix(app.wsgi_app, 2)
# Pre and post request stuff
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import os
from flask import Flask, g, request, render_template, redirect, url_for, abort
from sqlalchemy import and_
from sqlalchemy.orm.exc import NoResultFound
from webhelpers import paginate
from lib.messages import parse_line
from lib.model import Log, LogPage
from lib.requests import connect_mysql, disconnect_mysql
from werkzeug.contrib.fixers import ProxyFix
and context (functions, classes, or occasionally code) from other files:
# Path: lib/messages.py
# def parse_line(line, id):
# # Lines consist of comma separated fields.
# parts = line.split(',', 4)
#
# try:
# if not isinstance(parts[4], unicode):
# parts[4] = unicode(parts[4], encoding='utf-8')
#
# timestamp = int(parts[0])
# counter = int(parts[1])
# except (ValueError, IndexError):
# return None
#
# return {
# 'id': id,
# 'timestamp': timestamp,
# 'counter': counter,
# 'type': parts[2],
# 'color': parts[3],
# 'line': parts[4]
# }
#
# Path: lib/model.py
# class Log(Base):
# __tablename__ = 'logs'
# id = Column(Integer, primary_key=True)
# url = Column(String(100), unique=True)
# page_count = Column(Integer, default=1)
# time_created = Column(DateTime(), nullable=False, default=now)
# time_saved = Column(DateTime(), nullable=False, default=now)
#
# class LogPage(Base):
# __tablename__ = 'log_pages'
# log_id = Column(Integer, ForeignKey('logs.id'), primary_key=True, autoincrement=False)
# number = Column(Integer, primary_key=True)
# content = Column(UnicodeText, nullable=False)
#
# Path: lib/requests.py
# def connect_mysql():
# g.mysql = sm()
#
# def disconnect_mysql(response=None):
# g.mysql.close()
# del g.mysql
# return response
. Output only the next line. | app.before_request(connect_mysql) |
Predict the next line for this snippet: <|code_start|>
app = Flask(__name__)
# Export config
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config['EXPORT_URL'] = os.environ.get("EXPORT_URL", "http://unsupportedlogs.msparp.com")
app.wsgi_app = ProxyFix(app.wsgi_app, 2)
# Pre and post request stuff
app.before_request(connect_mysql)
<|code_end|>
with the help of current file imports:
import datetime
import os
from flask import Flask, g, request, render_template, redirect, url_for, abort
from sqlalchemy import and_
from sqlalchemy.orm.exc import NoResultFound
from webhelpers import paginate
from lib.messages import parse_line
from lib.model import Log, LogPage
from lib.requests import connect_mysql, disconnect_mysql
from werkzeug.contrib.fixers import ProxyFix
and context from other files:
# Path: lib/messages.py
# def parse_line(line, id):
# # Lines consist of comma separated fields.
# parts = line.split(',', 4)
#
# try:
# if not isinstance(parts[4], unicode):
# parts[4] = unicode(parts[4], encoding='utf-8')
#
# timestamp = int(parts[0])
# counter = int(parts[1])
# except (ValueError, IndexError):
# return None
#
# return {
# 'id': id,
# 'timestamp': timestamp,
# 'counter': counter,
# 'type': parts[2],
# 'color': parts[3],
# 'line': parts[4]
# }
#
# Path: lib/model.py
# class Log(Base):
# __tablename__ = 'logs'
# id = Column(Integer, primary_key=True)
# url = Column(String(100), unique=True)
# page_count = Column(Integer, default=1)
# time_created = Column(DateTime(), nullable=False, default=now)
# time_saved = Column(DateTime(), nullable=False, default=now)
#
# class LogPage(Base):
# __tablename__ = 'log_pages'
# log_id = Column(Integer, ForeignKey('logs.id'), primary_key=True, autoincrement=False)
# number = Column(Integer, primary_key=True)
# content = Column(UnicodeText, nullable=False)
#
# Path: lib/requests.py
# def connect_mysql():
# g.mysql = sm()
#
# def disconnect_mysql(response=None):
# g.mysql.close()
# del g.mysql
# return response
, which may contain function names, class names, or code. Output only the next line. | app.teardown_request(disconnect_mysql) |
Given the code snippet: <|code_start|> colored(gethostname(), 'blue'),
colored(':', 'cyan'),
colored('rpl-attacks', 'red'),
colored('>>', 'cyan'),
))
welcome = "\nType help or ? to list commands.\n"
def __init__(self, parallel):
self.continuation_prompt = self.prompt
self.parallel = parallel
width, height = get_terminal_size() or MIN_TERM_SIZE
if any(map((lambda s: s[0] < s[1]), zip((height, width), MIN_TERM_SIZE))):
stdout.write("\x1b[8;{rows};{cols}t".format(rows=max(MIN_TERM_SIZE[0], height),
cols=max(MIN_TERM_SIZE[1], width)))
if self.parallel:
processes = cpu_count()
self.__last_tasklist = None
self.tasklist = {}
self.pool = Pool(processes, lambda: signal(SIGINT, SIG_IGN))
atexit.register(self.graceful_exit)
self.reexec = ['status']
self.__bind_commands()
super(FrameworkConsole, self).__init__()
self.do_loglevel('info')
self.do_clear('')
def __bind_commands(self):
if not self.parallel:
for attr in ['complete_kill', 'do_kill', 'do_status']:
delattr(FrameworkConsole, attr)
<|code_end|>
, generate the next line using the imports in this file:
import atexit
import os
from copy import copy
from funcsigs import signature
from getpass import getuser
from multiprocessing import cpu_count, Pool
from signal import signal, SIGINT, SIG_IGN, SIGTERM
from six.moves import zip_longest
from socket import gethostname
from subprocess import check_output, Popen, PIPE
from sys import stdout
from termcolor import colored
from terminaltables import SingleTable
from types import MethodType
from core import *
from core.commands import get_commands
and context (functions, classes, or occasionally code) from other files:
# Path: core/commands.py
# def get_commands(include=None, exclude=None):
# commands = []
# for n, f in getmembers(modules[__name__], isfunction):
# if n in [c for c, _ in commands]:
# continue
# if hasattr(f, 'behavior'):
# if f.__name__.startswith('_'):
# shortname = f.__name__.lstrip('_')
# n, f = shortname, getattr(modules[__name__], shortname)
# f.__name__ = shortname
# if (include is None or n in include) and (exclude is None or n not in exclude):
# commands.append((n, f))
# return commands
. Output only the next line. | for name, func in get_commands(): |
Based on the snippet: <|code_start|>def read_config(path, sep=' = '):
"""
This helper function reads a simple configuration file with the following format:
max_range = 50.0
repeat = 1
blocks = []
goal = ""
...
:param path: path to the configuration file
:param sep: separator between the key and the value
:return: dictionary with the whole configuration
"""
config = {}
try:
with open(join(path, 'simulation.conf')) as f:
for line in f.readlines():
if line.strip().startswith('#'):
continue
try:
k, v = [x.strip() for x in line.split(sep)]
except ValueError:
continue
try:
v = ast.literal_eval(v)
except ValueError:
pass
config[k] = v
except OSError:
<|code_end|>
, predict the immediate next line with the help of imports:
import ast
from os.path import join
from six import string_types
from core.conf.logconfig import logger
and context (classes, functions, sometimes code) from other files:
# Path: core/conf/logconfig.py
# LOG_FORMAT = '%(asctime)s %(name)s[%(process)d] %(levelname)s %(message)s'
# LOG_LEVELS = {
# 'info': logging.INFO,
# 'warning': logging.WARNING,
# 'error': logging.ERROR,
# 'debug': logging.DEBUG,
# }
# HIDDEN_ALL = ['warnings', 'stdout', 'stderr', 'running']
# HIDDEN_KEEP_STDERR = ['warnings', 'stdout', 'running']
# def set_logging(lvl='info'):
. Output only the next line. | logger.error("Configuration file 'simulation.conf' does not exist !") |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
@task
def console():
""" Open framework's console. """
with settings(remote_interrupt=False):
local('python main.py')
<|code_end|>
, predict the immediate next line with the help of imports:
from fabric.api import local, settings, task
from core.commands import get_commands
and context (classes, functions, sometimes code) from other files:
# Path: core/commands.py
# def get_commands(include=None, exclude=None):
# commands = []
# for n, f in getmembers(modules[__name__], isfunction):
# if n in [c for c, _ in commands]:
# continue
# if hasattr(f, 'behavior'):
# if f.__name__.startswith('_'):
# shortname = f.__name__.lstrip('_')
# n, f = shortname, getattr(modules[__name__], shortname)
# f.__name__ = shortname
# if (include is None or n in include) and (exclude is None or n not in exclude):
# commands.append((n, f))
# return commands
. Output only the next line. | for name, func in get_commands(exclude=['list']): |
Continue the code snippet: <|code_start|> source = f.read()
for line in source.split('\n'):
if pattern in line:
return True
return False
def modify_cooja(cooja_dir):
"""
This function inserts a block in the IF statement for parsing Cooja's input arguments.
It searches for the IF statement pattern containing the '-nogui' case and inserts
an IF block for a new '-hidden' case (aimed to run a simulation with the GUI hidden).
:param cooja_dir: Cooja's directory
:return: None
"""
pattern = 'if (args.length > 0 && args[0].startsWith("-nogui="))'
cooja_file = join(cooja_dir, 'java', 'org', 'contikios', 'cooja', 'Cooja.java')
changed = False
with open(cooja_file) as f:
source = f.read()
buffer = []
for line in source.split('\n'):
if pattern in line:
with open('src/Cooja.java.snippet') as f:
line = line.replace(pattern, '{} else {}'.format(f.read().strip(), pattern))
changed = True
buffer.append(line)
with open(cooja_file, 'w') as f:
f.write('\n'.join(buffer))
<|code_end|>
. Use current file imports:
from os.path import exists, expanduser, join
from core.conf.logconfig import logger
and context (classes, functions, or code) from other files:
# Path: core/conf/logconfig.py
# LOG_FORMAT = '%(asctime)s %(name)s[%(process)d] %(levelname)s %(message)s'
# LOG_LEVELS = {
# 'info': logging.INFO,
# 'warning': logging.WARNING,
# 'error': logging.ERROR,
# 'debug': logging.DEBUG,
# }
# HIDDEN_ALL = ['warnings', 'stdout', 'stderr', 'running']
# HIDDEN_KEEP_STDERR = ['warnings', 'stdout', 'running']
# def set_logging(lvl='info'):
. Output only the next line. | logger.debug(" > Cooja.java modified" if changed else " > Cooja.java already up-to-date") |
Next line prediction: <|code_start|>class ExperimentTestCase(unittest.TestCase):
path = expanduser(join(EXPERIMENT_FOLDER, JSON))
backup = path + '.backup'
class Test6Prepare(ExperimentTestCase):
""" 6. Prepare a simulation campaign """
@classmethod
def setUpClass(cls):
if exists(cls.path):
sh.mv(cls.path, cls.backup)
prepare(JSON, ask=False, silent=True)
def test1_campaign_format(self):
""" > Is the new experiment campaign a correct JSON file ? """
try:
with open(self.path) as f:
loads(jsmin(f.read()))
passed = True
except:
passed = False
self.assertTrue(passed)
class Test7Drop(ExperimentTestCase):
""" 7. Drop the same simulation campaign """
@classmethod
def setUpClass(cls):
<|code_end|>
. Use current file imports:
(import sh
import unittest
from jsmin import jsmin
from json import loads
from os.path import exists, expanduser, join
from core.commands import drop, prepare
from core.conf.constants import EXPERIMENT_FOLDER)
and context including class names, function names, or small code snippets from other files:
# Path: core/commands.py
# @command(autocomplete=lambda: list_campaigns(),
# examples=["my-simulation-campaign"],
# expand=('exp_file', {'into': EXPERIMENT_FOLDER, 'ext': 'json'}),
# exists=('exp_file', {'on_boolean': 'ask', 'confirm': "Are you sure ? (yes|no) [default: no] "}),
# start_msg=("REMOVING EXPERIMENT CAMPAIGN AT '{}'", 'exp_file'))
# def drop(exp_file, ask=True, **kwargs):
# """
# Remove a campaign of experiments.
#
# :param exp_file: experiments JSON filename or basename (absolute or relative path ; if no path provided,
# the JSON file is searched in the experiments folder)
# :param ask: ask confirmation
# :param kwargs: simulation keyword arguments (see the documentation for more information)
# """
# remove_files(EXPERIMENT_FOLDER, exp_file)
#
# @command(autocomplete=lambda: list_campaigns(),
# examples=["my-simulation-campaign"],
# expand=('exp_file', {'into': EXPERIMENT_FOLDER, 'ext': 'json'}),
# exists=('exp_file', {'loglvl': 'warning', 'msg': (" > Experiment campaign '{}' already exists !", 'exp_file'),
# 'on_boolean': 'ask', 'confirm': "Overwrite ? (yes|no) [default: no] "}),
# start_msg=("CREATING NEW EXPERIMENT CAMPAIGN AT '{}'", 'exp_file'))
# def prepare(exp_file, ask=True, **kwargs):
# """
# Create a campaign of experiments from a template.
#
# :param exp_file: experiments JSON filename or basename (absolute or relative path ; if no path provided,
# the JSON file is searched in the experiments folder)
# :param ask: ask confirmation
# :param kwargs: simulation keyword arguments (see the documentation for more information)
# """
# render_campaign(exp_file)
#
# Path: core/conf/constants.py
# EXPERIMENT_FOLDER = abspath(expanduser(confparser.get("RPL Attacks Framework Configuration", "experiments_folder")))
. Output only the next line. | drop(JSON, ask=False, silent=True) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
JSON = 'test-campaign.json'
class ExperimentTestCase(unittest.TestCase):
path = expanduser(join(EXPERIMENT_FOLDER, JSON))
backup = path + '.backup'
class Test6Prepare(ExperimentTestCase):
""" 6. Prepare a simulation campaign """
@classmethod
def setUpClass(cls):
if exists(cls.path):
sh.mv(cls.path, cls.backup)
<|code_end|>
, predict the immediate next line with the help of imports:
import sh
import unittest
from jsmin import jsmin
from json import loads
from os.path import exists, expanduser, join
from core.commands import drop, prepare
from core.conf.constants import EXPERIMENT_FOLDER
and context (classes, functions, sometimes code) from other files:
# Path: core/commands.py
# @command(autocomplete=lambda: list_campaigns(),
# examples=["my-simulation-campaign"],
# expand=('exp_file', {'into': EXPERIMENT_FOLDER, 'ext': 'json'}),
# exists=('exp_file', {'on_boolean': 'ask', 'confirm': "Are you sure ? (yes|no) [default: no] "}),
# start_msg=("REMOVING EXPERIMENT CAMPAIGN AT '{}'", 'exp_file'))
# def drop(exp_file, ask=True, **kwargs):
# """
# Remove a campaign of experiments.
#
# :param exp_file: experiments JSON filename or basename (absolute or relative path ; if no path provided,
# the JSON file is searched in the experiments folder)
# :param ask: ask confirmation
# :param kwargs: simulation keyword arguments (see the documentation for more information)
# """
# remove_files(EXPERIMENT_FOLDER, exp_file)
#
# @command(autocomplete=lambda: list_campaigns(),
# examples=["my-simulation-campaign"],
# expand=('exp_file', {'into': EXPERIMENT_FOLDER, 'ext': 'json'}),
# exists=('exp_file', {'loglvl': 'warning', 'msg': (" > Experiment campaign '{}' already exists !", 'exp_file'),
# 'on_boolean': 'ask', 'confirm': "Overwrite ? (yes|no) [default: no] "}),
# start_msg=("CREATING NEW EXPERIMENT CAMPAIGN AT '{}'", 'exp_file'))
# def prepare(exp_file, ask=True, **kwargs):
# """
# Create a campaign of experiments from a template.
#
# :param exp_file: experiments JSON filename or basename (absolute or relative path ; if no path provided,
# the JSON file is searched in the experiments folder)
# :param ask: ask confirmation
# :param kwargs: simulation keyword arguments (see the documentation for more information)
# """
# render_campaign(exp_file)
#
# Path: core/conf/constants.py
# EXPERIMENT_FOLDER = abspath(expanduser(confparser.get("RPL Attacks Framework Configuration", "experiments_folder")))
. Output only the next line. | prepare(JSON, ask=False, silent=True) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.