Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|> # mixed type, such as L, GL, GF, because the backoff
# involves getting just the first ORDER words ...
for index, count in data.iteritems():
#gramm = index.split('/')
# order == 1 still gives us a tuple for now!
... | if isinstance(data, STRINGTYPE): |
Next line prediction: <|code_start|> """
Stores results of a corpus interrogation, before or after editing. The main
attribute, :py:attr:`~corpkit.interrogation.Interrogation.results`, is a
Pandas object, which can be edited or plotted.
"""
def __init__(self, results=None, totals=None, query=N... | return "<%s instance: %d total>" % (classname(self), self.totals.sum()) |
Given snippet: <|code_start|>
# store kwargs and locs
locs = locals().copy()
locs.update(kwargs)
locs.pop('kwargs', None)
have_java = check_jdk()
# remake corpus without bad files and folders
corpus, skip_metadata, just_metadata = delete_files_and_subcorpora(corpus, skip_metadata, ... | if not kwargs.get('cql') and isinstance(search, STRINGTYPE) and len(search) > 3: |
Given the code snippet: <|code_start|> """Say goodbye before exiting"""
if not kwargs.get('printstatus', True):
return
thetime = strftime("%H:%M:%S", localtime())
if only_conc:
finalstring = '\n\n%s: Concordancing finished! %s results.' % (thetime, format(len(conc_... | if PYTHON_VERSION == 2: |
Here is a snippet: <|code_start|> # use tregex if simple because it's faster
# but use dependencies otherwise
search = 't' if not subcorpora and not just_metadata and not skip_metadata and have_java else {'w': 'any'}
if search == 'lexicon':
search = 't' if not subcorpora and not just_... | INPUTFUNC('\n\n%s: Paused. Press any key to resume, or ctrl+c to quit.\n' % thetime) |
Predict the next line for this snippet: <|code_start|>
if word_in_ref == 0:
logaE1 = 0
else:
logaE1 = math.log(word_in_ref/E1)
if word_in_target == 0:
logaE2 = 0
else:
logaE2 = math.log(word_in_target/E2)
score = float(2* ((... | if isinstance(threshold, STRINGTYPE): |
Given the code snippet: <|code_start|>from __future__ import print_function
"""
In here are functions used internally by corpkit, but also
might be called by the user from time to time
"""
def quickview(results, n=25):
"""
View top n results as painlessly as possible.
:param results: Interrogation data
... | if isinstance(results, STRINGTYPE): |
Predict the next line after this snippet: <|code_start|> firstpart = ''
firstpart = os.path.basename(firstpart)
if firstpart:
return firstpart + '-' + savename
else:
return savename
savename = make_filename(interrogation, savename)
... | selection = INPUTFUNC(("\nSave error: %s already exists in %s.\n\n" \ |
Here is a snippet: <|code_start|> else:
oldd[tokens[1]] = parse_pattern(tokens[-1])
setattr(objs, tokens[0], oldd)
# delete the entire filter dict
elif tokens[-1] in ['none', 'None', 'off', 'default']:
setattr(objs, attr, Fal... | selected = INPUTFUNC('Pick a corpus by name or number: ') |
Here is a snippet: <|code_start|> continue
if search_related[i+1] == 'postags':
search = 'postags'
continue
if search_related[i+1] == 'wordclasses':
search = 'wordclasses'
continue
... | transshow = {v.lower(): k.replace(' ', '-') for k, v in transshow.items()} |
Continue the code snippet: <|code_start|> search = 'features'
continue
if search_related[i+1] == 'postags':
search = 'postags'
continue
if search_related[i+1] == 'wordclasses':
search = 'wo... | transobjs = {v.lower(): k.replace(' ', '-') for k, v in transobjs.items()} |
Next line prediction: <|code_start|> " +-----------------+--------------------------------------------------------------+--------------------------------------------------------------------------------------------+ \n"\
"\nMore information:\n\nYou can access more specific help by entering corpki... | completer = Completer(poss) |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import print_function
log = logging
def safe_import(path):
module = path.split('.')
g = __import__(module[0], fromlist=['*'])
s = [module[0]]
for i in module[1:]:
mod = g
if hasattr(mod, i):
... | if isinstance(path, string_types): |
Given the following code snippet before the placeholder: <|code_start|> _v = default
if v in _vars:
_v = _vars[v]
elif v in _env:
_v = _env[v]
return _v
return defined
e = {}
if isinstance... | exec_(code, e) |
Predict the next line for this snippet: <|code_start|>
def __repr__(self):
return self.__str__()
class BaseBlockNode(Node):
def __init__(self, name='', content=None):
self.nodes = []
self.name = name
self.content = content
self.block = 1
def add(... | s.append(u(str(x))) |
Here is a snippet: <|code_start|> return self._run(code, filename or 'template')
def _run(self, code, filename):
def f(_vars, _env):
def defined(v, default=None):
_v = default
if v in _vars:
_v = _vars[v]
elif v ... | if isinstance(code, string_types): |
Continue the code snippet: <|code_start|> return True
return False
def _parse_text(self, content, var):
try:
text = u(str(eval(var, self.env.to_dict(), self.vars)))
except:
if self.skip_error:
text = ''
else:
... | f = open(fname, 'r') |
Given snippet: <|code_start|> log.error("File %s can't be found, will be skipped" % fname)
continue
def make_title(x):
return '<li><a href="%s">%s</a></li>' % (x['link'], x['title'])
_fname, _ext = os.path.splitext(fname)
last = 1
titl... | for i in range(last, 1, -1): |
Predict the next line after this snippet: <|code_start|> e = ''
else:
b, e = [y.rstrip() for y in v]
if b.isdigit():
b = int(b)
else:
pattern = True
b = b or 1
if e.isdigit():
e = i... | with open(filename, 'r') as f: |
Continue the code snippet: <|code_start|> key : value
{% endcode-comment %}
"""
if 'new' in block:
txt = []
data = {}
txt.append('<script type="text/code-comment">')
d = {}
for line in block['body'].splitlines():
if li... | txt.append(u(json_dumps(data))) |
Continue the code snippet: <|code_start|>
{% code %}
code
{% endcode %}
"""
return block['body']
def toc(visitor, block, headers=None, relations=None):
"""
Format:
{% toc max_depth=2 %}
file1.md
file2.md
{% endtoc %}
"""
s = []
... | log.error("File %s can't be found, will be skipped" % fname) |
Next line prediction: <|code_start|> so that ManagementUtility can handle them before searching for
user commands.
"""
pass
class CommandError(Exception):
"""
Exception class indicating a problem while executing a management
command.
If this exception is raised during the execution of ... | ans = input(message).strip().upper() |
Using the snippet: <|code_start|> if not str(e).startswith('No module named'):
traceback.print_exc()
continue
find_mod_commands(mod)
collect_commands()
return __commands__
def register_command(kclass):
global __commands__
... | class Command(with_metaclass(CommandMetaclass)): |
Predict the next line after this snippet: <|code_start|> issubclass(c, Command) and c is not Command and c is not CommandManager)
def find_mod_commands(mod):
for name in dir(mod):
c = getattr(mod, name)
if check(c):
register_command(c)
def... | if isinstance(args, string_types): |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading cifar100.
"""
# setup
name = 'cifar100'
task = 'classification'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
, predict the immediate next line with the help of imports:
... | tester = TestBaseDB(name, task, data_dir, verbose) |
Next line prediction: <|code_start|>#!/usr/bin/env python3
"""
Test loading Leeds Sports Pose (extended).
"""
# setup
name = 'leeds_sports_pose_extended'
task = 'keypoints'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
. Use current file imports:
... | tester = TestBaseDB(name, task, data_dir, verbose) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
"""
Test loading ucf101.
"""
# setup
name = 'ucf_101'
task = 'recognition'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
. Use current file imports:
import os
from dbcollection.utils.... | tester = TestBaseDB(name, task, data_dir, verbose) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading MPII Human Pose.
"""
# setup
name = 'mpii_pose'
task = 'keypoints'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
. Use current file imports:
import os
from dbcollect... | tester = TestBaseDB(name, task, data_dir, verbose) |
Predict the next line after this snippet: <|code_start|>"""
Test dbcollection/utils/pad.py.
"""
@pytest.mark.parametrize("sample, output, fill_value", [
([[5, 1, 3], [9, 17, 324]], [[5, 1, 3], [9, 17, 324]], -1),
([[1, 1, 0], [1, 0]], [[1, 1, 0], [1, 0, -1]], -1),
([[1, 1, 0], [1, 0]], [[1, 1, 0], [1, 0... | assert(output == pad_list(sample, fill_value)) |
Given snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading Pascal VOC 2012.
"""
# setup
name = 'pascal_voc_2012'
task = 'detection'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
, continue by predicting the next line. Consider current fi... | tester = TestBaseDB(name, task, data_dir, verbose) |
Given snippet: <|code_start|>"""
Test dbcollection core API: remove.
"""
@pytest.fixture()
def mocks_init_class(mocker):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from dbcollection.core.api.remove import remove, RemoveAPI
and context:
# Path: dbcollection/... | mock_cache = mocker.patch.object(RemoveAPI, "get_cache_manager", return_value=True) |
Given the following code snippet before the placeholder: <|code_start|> Name of the dataset.
data_dir : str
Directory path to store the downloaded data.
save_data_dir : str
Data files save dir path.
save_cache_dir : str
Cache save dir path.
extract_data : bool
Flag... | return CacheManager() |
Here is a snippet: <|code_start|>
def run(self):
"""Main method."""
if not self.exists_dataset_in_cache():
if self.verbose:
print('==> Download {} data to disk...'.format(self.name))
self.download_dataset()
if self.verbose:
print('... | return MetadataConstructor(name) |
Using the snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading ucf101.
"""
# setup
name = 'ucf101'
task = 'recognition'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
, determine the next line of code. You have imports:
import os
from db... | tester = TestBaseDB(name, task, data_dir, verbose) |
Continue the code snippet: <|code_start|> delete_data : bool
Delete all data files from disk for this dataset if True.
Attributes
----------
name : str
Name of the dataset to delete.
task : str
Name of the task to delete.
delete_data : bool
Delete all data files f... | return CacheManager() |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
Test processing coco.
"""
# setup
name = 'coco'
task = 'detection'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
, generate the next line using the imports in this file:
import os
fr... | tester = TestBaseDB(name, task, data_dir, verbose) |
Given snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading cifar100.
"""
# setup
name = 'cifar100'
task = 'classification'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
, continue by predicting the next line. Consider current file import... | tester = TestBaseDB(name, task, data_dir, verbose) |
Given snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading INRIA Pedestrian.
"""
# setup
name = 'inria_pedestrian'
task = 'detection'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
, continue by predicting the next line. Consider current ... | tester = TestBaseDB(name, task, data_dir, verbose) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading Leeds Sports Pose.
"""
# setup
name = 'leeds_sports_pose'
task = 'keypoints'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
. Use current file imports:
import os
from... | tester = TestBaseDB(name, task, data_dir, verbose) |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading coco.
"""
# setup
name = 'coco'
task = 'keypoints_2016'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
, predict the immediate next line with the help of imports:
import o... | tester = TestBaseDB(name, task, data_dir, verbose) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading Caltech Pedestrian.
"""
# setup
name = 'caltech_pedestrian'
task = 'detection'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
. Use current file imports:
import os
fr... | tester = TestBaseDB(name, task, data_dir, verbose) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading mnist.
"""
# setup
name = 'mnist'
task = 'classification'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
with the help of current file imports:
import o... | tester = TestBaseDB(name, task, data_dir, verbose) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading Imagenet ilsvrc2012.
"""
# setup
name = 'ilsvrc2012'
task = 'classification'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
with the help of current file... | tester = TestBaseDB(name, task, data_dir, verbose) |
Next line prediction: <|code_start|>#!/usr/bin/env python3
"""
Test loading flic.
"""
# setup
name = 'flic'
task = 'keypoints'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
. Use current file imports:
(import os
from dbcollection.utils.test impor... | tester = TestBaseDB(name, task, data_dir, verbose) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading cifar10.
"""
# setup
name = 'cifar10'
task = 'classification'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
using the current file's imports:
import ... | tester = TestBaseDB(name, task, data_dir, verbose) |
Next line prediction: <|code_start|> Name of the dataset.
task : str
Name of the task to process.
verbose : bool
Displays text information (if true).
extract_data : bool
Flag to extract data (if True).
cache_manager : CacheManager
Cache manager object.
Raises
... | return CacheManager() |
Continue the code snippet: <|code_start|> def set_dirs_processed_metadata(self):
cache_dir = self.get_dataset_cache_dir_path()
self.create_dir(cache_dir)
def get_dataset_cache_dir_path(self):
cache_dir = self.get_cache_dir_path_from_cache()
return os.path.join(cache_dir, self.nam... | return MetadataConstructor(name) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading cifar10.
"""
# setup
name = 'cifar10'
task = 'classification'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
. Use current file imports:
import os
from dbcollection.u... | tester = TestBaseDB(name, task, data_dir, verbose) |
Predict the next line for this snippet: <|code_start|>"""
Test dataset's urls download status.
"""
TIMEOUT_SECONDS = 3
@pytest.mark.parametrize("dataset_name, urls", get_list_urls_dataset())
@pytest.mark.slow
def test_check_urls_are_valid(dataset_name, urls):
for url in urls:
response = requests.head(... | status = check_url_redirect(url, TIMEOUT_SECONDS) # try with redirect enabled |
Next line prediction: <|code_start|>#!/usr/bin/env python
"""
Test loading ucf sports.
"""
# setup
name = 'ucf_sports'
task = 'recognition'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
. Use current file imports:
(import os
from dbcollection.uti... | tester = TestBaseDB(name, task, data_dir, verbose) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading coco.
"""
# setup
name = 'coco'
task = 'detection_2015'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
with the help of current file imports:
import os
... | tester = TestBaseDB(name, task, data_dir, verbose) |
Using the snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading Caltech Pedestrian.
"""
# setup
name = 'caltech_pedestrian'
task = 'detection'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
, determine the next line of code. You have impor... | tester = TestBaseDB(name, task, data_dir, verbose) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
"""
Test downloading coco.
"""
# setup
name = 'coco'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data2')
verbose = True
# Run tester
<|code_end|>
. Write the next line using the current file imports:
import os
from dbcollection.utils.tes... | tester = TestBaseDB(name, 'no_task', data_dir, verbose) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
Test loading ucf sports.
"""
# setup
name = 'ucf_sports'
task = 'recognition'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
, generate the next line using the imports in this file:
i... | tester = TestBaseDB(name, task, data_dir, verbose) |
Given the code snippet: <|code_start|> Tuple of keyword strings to categorize the dataset.
verbose : bool
Displays text information.
force_overwrite : bool
Forces the overwrite of data in cache
cache_manager : CacheManager
Cache manager object.
"""
def __init__(self,... | return CacheManager() |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading Pascal VOC 2007.
"""
# setup
name = 'pascal_voc_2007'
task = 'detection'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
using the current file's import... | tester = TestBaseDB(name, task, data_dir, verbose) |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
"""
Test loading Imagenet ilsvrc2012.
"""
# setup
name = 'ilsvrc2012'
task = 'classification'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
. Write the next line using the current file import... | tester = TestBaseDB(name, task, data_dir, verbose) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
"""
Test loading coco.
"""
# setup
name = 'coco'
task = 'caption_2015'
data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data')
verbose = True
# Run tester
<|code_end|>
, predict the next line using import... | tester = TestBaseDB(name, task, data_dir, verbose) |
Continue the code snippet: <|code_start|>"""
Test the HDF5 metadata manager class.
"""
@pytest.fixture()
def test_data():
return {
"filename": '/path/to/filename.h5'
}
@pytest.fixture()
def mock_hdf5manager(mocker, test_data):
<|code_end|>
. Use current file imports:
import os
import numpy as np... | mocker.patch.object(HDF5Manager, "open_file", return_value={'test_group': 'dummy_data'}) |
Using the snippet: <|code_start|> session = requests.Session()
token = self.get_confirmation_token(session, file_id)
response = session.get(self.base_url, params={'id': file_id, 'confirm': token}, stream=True)
self.save_response_content(response, filename)
def get_confirmation_token(... | raise GoogleDriveFileIdDoesNotExist('Invalid google drive file id: {}.'.format(file_id)) |
Given the following code snippet before the placeholder: <|code_start|>
def download_url_to_file(self, url_metadata, filename, verbose=True):
"""Downloads a single url to a file.
Parameters
----------
url_metadata : dict
URL metadata.
filename : str
F... | raise InvalidURLDownloadSource('Invalid url source: {}'.format(method)) |
Next line prediction: <|code_start|> Returns
------
str
File name + path of the temporary file.
"""
filename_dir = os.path.dirname(filename)
(fd, tmpfile) = tempfile.mkstemp(".tmp", prefix=filename, dir=filename_dir)
os.close(fd)
os.unlink(tmpf... | raise MD5HashNotEqual("MD5 checksums do not match: {} != {}".format(md5hash, file_hash)) |
Given snippet: <|code_start|> str
URL file name.
"""
url_metadata = URL().parse_url_metadata(url)
return url_metadata['filename']
class URLDownload:
"""Download an URL using the requests module."""
def download(self, url, filename, verbose=False):
"""Downlo... | raise URLDoesNotExist("Invalid url or does not exist: {}".format(url)) |
Based on the snippet: <|code_start|>
Parameters
----------
index : int/list/tuple, optional
Index number of he field. If it is a list, returns the data
for all the value indexes of that list.
convert_to_str : bool, optional
Convert the output data into... | data = convert_ascii_to_str(data) |
Predict the next line for this snippet: <|code_start|>#coding: utf-8
class BaseMongoAdminTests(unittest.TestCase):
def setUp(self):
self.req = RequestFactory().get('/')
def testHasViewPermissions(self):
self.req.user = DummyUser(is_authenticated=True, is_active=True)
<|code_end|>
with the... | self.assertTrue(BaseMongoAdmin().has_view_permission(self.req)) |
Predict the next line for this snippet: <|code_start|>
urlpatterns = [
url(
regex=r'^$',
<|code_end|>
with the help of current file imports:
from django.conf.urls import url
from mongonaut import views
and context from other files:
# Path: mongonaut/views.py
# class IndexView(MongonautViewMixin, ListVi... | view=views.IndexView.as_view(), |
Given snippet: <|code_start|> u = NewUser(email='test@test.com')
u.id=ObjectId('abcabcabcabc')
p = Post(author=u, title='Test')
p.id = ObjectId('abcabcabcabc')
match_found = True
try:
v = get_document_value(p, 'author')
except NoReverseMatch as e:
... | self.view = DocumentDetailView.as_view()( |
Given the following code snippet before the placeholder: <|code_start|>#coding: utf-8
class IndexViewTests(unittest.TestCase):
def setUp(self):
self.req = RequestFactory().get('/')
django.setup()
def testURLResolver(self):
'''
Tests whether reverse function inside get_... | p = Post(author=u, title='Test') |
Here is a snippet: <|code_start|>#coding: utf-8
class IndexViewTests(unittest.TestCase):
def setUp(self):
self.req = RequestFactory().get('/')
django.setup()
def testURLResolver(self):
'''
Tests whether reverse function inside get_document_value can
correc... | u = NewUser(email='test@test.com') |
Next line prediction: <|code_start|>
class IndexViewTests(unittest.TestCase):
def setUp(self):
self.req = RequestFactory().get('/')
django.setup()
def testURLResolver(self):
'''
Tests whether reverse function inside get_document_value can
correctly return a do... | v = get_document_value(p, 'author') |
Predict the next line for this snippet: <|code_start|> """ Sets a number of commonly used attributes """
if hasattr(self, "app_label"):
# prevents us from calling this multiple times
return None
self.app_label = self.kwargs.get('app_label')
self.document_name = sel... | raise NoMongoAdminSpecified("No MongoAdmin for {0}.{1}".format(self.app_label, self.document_name)) |
Predict the next line after this snippet: <|code_start|> # document.
self.embedded_list_docs = {}
if self.new_document is None:
messages.error(self.request, u"Failed to save document")
else:
self.new_document = self.new_document()
... | key_array_digit = remaining_key_array[-1] if remaining_key_array and has_digit(remaining_key_array) else None |
Here is a snippet: <|code_start|> self.embedded_list_docs = {}
if self.new_document is None:
messages.error(self.request, u"Failed to save document")
else:
self.new_document = self.new_document()
for form_key in self.form.cleaned_data.... | remaining_key = make_key(remaining_key_array) |
Continue the code snippet: <|code_start|>
def process_document(self, document, form_key, passed_key):
"""
Given the form_key will evaluate the document and set values correctly for
the document given.
"""
if passed_key is not None:
current_key, remaining_key_array... | value = translate_value(document._fields[current_key], |
Based on the snippet: <|code_start|> self.document_map_dict = MongoModelForm(model=self.document_type).create_document_dictionary(self.document_type)
self.new_document = self.document_type
# Used to keep track of embedded documents in lists. Keyed by the list and the number of the
... | current_key, remaining_key_array = trim_field_key(document, passed_key) |
Given snippet: <|code_start|> raise TypeError(u"The model supplied must be a mongoengine Document")
if self.is_initialized and not isinstance(self.model_instance, self.model):
raise TypeError(u"The provided instance must be an instance of the given model")
if self.post_data_dict... | return_dict[field_key] = FieldTuple(widget, |
Based on the snippet: <|code_start|> def set_form_fields(self, form_field_dict, parent_key=None, field_type=None):
"""
Set the form fields for every key in the form_field_dict.
Params:
form_field_dict -- a dictionary created by get_form_field_dict
parent_key -- the key fo... | if has_digit(field_key)] |
Continue the code snippet: <|code_start|> if hasattr(self.model, 'Meta') and hasattr(self.model.Meta, 'form_fields_ordering'):
field_order_list = tuple(form_field for form_field
in self.model.Meta.form_fields_ordering
if form_f... | form_key = make_key(parent_key, form_key) if parent_key is not None else form_key |
Given the code snippet: <|code_start|> list_widget = deepcopy(field_value.widget)
new_key = make_key(new_base_key, six.text_type(key_index))
list_widget.attrs['class'] += " {0}".format(make_key(base_key, key_index))
self.set_... | field_class = get_form_field_class(model_field) |
Based on the snippet: <|code_start|> else:
self.form.fields[field_key].initial = default_value
else:
self.form.fields[field_key].initial = getattr(model_field, 'default', None)
if isinstance(model_field, ReferenceField):
self.form.fields[field_key].cho... | current_key, new_key_array = trim_field_key(document, field_key) |
Next line prediction: <|code_start|>
PLAT_LINE_SEP = '\n'
class BaseGenerator(object):
"""Base generator class"""
def __init__(self, site_config, base_path):
"""
:site_config: site global configuration parsed from _config.yml
:base_path: root path of wiki directory
"""
... | for _filter in jinja_exts.filters: |
Given snippet: <|code_start|> markdown_extensions = self._set_markdown_extensions()
html_content = markdown.markdown(
markup_text,
extensions=markdown_extensions,
)
return html_content
def _set_markdown_extensions(self):
"""Set the extensions for mar... | ext = import_string("markdown.extensions." + k).makeExtension() |
Next line prediction: <|code_start|>
return html
@property
def src_file(self):
return self._src_file
@src_file.setter
def src_file(self, filename):
self._src_file = os.path.relpath(filename, self.base_path)
def get_meta_and_content(self, do_render=True):
meta_str, ... | if is_py2: |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Convert Markdown file to html, which is embeded in html template.
"""
from __future__ import (print_function, with_statement, unicode_literals,
absolute_import)
try:
except ImportError:
<|code_end|>
, determin... | if is_py3: |
Given the following code snippet before the placeholder: <|code_start|> returns:
meta_str (str): page's meta string
content_str (str): html parsed from markdown or other markup text.
"""
regex = re.compile('(?sm)^---(?P<meta>.*?)^---(?P<body>.*)')
with io.open(filename... | if isinstance(meta['tag'], basestring): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import
yes_answer = ('y', 'yes')
class Initiator(object):
conf_template_dn = "conf_templates"
config_fn = "_config.yml"
fabfile_fn = "fabfile.py"
dem... | self.config = parse_config(self.config_file) |
Continue the code snippet: <|code_start|> def get_dockerfile(self):
src_dockerfile = os.path.join(
self.source_path,
self.conf_template_dn,
self.dockerfile_fn
)
dst_dockerfile = os.path.join(self.target_path, self.dockerfile_fn)
self.get_file(src_do... | copytree(src_theme, dst_theme) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import
yes_answer = ('y', 'yes')
class Initiator(object):
conf_template_dn = "conf_templates"
config_fn = "_config.yml"
fabfile_fn = "fabfile.py"
demo_fn = "gettingstarted... | mkdir_p(dst_directory) |
Predict the next line for this snippet: <|code_start|> if not os.path.exists(dst_directory):
mkdir_p(dst_directory)
logging.info("Creating directory: {0}".format(dst_directory))
shutil.copyfile(src, dst)
logging.info("Creating file: {0}".format(dst))
def get_config_f... | nohidden_dir = listdir_nohidden( |
Predict the next line after this snippet: <|code_start|> default_theme_name = self.config['theme']
src_theme = os.path.join(self.source_path, self.config['themes_dir'],
default_theme_name)
dst_theme = os.path.join(theme_path, default_theme_name)
if os.path... | _ans = raw_input('Create Dockerfile? (y/N) ') |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
class TestInitiator(unittest.TestCase):
def setUp(self):
BASE_DIR = os.path.join(os.path.dirname(__file__), '..')
<|code_end|>
, predict the next line using imports from the current file... | self.default_config = get_default_config() |
Next line prediction: <|code_start|>
class TestInitiator(unittest.TestCase):
def setUp(self):
BASE_DIR = os.path.join(os.path.dirname(__file__), '..')
self.default_config = get_default_config()
self.config_file = os.path.join(BASE_DIR, "simiki", "conf_templates",
... | i = Initiator(self.config_file, self.target_path) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Jinja2 custom filters and extensions
"""
filters = ['rfc3339']
def rfc3339(dt_obj):
"""
dt_obj: datetime object or string
The filter use `datetime.datetime.isoformat()`, which is in ISO 8601
forma... | elif isinstance(dt_obj, basestring): |
Predict the next line for this snippet: <|code_start|>
def setUp(self):
logging.disable(logging.NOTSET)
self.stream = StringIO()
self.logger = logging.getLogger()
self.handler = logging.StreamHandler(self.stream)
for handler in self.logger.handlers:
# exclude nose... | .format(color_msg(l2c[level], level.upper()), level) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, with_statement, unicode_literals
try:
# py2
except ImportError:
try:
# py2
except ImportError:
# py3
# from io import BytesIO as StringIO
... | logging_init(level=logging.DEBUG, handler=self.handler) |
Continue the code snippet: <|code_start|> logging.disable(logging.NOTSET)
self.stream = StringIO()
self.logger = logging.getLogger()
self.handler = logging.StreamHandler(self.stream)
for handler in self.logger.handlers:
# exclude nosetest capture handler
if... | if is_py2: |
Given the code snippet: <|code_start|> self.stream = StringIO()
self.logger = logging.getLogger()
self.handler = logging.StreamHandler(self.stream)
for handler in self.logger.handlers:
# exclude nosetest capture handler
if not isinstance(handler,
... | stream_output = unicode(stream_output) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
test_path = os.path.dirname(os.path.abspath(__file__))
class TestUtils(unittest.TestCase):
def setUp(self):
wiki_path = os.path.joi... | utils.emptytree(self.output) |
Given snippet: <|code_start|>
class TestUpdater(unittest.TestCase):
def setUp(self):
self.default_config = get_default_config()
self.wiki_path = os.path.join(test_path, 'mywiki_for_others')
os.chdir(self.wiki_path)
self.kwargs = {'themes_dir': 'themes'}
self.original_fabfi... | original_fn_md5 = utils.get_md5(self.original_fabfile) |
Predict the next line after this snippet: <|code_start|>base_path = os.path.dirname(test_path)
class TestUpdater(unittest.TestCase):
def setUp(self):
self.default_config = get_default_config()
self.wiki_path = os.path.join(test_path, 'mywiki_for_others')
os.chdir(self.wiki_path)
... | updater.update_builtin(**self.kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.