Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> except Exception:
raise
finally:
if self.enable_profiling:
output_path_ = self.output_path
if callable(output_path_):
self.output_path = output_path_(*args, **kwa... | pr = self.pr |
Based on the snippet: <|code_start|> body='{"error": "deu merda"}',
content_type="application/json",
status=500)
httpretty.register_uri(httpretty.GET, "http://localhost:8000/service1/",
bo... | body='{"success": true}', |
Predict the next line after this snippet: <|code_start|> assert response.ok
@httpretty.activate
def test_delete_not_ok(self):
httpretty.register_uri(httpretty.DELETE, "http://localhost:8000/service1/",
body='[{"error": "name required"}]',
... | status=200) |
Using the snippet: <|code_start|>#!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# 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/LI... | data = [{'id': str(n)} for n in range(100)] |
Given snippet: <|code_start|>class TestDataSourceProvider:
@mock.patch("pyspark.sql.SparkSession")
def test_get_spark_session(self, mocked_session):
spark = get_spark_session()
assert spark
mocked_session.assert_has_calls([
mock.call.builder.appName('marvin-engine'),
... | mock.call.builder.appName('marvin-engine'), |
Here is a snippet: <|code_start|>logger = get_logger('engine_base_training')
class EngineBaseTraining(EngineBaseBatchAction):
__metaclass__ = ABCMeta
_dataset = None
_model = None
_metrics = None
def __init__(self, **kwargs):
self._dataset = self._get_arg(kwargs=kwargs, arg='dataset')
... | def marvin_model(self, model): |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# 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://ww... | _model = None |
Next line prediction: <|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
#... | assert engine_action.marvin_metrics == engine_action._metrics == [3] |
Predict the next line after this snippet: <|code_start|> load_conf_from_file()
ConfigParserMocked.assert_called_once_with(os.environ['DEFAULT_CONFIG_PATH'])
@mock.patch('marvin_python_toolbox.common.config.logger')
@mock.patch('marvin_python_toolbox.common.config.ConfigObj.__getitem__')
def... | load_conf_from_file_mocked.return_value = config_fixture |
Using the snippet: <|code_start|> def test_get_invalid_key(self, load_conf_from_file_mocked, config_fixture):
load_conf_from_file_mocked.return_value = config_fixture
assert 'invalidkey' not in config_fixture
with pytest.raises(InvalidConfigException):
Config.get('invalidkey')
... | def test_keys_with_invalid_section(self, load_conf_from_file_mocked): |
Here is a snippet: <|code_start|> load_conf_from_file_mocked.return_value = config_fixture
assert 'invalidkey' not in config_fixture
with pytest.raises(InvalidConfigException):
Config.get('invalidkey')
@mock.patch('marvin_python_toolbox.common.config.load_conf_from_file')
def... | load_conf_from_file_mocked.return_value = {} |
Here is a snippet: <|code_start|> hdfs_comm_mock.assert_any_call(ssh, "hdfs dfs -ls -R '/home/' | grep -E '^-' | wc -l")
hdfs_comm_mock.assert_any_call(ssh, "hdfs dfs -ls -R '/tmp/' | grep -E '^-' | wc -l")
logger_mock.debug.assert_not_called()
sys_mock.exit.assert_not_called()
@mock... | sys_mock.exit.assert_called_once_with("Stoping process!") |
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 permissions and
# limita... | @click.pass_context |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# coding=utf-8
# Copyright [2017] [B2W Digital]
#
# 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... | return EngineAction(default_root_path="/tmp/.marvin") |
Given the code snippet: <|code_start|>
if sql_id:
confs = [x for x in confs if x['sql_id'] == sql_id]
for conf in confs:
hdi = HiveDataImporter(
max_query_size=max_query_size,
destination_host=destination_host,
destination_port=des... | print ("Table {} already exists, skiping data import. Use --force flag to force data importation".format(hdi.full_table_name)) |
Based on the 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 ... | super(KerasSerializer, self)._serializer_dump(obj, object_file_path) |
Given snippet: <|code_start|>
__all__ = ['EngineBaseDataHandler']
logger = get_logger('engine_base_data_handler')
class EngineBaseDataHandler(EngineBaseBatchAction):
__metaclass__ = ABCMeta
_initial_dataset = None
_dataset = None
def __init__(self, **kwargs):
self._initial_dataset = self._... | @marvin_dataset.setter |
Predict the next line after this 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.... | return self._load_obj(object_reference='_model') |
Predict the next line after this snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
__all__ = ['EngineBasePrediction']
logger = get_logger('engine_base_prediction')
class EngineBasePrediction(EngineBaseOnlineAction):
__metaclass__ = AB... | @property |
Next line prediction: <|code_start|> os.environ['TESTING'] = 'true'
if args:
args = args.split(' ')
else:
args = [os.path.relpath(
os.path.join(ctx.obj['base_path'], 'tests'))]
if no_capture:
args += ['--capture=no']
if pdb:
args += ['--pdb']
if par... | sys.exit(exitcode) |
Based on the snippet: <|code_start|>
@mock.patch('marvin_python_toolbox.management.pkg.shutil.ignore_patterns')
@mock.patch('marvin_python_toolbox.management.pkg.shutil.copytree')
def test_copy(copytree_mocked, ignore_mocked):
src = '/xpto'
dest = '/xpto_dest'
ignore = ('.git')
ignore_mocked.return_valu... | popen_mocked.assert_called_with(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], stdout=pipe_mocked, cwd='/tmp') |
Given the following code snippet before the placeholder: <|code_start|> join_mocked.assert_called_with('/path', 'requirements.txt')
open_mocked.assert_called_with('/tmp', 'r')
def test_get_tag_from_repo_url():
repos = ['http://www.xxx.org:80/tag@/repo.html']
tags = get_tag_from_repo_url(repos)
as... | def test_copy(copytree_mocked, ignore_mocked): |
Here is a snippet: <|code_start|> get_repos_from_requirements(path='/path')
join_mocked.assert_called_with('/path', 'requirements.txt')
open_mocked.assert_called_with('/tmp', 'r')
def test_get_tag_from_repo_url():
repos = ['http://www.xxx.org:80/tag@/repo.html']
tags = get_tag_from_repo_url(repos... | @mock.patch('marvin_python_toolbox.management.pkg.shutil.ignore_patterns') |
Next line prediction: <|code_start|>
# from click.testing import CliRunner
try:
except ImportError:
@mock.patch('marvin_python_toolbox.management.pkg.open')
@mock.patch('marvin_python_toolbox.management.pkg.os.path.join')
@mock.patch('marvin_python_toolbox.management.pkg.os.path.curdir')
def test_get_repos_from_req... | assert tags == {'http://www.xxx.org:80/tag@/repo.html': '/repo.html'} |
Given the following code snippet before the placeholder: <|code_start|>
@mock.patch('marvin_python_toolbox.management.pkg.subprocess.PIPE')
@mock.patch('marvin_python_toolbox.management.pkg.os.path.curdir')
@mock.patch('marvin_python_toolbox.management.pkg.subprocess.Popen')
def test_get_git_tags(popen_mocked, curdir_... | popen_mocked.assert_called_once_with(['git', 'diff', '--quiet', 'HEAD'], stdout=pipe_mocked, cwd=curdir_mocked) |
Given the code snippet: <|code_start|>def test_get_tag_from_repo_url():
repos = ['http://www.xxx.org:80/tag@/repo.html']
tags = get_tag_from_repo_url(repos)
assert tags == {'http://www.xxx.org:80/tag@/repo.html': '/repo.html'}
repos = ['http://www.xxx.org:80/tag/repo.html']
tags = get_tag_from_r... | ignore_mocked.return_value = 1 |
Given snippet: <|code_start|>from __future__ import unicode_literals
__all__ = ("Handler",)
logger = logging.getLogger("django.request")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import collections
import logging
import sys
from django import http
from django.conf imp... | class Handler(base.BaseHandler): |
Given snippet: <|code_start|>from __future__ import unicode_literals
__all__ = (
"ArchiveIndexView", "YearArchiveView", "MonthArchiveView",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.views import generic
from .base import View
and context:
# Path: daydream... | "WeekArchiveView", "DayArchiveView", "TodayArchiveView", "DateDetailView",) |
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import
#from crackling.celery import celery
@crackling.celery.celery.task
def newjob(engine, hashtype, attacktype, hashes, params):
logging.info("Job starting")
logging.debug(str(hashtype))
logging.debug(str(attacktype))
lo... | j.addHashes(hashes) |
Here is a snippet: <|code_start|>from __future__ import absolute_import
#from crackling.celery import celery
@crackling.celery.celery.task
def newjob(engine, hashtype, attacktype, hashes, params):
logging.info("Job starting")
<|code_end|>
. Write the next line using the current file imports:
import crackling.cel... | logging.debug(str(hashtype)) |
Given the following code snippet before the placeholder: <|code_start|>
class GetOrNoneManager(models.Manager):
def get_or_none(self, **kwargs):
try:
return self.get(**kwargs)
<|code_end|>
, predict the next line using imports from the current file:
from django.db import models
from itertoo... | except self.model.DoesNotExist: |
Given the following code snippet before the placeholder: <|code_start|> url(r'^delete-org/(.+)/$', views.delete_org, name='rolodex_delete_org'),
# Doc adds
url(r'^add-doc/org/(.+)/$', views.new_org_doc, name='rolodex_new_org_doc'),
url(r'^add-doc/person/(.+)/$', views.new_person_doc, name='rolodex_new_p... | url(r'^api/', include(router.router.urls)), |
Here is a snippet: <|code_start|>
pytestmark = pytest.mark.usefixtures('clean_context')
LOADED_DATA = {
'systems': [{'celestials': [{'name': 'Primary', 'orbit': 0, 'type': 'star'},
{'name': 'Friesland',
'orbit': 1,
... | 'name': 'property', |
Next line prediction: <|code_start|> 'name': 'Solar Observation Station',
'type': 'orbital'}],
'name': 'Test'}],
'property': [{'depreciation_rate': 3,
'mean_price': 1,
'name': 'property',
... | } |
Here is a snippet: <|code_start|># The idiom for unittests is to use classes for organization
# pylint: disable=no-self-use
pytestmark = pytest.mark.usefixtures('clean_context')
INVALID_DATA = (
('''{version: "1.0", types: {CommodityType: []}}''', VError,
("not a valid value for dictionary va... | ("extra keys not allowed @ data\\['types']\\[10]",)), |
Using the snippet: <|code_start|> assert results == []
def test_extra_conf_files_some_exist(self, mocker):
mocker.patch('os.path.exists', autospec=True, side_effect=self._sm_paths_exist)
results = c._find_config(conf_files=('/srv/sm/magnate.cfg', '~/sm.cfg'))
assert results == [ os.p... | ui_plugin: the_bestest_widget_set |
Here is a snippet: <|code_start|> assert results == []
def test_extra_conf_files_some_exist(self, mocker):
mocker.patch('os.path.exists', autospec=True, side_effect=self._sm_paths_exist)
results = c._find_config(conf_files=('/srv/sm/magnate.cfg', '~/sm.cfg'))
assert results == [ os.p... | ui_plugin: the_bestest_widget_set |
Next line prediction: <|code_start|>
@pytest.fixture
def clean_context():
old_engine = db.engine
db.engine = None
old_types = {}
for key, value in base_types.__dict__.items():
if key.endswith('Type'):
old_types[key] = value
old_system_schema = data_def.SYSTEM_SCHEMA
old_... | for key, value in old_types.items(): |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture
def clean_context():
old_engine = db.engine
db.engine = None
old_types = {}
for key, value in base_types.__dict__.items():
if key.endswith('Type'):
old_types[key] = value
old_system_schem... | datadir = os.path.join(os.path.dirname(__file__), '../data') |
Given snippet: <|code_start|> for name, value in db.__dict__.items():
if value is None and name not in ('engine', 'Base'):
undefined_schema.append(name)
db.init_schema(datadir)
first_schema = {}
for name, value in db.__dict__.items():
first_schema[name] = value
# A tabl... | assert frozenset((systems[0].celestials[0].name, systems[0].celestials[1].name)) == frozenset(('Primary', 'Friesland')) |
Next line prediction: <|code_start|> # A table wasn't initialized globally yet
db.CommodityCategory = None
db.init_schema(datadir)
# Assert nothing was added
assert len(db.__dict__) == db_items
# Assert that all of the schema values have changed
for name in undefined_schema:
assert ... | assert ships[0].name == 'ship' |
Predict the next line for this snippet: <|code_start|>
def test_init_schema(datadir):
db_items = len(db.__dict__)
undefined_schema = []
for name, value in db.__dict__.items():
if value is None and name not in ('engine',):
<|code_end|>
with the help of current file imports:
import os.path
import... | undefined_schema.append(name) |
Predict the next line for this snippet: <|code_start|>state_dir: {state_dir}
# Name of the User Interface plugin to use
ui_plugin: urwid
# Whether to use uvloop instead of the stdlib asyncio event loop
use_uvloop: False
# Configuration of logging output. This is given directly to twiggy.dict_cnfig()
logging:
vers... | args: |
Here is a snippet: <|code_start|># You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Functions to read configuration files
"""
mlog = log.fields(mod=__name__)
STATE_DIR = os.path.expanduser('~/.stellarmagnate')
USER... | state_dir: {state_dir} |
Predict the next line after this snippet: <|code_start|>@pytest.mark.usefixtures('setup_base_types')
def test_define_schemas(datadir):
data_def._define_schemas(datadir)
assert isinstance(data_def.BASE_SCHEMA, voluptuous.Schema)
assert isinstance(data_def.SYSTEM_SCHEMA, voluptuous.Schema)
GOOD_BASE_DATA =... | 'depreciation_rate': 3, |
Here is a snippet: <|code_start|> data = copy.deepcopy(GOOD_BASE_DATA)
data['events'][0]['affects'] = ['food', 'illegal']
yield data
data = copy.deepcopy(GOOD_BASE_DATA)
data['events'][0]['affects'] = ['food', ['chemical', 'illegal']]
yield data
data = copy.deepcopy(GOOD_BASE_DATA)
data... | yield (data, "not a valid value for dictionary value @ data['version']") |
Here is a snippet: <|code_start|>@app.route('/login', methods=('POST', ))
def login_post():
login = request.form.get('login')
password = request.form.get('password')
employee = view.EmployeeView.model.query.filter_by(
login=login, password=password).first()
if employee:
session['id'] = e... | def companies(): |
Using the snippet: <|code_start|>
class EmployeeView(nuts.ModelView):
model = database.Employee
list_column = 'fullname'
table_columns = ('fullname', )
create_columns = ('login', 'password', 'name', 'firstname', 'company')
read_columns = ('person_id', 'name', 'firstname', 'fullname', 'company')
... | fullname = TextField(u'Employee name') |
Based on the snippet: <|code_start|>
class EmployeeView(nuts.ModelView):
model = database.Employee
list_column = 'fullname'
create_columns = ('name', 'firstname')
class Form(BaseForm):
id = IntegerField(u'ID')
name = TextField(u'Surname', validators=[Required()])
firstname = ... | fullname = TextField(u'Fullname') |
Given the code snippet: <|code_start|> if value:
value = json.loads(value)
except:
logger.debug("Redis exception: couldn't get_cache {}".format(key))
value = None
return value
def del_cache(key):
"""Delete a cached item."""
key = Config.db.redis_prefix + key
clie... | lock = client.lock(key, timeout=expire) |
Based on the snippet: <|code_start|>
try:
value = client.get(key)
if value:
value = json.loads(value)
except:
logger.debug("Redis exception: couldn't get_cache {}".format(key))
value = None
return value
def del_cache(key):
"""Delete a cached item."""
ke... | return |
Predict the next line after this snippet: <|code_start|> if value:
value = json.loads(value)
except:
logger.debug("Redis exception: couldn't get_cache {}".format(key))
value = None
return value
def del_cache(key):
"""Delete a cached item."""
key = Config.db.redis_pre... | lock = client.lock(key, timeout=expire) |
Here is a snippet: <|code_start|> return {
key: data for key, data in db.items() if data["privacy"] == "private"
}
def rebuild_index():
"""Rebuild the index.json if it goes missing."""
index = {}
entries = JsonDB.list_docs("blog/entries")
for post_id in entries:
db = JsonDB.get... | fid = post["fid"], |
Based on the snippet: <|code_start|> db = JsonDB.get("blog/index")
# Filter out only the draft posts.
return {
key: data for key, data in db.items() if data["privacy"] == "private"
}
def rebuild_index():
"""Rebuild the index.json if it goes missing."""
index = {}
entries = JsonDB.... | index = get_index(drafts=True) |
Based on the snippet: <|code_start|> except Exception as e:
logger.error("Couldn't load JSON from emoticon file: {}".format(e))
data = {}
# Cache and return it.
_cache = data
return data
def render(message):
"""Render the emoticons into a message.
The message should already be... | ) |
Based on the snippet: <|code_start|> # Give up.
return {}
# Read it.
fh = codecs.open(settings, "r", "utf-8")
text = fh.read()
fh.close()
try:
data = json.loads(text)
except Exception as e:
logger.error("Couldn't load JSON from emoticon file: {}".format(e... | for img in sorted(smileys["map"]): |
Given the code snippet: <|code_start|>
# Username musn't exist.
if exists(username):
# The front-end shouldn't let this happen.
raise Exception("Can't create username {}: already exists!".format(username))
# Crypt their password.
hashedpass = hash_password(password)
logger.info("Cr... | def update_user(uid, data): |
Given the following code snippet before the placeholder: <|code_start|> if photo:
return photo["avatar"]
return None
def exists(uid=None, username=None):
"""Query whether a user ID or name exists."""
if uid:
return JsonDB.exists("users/by-id/{}".format(uid))
elif username:
... | test = bcrypt.hashpw(str(password).encode("utf-8"), str(db["password"]).encode("utf-8")).decode("utf-8") |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
parser = argparse.ArgumentParser(description="Rophako")
parser.add_argument(
"--port", "-p",
type=int,
help="Port to listen on",
... | "--key", "-k", |
Next line prediction: <|code_start|>
"""Wiki models."""
def render_page(content):
"""Render the Markdown content of a Wiki page, and support inter-page
linking with [[double braces]].
For simple links, just use the [[Page Name]]. To have a different link text
than the page name, use [[Link Text|Page... | ) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
"""Wiki models."""
def render_page(content):
"""Render the Markdown content of a Wiki page, and support inter-page
linking with [[double braces]].
For simple links, just use the [[Page N... | label=label, |
Using the snippet: <|code_start|> )
def rename_album(old_name, new_name):
"""Rename an existing photo album.
Returns True on success, False if the new name conflicts with another
album's name."""
old_name = sanitize_name(old_name)
new_name = sanitize_name(new_name)
index = get_index()
... | if index["map"][photo] == old_name: |
Using the snippet: <|code_start|>
return dict(
name=name,
format=index["settings"][name]["format"],
description=index["settings"][name]["description"],
cover=album[cover]["thumb"],
)
def rename_album(old_name, new_name):
"""Rename an existing photo album.
Returns True ... | transfer_key(index["covers"], old_name, new_name) |
Given the following code snippet before the placeholder: <|code_start|>
def rename_album(old_name, new_name):
"""Rename an existing photo album.
Returns True on success, False if the new name conflicts with another
album's name."""
old_name = sanitize_name(old_name)
new_name = sanitize_name(new_na... | index["map"][photo] = new_name |
Predict the next line after this snippet: <|code_start|> index = get_index()
if not name in index["albums"]:
return None
album = index["albums"][name]
cover = index["covers"][name]
return dict(
name=name,
format=index["settings"][name]["format"],
description=index["... | def transfer_key(obj, old_key, new_key): |
Based on the snippet: <|code_start|>
# Refresh their login status from the DB.
if session["login"]:
if not User.exists(uid=session["uid"]):
# Weird! Log them out.
logout()
return
db = User.get_user(uid=session["uid"])
session["username"] = db["usernam... | if path.endswith("/"): |
Next line prediction: <|code_start|>
@app.context_processor
def after_request():
"""Called just before render_template. Inject g.info into the template vars."""
return g.info
@app.route("/<path:path>")
def catchall(path):
"""The catch-all path handler. If it exists in the www folders, it's sent,
other... | if not "." in path and os.path.isfile(abspath + suffix): |
Next line prediction: <|code_start|> if session["login"]:
if not User.exists(uid=session["uid"]):
# Weird! Log them out.
logout()
return
db = User.get_user(uid=session["uid"])
session["username"] = db["username"]
session["name"] = db["name"]
... | return redirect(path) |
Given the code snippet: <|code_start|>
def count_comments(thread):
"""Count the comments on a thread."""
comments = get_comments(thread)
return len(comments.keys())
def add_subscriber(thread, email):
"""Add a subscriber to a thread."""
if not "@" in email:
return
# Sanity check: only ... | threads = JsonDB.list_docs("comments/subscribers") |
Based on the snippet: <|code_start|> if not "@" in email:
return
# Sanity check: only subscribe to threads that exist.
if not JsonDB.exists("comments/threads/{}".format(thread)):
return
logger.info("Subscribe e-mail {} to thread {}".format(email, thread))
subs = get_subscribers(thre... | del db[email] |
Here is a snippet: <|code_start|> """Count the comments on a thread."""
comments = get_comments(thread)
return len(comments.keys())
def add_subscriber(thread, email):
"""Add a subscriber to a thread."""
if not "@" in email:
return
# Sanity check: only subscribe to threads that exist.
... | threads = [thread] |
Given the following code snippet before the placeholder: <|code_start|> return
# Sanity check: only subscribe to threads that exist.
if not JsonDB.exists("comments/threads/{}".format(thread)):
return
logger.info("Subscribe e-mail {} to thread {}".format(email, thread))
subs = get_subscr... | write_subscribers(thread, db) |
Given snippet: <|code_start|>#!/usr/bin/env python3
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
class GenotypeTestCase(unittest.TestCase):
def setUp(self):
self.graph = RDFGraph()
self.curie_map = curie_map.get()
self.genotype = Genotype(self.graph)
... | Literal(label)) in self.genotype.graph) |
Given the code snippet: <|code_start|> (phenotyping_center,
colony) = self.test_set_1[2:4]
(project_name,
project_fullname,
pipeline_name,
pipeline_stable_id,
procedure_stable_id,
procedure_name,
parameter_stable_id,
parameter_name) ... | <https://monarchinitiative.org/.well-known/genid/b6f14f763c8d0629360e> a OBI:0000471 ; |
Continue the code 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 pe... | "using", |
Predict the next line for 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 g... | "score", |
Here is a snippet: <|code_start|> n = analysis.CustomNormalizer(
"my_normalizer", filter=["lowercase", "asciifolding"], char_filter=["quote"]
)
assert {
"type": "custom",
"filter": ["lowercase", "asciifolding"],
"char_filter": ["quote"],
} == n.get_definition()
def test... | assert { |
Given snippet: <|code_start|># Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "L... | return super(AttrJSONSerializer, self).default(data) |
Continue the code snippet: <|code_start|># KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
class Hit(AttrDict):
def __init__(self, document):
data = {}
if "_source" in document:
data = document... | def __repr__(self): |
Next line prediction: <|code_start|># Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 ... | data.update(document["fields"]) |
Given the following code snippet before the placeholder: <|code_start|> write_client.indices.create(
index="test-mapping", body={"settings": {"analysis": new_analysis}}
)
m.field("title", "text", analyzer=analyzer)
m.save("test-mapping", using=write_client)
assert {
"test-mapping": ... | "fields": {"raw": {"type": "keyword"}}, |
Continue the code snippet: <|code_start|> write_client.indices.create(index="test-mapping")
with raises(exceptions.IllegalOperation):
m.save("test-mapping", using=write_client)
write_client.cluster.health(index="test-mapping", wait_for_status="yellow")
write_client.indices.close(index="test-map... | ) |
Given snippet: <|code_start|># this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you 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
#
#... | "name": {"type": "text", "analyzer": "my_analyzer"}, |
Continue the code snippet: <|code_start|># ownership. Elasticsearch B.V. licenses this file to you 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
#
#... | assert search.count() == 53 |
Predict the next line after this snippet: <|code_start|># Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache L... | assert data_client.count.call_count == 0 |
Next line prediction: <|code_start|># this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you 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... | if args and (len(args) > 1 or kwargs or not isinstance(args[0], dict)): |
Given snippet: <|code_start|>def test_bool_with_different_minimum_should_match_should_not_be_combined():
q1 = query.Q(
"bool",
minimum_should_match=2,
should=[
query.Q("term", field="aa1"),
query.Q("term", field="aa2"),
query.Q("term", field="aa3"),
... | ) |
Here is a snippet: <|code_start|>
assert ~q == query.Bool(must_not=[query.Match(f=42)])
def test_inverted_query_with_must_not_become_should():
q = query.Q("bool", must_not=[query.Q("match", f=1), query.Q("match", f=2)])
assert ~q == query.Q("bool", should=[query.Q("match", f=1), query.Q("match", f=2)])
... | def test_double_invert_returns_original_query(): |
Given the following code snippet before the placeholder: <|code_start|> self.assertEqual(token_instance['email'], self.email)
def test_login_social_simple_jwt_pair_only(self):
self._check_login_social_simple_jwt_only(
reverse('login_social_jwt_pair'),
data={'provider': 'faceb... | def test_login_social_simple_jwt_sliding_only(self): |
Based on the snippet: <|code_start|> self._check_login_social_simple_jwt_user(
reverse('login_social_jwt_pair_user'),
data={'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'},
token_type='access',
)
def test_login_social_simple_jwt_pair_user_provider_in_u... | data={'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'}, |
Predict the next line for this snippet: <|code_start|>
class HomeJWTView(TemplateView):
template_name = 'home_jwt.html'
class HomeKnoxView(TemplateView):
template_name = 'home_knox.html'
class LogoutSessionView(APIView):
def post(self, request, *args, **kwargs):
logout(request)
return ... | class UserTokenDetailView(BaseDetailView): |
Based on the snippet: <|code_start|>
class HomeTokenView(TemplateView):
template_name = 'home_token.html'
class HomeJWTView(TemplateView):
template_name = 'home_jwt.html'
class HomeKnoxView(TemplateView):
template_name = 'home_knox.html'
class LogoutSessionView(APIView):
def post(self, request, ... | class UserSessionDetailView(BaseDetailView): |
Based on the snippet: <|code_start|>class HomeSessionView(TemplateView):
template_name = 'home_session.html'
@method_decorator(ensure_csrf_cookie)
def get(self, request, *args, **kwargs):
return super(HomeSessionView, self).get(request, *args, **kwargs)
class HomeTokenView(TemplateView):
temp... | model = get_user_model() |
Next line prediction: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True)
LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EX... | def load_strategy(request=None): |
Given the code snippet: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
<|code_end|>
, generate the next line using the imports in this file:
import logging
import warnings
from urllib.parse import urljoin, u... | DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) |
Next line prediction: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
<|code_end|>
. Use current file imports:
(import logging
import warnings
from urllib.parse import urljoin, urlencode, urlparse # python 3x
from urllib import urlencode # python 2x
from urlparse import... | REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True)
LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_... | @psa(REDIRECT_URI, load_strategy=load_strategy) |
Continue the code snippet: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True)
LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AU... | pass |
Predict the next line after this snippet: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
<|code_end|>
using the current file's imports:
import logging
import warnings
from urllib.parse import urljoin, urlen... | DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) |
Next line prediction: <|code_start|>
try:
except ImportError:
logger = logging.getLogger(__name__)
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True)
LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EX... | def decorate_request(request, backend): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.