Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|># under the License.
_POSTGRESQL = 'postgresql'
_MYSQL = 'mysql'
_ORM = 'orm'
_REPO_DRIVERS_MAP = {
_POSTGRESQL: 'monasca_notification.common.repositories.'
'postgres.pgsql_repo:PostgresqlRepo',
_MYSQL: 'monasca_notification.common.repositories.'
... | types.PluginOpt(name='repo_driver', choices=_ACCEPTABLE_DRIVER_KEYS, |
Next line prediction: <|code_start|>Link to Grafana: {grafana_url}
With dimensions:
{metric_dimensions}'''
EMAIL_MULTIPLE_HOST_BASE = u'''On host "{hostname}" {message}
Alarm "{alarm_name}" transitioned to the {state} state at {timestamp} UTC
alarm_id: {alarm_id}
Lifecycle state: {lifecycle_state}
Link: {link}
Link... | class EmailNotifier(abstract_notifier.AbstractNotifier): |
Given the code snippet: <|code_start|># (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
#
# 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... | self._db_repo = get_db_repo() |
Using the snippet: <|code_start|># (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
#
# 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/LICE... | self.statsd = get_statsd_client() |
Using the snippet: <|code_start|># (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
#
# 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/LICE... | notifiers.init(self.statsd) |
Given the code snippet: <|code_start|># Copyright 2016-2017 FUJITSU LIMITED
#
# 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 requ... | utils.get_statsd_client() |
Continue the code 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 o... | test_notification = notification.Notification(1, 'ntype', 'name', |
Next line prediction: <|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 wri... | cfg.ListOpt(name='url', item_type=types.HostAddressPortType(), |
Predict the next line for this snippet: <|code_start|># limitations under the License.
CONF = cfg.CONF
"""
notification.address = https://hipchat.hpcloud.net/v2/room/<room_id>/notification?auth_token=432432
How to get access token?
1) Login to Hipchat with the user account which is used for notification
2... | class HipChatNotifier(abstract_notifier.AbstractNotifier): |
Continue the code snippet: <|code_start|> def _start_processor(self, notifications, mock_log, mock_smtp, mock_statsd, mock_pymsql):
"""Start the processor with the proper mocks
"""
# Since the log runs in another thread I can mock it directly,
# instead change the methods to put to a ... | notification = m_notification.Notification( |
Next line prediction: <|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.
"""Tests NotificationProcessor"""
... | email_notifier.register_opts(base.config.CONF) |
Here is a snippet: <|code_start|>
email_notifier.register_opts(base.config.CONF)
self.conf_default(group='email_notifier', server='my.smtp.server',
port=25, user=None, password=None,
timeout=60, from_addr='hpcs.mon@hp.com')
self.conf_default(g... | np.NotificationProcessor.insert_configured_plugins = mock.Mock() |
Here is a 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... | class TestNotificationProcessor(base.BaseTestCase): |
Continue the code snippet: <|code_start|> def setUp(self):
super(TestSlack, self).setUp(
slack_notifier.register_opts
)
self.conf_default(group='slack_notifier', timeout=50,
ca_certs='/etc/ssl/certs/ca-bundle.crt',
proxy='http://... | notification = m_notification.Notification(0, 'slack', 'slack notification', |
Given the code snippet: <|code_start|> return {'old_state': 'OK',
'alarm_description': 'test Alarm description',
'message': 'I am alarming!',
'alarm_definition_id': 0,
'alarm_name': 'test Alarm',
'tenant_id': '0',
'metrics': [
{'... | slack_notifier.register_opts |
Using the snippet: <|code_start|> 'metrics': metrics}
def slack_text():
return {'old_state': 'OK',
'alarm_description': 'test Alarm description',
'message': 'I am alarming!',
'alarm_definition_id': 0,
'alarm_name': 'test Alarm',
'tenant_id': '... | class TestSlack(base.PluginTestCase): |
Using the snippet: <|code_start|># (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP
# Copyright 2017 Fujitsu LIMITED
#
# 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
#
# ht... | self._statsd = get_statsd_client() |
Given 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 Licen... | self._alarms = ap.AlarmProcessor() |
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 Lice... | self._notifier = np.NotificationProcessor() |
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, so... | notification = Notification(notification_json['id'], |
Continue the code snippet: <|code_start|> self.trap.put(data)
self.trap.put(headers)
r = requestsResponse(200)
return r
def _http_post_404(self, url, data, headers, **kwargs):
r = requestsResponse(404)
return r
def _http_post_exception(self, url, data, headers, *... | notification = m_notification.Notification(0, 'webhook', 'webhook notification', |
Given the code snippet: <|code_start|># limitations under the License.
def alarm(metrics):
return {"tenantId": "0",
"alarmId": "0",
"alarmDefinitionId": 0,
"alarmName": "test Alarm",
"alarmDescription": "test Alarm description",
"oldState": "OK",
... | super(TestWebhook, self).setUp(webhook_notifier.register_opts) |
Next line prediction: <|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 alarm(metrics):
return {"tenantId": "0",
"alarmId": "0",
"alarmDefi... | class TestWebhook(base.PluginTestCase): |
Based on the snippet: <|code_start|># Copyright 2017 FUJITSU LIMITED
#
# 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... | cfg.ListOpt(name='url', item_type=types.HostAddressPortType(), |
Given the code snippet: <|code_start|> self.assertEqual(data['client_url'], '')
details = dict(data['details'])
self.assertEqual(details['alarm_id'], '0')
self.assertEqual(details['alarm_name'], 'test Alarm')
self.assertEqual(details['current'], 'ALARM')
self.assertEqual(... | notification = m_notification.Notification(0, |
Using the snippet: <|code_start|># implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def alarm(metrics):
return {"tenantId": "0",
"alarmId": "0",
"alarmName": "test Alarm",
"oldState": "OK",
"newState":... | pagerduty_notifier.register_opts |
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 gov... | class TestPagerduty(base.PluginTestCase): |
Given the code snippet: <|code_start|> self.assertEqual(len(notifications), 6)
self.assertItemsEqual(notifications,
['EMAIL', 'PAGERDUTY', 'WEBHOOK',
'HIPCHAT', 'SLACK', 'JIRA'])
@mock.patch('monasca_notification.plugins.email_notifier')
... | m_notification.Notification(0, 'email', 'email notification', |
Given snippet: <|code_start|> def start(self, key):
key = key + "_start"
if key in self.timer_calls:
self.timer_calls[key] += 1
else:
self.timer_calls[key] = 1
def stop(self, key):
key = key + "_stop"
if key in self.timer_calls:
self.ti... | email_notifier.register_opts(base.config.CONF) |
Next line prediction: <|code_start|> if key in self.timer_calls:
self.timer_calls[key] += 1
else:
self.timer_calls[key] = 1
def stop(self, key):
key = key + "_stop"
if key in self.timer_calls:
self.timer_calls[key] += 1
else:
se... | pagerduty_notifier.register_opts(base.config.CONF) |
Using the snippet: <|code_start|> key = key + "_start"
if key in self.timer_calls:
self.timer_calls[key] += 1
else:
self.timer_calls[key] = 1
def stop(self, key):
key = key + "_stop"
if key in self.timer_calls:
self.timer_calls[key] += 1
... | webhook_notifier.register_opts(base.config.CONF) |
Based on the snippet: <|code_start|> self.timer_calls[key] += 1
else:
self.timer_calls[key] = 1
class StatsdCounter(object):
def __init__(self):
self.counter = 0
def increment(self, val):
self.counter += val
class TestInterface(base.BaseTestCase):
def set... | notifiers.possible_notifiers = [] |
Here is a snippet: <|code_start|>
@contextlib.contextmanager
def time(self, key):
self.start(key)
yield
self.stop(key)
def start(self, key):
key = key + "_start"
if key in self.timer_calls:
self.timer_calls[key] += 1
else:
self.timer_c... | class TestInterface(base.BaseTestCase): |
Predict the next line after this snippet: <|code_start|> removal_version='3.0.0'
)
def config(self, config_dict):
pass
@property
def statsd_name(self):
return 'sent_webhook_count'
def send_notification(self, notification):
"""Send the notification via webhook
... | auth_token = utils.get_auth_token() |
Here is a snippet: <|code_start|># (C) Copyright 2014-2017 Hewlett Packard Enterprise Development LP
# Copyright 2017 FUJITSU LIMITED
#
# 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
#
# ht... | CONF = config.CONF |
Based on the snippet: <|code_start|>
# Kill everything, that didn't already die
for child in multiprocessing.active_children():
LOG.debug('Killing pid %s' % child.pid)
try:
os.kill(child.pid, signal.SIGKILL)
except Exception: # nosec
# There is really nothing to ... | args=(notification_engine.NotificationEngine,)) |
Next line prediction: <|code_start|> if signum == signal.SIGTERM:
sys.exit(0)
sys.exit(signum)
def start_process(process_type, *args):
LOG.info("start process: {}".format(process_type))
p = process_type(*args)
p.run()
def main(argv=None):
warnings.simplefilter('always')
config.pa... | args=(periodic_engine.PeriodicEngine, int(notification_period))) |
Given snippet: <|code_start|> os.kill(child.pid, signal.SIGKILL)
except Exception: # nosec
# There is really nothing to do if the kill fails, so just go on.
# The # nosec keeps bandit from reporting this as a security issue
pass
if signum == signal.SIGTERM:
... | args=(retry_engine.RetryEngine,)) |
Next line prediction: <|code_start|> self.logger = logger or setup_logger('cloudify_agent.api.factory')
@staticmethod
def _find_implementation(process_management):
"""
Locates the proper daemon implementation for the specific
process management system. For this to work, all impl... | raise exceptions.DaemonNotImplementedError(process_management) |
Using the snippet: <|code_start|> """
Factory class for manipulating various daemon instances.
"""
def __init__(self, username=None, storage=None, logger=None):
"""
:param username: the username the daemons are registered under.
if no username if passed, the cur... | self.storage = storage or utils.internal.get_storage_directory( |
Based on the snippet: <|code_start|>
logger = setup_logger(
'cloudify-agent.tests.daemon',
logger_level=logging.DEBUG)
def _is_agent_alive(name, timeout=10):
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import time
from cloudify.amqp_client import get_client
from... | return agent_utils.is_agent_alive( |
Here is a snippet: <|code_start|> daemon.stop()
daemon.delete()
assert not os.path.exists(daemon.config_path)
pytest.raises(
CommandExecutionException,
nssm_daemon.runner.run,
'sc getdisplayname {0}'.format(daemon.name))
@pytest.mark.only_rabbit
@pytest.mark.only_nt
def test_sta... | shared._test_create(nssm_daemon) |
Predict the next line after this snippet: <|code_start|> assert os.path.exists(daemon.script_path)
assert os.path.exists(daemon.config_path)
@pytest.mark.only_rabbit
@pytest.mark.only_posix
def test_delete(detach_daemon):
daemon = detach_daemon.create_daemon()
daemon.create()
daemon.configure()
... | wait_for_daemon_alive(daemon.queue) |
Continue the code snippet: <|code_start|>@pytest.mark.only_rabbit
@pytest.mark.only_posix
def test_delete(detach_daemon):
daemon = detach_daemon.create_daemon()
daemon.create()
daemon.configure()
daemon.start()
daemon.stop()
daemon.delete()
assert not os.path.exists(daemon.script_path)
a... | wait_for_daemon_dead(daemon.queue) |
Given snippet: <|code_start|>def test_cron_respawn(detach_daemon):
daemon = detach_daemon.create_daemon(cron_respawn=True,
cron_respawn_delay=1)
daemon.create()
daemon.configure()
daemon.start()
crontab = detach_daemon.runner.run('crontab -l').std_out
as... | shared._test_create(detach_daemon) |
Given snippet: <|code_start|> else:
return winrm.Session(
target=winrm_url,
auth=(self.session_config['user'],
self.session_config['password']),
transport=self.session_config['transport'])
def run(self, command, raise_on_failu... | env_file = utils.env_to_file(execution_env, posix=False) |
Predict the next line for this snippet: <|code_start|> return self.run(
'@powershell -Command "[System.IO.Path]::GetTempPath()"'
).std_out.strip()
def new_dir(self, path):
"""
Creates the path as a new directory.
:param path: The directory path to create.
... | return api_utils.json_loads(response) |
Given the following code snippet before the placeholder: <|code_start|> """
return os.environ[cls.CLOUDIFY_DAEMON_USER_KEY]
@classmethod
def get_storage_directory(cls, username=None):
"""
Retrieve path to the directory where all daemon
registered under a specific userna... | return '{0}-{1}'.format(defaults.CLOUDIFY_AGENT_PREFIX, uuid.uuid4()) |
Given the code snippet: <|code_start|> '[%(name)s] %(message)s',
logger_level=logging.INFO)
def get_logger():
return _logger
def show_version(ctx, param, value):
if not value or ctx.resilient_parsing:
return
ver = get_agent_version()
... | api_utils_logger.setLevel(logging.DEBUG) |
Next line prediction: <|code_start|>
@cfy.group()
@click.option('--debug', default=False, is_flag=True)
@click.option('--version', is_flag=True, callback=show_version,
expose_value=False, is_eager=True, help='Show version and exit')
def main(debug):
if debug:
# configure global logger level
... | daemon_sub_command.add_command(daemons.create) |
Next line prediction: <|code_start|> logger.info('Cloudify Agent {0}'.format(ver))
ctx.exit()
@cfy.group()
@click.option('--debug', default=False, is_flag=True)
@click.option('--version', is_flag=True, callback=show_version,
expose_value=False, is_eager=True, help='Show version and exit')
def mai... | main.add_command(configure.configure) |
Given snippet: <|code_start|># * See the License for the specific language governing permissions and
# * limitations under the License.
# adding all of our commands.
_logger = setup_logger('cloudify_agent.shell.main',
logger_format='%(asctime)s [%(levelname)-5s] '
... | @cfy.group() |
Predict the next line after this snippet: <|code_start|> password=None,
validate_connection=True,
fabric_env=None,
tmpdir=None):
# logger
self.logger = logger or setup_logger('fabric_runner')
# silence paramiko
logging.... | raise exceptions.AgentInstallerConfigurationError('Missing host') |
Next line prediction: <|code_start|> stdout = self.run('{0} -c "import sys; {1}; '
'sys.stdout.write(\'{2}{3}{4}\\n\''
'.format({5}))"'
.format(python_bin,
imports_line,
... | return api_utils.json_loads(response) |
Predict the next line for this snippet: <|code_start|>@pytest.mark.only_rabbit
@pytest.mark.only_ci
@pytest.mark.only_posix
def test_configure_start_on_boot(initd_daemon):
daemon = initd_daemon.create_daemon(start_on_boot=True)
daemon.create()
daemon.configure()
@pytest.mark.only_rabbit
@pytest.mark.only_... | wait_for_daemon_alive(daemon.queue) |
Predict the next line for this snippet: <|code_start|> daemon.delete()
assert not os.path.exists(daemon.script_path)
assert not os.path.exists(daemon.config_path)
@pytest.mark.only_rabbit
@pytest.mark.only_ci
@pytest.mark.only_posix
def test_configure_start_on_boot(initd_daemon):
daemon = initd_daemon.... | wait_for_daemon_dead(daemon.queue) |
Given snippet: <|code_start|> daemon = initd_daemon.create_daemon(cron_respawn=True,
cron_respawn_delay=1)
daemon.create()
daemon.configure()
daemon.start()
# initd daemon's cron is for root, so that respawning the daemon can
# use the init system which re... | shared._test_create(initd_daemon) |
Using the snippet: <|code_start|>
# these imports may run on a windows box, in which case they may fail. (if
# the pywin32 extensions). The tests wont run anyway because of the decorator,
# so we can just avoid this import.
try:
except ImportError:
FabricRunner = None
FabricCommandExecutionException = None
#... | with pytest.raises(exceptions.AgentInstallerConfigurationError, |
Continue the code snippet: <|code_start|>
try:
except ImportError:
# py2
class AgentPackageGenerator(object):
def __init__(self, file_server):
self.initialized = False
self._fs = file_server
def _initialize(self):
config = RawConfigParser()
config.add_section('install')
... | package_name = create_agent_package(self._fs.root_path, config) |
Here is a snippet: <|code_start|>
try:
except ImportError:
# py2
class AgentPackageGenerator(object):
def __init__(self, file_server):
self.initialized = False
self._fs = file_server
def _initialize(self):
config = RawConfigParser()
config.add_section('install')
c... | get_requirements_uri()) |
Next line prediction: <|code_start|>
try:
except ImportError:
# py2
class AgentPackageGenerator(object):
def __init__(self, file_server):
self.initialized = False
self._fs = file_server
def _initialize(self):
config = RawConfigParser()
config.add_section('install')
<|code... | config.set('install', 'cloudify_agent_module', get_source_uri()) |
Based on the snippet: <|code_start|>@click.option('--no-sudo',
help='Indication whether sudo should be used when applying '
' disable-requiretty part',
is_flag=True)
@handle_failures
def configure(disable_requiretty, relocated_env, no_sudo):
"""
Configures global ... | disable_requiretty_script_path = utils.resource_to_tempfile( |
Based on 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 ... | @handle_failures |
Given the code snippet: <|code_start|>
##############################################################################
# note that this file only tests validation and defaults of the winrm runner.
# it does not test the actual functionality because that requires starting
# a vm. functional tests are executed as local w... | winrm_runner.validate(session_config) |
Continue the code snippet: <|code_start|> # Missing password
session_config = {
'host': 'test_host',
'user': 'test_user'
}
with pytest.raises(ValueError, match='.*Invalid password.*'):
winrm_runner.validate(session_config)
def test_defaults():
runner = winrm_runner.WinRMRunn... | assert split_into_chunks(contents) == expected_chunks |
Continue the code snippet: <|code_start|>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.a... | operations.create(**kwargs) |
Using the snippet: <|code_start|>@pytest.fixture(scope='function')
def detach_daemon(tmp_path, agent_ssl_cert):
daemon = TestDetachedDaemon(tmp_path, logger, agent_ssl_cert)
yield daemon
daemon.runner.run("pkill -9 -f 'cloudify_agent.worker'",
exit_on_failure=False)
for _daemon i... | nssm_path = utils.get_absolute_resource_path( |
Predict the next line for this snippet: <|code_start|>
logger = setup_logger('cloudify_agent.tests.api.pm')
@pytest.fixture(scope='function', autouse=True)
def always_mock_storage_dir(mock_get_storage_dir):
yield
@pytest.fixture(scope='function')
def detach_daemon(tmp_path, agent_ssl_cert):
<|code_end|>
wit... | daemon = TestDetachedDaemon(tmp_path, logger, agent_ssl_cert) |
Given snippet: <|code_start|>
logger = setup_logger('cloudify_agent.tests.api.pm')
@pytest.fixture(scope='function', autouse=True)
def always_mock_storage_dir(mock_get_storage_dir):
yield
@pytest.fixture(scope='function')
def detach_daemon(tmp_path, agent_ssl_cert):
daemon = TestDetachedDaemon(tmp_path, ... | daemon = TestInitdDaemon(tmp_path, logger, agent_ssl_cert) |
Given snippet: <|code_start|>def always_mock_storage_dir(mock_get_storage_dir):
yield
@pytest.fixture(scope='function')
def detach_daemon(tmp_path, agent_ssl_cert):
daemon = TestDetachedDaemon(tmp_path, logger, agent_ssl_cert)
yield daemon
daemon.runner.run("pkill -9 -f 'cloudify_agent.worker'",
... | daemon = TestNSSMDaemon(tmp_path, logger, agent_ssl_cert) |
Predict the next line for this snippet: <|code_start|>
class AutoscaleApp(AppMixin, TemplateView):
template_name = 'app/index.html'
def get_context_data(self, *args, **kwargs):
context = super(AutoscaleApp, self).get_context_data(*args, **kwargs)
token = self.request.session.get('tsuru_toke... | instances = client.list(token).json() or [] |
Given the code snippet: <|code_start|>
class AutoscaleApp(AppMixin, TemplateView):
template_name = 'app/index.html'
def get_context_data(self, *args, **kwargs):
context = super(AutoscaleApp, self).get_context_data(*args, **kwargs)
token = self.request.session.get('tsuru_token').split(" ")[-... | pool_info = wclient.pool_info(pool_name, token) if pool_name else None |
Continue the code snippet: <|code_start|>
def new(request):
form = DataSourceForm(request.POST or None)
if form.is_valid():
token = request.GET.get("TSURU_TOKEN")
<|code_end|>
. Use current file imports:
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from ... | response = client.new(form.cleaned_data, token) |
Predict the next line for this snippet: <|code_start|>
class ScaleFormTest(TestCase):
def test_required_fields(self):
fields = {
"metric": True,
"operator": True,
"value": True,
"step": True,
"wait": True,
"aggregator": True,
... | form = forms.ScaleForm(42) |
Next line prediction: <|code_start|> "wait": True,
"aggregator": True,
}
form = forms.ScaleForm(42)
for field, required in fields.items():
self.assertEqual(form.fields[field].required, required)
self.assertEqual(form.fields['wait'].min_value, 42)
cl... | self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key |
Using the snippet: <|code_start|>
class RemoveTestCase(TestCase):
@mock.patch("tsuru_autoscale.action.client.list")
@mock.patch("tsuru_autoscale.action.client.remove")
def test_new_post(self, remove_mock, list_mock):
url = "{}?TSURU_TOKEN=bla".format(reverse("action-remove", args=["name"]))
... | self.assertIsInstance(response.context['form'], ActionForm) |
Given the code snippet: <|code_start|>
class RemoveTestCase(TestCase):
@mock.patch("tsuru_autoscale.action.client.list")
@mock.patch("tsuru_autoscale.action.client.remove")
def test_new_post(self, remove_mock, list_mock):
url = "{}?TSURU_TOKEN=bla".format(reverse("action-remove", args=["name"]))... | response = self.client.delete(url) |
Predict the next line after this snippet: <|code_start|>
def new(request):
form = ActionForm(request.POST or None)
if form.is_valid():
token = request.GET.get("TSURU_TOKEN")
<|code_end|>
using the current file's imports:
from django.shortcuts import render, redirect
from django.core.urlresolvers im... | client.new(form.cleaned_data, token) |
Predict the next line after this snippet: <|code_start|>
def get_or_create_tsuru_instance(instance_name, token):
token = urllib.unquote(token)
token = "bearer {}".format(token)
url = "{}/services/autoscale/instances/{}".format(client.tsuru_host(), instance_name)
headers = {"Authorization": token}
... | scale_up_form = forms.ScaleForm(30, request.POST or None, prefix="scale_up", initial={"operator": ">"}) |
Given the code snippet: <|code_start|>
def get_or_create_tsuru_instance(instance_name, token):
token = urllib.unquote(token)
token = "bearer {}".format(token)
<|code_end|>
, generate the next line using the imports in this file:
from django.shortcuts import render, redirect
from django.core.urlresolvers imp... | url = "{}/services/autoscale/instances/{}".format(client.tsuru_host(), instance_name) |
Continue the code snippet: <|code_start|>
def get_or_create_tsuru_instance(instance_name, token):
token = urllib.unquote(token)
token = "bearer {}".format(token)
url = "{}/services/autoscale/instances/{}".format(client.tsuru_host(), instance_name)
headers = {"Authorization": token}
response = req... | dlist = [(d["Name"], d["Name"]) for d in dclient.list(token).json()] |
Given the following code snippet before the placeholder: <|code_start|>
class ListTestCase(TestCase):
@mock.patch("tsuru_autoscale.event.client.list")
def test_list(self, list_mock):
url = "{}?TSURU_TOKEN=bla".format(reverse("event-list", args=["alarm_name"]))
<|code_end|>
, predict the next line us... | response = self.client.get(url) |
Predict the next line after this snippet: <|code_start|>
urlpatterns = [
url(r'^$', views.list, name='alarm-list'),
url(r'^new/$', views.new, name='alarm-new'),
url(r'^(?P<name>[\w\s-]+)/remove/$', views.remove, name='alarm-remove'),
<|code_end|>
using the current file's imports:
from django.conf.urls im... | url(r'^(?P<alarm_name>[\w\s-]+)/event/$', event_list, name='event-list'), |
Given the code snippet: <|code_start|>
class ListTestCase(TestCase):
def setUp(self):
settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'
engine = import_module(settings.SESSION_ENGINE)
store = engine.SessionStore()
store.save()
self.session = store
<|code_... | self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key |
Based on the snippet: <|code_start|>
class RemoveTestCase(TestCase):
@mock.patch("tsuru_autoscale.datasource.client.list")
@mock.patch("tsuru_autoscale.datasource.client.remove")
def test_remove(self, remove_mock, list_mock):
url = "{}?TSURU_TOKEN=bla".format(reverse("datasource-remove", args=["... | self.assertIsInstance(response.context['form'], DataSourceForm) |
Given snippet: <|code_start|>
class RemoveTestCase(TestCase):
@mock.patch("tsuru_autoscale.datasource.client.list")
@mock.patch("tsuru_autoscale.datasource.client.remove")
def test_remove(self, remove_mock, list_mock):
url = "{}?TSURU_TOKEN=bla".format(reverse("datasource-remove", args=["name"])... | response = self.client.delete(url) |
Predict the next line after this snippet: <|code_start|>
class NativeAutoscale(AppMixin, FormView):
template_name = "native/index.html"
form_class = forms.ScaleForm
def get_form(self):
token = self.request.session.get('tsuru_token').split(" ")[-1]
app_name = self.kwargs.get('app_name')
... | p_list = wclient.process_list(app_name, token) |
Predict the next line for this snippet: <|code_start|>
class RemoveTestCase(TestCase):
@mock.patch("tsuru_autoscale.alarm.client.list")
@mock.patch("tsuru_autoscale.alarm.client.remove")
def test_remove(self, remove_mock, list_mock):
url = "{}?TSURU_TOKEN=bla".format(reverse("alarm-remove", args... | self.assertIsInstance(response.context['form'], AlarmForm) |
Predict the next line after this snippet: <|code_start|>
class RemoveTestCase(TestCase):
@mock.patch("tsuru_autoscale.alarm.client.list")
@mock.patch("tsuru_autoscale.alarm.client.remove")
def test_remove(self, remove_mock, list_mock):
url = "{}?TSURU_TOKEN=bla".format(reverse("alarm-remove", ar... | response = self.client.delete(url) |
Here is a snippet: <|code_start|>
def new(request):
token = request.GET.get("TSURU_TOKEN")
form = AlarmForm(request.POST or None)
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.contrib ... | form.fields['datasource'].choices = datasource_list(token) |
Here is a snippet: <|code_start|>
def new(request):
token = request.GET.get("TSURU_TOKEN")
form = AlarmForm(request.POST or None)
form.fields['datasource'].choices = datasource_list(token)
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import render, redirect
fr... | form.fields['actions'].choices = action_list(token) |
Here is a snippet: <|code_start|>
def new(request):
token = request.GET.get("TSURU_TOKEN")
form = AlarmForm(request.POST or None)
form.fields['datasource'].choices = datasource_list(token)
form.fields['actions'].choices = action_list(token)
<|code_end|>
. Write the next line using the current file im... | form.fields['instance'].choices = service_instance_list(token) |
Given the following code snippet before the placeholder: <|code_start|>
def new(request):
token = request.GET.get("TSURU_TOKEN")
form = AlarmForm(request.POST or None)
form.fields['datasource'].choices = datasource_list(token)
form.fields['actions'].choices = action_list(token)
form.fields['insta... | client.new(form.cleaned_data, token) |
Given the following code snippet before the placeholder: <|code_start|>
def list(request, app_name=None):
token = request.session.get('tsuru_token').split(" ")[-1]
instances = client.list(token).json()
context = {
"list": instances,
}
return render(request, "instance/list.html", context)
... | events.extend(eclient.list(alarm["name"], token).json()) |
Using the snippet: <|code_start|> if x.startswith("("):
x = x[1:].strip()
if x.endswith(")"):
x = x[:-1].strip()
if x.startswith("v"):
x = x[1:].strip()
return x
def up_to_date(env, cmd, version, args=None, stdout_flag=None,
stdout_index=-1):
iversion = get_ins... | if shared._executable_not_on_path(cmd): |
Given the code snippet: <|code_start|> if x.startswith("v"):
x = x[1:].strip()
return x
def up_to_date(env, cmd, version, args=None, stdout_flag=None,
stdout_index=-1):
iversion = get_installed_version(env, cmd, version, args, stdout_flag,
stdout_i... | with quiet(): |
Given the code snippet: <|code_start|>"""
Automated installation on debian package systems with apt.
"""
def _apt_packages(to_install=None, pkg_list=None):
"""
Install packages available via apt-get.
Note that ``to_install`` and ``pkg_list`` arguments cannot be used simultaneously.
:type to_install:... | (packages, _) = _yaml_to_packages(config_file.base, to_install, config_file.dist) |
Continue the code snippet: <|code_start|>
TODO: Rename versions and document options.
"""
if type(versions) is str:
versions = [versions]
for version_info in versions:
if type(version_info) is str:
_install_tool(env, name, version=version_info, requirement_name=name, tool_ins... | _set_default_config(tool_env, tool_env["system_install"], symlink_version) |
Here is a snippet: <|code_start|>def _tools_conf_path(env):
"""
Load path to galaxy_tools_conf file from env, allowing expansion of $__contrib_dir__.
Default to $__contrib_dir__/flavor/cloudman/tools.yaml.
"""
contrib_dir = os.path.join(env.config_dir, os.pardir, "contrib")
default_tools_conf_pa... | _add_to_profiles(line) |
Given snippet: <|code_start|> py_version = ENV_PY_VERSIONS[env_name]
if "deepvariant" in env_packages:
# Ignore /etc/boto.cfg which creates conflicts with conda gsutils
# https://github.com/GoogleCloudPlatform/gsutil/issues/516
exports = "export BOTO_CONFIG=/ignoreglobal && "
else:
... | (packages, _) = _yaml_to_packages(config_file) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.