Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> else:
data_dir = os.path.join(get_home(), app_profiles[app]['dir'])
icon_path = os.path.join(image_dir, 'icons', app_profiles[app]['icon'])
if not os.path.exists(data_dir):
continue... | if not self.projects_list: |
Given snippet: <|code_start|> project['app'] = app
project['data_dir'] = data_dir
project['file'] = filename
project['display_name'] = os.path.splitext(filename)[0]
project['icon'] = icon_path
... | def __init__(self, project): |
Based on the snippet: <|code_start|> self.title.get_style_context().add_class('project_item_title')
self.title.set_alignment(xalign=0, yalign=1)
self.label_container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
self.label_container.pack_start(self.title, False, False, 0)
... | def activate(_win): |
Given the code snippet: <|code_start|> project['file'] = filename
project['display_name'] = os.path.splitext(filename)[0]
project['icon'] = icon_path
self.projects_list.append(project)
self.background = Gtk.EventBox(... | self.background.get_style_context().add_class('white') |
Next line prediction: <|code_start|>
icon_path = os.path.join(image_dir, 'icons', app_profiles[app]['icon'])
if not os.path.exists(data_dir):
continue
files = os.listdir(data_dir)
files_filtered = [f for f in files... | image_no_projects.set_margin_top(70) |
Given snippet: <|code_start|>#!/usr/bin/env python
# swag_screen.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# Shows profile created
#
class SwagScreen(Template):
def __init__(self, win):
# Set window
sel... | if login: |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# swag_screen.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# Shows profile created
#
class SwagScreen(Template):
def __init__(self, win):
... | if login: |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# swag_screen.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# Shows profile created
#
class SwagScreen(Template):
def __init__(self, win):
... | if login: |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# progress_bar.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
# This displays orange progress bar along top of each screen
class ProgressBar(Gtk.Fixed):
def __init__... | self.label_height = 30 |
Given the following code snippet before the placeholder: <|code_start|>
self.rest_of_bar = Gtk.EventBox()
self.rest_of_bar.get_style_context().add_class('rest_of_bar')
self.progress_label = Gtk.Label()
self.progress_label.set_alignment(xalign=0.5, yalign=0.5)
self.endpoint_labe... | progress_width = (self.total_width - self.label_width) * self.fraction |
Next line prediction: <|code_start|>
class CategoryMenu(SelectMenu):
__gsignals__ = {
'category_item_selected': (GObject.SIGNAL_RUN_FIRST, None, (str,))
}
def __init__(self, parser):
# for some reason, this is not being obeyed
self.item_width = 55
self.item_height = 50
... | self.add(sw) |
Given the code snippet: <|code_start|># quests.py
#
# Copyright (C) 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
QUESTS_LOAD_PATHS = [
os.path.join(os.path.dirname(os.path.abspath(__file__)), '../quests'),
'/usr/share/kano-profile/quests'
<|code_end|>
, generate th... | ] |
Based on the snippet: <|code_start|># launch.py
#
# Copyright (C) 2015-2017 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# args is an array of arguments that were passed through the URL
# e.g., kano:launch:app-name, it will be ["app-name"]
def run(args):
try:
ret =... | logger.error( |
Given the following code snippet before the placeholder: <|code_start|># launch.py
#
# Copyright (C) 2015-2017 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# args is an array of arguments that were passed through the URL
# e.g., kano:launch:app-name, it will be ["app-name"]
de... | logger.error( |
Based on the snippet: <|code_start|>def upload_share(file_path, title, app_name):
glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
return glob_session.upload_share(file_path, title, app_name)
def delete_share(share_id):
glob_session = get_glob_s... | description = entry['description'] |
Predict the next line after this snippet: <|code_start|>
success, text = download_url(attachment_url, attachment_path)
if not success:
msg = "Error with downloading share file: {}".format(text)
logger.error(msg)
return False, msg
# Download screenshot
if cover_url:
cover... | msg = "Error with downloading resource file: {}".format(text) |
Based on the snippet: <|code_start|> glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
return glob_session.post_comment(share_id, comment)
def like_share(share_id):
glob_session = get_glob_session()
if not glob_session:
return False,... | return False, _("You are not logged in!") |
Continue the code snippet: <|code_start|> app_profiles = read_json(app_profiles_file)
if app not in app_profiles:
logger.error("Cannot download share, app not found in app-profiles")
return
app_profile = app_profiles[app]
folder = os.path.join(get_home(), app_profile['dir'], 'webload')... | success, text = download_url(cover_url, cover_path) |
Based on the snippet: <|code_start|> glob_session = get_glob_session()
if not glob_session:
return False, _("You are not logged in!")
return glob_session.unlike_share(share_id)
def get_following():
glob_session = get_glob_session()
if not glob_session:
return False, _("You are no... | if not glob_session: |
Given the code snippet: <|code_start|># cache_functions.py
#
# Copyright (C) 2015-2016 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
def cache_data(category, value):
if category in ['username', 'email']:
save_app_state_variable('kano-avatar-regist... | cache_data('email', email) |
Next line prediction: <|code_start|># cache_functions.py
#
# Copyright (C) 2015-2016 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
def cache_data(category, value):
if category in ['username', 'email']:
save_app_state_variable('kano-avatar-registra... | cache_data('email', email) |
Given snippet: <|code_start|>def set_from_name(name):
image = Gtk.Image()
image.set_from_file(media_dir + "/images/icons/" + name + ".png")
return image
MEDIA_LOCS = ['../media', '/usr/share/kano-profile/media']
APP_ICON_SIZE = 68
def get_app_icon(loc, size=APP_ICON_SIZE):
try:
pb = GdkPixbuf... | icon_number = 4 |
Next line prediction: <|code_start|> else:
with f:
json.dump(data, f)
if 'SUDO_USER' in os.environ:
chown_path(path)
return path
def session_end(session_file):
if not os.path.exists(session_file):
msg = "Someone removed the tracker file, the runtime of this ... | logger.error( |
Continue the code snippet: <|code_start|> f for f in os.listdir(tracker_dir) # noqa
if os.path.isfile(os.path.join(tracker_dir, f)) and # noqa
os.path.join(tracker_dir, f) != PAUSED_SESSIONS_FILE # noqa
] # noqa
def get_open_sessions():
open_sessions = []
for session_file in li... | try: |
Using the snippet: <|code_start|> '{}\n'.format(session.dumps())
)
return session.path
data = {
'pid': pid,
'name': name,
'started': int(time.time()),
'elapsed': 0,
'app_session_id': str(uuid5(uuid1(), name + str(pid))),
'finis... | def session_end(session_file): |
Predict the next line for this snippet: <|code_start|> try:
wf = open(session_file, 'w')
except IOError as e:
logger.error(
"Error opening the tracker session file {}".format(e))
else:
with wf:
jso... | except TypeError: |
Based on the snippet: <|code_start|> else:
with rf:
data = json.load(rf)
data['elapsed'] = int(time.time()) - data['started']
data['finished'] = True
try:
wf = open(session_file, 'w')
except IOError as e:
logger.err... | paused_sessions = [] |
Using the snippet: <|code_start|>def list_sessions():
return [ # noqa
f for f in os.listdir(tracker_dir) # noqa
if os.path.isfile(os.path.join(tracker_dir, f)) and # noqa
os.path.join(tracker_dir, f) != PAUSED_SESSIONS_FILE # noqa
] # noqa
def get_open_sessions():
open_session... | data = {} |
Using the snippet: <|code_start|> try:
paused_sessions_f = open_locked(PAUSED_SESSIONS_FILE, 'a')
except IOError as err:
logger.error(
'Error while opening the paused sessions file: {}'.format(err)
)
else:
paused_sessions_f.write(
... | with f: |
Next line prediction: <|code_start|> app_data_dir = os.path.join(get_app_dir(app_name), data_str)
return app_data_dir
def get_app_state_file(app_name):
app_state_str = 'state.json'
app_state_file = os.path.join(get_app_dir(app_name), app_state_str)
return app_state_file
def load_app_state(app_nam... | data = load_app_state(app_name) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# apps.py
#
# Copyright (C) 2014, 2015, 2017 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
def get_app_dir(app_name):
app_dir = os.path.join(apps_dir, app_name)
return app_dir
def get_app_... | return app_state_file |
Next line prediction: <|code_start|>
def get_app_data_dir(app_name):
data_str = 'data'
app_data_dir = os.path.join(get_app_dir(app_name), data_str)
return app_data_dir
def get_app_state_file(app_name):
app_state_str = 'state.json'
app_state_file = os.path.join(get_app_dir(app_name), app_state_str... | logger.error("Could not encode and load app state:\n{}".format(e)) |
Based on the snippet: <|code_start|>
def load_app_state(app_name):
app_state_file = get_app_state_file(app_name)
app_state = read_json(app_state_file)
if not app_state:
app_state = dict()
return app_state
def load_app_state_encode(app_name):
try:
data = load_app_state(app_name)
... | encoded_data = json.dumps(data) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
__author__ = 'anewbigging'
fake = Factory.create()
def typeof_rave_data(value):
"""Function to duck-type values, not relying on standard Python functions because, for example,
a string of '1' should be typed as an integer and not as a string or float... | try: |
Predict the next line for this snippet: <|code_start|>class TestRWSStudies(unittest.TestCase):
def test_parse(self):
text = u"""<ODM FileType="Snapshot" FileOID="767a1f8b-7b72-4d12-adbe-37d4d62ba75e"
CreationDateTime="2013-04-08T10:02:17.781-00:00"
ODMVersion="1.3"
xmlns:mdsol="ht... | class TestUtils(unittest.TestCase): |
Using the snippet: <|code_start|> self.assertNotEqual(s, i)
s = 'This is a large string to test scrambling of large strings'
i = self.scr.scramble_value(s)
self.assertNotEqual(s, i)
def test_scramble_date(self):
"""Test scrambling dates"""
dt = self.scr.scramble_value... | <MetaDataVersion OID="1" Name="Metadata version 1"> |
Continue the code snippet: <|code_start|> """Test scrambling strings"""
s = 'asdf'
i = self.scr.scramble_value(s)
self.assertEqual(len(s), len(i))
self.assertNotEqual(s, i)
s = 'This is a large string to test scrambling of large strings'
i = self.scr.scramble_value... | <StudyDescription></StudyDescription> |
Given the following code snippet before the placeholder: <|code_start|> result = self.runner.invoke(rwscmd.rws,
['--verbose', 'https://innovate.mdsol.com', 'autofill', '--steps', '1',
'--fixed', 'fixed.txt', 'Test', 'Prod', '001... | unittest.main() |
Given snippet: <|code_start|>
class JumpToKeyword(sublime_plugin.TextCommand):
def run(self, edit):
open_tab = self.view.file_name()
db_dir = get_setting(SettingObject.table_dir)
index_db = get_setting(SettingObject.index_dir)
<|code_end|>
, continue by predicting the next line... | rf_cell = get_rf_table_separator(self.view)
|
Continue the code snippet: <|code_start|>
class ShowKeywordDocumentation(sublime_plugin.TextCommand):
def run(self, edit):
w = sublime.active_window()
panel = w.create_output_panel('kw_documentation')
<|code_end|>
. Use current file imports:
import sublime_plugin
import sublime
from ..se... | open_tab = self.view.file_name()
|
Predict the next line after this snippet: <|code_start|> local('mv src/modules/{0}-beautified.js src/modules/{0}.js'.format(name))
# fab unify:list_modules='ajax'
def unify(list_modules=None):
# list of all dependencies of own Tiramisu
list_dependency = []
# read tiramisu.json
f = open('ti... | cat = "cat src/tiramisu.core.js {0} > src/custom/tiramisu-{1}.js".format(' '.join(modules), name_custom) |
Based on the snippet: <|code_start|>
class TestApp(WebAppTestBase):
def test_welcome(self):
resp = self.get('/')
self.assertEquals(resp.status_code, 200)
<|code_end|>
, predict the immediate next line with the help of imports:
from gap.utils.tests import WebAppTestBase
and context (classes, func... | self.assertEquals(resp.content_type, 'text/html') |
Next line prediction: <|code_start|>
@as_view
def welcome_screen(request, response):
return get_template("homepage.html").render({
'project_name': 'Example project',
})
@as_view
def not_found(request, response, *args, **kwargs):
response.set_status(404)
text = 'The page you are requesting was... | for route in routes: |
Next line prediction: <|code_start|>#!/usr/bin/env python
app_path = join(realpath(dirname(dirname(__file__))), 'src')
fix_sys_path(app_path)
TESTBED = setup_testbed()
# preimport common google apis
<|code_end|>
. Use current file imports:
(import sys
import IPython
from os.path import dirname, realpath, join
from ... | IPython.embed() |
Using the snippet: <|code_start|>#
# part of gap project (https://github.com/czervenka/gap)
__author__ = 'Lukas Lukovsky'
DEFAULT = object()
class TestBase(TestCase):
testbed = None
_gae_stubs = setup.DEFAULT_TESTBEDS
# Allow to share the setUpClass method among all parallel test classes
_multipro... | env['USER_EMAIL'] = email |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# Copyright 2007 Robin Gottfried <google@kebet.cz>
#
# 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/li... | taskqueue.add( |
Given the code snippet: <|code_start|>
def include(prefix, routes):
if isinstance(routes, StringTypes):
routes = import_class('%s.routes' % routes)
elif hasattr(routes, 'routes'):
routes = routes.routes
routes = [ Router.route_class(*route) if isinstance(route, tuple) else route for route i... | self._run_filters(1, 'process_request', request, response) |
Using the snippet: <|code_start|>
class JsonException(Exception):
def __init__(self, code, message=None, exception=None):
self.code = int(code)
if message is None:
message = self.get_status_message(code)
self.message = message
self.exception = exception
def get_sta... | return time.mktime(o.timetuple()) |
Given snippet: <|code_start|> # fix the parent at run time.
self.env = builder.env
self.bytecode = bytecode
self.argc = len(builder.args)
if builder.rest_arg:
self.fixed_argc = self.argc-1
else:
self.fixed_argc = self.argc
self.li... | "Show the disassemble of the instructions of the proc. Useful for debug." |
Continue the code snippet: <|code_start|> self.fixed_argc = self.argc-1
else:
self.fixed_argc = self.argc
self.literals = list(builder.literals)
def lexical_parent_get(self):
return self.env.parent
def lexical_parent_set(self, parent):
self.env.parent = p... | args = [self.env.get_name(i) for i in range(self.argc)] |
Next line prediction: <|code_start|> literals = literals.rest
if literals is not None:
raise SyntaxError("Invalid syntax rule format: literals should be a proper list.")
self.rules = []
# Process syntax rules
rules = body.rest
w... | self.variables = {} |
Given the following code snippet before the placeholder: <|code_start|>
class Macro(object):
def __init__(self, env, body):
self.lexical_parent = env
<|code_end|>
, predict the next line using imports from the current file:
from .types.pair import Pair as pair
from .types.symbol import Symbol as sym
from... | try: |
Given the code snippet: <|code_start|> literals = literals.rest
if literals is not None:
raise SyntaxError("Invalid syntax rule format: literals should be a proper list.")
self.rules = []
# Process syntax rules
rules = body.rest
... | self.variables = {} |
Here is a snippet: <|code_start|>
lib = find_library("mzscheme3m")
if lib is None:
raise RuntimeError("Can't find a mzscheme library to use.")
mz = cdll.LoadLibrary(lib)
# Load the helper library which exports the macro's as C functions
path = os.path.abspath(os.path.join(os.path.split(__file__)[0], '_mzhelper.so... | class SCM(c_void_p): |
Here is a snippet: <|code_start|> self.report_error("Expecting end of code, but more code is got")
return expr
def parse_expr(self):
def parse_pound():
if self.peak(idx=1) == 't':
self.pop(n=2)
return True
if self.peak(idx=1) == 'f... | self.skip_all() |
Given snippet: <|code_start|> def parse_symbol(self):
pos1 = self.pos
self.pop()
while self.more() and \
not self.isspace(self.peak()) and \
not self.peak() in ['\'', ')', '(', ',', '@']:
self.pop()
pos2 = self.pos
return sym(self.text[p... | self.pop() |
Based on the snippet: <|code_start|> isfloat = False
pos1 = self.pos
while self.isdigit(self.peak()):
self.pop()
if self.eat('.'):
isfloat = True
while self.isdigit(self.peak()):
self.pop()
pos2 = self.pos
if pos2 == pos1:
... | elems.append(self.parse_expr()) |
Using the snippet: <|code_start|> field, request, params, model, model_admin, field_path
)
if hasattr(field, 'verbose_name'):
self.lookup_title = field.verbose_name
else:
self.lookup_title = other_model._meta.verbose_name
self.title = self.lookup_title
... | 'display': _('All'), |
Based on the snippet: <|code_start|>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
def cart(self):
try:
c = Cart.objects.get(id=self.session[settings.SESSION_KEY_CART], order=None)
except (KeyError, Cart.DoesNotExist):
... | class CartMiddleware(object): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
@apphook_pool.register
class CatalogApp(CMSApp):
name = _('Catalog')
urls = [catalog]
app_name = 'Catalog'
@apphoo... | class CartApp(CMSApp): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
@apphook_pool.register
class CatalogApp(CMSApp):
name = _('Catalog')
urls = [catalog]
app_name = 'Catalog'
@apphoo... | app_name = 'Order' |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
@apphook_pool.register
class CatalogApp(CMSApp):
name = _('Catalog')
urls = [catalog]
app_name = 'Catalog'
<|c... | @apphook_pool.register |
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
class ProductPlugin(CMSPluginBase):
model = ProductPlugin
name = _('Product')
text_enabled = True
def render(self, c... | }) |
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
class ProductPlugin(CMSPluginBase):
model = ProductPlugin
name = _('Product')
text_enabled = True
def render(self, c... | text_enabled = True |
Given the code snippet: <|code_start|>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
@python_2_unicode_compatible
class BasePrice(object):
def __lt__(self, other):
try:
if PRICE_TYPE == 'gross':
... | def __le__(self, other): |
Continue the code snippet: <|code_start|> try:
if PRICE_TYPE == 'gross':
return self.gross < other.gross
else:
return self.net < other.net
except:
return NotImplemented
def __le__(self, other):
return self < other or self ... | def tax(self): |
Using the snippet: <|code_start|>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
@python_2_unicode_compatible
class BasePrice(object):
def __lt__(self, other):
try:
if PRICE_TYPE == 'gross':
retur... | def __le__(self, other): |
Predict the next line after this snippet: <|code_start|>
class PriceField(models.DecimalField):
def __init__(self, *args, **kwargs):
kwargs.setdefault('decimal_places', settings.DECIMAL_PLACES)
kwargs.setdefault('max_digits', settings.MAX_DIGITS)
super(PriceField, self).__init__(*args, *... | help_text=_('overwrite the title (html title tag)')) |
Next line prediction: <|code_start|> cart = models.OneToOneField(Cart, verbose_name=_('cart'), editable=False)
state = models.ForeignKey(OrderState, verbose_name=_('state'))
first_name = models.CharField(_('first name'), max_length=30)
last_name = models.CharField(_('last ... | return self.user \ |
Given the code snippet: <|code_start|>class OrderState(models.Model):
code = models.SlugField(_('code'))
name = models.CharField(_('name'), max_length=150)
description = HTMLField(_('description'), blank=True, default='')
class Meta:
verbose_name = _('order state')
... | comment = models.TextField(_('internal comment'), blank=True) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
conn = get_vendor("DB").get_redis()
@controller_get
def get_worker_names(
<|code_end|>
, predict the next line using imports from the current file:
import redis
import copy
import dHydra.core.util as util
import to... | query_arguments, |
Based on the snippet: <|code_start|># coding: utf-8
start_worker(
worker_name="CtpMd",
nickname="CtpMd",
config="CtpMd.json"
<|code_end|>
, predict the immediate next line with the help of imports:
from dHydra.main import start_worker
and context (classes, functions, sometimes code) from other files:
# ... | ) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class EasyUncle(Vendor):
def __init__(
self,
accounts="easyuncle.json",
**kwargs
):
<|code_end|>
using the current file's imports:
from dHydra.core.Functions import get_vendor
from dHydra.core.Vendor imp... | super().__init__(**kwargs) |
Using the snippet: <|code_start|> ):
super().__init__(**kwargs)
self.request_id = 0
# Note (IMPORTANT):
# broker_id, user_id, password, instrument_ids, market_front should
# be bytes
cfg = util.read_config(os.getcwd() + "/" + account)
if "broker_id" in cfg:
... | self.market_front = market_front.encode() |
Given the code snippet: <|code_start|> ]
for s in shutdown_signals:
if hasattr(signal, s):
signal.signal(
getattr(signal, s, None),
__on_termination__
)
def start_worker(worker_name, **kwargs):
worker = get_worker_class(worker_name=worker_name... | by="nickname", |
Given the code snippet: <|code_start|> "SIGTERM", # kill 命令
]
for s in shutdown_signals:
if hasattr(signal, s):
signal.signal(
getattr(signal, s, None),
__on_termination__
)
def start_worker(worker_name, **kwargs):
worker = get_worker... | redis_cli=None, |
Next line prediction: <|code_start|> if hasattr(signal, s):
signal.signal(
getattr(signal, s, None),
__on_termination__
)
def start_worker(worker_name, **kwargs):
worker = get_worker_class(worker_name=worker_name, **kwargs)
worker_dict[worker.nick... | worker_name=None, |
Given 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 permission... | self.assertEqual('success', ret) |
Given snippet: <|code_start|># (c) Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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.counter = 0 |
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 KIN... | ret = succeeds() |
Next line prediction: <|code_start|>
def test_fake_execute(self):
mock_execute = mock.Mock()
executor = brick_executor.Executor(root_helper=None,
execute=mock_execute)
self.assertEqual(mock_execute, executor._Executor__execute)
@mock.patch('sys... | @mock.patch('os_brick.executor.priv_rootwrap.execute') |
Predict the next line after this snippet: <|code_start|> @mock.patch('os_brick.executor.priv_rootwrap.execute')
def test_execute_non_safe_str_exception(self, execute_mock, stdin_mock):
execute_mock.side_effect = putils.ProcessExecutionError(
stdout='España', stderr='Zürich')
executor... | executor._execute) |
Next line prediction: <|code_start|>
executor = brick_executor.Executor(root_helper=None)
exc = self.assertRaises(putils.ProcessExecutionError,
executor._execute)
self.assertEqual('Espa\xf1a', exc.stdout)
self.assertEqual('Z\xfcrich', exc.stderr)
@moc... | @mock.patch('sys.stdin', encoding='UTF-8') |
Given the following code snippet before the placeholder: <|code_start|> mock.call('cryptsetup', 'isLuks', '--verbose', self.dev_path,
root_helper=self.root_helper,
run_as_root=True, check_exit_code=True),
], any_order=False)
@mock.patch('os_brick.execu... | keymgr=self.keymgr) |
Given the following code snippet before the placeholder: <|code_start|> run_as_root=True, check_exit_code=True, attempts=3),
])
@mock.patch('os_brick.executor.Executor._execute')
def test__open_volume(self, mock_execute):
self.encryptor._open_volume("passphrase")
m... | root_helper=self.root_helper, |
Using the snippet: <|code_start|> def test_get_volume_paths(self, mock_get_disk_paths_by_scsi_id,
mock_get_fc_mappings,
mock_sleep,
volume_mappings, expected_paths,
scsi_id_side_eff=None,
... | dev_names = [mapping['device_name'] |
Next line prediction: <|code_start|> fake_init_target_map = {mock.sentinel.local_wwpn: remote_wwpns}
conn_props = dict(initiator_target_map=fake_init_target_map)
mock_get_dev_nums.side_effect = [os_win_exc.FCException,
[mock.sentinel.dev_num]]
moc... | dev_nums = self._connector._get_dev_nums_by_scsi_id( |
Given the following code snippet before the placeholder: <|code_start|> self.assertEqual([mock.sentinel.dev_name], disk_paths)
mock_get_dev_nums.assert_has_calls([
mock.call(mock.sentinel.local_wwpn,
remote_wwpn,
mock.sentinel.fcp_lun)
... | self._diskutils.get_disk_numbers_by_unique_id.assert_called_once_with( |
Using the snippet: <|code_start|># All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | props['target_lun'] = lun |
Here is a snippet: <|code_start|># All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | props = {} |
Given the code snippet: <|code_start|># Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.or... | self._fc_utils = utilsfactory.get_fc_utils() |
Next line prediction: <|code_start|> mappings[port['node_name']].append(port['port_name'])
return mappings
def _get_disk_paths_by_scsi_id(self, connection_properties, fcp_lun):
for local_port_wwn, remote_port_wwns in connection_properties[
'initiator_target_map'].items():... | local_port_wwn=local_port_wwn, |
Given snippet: <|code_start|>
mock_mkdirs.assert_called_once_with('/etc/nvme',
mode=0o755,
exist_ok=True)
mock_exec.assert_called_once_with('nvme', 'show-hostnqn')
mock_open.assert_called_once_with('/etc/nvme... | mock_exec.assert_has_calls([mock.call('nvme', 'show-hostnqn'), |
Using the snippet: <|code_start|>
@mock.patch('os.chmod')
@mock.patch.object(builtins, 'open', new_callable=mock.mock_open)
@mock.patch('os.makedirs')
@mock.patch.object(rootwrap, 'custom_execute')
def test_create_hostnqn_generate_old_nvme_cli(self, mock_exec, mock_mkdirs,
... | @ddt.data(OSError(errno.ENOENT), # nvme not present in system |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2016 Cloudbase Solutions Srl
# 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... | return [] |
Predict the next line after this snippet: <|code_start|> def test_get_mapped_casdev(self, moc_exec):
out_ready = """type id disk status write policy device
cache 1 /dev/nvme0n1 Running wt -
└core 1 /dev/sdd Active - /dev/cas1-1"""
err = ''
engine = opencas... | moc_exec.return_value = ('', '') |
Given snippet: <|code_start|> cache 1 /dev/nvme0n1 Running wt -
└core 1 /dev/sdd Active - /dev/cas1-1"""
err = ''
engine = opencas.OpenCASEngine(root_helper=None, opencas_cache_id=1)
moc_exec.return_value = (out_ready, err)
ret1, ret2 = engine._get_mapped_... | moc_exec.assert_has_calls([ |
Next line prediction: <|code_start|># Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# 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 a... | }, |
Here is a snippet: <|code_start|> self.mock_execute.assert_has_calls(calls)
@mock.patch.object(remotefs.RemoteFsClient, '_read_mounts',
return_value=[])
def test_vzstorage_invalid_share(self, mock_read_mounts):
client = remotefs.VZStorageRemoteFSClient(
"vzstor... | mock_execute.assert_called_once_with( |
Next line prediction: <|code_start|> smbfs_mount_point_base='/mnt')
share = '10.0.0.1:/qwe'
mount_point = client.get_mount_point(share)
client.mount(share)
calls = [mock.call('mkdir', '-p', mount_point, check_exit_code=0),
mock.cal... | smbfs_mount_point_base='/mnt') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.