Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>
class TestProfileCopier(BaseTestCase):
def setUp(self):
self.profile = Profile('test/vimrc')
self.settings = Settings(os.path.normpath('/home/foo'))
self.diskIo = Stubs.DiskIoStub()
# We use the real ProfileCache (with stubbed dependencies) becau... | homePath = os.path.normpath('/home/foo') |
Given the code snippet: <|code_start|>
class TestProfileCopier(BaseTestCase):
def setUp(self):
self.profile = Profile('test/vimrc')
self.settings = Settings(os.path.normpath('/home/foo'))
self.diskIo = Stubs.DiskIoStub()
# We use the real ProfileCache (with stubbed dependencies) bec... | def test_copyToHome_copiesFromProfileToHome(self): |
Predict the next line for this snippet: <|code_start|>
class VimSwitch:
def __init__(self, app=Application()):
self.app = app
self.raiseExceptions = False
<|code_end|>
with the help of current file imports:
from .ActionResolver import getActionResolver
from .Application import Application
from .... | def main(self, argv): |
Here is a snippet: <|code_start|>
class VimSwitch:
def __init__(self, app=Application()):
self.app = app
<|code_end|>
. Write the next line using the current file imports:
from .ActionResolver import getActionResolver
from .Application import Application
from .ApplicationDirs import getApplicationDirs
fro... | self.raiseExceptions = False |
Continue the code snippet: <|code_start|>
class VimSwitch:
def __init__(self, app=Application()):
self.app = app
<|code_end|>
. Use current file imports:
from .ActionResolver import getActionResolver
from .Application import Application
from .ApplicationDirs import getApplicationDirs
from .CommandLinePars... | self.raiseExceptions = False |
Predict the next line for this snippet: <|code_start|>
class TestProfileUrlResolver(BaseTestCase):
def test_getProfileUrl_convertsUserSlashRepo(self):
profile = Profile('testuser/testrepo')
url = getProfileUrl(profile)
expectedUrl = 'https://github.com/testuser/testrepo/archive/master.zi... | self.assertEqual(url, expectedUrl) |
Here is a snippet: <|code_start|>
class TestProfileUrlResolver(BaseTestCase):
def test_getProfileUrl_convertsUserSlashRepo(self):
profile = Profile('testuser/testrepo')
url = getProfileUrl(profile)
expectedUrl = 'https://github.com/testuser/testrepo/archive/master.zip'
<|code_end|>
. Wri... | self.assertEqual(url, expectedUrl) |
Given the following code snippet before the placeholder: <|code_start|>
class TestProfileUrlResolver(BaseTestCase):
def test_getProfileUrl_convertsUserSlashRepo(self):
profile = Profile('testuser/testrepo')
url = getProfileUrl(profile)
<|code_end|>
, predict the next line using imports from the ... | expectedUrl = 'https://github.com/testuser/testrepo/archive/master.zip' |
Here is a snippet: <|code_start|>
class FileDownloader:
def __init__(self, settings, diskIo):
self.settings = settings
self.diskIo = diskIo
<|code_end|>
. Write the next line using the current file imports:
import os
import re
import datetime
from .six.moves.urllib_parse import urlparse
from .six... | def download(self, url, path): |
Given snippet: <|code_start|>
# ProfileDataIo.delete#dirs
def test_delete_whenDirExists_deletesDir(self):
profilePath = os.path.normpath('/home/foo')
self.diskIo.dirExists.return_value = True
self.profileDataIo.delete(profilePath)
self.diskIo.deleteDir.assert_any_call(os.path.... | self.diskIo.dirExists.return_value = True |
Given the following code snippet before the placeholder: <|code_start|>
self.diskIo.deleteFile.assert_any_call(os.path.normpath('/home/foo/file1'))
self.diskIo.deleteFile.assert_any_call(os.path.normpath('/home/foo/file2'))
self.diskIo.deleteDir.assert_any_call(os.path.normpath('/home/foo/dir1')... | def test_copy_usesGetProfileFiles_fromSettings(self): |
Using the snippet: <|code_start|>
class TestProfileDataIo(BaseTestCase):
def setUp(self):
self.diskIo = Stubs.DiskIoStub()
self.settings = Settings(os.path.normpath('/home/foo'))
self.profileDataIo = ProfileDataIo(self.settings, self.diskIo)
# ProfileDataIo.delete#files
def test_d... | self.diskIo.deleteFile.assert_any_call(os.path.normpath('/home/foo/.vimrc')) |
Predict the next line for this snippet: <|code_start|>
def test_copy_copiesMultipleDirs(self):
srcPath = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc')
destPath = os.path.normpath('/home/foo')
self.diskIo.dirExists.return_value = True
self.settings.profileDirs = ['dir1'... | destDir1 = os.path.normpath('/home/foo/dir1') |
Using the snippet: <|code_start|>
class TestUpdateProfileAction(BaseTestCase):
def setUp(self):
app = Application()
self.settings = getSettings(app)
self.switchProfileAction = MagicMock(SwitchProfileAction)
self.updateProfileAction = UpdateProfileAction(self.settings, self.switchPro... | self.updateProfileAction.profile = None |
Given snippet: <|code_start|>
class TestUpdateProfileAction(BaseTestCase):
def setUp(self):
app = Application()
self.settings = getSettings(app)
self.switchProfileAction = MagicMock(SwitchProfileAction)
self.updateProfileAction = UpdateProfileAction(self.settings, self.switchProfile... | self.assertTrue(self.switchProfileAction.execute.called) |
Using the snippet: <|code_start|>
class TestUpdateProfileAction(BaseTestCase):
def setUp(self):
app = Application()
self.settings = getSettings(app)
self.switchProfileAction = MagicMock(SwitchProfileAction)
self.updateProfileAction = UpdateProfileAction(self.settings, self.switchPro... | self.assertEqual(self.switchProfileAction.update, True) |
Using the snippet: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
<|code_end|>
, determine the next line of code. You have imports:
from .CommandLineParser import getCommandLineParser
from .InvalidArgsAction import createInvalidArgsAction
from .ShowCurrentP... | self.commandLineParser = commandLineParser |
Predict the next line after this snippet: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
self.commandLineParser = commandLineParser
self.exitCode = 0
def doActions(self):
actionString = self.commandLineParser.action
if a... | else: |
Using the snippet: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
self.commandLineParser = commandLineParser
<|code_end|>
, determine the next line of code. You have imports:
from .CommandLineParser import getCommandLineParser
from .InvalidArgsActio... | self.exitCode = 0 |
Next line prediction: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
self.commandLineParser = commandLineParser
self.exitCode = 0
def doActions(self):
actionString = self.commandLineParser.action
if actionString == 'swit... | action.profile = self.commandLineParser.profile |
Based on the snippet: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
self.commandLineParser = commandLineParser
self.exitCode = 0
def doActions(self):
actionString = self.commandLineParser.action
if actionString == 'swit... | else: |
Predict the next line for this snippet: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
self.commandLineParser = commandLineParser
self.exitCode = 0
def doActions(self):
actionString = self.commandLineParser.action
if act... | else: |
Next line prediction: <|code_start|> model = Jury
fields = '__all__'
def get_object(self):
return Jury.objects.get(event__slug=self.kwargs.get('slug'))
class InviteEvent(BaseEventView, UpdateView):
template_name = 'event/jury_invite.html'
form_class = InviteForm
def form_valid(self, f... | def remove_user_from_event_jury(request, slug, user_pk): |
Here is a snippet: <|code_start|>
class JuryView(UpdateView):
template_name = 'jury/jury_detail.html'
lookup_field = 'slug'
model = Jury
fields = '__all__'
def get_object(self):
return Jury.objects.get(event__slug=self.kwargs.get('slug'))
class InviteEvent(BaseEventView, UpdateView):
... | form.add_to_jury() |
Based on the snippet: <|code_start|>@register.filter
def already_voted(user, proposal):
return proposal.user_already_voted(user)
@register.filter
def allowed_to_vote(user, proposal):
return proposal.user_can_vote(user)
@register.filter
def get_rate_display(user, proposal):
if user.is_authenticated():
... | if social: |
Here is a snippet: <|code_start|># coding: utf-8
class AboutViewTest(TestCase):
def setUp(self):
self.resp = self.client.get('/about/')
def test_get(self):
'GET /about/ must return status code 200'
self.assertEqual(200, self.resp.status_code)
def test_template(self):
'A... | self.assertTemplateUsed(self.resp, 'about.html') |
Next line prediction: <|code_start|> self.assertQuerysetEqual(event.proposals.all(),
["<Proposal: Python For Zombies>"])
python_for_zombies = event.proposals.get()
self.assertEquals('Python For Zombies', python_for_zombies.title)
self.assertEquals('Brain.... | self.client.logout() |
Next line prediction: <|code_start|>
python_for_zombies = event.proposals.get()
self.assertEquals('Python For Zombies', python_for_zombies.title)
self.assertEquals('Brain...', python_for_zombies.description)
def test_notify_event_jury_and_proposal_author_on_new_proposal(self):
if no... | 'create_event_proposal', kwargs={'slug': event.slug}) |
Continue the code snippet: <|code_start|> self.proposal = Proposal.objects.first()
self.assertEquals(200, response.status_code)
self.assertEquals(False, self.proposal.is_approved)
def test_disapprove_proposal_with_the_jury_user(self):
self.event.jury.users.add(User.objects.get(userna... | self.proposal.save() |
Given snippet: <|code_start|> follow=True
)
self.assertEquals(200, response.status_code)
self.assertQuerysetEqual(response.context['event_proposals'], [])
def test_list_proposal_with_public_voting(self):
self.client.logout()
self.client.login(username='another', p... | self.assertEquals(200, response.status_code) |
Predict the next line for this snippet: <|code_start|> response = self.client.get(
reverse('view_event', kwargs={'slug': self.event.slug}),
follow=True
)
self.assertEquals(200, response.status_code)
self.assertQuerysetEqual(response.context['event_proposals'],
... | reverse('view_event', kwargs={'slug': self.event.slug}), |
Predict the next line after this snippet: <|code_start|> self.event.jury.users.add(User.objects.get(username='another'))
self.client.logout()
self.client.login(username='another', password='another')
rate_proposal_data = {
'event_slug': self.proposal.event.slug,
'... | reverse('rate_proposal', kwargs=rate_proposal_data), |
Next line prediction: <|code_start|> new_proposal_data = self.proposal_data.copy()
new_proposal_data['description'] = 'A really really good proposal.'
new_proposal_data['slides_url'] = 'john_doe/talk'
proposal_update_url = reverse(
'update_proposal',
kwarg... | reverse('delete_proposal', |
Continue the code snippet: <|code_start|> closing_date=now() - timedelta(days=7)
)
Event.objects.create(**past_event_data)
response = self.client.get(reverse('list_events'), follow=True)
self.assertEquals(200, response.status_code)
self.assertQuerysetEqual(response.co... | event_data.update(is_published=True) |
Continue the code snippet: <|code_start|> }
self.client.post(
reverse('rate_proposal', kwargs=rate_proposal_data),
follow=True
)
self.assertEquals(3, self.proposal.get_rate)
rate_proposal_data.update({'rate': 'happy'})
response = self.client.post(
... | response = self.client.get( |
Given snippet: <|code_start|> _('Twitter username'), max_length=50, null=True, blank=True)
site = models.URLField(
_('Site url'), max_length=200, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
# relations
user = models.OneToOneField(to=settings.AUTH_USER_MODEL)
... | def get_site_url(self): |
Here is a snippet: <|code_start|>
class PermissionsTestCase(TestCase):
def setUp(self):
self.user = mommy.make(settings.AUTH_USER_MODEL)
self.event = mommy.make(Event)
def test_super_user_is_always_allowed(self):
<|code_end|>
. Write the next line using the current file imports:
from djang... | self.user.is_superuser = True |
Predict the next line for this snippet: <|code_start|> raise ValidationError(message)
return username
def save(self, *args, **kwargs):
self.save_user_data()
return super(ProfileForm, self).save(*args, **kwargs)
def save_user_data(self):
data = self.cleaned_data
... | fields = ('image',) |
Next line prediction: <|code_start|>
def setUp(self):
User = get_user_model()
self.user = User.objects.get(username='user')
self.client = Client()
self.client.login(username='user', password='user')
def test_create_organization(self):
url = reverse('create_organization')... | created_by=self.user, |
Given snippet: <|code_start|>#
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
#
class BlockPacker():
def __init__(self, w = 0, h = 0):
self.nodes = []
self.autogrow = False
if w > 0 and h > 0:
self.root = BlockNode(self, 0, 0, w, h)
<|code_end|>
, contin... | else: |
Continue the code snippet: <|code_start|> result = type
elif type in self.__prefixes:
if getattr(node, "postfix", False):
result = self.compress(node[0]) + self.__prefixes[node.type]
else:
result = self.__prefixes[node.type] + self.compress(node... | try: |
Continue the code snippet: <|code_start|> "lt" : '<',
"ursh" : '>>>',
"rsh" : '>>',
"ge" : '>=',
"gt" : '>',
"bitwise_or" : '|',
"bitwise_xor" : '^',
"bitwise_and" : '&'
}
__prefixes = {
"incre... | return self.__statements(node) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
# Extend PYTHONPATH with local 'lib' folder
if __name__ == "__main__":
jasyroot = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir, os.pardir, os.pardir))
sys.path.insert(0, jasyroot)
print("Runn... | /** |
Using the snippet: <|code_start|>extensions = {
".png" : "image",
".jpeg" : "image",
".jpg" : "image",
".gif" : "image",
".mp3" : "audio",
".ogg" : "audio",
".m4a" : "audio",
".aac" : "audio",
".wav" : "audio",
".avi" : "video",
".mpeg" : "video",
".mpg" : "vide... | ".html" : "text", |
Predict the next line for this snippet: <|code_start|> ".css" : "text",
".htc" : "text",
".xml" : "text",
".tmpl" : "text",
".fla" : "binary",
".swf" : "binary",
".psd" : "binary",
".pdf" : "binary"
}
class AssetItem(jasy.item.Abstract.AbstractItem):
kind = "asset"
__... | return self.isText() and (os.path.basename(self.id) == "jasysprite.yaml" or os.path.basename(self.id) == "jasysprite.json") |
Using the snippet: <|code_start|>
def get_default_parameters():
aggregated_data = pd.read_csv(join(utils_data.FOLDER_SIMULATOR_INPUT, 'aggregated_data.csv'), index_col=0)
params = {
# seed for random number generator of current simulation
'seed': 666,
# start and end date of simulati... | 'num_merchants': int(aggregated_data.loc['num merchants', 'all']), |
Using the snippet: <|code_start|>
FOLDER_RESULTS = join(dirname(__file__), 'results')
FILE_RESULTS_IDX = join(FOLDER_RESULTS, 'curr_idx.txt')
def get_result_idx():
for line in open(FILE_RESULTS_IDX):
if line.strip(): # line contains eol character(s)
return int(line)
def update_result_idx(o... | f = open(FILE_RESULTS_IDX, 'w+') |
Here is a snippet: <|code_start|> def authorise_transaction(self, customer):
if customer.fraudster:
customer.give_authentication()
class NeverSecondAuthenticator(AbstractAuthenticator):
def authorise_transaction(self, customer):
pass
class AlwaysSecondAuthenticator(AbstractAuthent... | def authorise_transaction(self, customer): |
Given snippet: <|code_start|>
def test_word_count():
with open("WordCount/birds.txt", "r") as f:
data = f.read()
num_words = word_count.count_words(data)
assert(num_words == 34)
def test_line_count():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from... | with open("WordCount/birds.txt", "r") as f: |
Given the code snippet: <|code_start|>
def test_word_count():
with open("WordCount/birds.txt", "r") as f:
data = f.read()
num_words = word_count.count_words(data)
assert(num_words == 34)
<|code_end|>
, generate the next line using the imports in this file:
from WordCount.word_count import... | def test_line_count(): |
Next line prediction: <|code_start|>
def test_create_wave():
try:
for f in glob.glob("test.wav"):
os.remove(f)
except:
pass
create_wave.create_wav()
assert(os.path.exists("test.wav"))
def test_get_freq():
assert(1000 == get_freq.get_freq(True))
<|code_end|>
. Use curren... | def test_noisy(): |
Here is a snippet: <|code_start|>
def test_edge():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
edge_detect.edge_detect(image, True)
assert(os.path.exists("test_edge.png"))
def test_count_cards():
try:
for f... | except: |
Given snippet: <|code_start|>
def test_blur():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
blur.blur_display(image, True)
assert(os.path.exists("test_blurred.png"))
def test_edge():
try:
for f in glob.glob("... | image = "Image_Video/cards.jpg" |
Predict the next line after this snippet: <|code_start|> os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
blur.blur_display(image, True)
assert(os.path.exists("test_blurred.png"))
def test_edge():
try:
for f in glob.glob("test*.png"):
os.remove(f)
... | os.remove(f) |
Here is a snippet: <|code_start|>def test_count_cards():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/cards.jpg"
cards = count_cards.count_cards(image, True)
assert(cards == 5)
assert(os.path.exists("test_count_cards.png"))
... | os.remove(f) |
Using the snippet: <|code_start|> image = "Image_Video/ship.jpg"
display.display(image, True)
assert(os.path.exists("test_display2.png"))
def test_blur():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
blur.blur_dis... | os.remove(f) |
Continue the code snippet: <|code_start|>
class Command(BaseCommand):
help = 'Delete all DedupEvents for a particular task'
def add_arguments(self, parser):
parser.add_argument('task_pair_id', nargs='+', type=int)
parser.add_argument('--no-op', action='store_true', help="dry run")
def hand... | count = qs.count() |
Given the code snippet: <|code_start|>
@shared_task
@format_options_from_event
def send_file_to_dropbox(data, task_pair_id, access_token,
filename, path, url):
client = DropboxClient(access_token)
file_path = posixpath.join(path, filename)
file_path = file_path.replace('\\', '|')... | client.put_file(file_path, resp.content, overwrite=True) |
Using the snippet: <|code_start|>
class Command(BaseCommand):
help = 'Popoulate DedupEvents for a particular task'
def add_arguments(self, parser):
parser.add_argument('task_pair_id', nargs='+', type=int)
def handle(self, *args, **options):
<|code_end|>
, determine the next line of code. You have ... | for task_pair_id in options['task_pair_id']: |
Based on the snippet: <|code_start|>
class Command(BaseCommand):
help = 'Runs the specified task'
def add_arguments(self, parser):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.management.base import BaseCommand, CommandError
from helper.models import TaskPair
and ... | parser.add_argument('task_id', nargs='+', type=int) |
Predict the next line for this snippet: <|code_start|> url(r'^agent/?$',
AgentConfigListView.as_view(),
name='agent_config_list'),
url(r'^agent/add/?$',
AgentConfigCreateView.as_view(),
name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetail... | url(r'^task/(?P<pk>\d+)/advanced/?$', |
Given snippet: <|code_start|> url(r'^task/add/?$',
TaskPairWizard.as_view(),
name='task_pair_create'),
url(r'^task/add/advanced/?$',
TaskPairCreateView.as_view(),
name='task_pair_create_advanced'),
url(r'^task/(?P<pk>\d+)/?$',
TaskPairDetailView.as_view(),
name... | ] |
Given the following code snippet before the placeholder: <|code_start|> name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetailView.as_view(),
name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
... | name='task_pair_delete'), |
Based on the snippet: <|code_start|>
urlpatterns = [
# redirect to tasks for now
url(r'^$', RedirectView.as_view(pattern_name='task_pair_list',
permanent=False), name='home'),
# agentconfig generics
url(r'^agent/?$',
AgentConfigListView.as_view(),
n... | 'helper.views.dispatch_agent_config_url', |
Given snippet: <|code_start|> name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetailView.as_view(),
name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
name='agent_config_delete'),
# age... | name='task_pair_delete'), |
Here is a snippet: <|code_start|> url(r'^agent/add/?$',
AgentConfigCreateView.as_view(),
name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetailView.as_view(),
name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentCon... | url(r'^task/(?P<pk>\d+)/delete/?$', |
Predict the next line for this snippet: <|code_start|> name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
name='agent_config_delete'),
# agentconfig custom view
url(r'^agent/(?P<agent_config_id>[a-zA-Z.]+)/(?P<view_name>\w+)',
... | 'helper.views.dispatch_task_pair_url', |
Given the code snippet: <|code_start|> permanent=False), name='home'),
# agentconfig generics
url(r'^agent/?$',
AgentConfigListView.as_view(),
name='agent_config_list'),
url(r'^agent/add/?$',
AgentConfigCreateView.as_view(),
name='agent_con... | url(r'^task/(?P<pk>\d+)/?$', |
Here is a snippet: <|code_start|>
urlpatterns = [
# redirect to tasks for now
url(r'^$', RedirectView.as_view(pattern_name='task_pair_list',
permanent=False), name='home'),
# agentconfig generics
url(r'^agent/?$',
AgentConfigListView.as_view(),
name... | url(r'^task/?$', |
Here is a snippet: <|code_start|>
def _check_photos(access_token, paginate=False, extra_params=None,
taskname=None, task_pair_id=None):
params = {'access_token': access_token}
if extra_params is not None:
params.update(extra_params)
while True:
resp = requests.get('https... | @shared_task |
Predict the next line for this snippet: <|code_start|>
def get_from_event_store(task_pair_id, task_type):
return [{k: json.loads(v) for k, v in event.items()}
for event in Event.objects.filter(
<|code_end|>
with the help of current file imports:
import json
from ..models import Event
and context fr... | task_pair__id=task_pair_id, task_type=task_type)\ |
Given the code snippet: <|code_start|>@shared_task
def rail_incident(api_key, line, task_pair_id, commute_only='always'):
now = datetime.now()
if not any([l <= now.hour < u and dl <= now.weekday() < du
for l, u, dl, du in time_ranges[commute_only]]):
return []
resp = requests.get('h... | ('BL', 'Blue'), |
Continue the code snippet: <|code_start|>
time_ranges = {
'both': [(7, 10, 0, 5), (16, 19, 0, 5)],
'morning': [(7, 10, 0, 5)],
'evening': [(16, 19, 0, 5)],
'always': [(0, 24, 0, 8)],
}
@dedup('id')
@schedule(1)
@shared_task
def rail_incident(api_key, line, task_pair_id, commute_only='always'):
now... | 'description': incident['Description'], |
Here is a snippet: <|code_start|> )
else:
effect = self.effect.s(**effect_options)
return chain(cause, dmap.s(effect))()
def populate_dedup_events(self):
if getattr(self.cause, 'dedup_key', None) is not None:
cause_options = self.cause_agent.options or {}... | class DedupEvent(models.Model): |
Given the following code snippet before the placeholder: <|code_start|>
@property
def effect_view(self):
return getattr(import_module(self.effect_agent.name + '.views'),
self.effect_task)
@property
def cause_name(self):
return getattr(self.cause, 'label',
... | if not k.startswith('_')}) |
Continue the code snippet: <|code_start|> return getattr(import_module(self.effect_agent.name + '.views'),
self.effect_task)
@property
def cause_name(self):
return getattr(self.cause, 'label',
self.cause_task.replace('_', ' ').capitalize())
@pro... | cause = self.cause.s(**cause_options) |
Based on the snippet: <|code_start|>
@shared_task
@format_options_from_event
def send_push(data, token, user, message, title, device, url, url_title,
priority, html, task_pair_id=None):
resp = requests.post('https://api.pushover.net/1/messages.json', data={
'title': title,
'message':... | resp.raise_for_status() |
Given snippet: <|code_start|>
def struct2isoformat(struct):
if struct is None:
return ''
return datetime.datetime.fromtimestamp(time.mktime(struct)).isoformat()
@schedule(1)
@dedup('id')
@shared_task
def get_rss_feed(url, task_pair_id, secret):
resp = feedparser.parse(url)
assert 'bozo_excep... | 'title': entry.title, |
Here is a snippet: <|code_start|>def get_rss_feed(url, task_pair_id, secret):
resp = feedparser.parse(url)
assert 'bozo_exception' not in resp
return [{
'title': entry.title,
'link': entry.link,
'description': entry.description,
'published': ('' if 'published_parsed' not in e... | 'item_pubdate': forms.CharField(label='Item publication date'), |
Here is a snippet: <|code_start|>
def struct2isoformat(struct):
if struct is None:
return ''
return datetime.datetime.fromtimestamp(time.mktime(struct)).isoformat()
@schedule(1)
@dedup('id')
@shared_task
def get_rss_feed(url, task_pair_id, secret):
resp = feedparser.parse(url)
assert 'bozo_e... | get_rss_feed.options = {'url': forms.URLField(label='URL')} |
Given the following code snippet before the placeholder: <|code_start|>
@shared_task
@format_options_from_event
def send_email(data, access_token, from_, to, subject, body, task_pair_id,
**kwargs):
message = MIMEText(body)
<|code_end|>
, predict the next line using imports from the current file:
... | message['to'] = to |
Continue the code snippet: <|code_start|>
def _check_photos(access_token, paginate=False, extra_params=None,
url=None, taskname=None, task_pair_id=None):
params = {'access_token': access_token}
if extra_params is not None:
params.update(extra_params)
while True:
resp = ... | else: |
Given the following code snippet before the placeholder: <|code_start|>
def _check_photos(access_token, paginate=False, extra_params=None,
url=None, taskname=None, task_pair_id=None):
params = {'access_token': access_token}
if extra_params is not None:
params.update(extra_params)
... | @shared_task |
Next line prediction: <|code_start|> kwargs = {}
if user or pass_:
kwargs['auth'] = (user, pass_)
if json:
kwargs['json'] = json
if data_:
kwargs['data'] = data_
if verify == 'false':
kwargs['verify'] = False
resp = requests.request(method, url, **kwargs)
res... | widget=forms.Textarea())), |
Predict the next line after this snippet: <|code_start|>
def generate_rss_feed(request, task_pair):
rss = PyRSS2Gen.RSS2(
title=task_pair.effect_options['feed_title'],
link=task_pair.effect_options['feed_link'],
description=task_pair.effect_options['feed_description'],
lastBuildD... | items=[PyRSS2Gen.RSSItem( |
Predict the next line after this snippet: <|code_start|>
class Command(BaseCommand):
help = 'Delete all Events for a particular task'
def add_arguments(self, parser):
parser.add_argument('task_pair_id', nargs='+', type=int)
parser.add_argument('--no-op', action='store_true', help="dry run")
<|... | def handle(self, *args, **options): |
Predict the next line after this snippet: <|code_start|>
def get_api(consumer_key, consumer_secret,
access_token, access_token_secret):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth)
@shared_task
@format... | return [{ |
Given the following code snippet before the placeholder: <|code_start|> auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth)
@shared_task
@format_options_from_event
def send_tweet(data, status, task_pair_id,
consumer_key, consumer_secret,
access_token, a... | 'raw': json.dumps(t._json), |
Given the code snippet: <|code_start|>
def get_api(consumer_key, consumer_secret,
access_token, access_token_secret):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth)
@shared_task
@format_options_from_even... | return [{ |
Predict the next line for this snippet: <|code_start|>
@dedup('id')
@schedule(1)
@shared_task
def get_notifications(access_token, user, task_pair_id):
resp = requests.get('https://api.github.com/notifications',
auth=(user, access_token))
resp.raise_for_status()
events = []
for... | 'title': notification['subject']['title'], |
Given snippet: <|code_start|>
@dedup('id')
@schedule(1)
@shared_task
def get_notifications(access_token, user, task_pair_id):
resp = requests.get('https://api.github.com/notifications',
auth=(user, access_token))
resp.raise_for_status()
<|code_end|>
, continue by predicting the next l... | events = [] |
Given the code snippet: <|code_start|># Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# See COPYING for license information.
logger = log.setup_logger(__name__)
logger_utils = log.LoggerUtils(logger)
class TerminateSubCommand(Exception):
"""
This is an exception to jump out of subcommand... | def filter_keys(key_list, args, sign="="): |
Predict the next line after this snippet: <|code_start|># Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# See COPYING for license information.
logger = log.setup_logger(__name__)
def get_tag_by_id(node, tag, ident):
"Find a doc node which matches tag and id."
<|code_end|>
using the current ... | for n in node.xpath(".//%s" % tag): |
Using the snippet: <|code_start|># Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# See COPYING for license information.
logger = log.setup_logger(__name__)
def get_tag_by_id(node, tag, ident):
"Find a doc node which matches tag and id."
<|code_end|>
, determine the next line of code. You hav... | for n in node.xpath(".//%s" % tag): |
Using the snippet: <|code_start|># Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# See COPYING for license information.
logger = log.setup_logger(__name__)
def get_tag_by_id(node, tag, ident):
"Find a doc node which matches tag and id."
for n in node.xpath(".//%s" % tag):
if n.ge... | if n.get("id") == node: |
Given snippet: <|code_start|> if msg.startswith("ERROR: "):
logger.error(msg[7:])
elif msg.startswith("WARNING: "):
logger.warning(msg[9:])
elif msg.startswith("INFO: "):
logger.info(msg[6:])
elif msg.startswith("DEBUG: "):
... | primitive {id} ocf:heartbeat:LVM-activate \ |
Based on the snippet: <|code_start|>
DLM_RA_SCRIPTS = """
primitive {id} ocf:pacemaker:controld \
op start timeout=90 \
op stop timeout=100 \
op monitor interval=60 timeout=60"""
FILE_SYSTEM_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:Filesystem \
params directory="{mnt_point}" fstype="{fs_type}" device="{device}" \... | CONFIGURE_RA_TEMPLATE_DICT = { |
Predict the next line for this snippet: <|code_start|> my_env["OCF_RESKEY_" + k] = v
cmd = [os.path.join(config.path.ocf_root, "resource.d", agent.ra_provider, agent.ra_type), "validate-all"]
if options.regression_tests:
print(".EXT", " ".join(cmd))
p = subprocess.Popen(cmd, stdout=subprocess... | primitive {id} ocf:heartbeat:Filesystem \ |
Here is a snippet: <|code_start|>op stop timeout=100 \
op monitor interval=60 timeout=60"""
FILE_SYSTEM_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:Filesystem \
params directory="{mnt_point}" fstype="{fs_type}" device="{device}" \
op monitor interval=20 timeout=40 \
op start timeout=60 \
op stop timeout=60"""
LVMLOCK... | "GROUP": GROUP_SCRIPTS, |
Using the snippet: <|code_start|> if log is True:
for msg in out.splitlines():
if msg.startswith("ERROR: "):
logger.error(msg[7:])
elif msg.startswith("WARNING: "):
logger.warning(msg[9:])
elif msg.startswith("INFO: "):
logge... | op monitor interval=30 timeout=90""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.