Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>
class Lyrics(list):
"""A list that holds the contents of the lrc file"""
def __init__(self, items=[]):
self.artist = ""
self.album = ""
self.title = ""
self.author = ""
self.length = ""
self.offset = ""
self.extend(... | if is_timecode(word[0:10]): |
Based on the snippet: <|code_start|> else:
srt = srt + self[i].text + '\n'
output.append(srt)
return '\n'.join(output).rstrip()
def to_ESRT(self):
"""Convert ELRC to ESRT"""
output = []
for i in range(len(self) - 1):
su... | end = timecode_to_srt(text[0:10]) |
Predict the next line after this snippet: <|code_start|> Checks if the subs is an enhanced lrc
"""
for sub in self:
word = '<' + sub.text.split('<')[-1]
if is_timecode(word[0:10]):
return True
return False
def to_SRT(self):
"""Returns a... | srt = srt + find_even_split(self[i].text) + '\n' |
Predict the next line for this snippet: <|code_start|>
@classmethod
def stream(cls, source_file, error_handling=ERROR_PASS):
"""
stream(source_file, [error_handling])
This method yield SubRipItem instances a soon as they have been parsed
without storing them. It is a kind of SAX... | except Error as error: |
Predict the next line after this snippet: <|code_start|> return self
@classmethod
def stream(cls, source_file, error_handling=ERROR_PASS):
"""
stream(source_file, [error_handling])
This method yield SubRipItem instances a soon as they have been parsed
without storing the... | yield SubRipItem.from_lines(source) |
Based on the snippet: <|code_start|> if len(text_strips) > 0:
return True
else:
return False
except AttributeError:
return False
def execute(self, context):
scene = context.scene
words = collect_words(scene)
found_... | hyphenator = Hyphenator() |
Here is a snippet: <|code_start|>
class SEQUENCER_OT_syllabify(bpy.types.Operator, ExportHelper):
bl_label = 'Syllabify'
bl_idname = 'sequencerextra.syllabify'
bl_description = "Create a list of words, separated by syllables.\nNeeded for splitting words with accurate syllable differentiation"
filename... | dictionary = get_dictionary( |
Predict the next line after this snippet: <|code_start|>
def collect_words(scene):
"""Collect, clean, and alphabetize the words in the subtitles"""
words = []
text_strips = get_text_strips(scene)
for strip in text_strips:
strip_words = strip.text.lower().replace('--', ' ').replace('\n', ' '... | words[i] = remove_punctuation(words[i]) |
Here is a snippet: <|code_start|>
class SEQUENCER_OT_refresh_font_data(bpy.types.Operator):
bl_label = "Refresh Font Data"
bl_idname = 'sequencerextra.refresh_font_data'
bl_description = "Refresh the font size for all text strips on the edit channel"
@classmethod
def poll(self, context):
... | text_strips = get_text_strips(scene) |
Predict the next line after this snippet: <|code_start|>
class SEQUENCER_OT_refresh_font_data(bpy.types.Operator):
bl_label = "Refresh Font Data"
bl_idname = 'sequencerextra.refresh_font_data'
bl_description = "Refresh the font size for all text strips on the edit channel"
@classmethod
def poll(s... | strip.font = get_font(scene.subtitle_font) |
Predict the next line for this snippet: <|code_start|>
class SEQUENCER_OT_save_syllables(bpy.types.Operator):
bl_label = 'Save'
bl_idname = 'sequencerextra.save_syllables'
bl_description = "Add the syllables to the default syllable dictionary"
@classmethod
def poll(self, context):
scene = c... | dictionary = get_dictionary( |
Here is a snippet: <|code_start|>
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, os.path.abspath(file_path))
class TestTextParser(unittest.TestCase):
def setUp(self):
self.static_path = os.path.join(file_path, 'tests', 'static')
lyrics_path ... | self.assertEqual(text_to_srt(self.lyrics), self.output)
|
Given snippet: <|code_start|>
def text_to_srt(text, fps, reflow_long_lines=False):
"""
Creates an SRT string out of plain text, with 1 second for each
segment
"""
text = text.strip()
lines = text.split('\n')
output = []
sec_time = 0
for i in range(len(lines)):
seg = str(i + ... | lines[i] = find_even_split(lines[i].rstrip()) |
Given the following code snippet before the placeholder: <|code_start|>
def text_to_srt(text, fps, reflow_long_lines=False):
"""
Creates an SRT string out of plain text, with 1 second for each
segment
"""
text = text.strip()
lines = text.split('\n')
output = []
sec_time = 0
for i in... | start = seconds_to_srt_timecode(i + 0.00000001) |
Given the following code snippet before the placeholder: <|code_start|>
class LyricLine():
"""An object that holds a lyric line and it's time"""
def __init__(self, timecode, text=""):
self.hours = 0
<|code_end|>
, predict the next line using imports from the current file:
from .tools.timecode import u... | self.minutes, self.seconds, self.milliseconds = unpack_timecode(timecode) |
Given the code snippet: <|code_start|>
def subtitles_to_sequencer(context, subs):
"""Add subtitles to the video sequencer"""
scene = context.scene
fps = scene.render.fps / scene.render.fps_base
<|code_end|>
, generate the next line using the imports in this file:
import bpy
from .get_open_channel import ... | open_channel = get_open_channel(scene) |
Here is a snippet: <|code_start|> scene.sequence_editor_create()
wm = context.window_manager
wm.progress_begin(0, 100.0)
added_strips = []
for i in range(len(subs)):
start_time = subs[i].start.to_millis() / 1000
strip_start = round(start_time * fps, 0)
end_time = subs[... | text_strip.font = get_font(scene.subtitle_font) |
Using the snippet: <|code_start|>
class SEQUENCER_OT_refresh_highlight(bpy.types.Operator):
bl_label = ""
bl_idname = 'sequencerextra.refresh_highlight'
bl_description = "Refresh the color of highlighted words"
@classmethod
def poll(self, context):
scene = context.scene
try:
<|code... | text_strips = get_text_strips(scene) |
Given the code snippet: <|code_start|> yield self.hours
yield self.minutes
yield self.seconds
yield self.milliseconds
def shift(self, *args, **kwargs):
"""
shift(hours, minutes, seconds, milliseconds)
All arguments are optional and have a default value of 0.
... | raise InvalidTimeString |
Continue the code snippet: <|code_start|>
class SEQUENCER_OT_duration_x_2(bpy.types.Operator):
bl_label = 'Dur x 2'
bl_idname = 'sequencerextra.duration_x_two'
bl_description = 'Make all text strips in subtitle edit channel twice as long'
@classmethod
def poll(self, context):
scene = contex... | text_strips = get_text_strips(scene) |
Using the snippet: <|code_start|> text_strips = get_text_strips(scene)
if len(text_strips) == 0:
return {"FINISHED"}
except AttributeError:
return {"FINISHED"}
current_frame = scene.frame_current
base_channel = text_strips[0].channel - 1
... | base = get_base_strip(strip, base_strips) |
Using the snippet: <|code_start|>
class SEQUENCER_OT_shift_frame_start(bpy.types.Operator):
bl_idname = "sequencerextra.shift_frame_start"
bl_label = "Shift Frame Start of Next Text Strip"
bl_description = "Shifts frame start of text strip to the current frame"
def execute(self, context):
scene... | text_strips = get_text_strips(scene) |
Next line prediction: <|code_start|>#!/usr/bin/python
# *****BatteryMonitor Getdata from battery cells getdata.py*****
# Copyright (C) 2020 Simon Richard Matthews
# Project loaction https://github.com/simat/BatteryMonitor
# This program is free software; you can redistribute it and/or modify
# it under the terms of the... | minsoc = config['battery']['targetsoc'] -config['battery']['minsocdif'] |
Using the snippet: <|code_start|>
summaryfile = SafeConfigParser()
def tail(file, n=1, bs=1024):
f = open(file)
f.seek(-1,2)
l = 1-f.read(1).count('\n') # If file doesn't end in \n, count it anyway.
B = f.tell()
while n >= l and B > 0:
block = min(bs, B)
B -= block
... | loadconfig() |
Based on the snippet: <|code_start|> return v
def getv():
global voltages
try:
summaryfile.read(config['files']['summaryfile'])
except IOError:
pass
voltages=literal_eval(summaryfile.get('current','maxvoltages'))
vprint = ''
for i in range(numcells+1):
vprint = vprint + str(i+1) + '=' + str(... | loadconfig() |
Given the following code snippet before the placeholder: <|code_start|>
def avv():
vstr=""
v=[0.0 for i in range(numcells+1)]
endlog=tail(config['files']['logfile'],11)
for j in range(1,numcells+1):
for i in range(10):
x=float(endlog[i][(j-1)*6+15:(j-1)*6+20])+config['calibrate']['delta'][j-1]
v... | loadconfig() |
Continue the code snippet: <|code_start|># *****BatteryMonitor main file batteries.py*****
# Copyright (C) 2014 Simon Richard Matthews
# Project loaction https://github.com/simat/BatteryMonitor
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... | for i in config['alarms']: |
Using the snippet: <|code_start|>
def getv():
global voltages
try:
summaryfile.read(config['files']['summaryfile'])
except IOError:
pass
voltages=literal_eval(summaryfile.get('current','maxvoltages'))
vprint = ''
for i in range(numcells+1):
vprint = vprint + str(i+1) + '=' + str(voltages[i]).lj... | loadconfig() |
Given the following code snippet before the placeholder: <|code_start|># *****BatteryMonitor MQTT client*****
# Copyright (C) 2021 Simon Richard Matthews
# Project loaction https://github.com/simat/BatteryMonitor
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Gene... | editbatconfig(section,item,payload[section][item]) |
Given snippet: <|code_start|>log = logger.logging.getLogger(__name__)
log.setLevel(logger.logging.DEBUG)
log.addHandler(logger.errfile)
def on_message(client,userata,message):
"""Executed when any subscribed MQTT message arives
At present assumes payload is item to change in battery.config
makes change and rewr... | client = mqtt_client.Client(config['mqtt']['clientname'],clean_session=False) |
Predict the next line after this snippet: <|code_start|>
def render_node(node, context=None, edit=True):
"""
Render node as html for templates, with edit tagging.
"""
output = node.render(**context or {}) or u''
if edit:
return u'<span data-i18n="{0}">{1}</span>'.format(node.uri.clone(schem... | @register.lazy_tag |
Based on the snippet: <|code_start|> """
output = node.render(**context or {}) or u''
if edit:
return u'<span data-i18n="{0}">{1}</span>'.format(node.uri.clone(scheme=None, ext=None, version=None), output)
else:
return output
@register.lazy_tag
def node(key, default=None, edit=True):
... | args, kwargs = parse_bits(parser, bits, params, None, True, (True,), None, 'blocknode') |
Next line prediction: <|code_start|>
class PanelTest(ClientTest):
def test_embed(self):
url = reverse('index')
response = self.client.get(url)
<|code_end|>
. Use current file imports:
(from unittest import skip
from djedi.utils.encoding import smart_unicode
from djedi.tests.base import ClientTest... | self.assertIn(u'Djedi Test', smart_unicode(response.content)) |
Continue the code snippet: <|code_start|>
app_name = 'rest'
def not_found(*args, **kwargs):
raise Http404
<|code_end|>
. Use current file imports:
from django.http import Http404
from ..compat import patterns, url
from .api import EmbedApi, NodesApi
and context (classes, functions, or code) from other files:... | urlpatterns = patterns( |
Next line prediction: <|code_start|>
app_name = 'rest'
def not_found(*args, **kwargs):
raise Http404
urlpatterns = patterns(
<|code_end|>
. Use current file imports:
(from django.http import Http404
from ..compat import patterns, url
from .api import EmbedApi, NodesApi)
and context including class names, fun... | url(r'^$', not_found, name='api-base'), |
Next line prediction: <|code_start|>
app_name = 'rest'
def not_found(*args, **kwargs):
raise Http404
urlpatterns = patterns(
url(r'^$', not_found, name='api-base'),
<|code_end|>
. Use current file imports:
(from django.http import Http404
from ..compat import patterns, url
from .api import EmbedApi, Nodes... | url(r'^embed/$', EmbedApi.as_view(), name='embed'), |
Given snippet: <|code_start|>
app_name = 'rest'
def not_found(*args, **kwargs):
raise Http404
urlpatterns = patterns(
url(r'^$', not_found, name='api-base'),
url(r'^embed/$', EmbedApi.as_view(), name='embed'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from dja... | url(r'^nodes/$', NodesApi.as_view(), name='nodes'), |
Using the snippet: <|code_start|>
self._cache = cache
def clear(self):
self._cache.clear()
def _get(self, key):
return self._cache.get(key)
def _get_many(self, keys):
return self._cache.get_many(keys)
def _set(self, key, value):
self._cache.set(key, value, tim... | return smart_str('|'.join([six.text_type(uri), content])) |
Here is a snippet: <|code_start|> def _get(self, key):
return self._cache.get(key)
def _get_many(self, keys):
return self._cache.get_many(keys)
def _set(self, key, value):
self._cache.set(key, value, timeout=None) # TODO: Fix eternal timeout like viewlet
def _set_many(self, da... | content = smart_unicode(content) |
Using the snippet: <|code_start|>
class DjangoCacheBackend(CacheBackend):
def __init__(self, **config):
"""
Get cache backend. Look for djedi specific cache first, then fallback on default
"""
super(DjangoCacheBackend, self).__init__(**config)
try:
cache_name ... | cache = get_cache(cache_name) |
Given snippet: <|code_start|>
admin.autodiscover()
if django.VERSION < (2, 0):
admin_urls = include(admin.site.urls)
else:
admin_urls = admin.site.urls
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import django
from django.contrib import admin
from django.shortcuts imp... | urlpatterns = patterns( |
Continue the code snippet: <|code_start|>
admin.autodiscover()
if django.VERSION < (2, 0):
admin_urls = include(admin.site.urls)
else:
admin_urls = admin.site.urls
urlpatterns = patterns(
<|code_end|>
. Use current file imports:
import django
from django.contrib import admin
from django.shortcuts import ren... | url(r'^$', lambda r: render_to_response('index.html'), name='index'), |
Given the code snippet: <|code_start|> return render
"""
def dec(func):
params, varargs, varkw, defaults = getargspec(func)
class SimpleNode(Node):
def __init__(self, takes_context, args, kwargs):
self.takes_context = takes_context
self.args =... | compile_func = partial(generic_tag_compiler, |
Predict the next line after this snippet: <|code_start|>
register = template.Library()
def lazy_tag(self, func=None, takes_context=None, name=None, node_class=None):
"""
A tag function decorator, injected on Django's template tag library, similar to simple_tag().
The decorated function gets called when t... | params, varargs, varkw, defaults = getargspec(func) |
Given the code snippet: <|code_start|>
app_name = 'djedi'
urlpatterns = patterns(
url(r'^$', DjediCMS.as_view(), name='cms'),
url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'),
<|code_end|>
, generate the next line using the imports in this file:
from ..compat import include, patterns... | url(r'^node/(?P<uri>.+)/load$', LoadApi.as_view(), name='api.load'), |
Here is a snippet: <|code_start|>
app_name = 'djedi'
urlpatterns = patterns(
url(r'^$', DjediCMS.as_view(), name='cms'),
url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'),
url(r'^node/(?P<uri>.+)/load$', LoadApi.as_view(), name='api.load'),
url(r'^node/(?P<uri>.+)/publish$', Pu... | url(r'^node/(?P<uri>.+)$', NodeApi.as_view(), name='api'), |
Next line prediction: <|code_start|>
app_name = 'djedi'
urlpatterns = patterns(
url(r'^$', DjediCMS.as_view(), name='cms'),
<|code_end|>
. Use current file imports:
(from ..compat import include, patterns, url
from .api import LoadApi, NodeApi, NodeEditor, PublishApi, RenderApi, RevisionsApi
from .cms import Djed... | url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'), |
Predict the next line after this snippet: <|code_start|>
app_name = 'djedi'
urlpatterns = patterns(
url(r'^$', DjediCMS.as_view(), name='cms'),
url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'),
url(r'^node/(?P<uri>.+)/load$', LoadApi.as_view(), name='api.load'),
<|code_end|>
usin... | url(r'^node/(?P<uri>.+)/publish$', PublishApi.as_view(), name='api.publish'), |
Predict the next line for this snippet: <|code_start|>
app_name = 'djedi'
urlpatterns = patterns(
url(r'^$', DjediCMS.as_view(), name='cms'),
url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'),
url(r'^node/(?P<uri>.+)/load$', LoadApi.as_view(), name='api.load'),
url(r'^node/(?P<... | url(r'^plugin/(?P<ext>\w+)$', RenderApi.as_view(), name='api.render'), |
Using the snippet: <|code_start|>
app_name = 'djedi'
urlpatterns = patterns(
url(r'^$', DjediCMS.as_view(), name='cms'),
url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'),
url(r'^node/(?P<uri>.+)/load$', LoadApi.as_view(), name='api.load'),
url(r'^node/(?P<uri>.+)/publish$', Pu... | url(r'^node/(?P<uri>.+)/revisions$', RevisionsApi.as_view(), name='api.revisions'), |
Predict the next line after this snippet: <|code_start|> {% endblocknode %}
"""
context = {'user': User(first_name=u'Jonas', last_name=u'Lundberg')}
html = self.render(source, context)
assert html == u'Hej Jonas Lundberg!'
with cio.env(i18n='en-us'):
html... | register.lazy_tag('') |
Predict the next line for this snippet: <|code_start|>
class TagTest(DjediTest, AssertionMixin):
def render(self, source, context=None):
source = u'{% load djedi_tags %}' + source.strip()
<|code_end|>
with the help of current file imports:
import cio
from django.contrib.auth.models import User
from djan... | context = cmpt_context(context or {}) |
Here is a snippet: <|code_start|>
class TagTest(DjediTest, AssertionMixin):
def render(self, source, context=None):
source = u'{% load djedi_tags %}' + source.strip()
context = cmpt_context(context or {})
<|code_end|>
. Write the next line using the current file imports:
import cio
from django.co... | return get_template_from_string(source).render(context).strip() |
Given the following code snippet before the placeholder: <|code_start|>def get_custom_render_widget(cls):
class CustomRenderWidget(cls):
def render(self, *args, **kwargs):
name = kwargs.pop("name", None)
if not name:
name = args[0]
args = args[1:]
... | class FormsBasePlugin(DjediPlugin): |
Predict the next line for this snippet: <|code_start|>
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
context.update(
{
"cms_url": prefix + reverse("admin... | except NoReverseMatch: |
Predict the next line after this snippet: <|code_start|>
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
context.update(
{
"cms_url": prefix + reverse("adm... | output = render(request, "djedi/cms/embed.html", context) |
Given the following code snippet before the placeholder: <|code_start|>
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
context.update(
{
"cms_url": prefix +... | output = render_to_string("djedi/cms/embed.html", context) |
Based on the snippet: <|code_start|>
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
context.update(
{
<|code_end|>
, predict the immediate next line with the help of imports:... | "cms_url": prefix + reverse("admin:djedi:cms"), |
Given snippet: <|code_start|> def test_render(self):
response = self.post('api.render', 'foo', {'data': u'# Djedi'})
assert response.status_code == 404
response = self.post('api.render', 'md', {'data': u'# Djedi'})
assert response.status_code == 200
self.assertRenderedMarkdow... | assert isinstance(response.context_data['forms']['HTML'], BaseEditorForm) |
Given the following code snippet before the placeholder: <|code_start|> del node['meta']
return node
class PermissionTest(DjediTest, UserMixin):
def setUp(self):
super(PermissionTest, self).setUp()
self.master = self.create_djedi_master()
self.apprentice = self.create_djedi_app... | class PrivateRestTest(ClientTest): |
Using the snippet: <|code_start|>
def json_node(response, simple=True):
node = json.loads(response.content)
if simple and 'meta' in node:
del node['meta']
return node
<|code_end|>
, determine the next line of code. You have imports:
import os
import simplejson as json
import cio
import cio.co... | class PermissionTest(DjediTest, UserMixin): |
Predict the next line for this snippet: <|code_start|>
def json_node(response, simple=True):
node = json.loads(response.content)
if simple and 'meta' in node:
del node['meta']
return node
<|code_end|>
with the help of current file imports:
import os
import simplejson as json
import cio
impor... | class PermissionTest(DjediTest, UserMixin): |
Predict the next line after this snippet: <|code_start|> self.assertEqual(response.status_code, 200)
node = json_node(response, simple=False)
meta = node.pop('meta')
content = u'# Djedi' if cio.PY26 else u'<h1>Djedi</h1>'
self.assertDictEqual(node, {'uri': 'i18n://sv-se@page/title... | self.assertEqual(smart_unicode(response.content), u'') |
Next line prediction: <|code_start|>
def json_node(response, simple=True):
node = json.loads(response.content)
if simple and 'meta' in node:
del node['meta']
return node
class PermissionTest(DjediTest, UserMixin):
def setUp(self):
super(PermissionTest, self).setUp()
self.m... | url = reverse('admin:djedi:api', args=['i18n://sv-se@page/title']) |
Continue the code snippet: <|code_start|>
app_name = 'djedi'
if django.VERSION < (2, 0):
urlpatterns = patterns(
<|code_end|>
. Use current file imports:
import django
from .compat import include, patterns, url
from django.urls import path
and context (classes, functions, or code) from other files:
# Path:... | url(r'^', include('djedi.admin.urls', namespace='djedi')), |
Based on the snippet: <|code_start|>
app_name = 'djedi'
if django.VERSION < (2, 0):
urlpatterns = patterns(
<|code_end|>
, predict the immediate next line with the help of imports:
import django
from .compat import include, patterns, url
from django.urls import path
and context (classes, functions, sometime... | url(r'^', include('djedi.admin.urls', namespace='djedi')), |
Here is a snippet: <|code_start|>
class DataForm(BaseEditorForm):
data__id = forms.CharField(
label="ID",
max_length=255,
required=False,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
data__alt = forms.CharField(
label="Alt text",
max_length=25... | class ImagePluginBase(FormsBasePlugin): |
Given the following code snippet before the placeholder: <|code_start|> def test_parse_spanish_date_datetime(self):
start_date = datetime.datetime(2016, 12, 3, 13, 50) # Monday
result = parse_spanish_date('03-Dic-16 13:50')
self.assertTrue(result, start_date)
class TestSpanishDate(TestCase... | with TemporaryFolder('my_temp_list', delete_on_exit=True) as folder: |
Next line prediction: <|code_start|> self.assertTrue(result, start_date)
class TestSpanishDate(TestCase):
def test_to_string(self):
start_date = datetime.date(2016, 12, 3)
str_date = spanish_date_util.to_string(start_date)
self.assertEqual('03-Dic-16', str_date)
def test_to_str... | digest = hash_file(filename) |
Predict the next line for this snippet: <|code_start|> self.assertEqual(2, len(same))
def test_dict_compare_removed(self):
dict1 = {'name': 'Luis', 'colors': ['red', 'blue', 'black']}
dict2 = {'name': 'Luis', 'colors': ['red', 'blue', 'black'], 'type': 'human'}
added, removed, modifi... | stopwatch = Timer() |
Here is a snippet: <|code_start|>
class TestTimer(TestCase):
def test_get_elapsed_time_str(self):
clock = MockPerfCounter()
with mock.patch('time.perf_counter', clock.perf_counter):
# clock.increment(3600.0)
stopwatch = Timer()
stopwatch.start()
clock.... | new_filename = add_date_to_filename(filename) |
Here is a snippet: <|code_start|> mock_now.return_value = self.mock_datetime
filename = r'c:\kilo\poli\namos.txt'
new_filename = add_date_to_filename(filename, date_position='prefix')
self.assertEquals(r'c:\kilo\poli\20160707_1640_namos.txt', new_filename)
filename = r'/my/linux/... | for dt in daterange(start_date, end_date): |
Continue the code snippet: <|code_start|> end_date = datetime.date(2015, 9, 30)
work_days = 0
for dt in daterange(start_date, end_date):
work_days += 1
# logger.debug('Date: %s' % dt.strftime('%m-%d %a'))
# self.assertFalse(dt.weekday() not in set([5, 6]))
... | result = parse_spanish_date('03-Dic-16') |
Predict the next line after this snippet: <|code_start|> for dt in daterange(start_date, end_date):
work_days += 1
self.assertEqual(5, work_days)
def test_daterange_week_2(self):
start_date = datetime.date(2016, 10, 3) # Monday
end_date = datetime.date(2016, 10, 7) # Fr... | str_date = spanish_date_util.to_string(start_date) |
Continue the code snippet: <|code_start|> filename = r'c:\kilo\poli\namos.txt'
new_filename = add_date_to_filename(filename, date_position='prefix')
self.assertEquals(r'c:\kilo\poli\20160707_164039_namos.txt', new_filename)
filename = r'/my/linux/path/namos.nemo.txt'
new_filename... | create_output_filename_with_date('kilo.txt') |
Next line prediction: <|code_start|>
logger = logging.getLogger(__name__)
__author__ = 'lberrocal'
class MockPerfCounter(object):
def __init__(self):
self.t = 0
def increment(self, n):
self.t += n
def perf_counter(self):
return self.t
class Testdict_compare(TestCase):
def... | added, removed, modified, same = dict_compare(dict1, dict2) |
Predict the next line after this snippet: <|code_start|>class TemporyFolderTest(TestCase):
def test_temporary_folder_write_list(self):
with TemporaryFolder('my_temp_list', delete_on_exit=True) as folder:
self.assertTrue(os.path.exists(folder.new_path))
filename = folder.write('m.txt'... | snake_case = convert_to_snake_case(camel_case) |
Using the snippet: <|code_start|> def test_temporary_folder_write_other(self):
with TemporaryFolder('my_temp_date') as folder:
self.assertTrue(os.path.exists(folder.new_path))
filename = folder.write('m.txt', datetime.date(2016, 12, 3))
digest = hash_file(filename)
... | datetime_object_with_timezone = datetime_to_local_time(datetime_object) |
Based on the snippet: <|code_start|>
faker = FakerFactory.create()
class OperatingSystemFactory(DjangoModelFactory):
class Meta:
<|code_end|>
, predict the immediate next line with the help of imports:
import string
from random import randint
from pytz import timezone
from django.conf import settings
from f... | model = OperatingSystem |
Given the code snippet: <|code_start|>
faker = FakerFactory.create()
class OperatingSystemFactory(DjangoModelFactory):
class Meta:
model = OperatingSystem
name = LazyAttribute(lambda x: faker.text(max_nb_chars=20))
version = LazyAttribute(lambda x: faker.text(max_nb_chars=5))
licenses_av... | model = Server |
Here is a snippet: <|code_start|> # )
# parser.add_argument("-a", "--assign",
# action='store_true',
# dest="assign",
# help="Create unit assignments",
# )
#
... | app_manager = DjangoAppManager() |
Continue the code snippet: <|code_start|> # dest="assign",
# help="Create unit assignments",
# )
#
# parser.add_argument("--office",
# dest="office",
# help="Organiz... | app_model_tests = AppModelsTestCaseGenerator(app) |
Predict the next line after this snippet: <|code_start|> def get_results(self, content=None):
if content is None:
content = self.content
content.seek(0)
lines = content.readlines()
results = list()
for line in lines:
results.append(line.strip('\n'))
... | adapter = ExcelAdapter() |
Given snippet: <|code_start|>
def get_fixture_fullpath(self, fixture_filename):
"""
Get full patch for the fixture file
:param fixture_filename: <str> name of the fixture file
:return: <str> full path to fixture file
"""
self._sanity_check()
if self.app_name ... | raise DjangoTestToolsException('app_name not defined') |
Predict the next line for this snippet: <|code_start|>
class UrlGenerator(object):
def __init__(self, model_name):
self.model_name = model_name
self.template = 'django_test_tools/urls.py.j2'
def print_urls(self, filename):
self._print(filename, 'urls')
def print_paths(self, filen... | self.env.filters['to_snake_case'] = to_snake_case |
Using the snippet: <|code_start|>
class Command(BaseCommand):
"""
$ python manage.py generate_serializers_test my_application.app.api.serializers.MyObjectSerializer -f output/m.py
"""
def add_arguments(self, parser):
parser.add_argument('serializer_class')
parser.add_argument("... | generator = SerializerTestGenerator() |
Given the code snippet: <|code_start|>
class FactoryBoyGenerator(object):
"""
Currently supporting:
- BooleanField
- CharField
- CountryField: from https://github.com/SmileyChris/django-countries
- DateField:
- DateTimeField
- DecimalField
- ForeignKey
... | self.app_manager = DjangoAppManager() |
Using the snippet: <|code_start|> self.assertIsNotNone(operatingsystem.cost)
# def test_(self):
# operatingsystem = OperatingSystemFactory.create()
# servers = ServerFactory.create_batch(5, operating_system=operatingsystem)
# from django.conf import settings
# from django.db ... | self.assertEqual(1, Server.objects.count()) |
Based on the snippet: <|code_start|> self.assertIsNotNone(operatingsystem.licenses_available)
self.assertIsNotNone(operatingsystem.cost)
# def test_(self):
# operatingsystem = OperatingSystemFactory.create()
# servers = ServerFactory.create_batch(5, operating_system=operatingsystem)
... | server = ServerFactory.create() |
Predict the next line for this snippet: <|code_start|>
class TestCaseOperatingSystem(TestCase):
def test_create(self):
"""
Test the creation of a OperatingSystem model using a factory
"""
operatingsystem = OperatingSystemFactory.create()
<|code_end|>
with the help of current file i... | self.assertEqual(1, OperatingSystem.objects.count()) |
Continue the code snippet: <|code_start|>
class TestCaseOperatingSystem(TestCase):
def test_create(self):
"""
Test the creation of a OperatingSystem model using a factory
"""
<|code_end|>
. Use current file imports:
from example.servers.models import Server
from ..factories import ServerFa... | operatingsystem = OperatingSystemFactory.create() |
Based on the snippet: <|code_start|> else:
file.writelines(str(content))
return os.path.join(self.new_path, filename)
def compare_file_content(*args, **kwargs):
errors = list()
file1 = args[0]
file2 = args[1]
excluded_lines = kwargs.get('excluded_lines', [])
enco... | raise DjangoTestToolsException(msg) |
Given the code snippet: <|code_start|> """
Converts a CamelCase name to snake case.
..code-block:: python
camel_case = 'OperatingSystemLongName'
snake_case = convert_to_snake_case(camel_case)
self.assertEqual(snake_case, 'operating_system_long_name')
:param camel_case: string. C... | return add_date(os.path.join(settings.TEST_OUTPUT_PATH, filename)) |
Next line prediction: <|code_start|> )
# parser.add_argument("-a", "--assign",
# action='store_true',
# dest="assign",
# help="Create unit assignments",
# )
#
... | app_manager = DjangoAppManager() |
Given the code snippet: <|code_start|> # )
# parser.add_argument("-a", "--assign",
# action='store_true',
# dest="assign",
# help="Create unit assignments",
# )
#
... | output_filename = add_date(options.get('input_file')) |
Continue the code snippet: <|code_start|>
class TestCommonRegExp(SimpleTestCase):
def test_match_regexp(self):
str_data = '10:45'
<|code_end|>
. Use current file imports:
from django.test import SimpleTestCase
from django_test_tools.re.regexp import CommonRegExp
and context (classes, functions, or code... | common_regexp = CommonRegExp() |
Given the code snippet: <|code_start|> writer = AssertionWriter(**kwargs)
return writer.write_assert_list(dictionary_list, variable_name, filename=kwargs.get('filename'))
@deprecated('Use assert_utils.write_assertions instead')
def write_assert_list(filename, dictionary_list, variable_name):
"""
Functi... | self.common_regexp = CommonRegExp(strict=True) |
Given the code snippet: <|code_start|>
class AssertionWriter(object):
"""
This class generates assertions using Django practice of putting actual value first and then expected value.
"""
def __init__(self, **kwargs):
self.excluded_variable_names = ['created', 'modified']
if kwargs.get(... | filename = create_output_filename_with_date('{}.py'.format(variable_name)) |
Continue the code snippet: <|code_start|> \"\"\"
{1} = {0}Factory.create()
"""
PRINT_TEST_ATTRIBUTE_UNIQUE = """
def test_{2}_is_unique(self):
\"\"\"
Tests attribute {2} of model {0} to see if the unique constraint works.
This test should break if the unique attribute is chan... | convert_to_snake_case(self.model.__name__)]}) |
Based on the snippet: <|code_start|> # help="List data",
# )
parser.add_argument("--format",
dest="format",
help="Git format",
default=None,
)
... | filename = add_date(filepath) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.