Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> raise RuntimeError("You must set a config file area if no depthfile is present and you are running a sub-region") self._set_vars_from_dict(gal_stats, check_none=True) if self.limmag_catalog is None: self....
self.member_dtype = copy.copy(member_dtype_base)
Given the code snippet: <|code_start|> class DuplicatableConfig(object): """ Class to hold instances of variables that need to be duplicated for parallelism. """ def __init__(self, config): """ Instantiate a DuplicatableConfig. Parameters ---------- config: `red...
version = ConfigField(default=__version__, required=True)
Given the code snippet: <|code_start|> res = scipy.optimize.minimize(self, p0, method='L-BFGS-B', bounds=bounds, jac=False, ...
spl = CubicSpline(self._z_nodes, pars)
Using the snippet: <|code_start|> if pval is None: result = numpy.pv(rate=nrate/100/pyr, nper=nper, fv=fval, pmt=pmt, when=due) elif fval is None: result = numpy.fv(rate=nrate/100/pyr, nper=nper, pv=pval, pmt=pmt, when=due) elif nper is None: result = numpy.nper(rate=nrate/100/pyr, pv...
params = _vars2list([pval, fval, nper, pmt, nrate])
Continue the code snippet: <|code_start|> admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^$', 'ssheepdog.views.view_access_summary'), url(r'^new_key/$', 'ssheepdog.views.generate_new_application_key'), url(r'^sync_keys/$', 'ssheepdog.views.sync_keys...
url(r'^awspolicies/', include(awsurls.aws_patterns, namespace='aws_urls')),
Given snippet: <|code_start|> add_introspection_rules([], ["^ssheepdog\.fields\.PublicKeyField"]) KEYS_DIR = os.path.join(os.path.dirname(__file__), '..', 'deploy', 'keys') ALL_FABRIC_WARNINGS = ['everything', 'status', 'aborts'] FABRIC_WARNINGS = [] <|code_end|> , continue by predicting the n...
class UserProfile(DirtyFieldsMixin, models.Model):
Using the snippet: <|code_start|> add_introspection_rules([], ["^ssheepdog\.fields\.PublicKeyField"]) KEYS_DIR = os.path.join(os.path.dirname(__file__), '..', 'deploy', 'keys') ALL_FABRIC_WARNINGS = ['everything', 'status', 'aborts'] FABRIC_WARNINGS = [] class UserProfile(DirtyFieldsMixin, mod...
ssh_key = PublicKeyField(blank=True)
Given snippet: <|code_start|> admin.site.register(models.Client) def unregister(Model): try: admin.site.unregister(Model) except: pass def reregister(Model, AdminModel): unregister(Model) admin.site.register(Model, AdminModel) class LoginAdmin(admin.ModelAdmin): model = models.Log...
form = forms.LoginForm
Using the snippet: <|code_start|># encoding: utf-8 NEW_PERMISSIONS = ( # Managed by South so added by data migration! ("can_view_all_users", "Can view other users"), ("can_view_all_logins", "Can view other's logins"), ) class Migration(SchemaMigration): def forwards(self, orm): # Adding field...
add_permission(orm, codename, name)
Given the following code snippet before the placeholder: <|code_start|> class AccessFilterForm(forms.Form): user = forms.CharField(label="User", required=False) login = forms.CharField(label="Login/Machine", required=False) class LoginForm(forms.ModelForm): named_application_key = forms.ModelChoiceField( ...
queryset=models.NamedApplicationKey.objects.all(),
Predict the next line after this snippet: <|code_start|># encoding: utf-8 PERMISSIONS = ( # Managed by South so added by data migration! ("can_view_access_summary", "Can view access summary"), ("can_sync", "Can sync login keys"), ("can_edit_own_public_key", "Can edit one's own public key"), ) class Mig...
add_permission(orm, codename, name)
Predict the next line for this snippet: <|code_start|># def updateRedirector(redirector): """ Correct the redirector in case the protocol and/or trailing slash are missing """ if not redirector.startswith("root://"): redirector = "root://" + redirector <|code_end|> with the help of current file imp...
tolog("Updated redirector for missing protocol: %s" % (redirector))
Given the code snippet: <|code_start|> cmd = "curl --silent --connect-timeout 100 --max-time 120 -X POST --data \'computingsite=%s&sourcesite=%s&pandaID=%s\' %s" % (computingSite, sourceSite, pandaID, url) tolog("Trying to get FAX redirectors: %s" % (cmd)) dictionary_string = commands.getoutput(c...
fax_redirectors_dictionary['computingsite'] = readpar('faxredirector')
Based on the snippet: <|code_start|># def updateRedirector(redirector): """ Correct the redirector in case the protocol and/or trailing slash are missing """ if not redirector.startswith("root://"): redirector = "root://" + redirector tolog("Updated redirector for missing protocol: %s" % (re...
fax_redirectors_dictionary = readJSON(file_name)
Based on the snippet: <|code_start|> redirector = redirector + "/" tolog("Updated redirector for missing trailing /: %s" % (redirector)) # Protect against triple slashes redirector = redirector.replace('///','//') return redirector def _getFAXRedirectors(computingSite, sourceSite, pandaID,...
status = writeJSON("fax_redirectors.json", fax_redirectors_dictionary)
Given the following code snippet before the placeholder: <|code_start|> logging.basicConfig(level=logging.DEBUG) class HPCManager: def __init__(self, logFileName=None): self.__globalWorkingDir = None self.__localWorkingDir = None self.__jobStateFile = 'HPCManagerState.json' self._...
self.__log= Logger(logFileName)
Predict the next line for this snippet: <|code_start|> if jobinfo.has_key("output_fields"): self.__env['jobDic'][k][1].output_fields = pUtil.stringToFields(jobinfo["output_fields"]) pUtil.tolog("Got output_fields=%s" % str(self.__env['j...
updatePilotErrorReport(self.__env['jobDic'][k][1].result[2], self.__env['jobDic'][k][1].pilotErrorDiag, "2", self.__env['jobDic'][k][1].jobId, self.__env['pilot_initdir'])
Next line prediction: <|code_start|> E.g. a file with state = "created", "not_registered" should first be transferred and then registered in the LFC. The file state dictionary should be created with "not_created" states as soon as the output files are known (pilot). The "created" states should be set after ...
tolog("Using file state dictionary: %s" % (self.filename))
Given snippet: <|code_start|> class JobState: """ This class is used to set the current job state. When the job is running, the file jobState-<JobID>.[pickle|json] is created which contains the state of the Site, Job and Node objects. The job state file is updated at every heartbeat. """ def...
tolog("JOBSTATE WARNING: Objects are missing in the recovery file (abort recovery)")
Predict the next line after this snippet: <|code_start|># This module contains functions related to file handling. def openFile(filename, mode): """ Open and return a file pointer for the given mode """ # Note: caller needs to close the file f = None if os.path.exists(filename): try: ...
tolog("!!WARNING!!2997!! Caught exception: %s" % (e))
Here is a snippet: <|code_start|> """ Open and return a file pointer for the given mode """ # Note: caller needs to close the file f = None if os.path.exists(filename): try: f = open(filename, mode) except IOError, e: tolog("!!WARNING!!2997!! Caught exception: %s"...
dictionary = convert(dictionary)
Here is a snippet: <|code_start|> directInLAN = useDirectAccessLAN() directInWAN = useDirectAccessWAN() directInType = 'None' directIn = False if directInLAN: directInType = 'LAN' directIn = True if directInWAN: # if (directInWAN and not analyjob) or (directInWAN and directI...
da = readpar(par)
Next line prediction: <|code_start|> tolog("!!WARNING!!1190!! Since at least one move to the external disk failed, the original work area") tolog("!!WARNING!!1190!! will not be removed and should be picked up by a later pilot doing the recovery") status = False ...
killProcesses(pid, os.getpgrp())
Given snippet: <|code_start|> utime = proctimes.split(' ')[13] # get stime from proc/<pid>/stat, 15 item stime = proctimes.split(' ')[14] # count total process used time proctotal = int(utime) + int(stime) return(float(proctotal)...
cpuConsumptionUnit, cpuConsumptionTime, cpuConversionFactor = getCPUTimes(os.getcwd())
Here is a snippet: <|code_start|> class Node: """ worker node information """ def __init__(self): self.cpu = 0 self.nodename = None self.mem = 0 self.disk = 0 self.numberOfCores = self.setNumberOfCores() self.benchmarks = None # set the batch job and mac...
tolog("CPU: %0.2f, memory: %0.2f, disk space: %0.2f" % (self.cpu, self.mem, self.disk))
Predict the next line for this snippet: <|code_start|> """ Add a substring field to the job metrics string """ jobMetrics = "" if value != "": jobMetrics += "%s=%s " % (name, value) return jobMetrics def addToJobMetrics(self, jobResult, path, jobId): """ Add the...
max_space = getMaxWorkDirSize(path, jobId)
Predict the next line after this snippet: <|code_start|> if self._loglevel is not None: if self._loglevel.isdigit(): if int(self._loglevel) >= 4: self._loglevel = logging.DEBUG elif int(self._loglevel) == 3: self._loglevel = logging.INFO ...
handler = FileHandler(target)
Based on the snippet: <|code_start|> class PilotTCPServer(threading.Thread): """ TCP server used to send TCP messages from runJob to pilot """ def __init__(self, handler, name='PilotTCPServer'): """ constructor, setting initial variables """ # find an available port to create the TCPServer ...
tolog("WARNING: Can not create TCP server on port %d, re-try... : %s" % (self.port, str(e)))
Using the snippet: <|code_start|> def extractSingularityOptions(): """ Extract any singularity options from catchall """ # e.g. catchall = "somestuff singularity_options=\'-B /etc/grid-security/certificates,/var/spool/slurmd,/cvmfs,/ceph/grid,/data0,/sys/fs/cgroup\'" #catchall = "singularity_options=\'-B...
tolog("container_options either does not exist in queuedata or is empty, trying with catchall instead")
Given the code snippet: <|code_start|> #catchall = "singularity_options=\'-B /etc/grid-security/certificates,/cvmfs,${workdir} --contain\'" #readpar("catchall") # ${workdir} should be there, otherwise the pilot cannot add the current workdir # if not there, add it # First try with reading new parameter...
e = getExperiment(experiment)
Given the following code snippet before the placeholder: <|code_start|>if t.TYPE_CHECKING: def _join_param_hints( param_hint: t.Optional[t.Union[t.Sequence[str], str]] ) -> t.Optional[str]: if param_hint is not None and not isinstance(param_hint, str): return " / ".join(repr(x) for x in param_hint) ...
file = get_text_stderr()
Predict the next line for this snippet: <|code_start|> def _join_param_hints( param_hint: t.Optional[t.Union[t.Sequence[str], str]] ) -> t.Optional[str]: if param_hint is not None and not isinstance(param_hint, str): return " / ".join(repr(x) for x in param_hint) return param_hint class ClickExce...
echo(_("Error: {message}").format(message=self.format_message()), file=file)
Predict the next line after this snippet: <|code_start|> # Can force a width. This is used by the test system FORCED_WIDTH: t.Optional[int] = None def measure_table(rows: t.Iterable[t.Tuple[str, str]]) -> t.Tuple[int, ...]: widths: t.Dict[int, int] = {} for row in rows: for idx, col in enumerate(ro...
widths[idx] = max(widths.get(idx, 0), term_len(col))
Next line prediction: <|code_start|> self.indent() try: yield finally: self.dedent() @contextmanager def indentation(self) -> t.Iterator[None]: """A context manager that increases the indentation.""" self.indent() try: yield ...
prefix = split_opt(opt)[0]
Predict the next line for this snippet: <|code_start|> self.buffer = byte_stream @property def name(self) -> str: return self.buffer.name def write(self, x: t.AnyStr) -> int: if isinstance(x, str): return self._text_stream.write(x) try: self.flush() ...
text_stream = _NonClosingTextIOWrapper(
Given the code snippet: <|code_start|> elif self.action == "store_const": state.opts[self.dest] = self.const # type: ignore elif self.action == "append": state.opts.setdefault(self.dest, []).append(value) # type: ignore elif self.action == "append_const": sta...
raise BadArgumentUsage(
Next line prediction: <|code_start|> # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed...
raise BadOptionUsage(
Here is a snippet: <|code_start|> else: state.rargs.insert(0, arg) return # Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i))...
raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)
Next line prediction: <|code_start|> option = Option(obj, opts, dest, action=action, nargs=nargs, const=const) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] ...
except UsageError:
Given snippet: <|code_start|>#! -*- coding: utf-8 -*- # test module # client module if six.PY2: else: # else __author__ = 'kensuke-mi' class TestServerHandler(unittest.TestCase): @classmethod def setUpClass(cls): if six.PY3: cls.test_senetence = '紗倉 まな(さくらまな、1993年3月23日 - )は、日本のAV女優。' ...
jumanpp_process_handler = sever_handler.JumanppHnadler(jumanpp_command=self.jumanpp_command)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from __future__ import division <|code_end|> . Use current file imports: from six import text_type from JapaneseTokenizer import init_log...
logger = init_logger.init_logger(logging.getLogger(init_logger.LOGGER_NAME))
Continue the code snippet: <|code_start|> raise Exception('Pos condition expects tuple of string. However = {}'.format(p_c_tuple)) converted = [text_type] * len(p_c_tuple) for i, pos_element in enumerate(p_c_tuple): if six.PY2 and isinstance(pos_element, str): """...
func_normalizer=normalize_text,
Here is a snippet: <|code_start|> self.is_feature = is_feature self.misc_info = misc_info self.analyzed_line = analyzed_line if isinstance(tuple_pos, tuple): self.tuple_pos = tuple_pos elif isinstance(tuple_pos, string_types): self.tuple_pos = ('*', ) ...
func_denormalizer=denormalize_text):
Next line prediction: <|code_start|> class Fortune(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=200, blank=False) slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') content = models.TextField(blank=False) pub_date = ...
objects = FortuneManager()
Predict the next line for this snippet: <|code_start|> class FortuneTransactionTestCase(TransactionTestCase): def create(self, title, author='Anon', content='', pub_date=datetime.now()): try: user = User.objects.get(username=author) except User.DoesNotExist: user = User(user...
f = Fortune(title=title, author=user, content=content, pub_date=pub_date)
Given the following code snippet before the placeholder: <|code_start|> class FortuneExtraTest(TestCase): def test_fortunize(self): self.assertEquals(fortunize(u'<niko> foo'), u'<dl><dt class="odd">&lt;niko&gt;</dt><dd><q>foo</q></dd>\n</dl>') self.assertEquals(fortunize(u'<niko> foo\n<david> bar')...
authors = top_contributors()['authors'];
Given snippet: <|code_start|> class FortuneTest(FortuneTransactionTestCase): def test_check_slug(self): f1 = self.create(title='plop') self.assertEquals(f1.slug, 'plop') f2 = self.create(title='plop') self.assertEquals(f2.slug, '1-plop') f3 = self.create(title='plop') ...
Fortune.objects.get(slug='plop').delete()
Given snippet: <|code_start|> def fortune_detail(request, year, month, day, slug, template_name='detail.html', template_object_name='fortune', **kwargs): ''' Display one fortune, and provides a comment form wich will be handled and persisted if request is POST ''' ...
queryset = Fortune.objects.published(),
Based on the snippet: <|code_start|> queryset = Fortune.objects.latest() # Ordering if order_type == 'top': queryset = queryset.order_by('-votes') elif order_type == 'worst': queryset = queryset.order_by('votes') else: # latest queryset = queryset.order_by('-p...
form = PublicFortuneForm(request.POST)
Here is a snippet: <|code_start|> class FortuneAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('author', 'title', 'slug', 'content', 'votes') }), ('Advanced options', { 'classes': ('collapse',), 'fields': ('pub_date',) }), ) list...
admin.site.register(Fortune, FortuneAdmin)
Next line prediction: <|code_start|> class FortuneFeed(Feed): author_name = 'The django_fortunes application' _site = Site.objects.get_current() <|code_end|> . Use current file imports: (from django.contrib.syndication.views import Feed from django.contrib.sites.models import Site from django.contrib.auth.mod...
manager = Fortune.objects
Next line prediction: <|code_start|> class FortuneFeed(Feed): author_name = 'The django_fortunes application' _site = Site.objects.get_current() manager = Fortune.objects def item_author_name(self, item): return item.author def item_description(self, item): <|code_end|> . Use current file...
return fortunize(item.content)
Predict the next line for this snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', fortune_list, name='fortune_index'), url(r'^author/(?P<author>\w+)/(?P<page>\w)?$', fortune_list, name='fortune_index_author'), url(r'^(?P<order_type>(top|worst|latest)?)/(?P<p...
LatestFortunes(),
Continue the code snippet: <|code_start|>urlpatterns = patterns('', url(r'^$', fortune_list, name='fortune_index'), url(r'^author/(?P<author>\w+)/(?P<page>\w)?$', fortune_list, name='fortune_index_author'), url(r'^(?P<order_type>(top|worst|latest)?)/(?P<page>\d)?$', ...
LatestFortunesByAuthor(),
Given the code snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', fortune_list, name='fortune_index'), url(r'^author/(?P<author>\w+)/(?P<page>\w)?$', fortune_list, name='fortune_index_author'), url(r'^(?P<order_type>(top|worst|latest)?)/(?P<page>\d)?$', ...
fortune_detail,
Predict the next line after this snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', fortune_list, name='fortune_index'), url(r'^author/(?P<author>\w+)/(?P<page>\w)?$', fortune_list, name='fortune_index_author'), url(r'^(?P<order_type>(top|worst|latest)?)/(?P...
fortune_vote,
Continue the code snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', fortune_list, name='fortune_index'), url(r'^author/(?P<author>\w+)/(?P<page>\w)?$', fortune_list, name='fortune_index_author'), url(r'^(?P<order_type>(top|worst|latest)?)/(?P<page>\d)?$', ...
fortune_new,
Using the snippet: <|code_start|> # Based on snippets from: https://code.djangoproject.com/ticket/10899 self.client.cookies[settings.SESSION_COOKIE_NAME] = 'fake' session = self.client.session session['deleted_email'] = 'test@domain.net' session.save() self.client.cookies[...
self.assertEqual(Feedback.objects.count(), 1)
Predict the next line for this snippet: <|code_start|> User = get_user_model() class RequiresLogin(LoginRequiredMixin, View): def get(self, *args, **kwargs): return HttpResponse('OK') <|code_end|> with the help of current file imports: from django.conf import settings from django.contrib.auth impor...
class RequiresAnonymous(AnonymousRequiredMixin, View):
Given the following code snippet before the placeholder: <|code_start|> class UserManagerTestCase(TestCase): _user_data = { 'email': 'test@example.com', 'password': '123', 'full_name': 'Test User', } def test_create_user(self): data = self._user_data.copy() <|code_end|> ,...
self.assertFalse(User.objects.exists())
Predict the next line for this snippet: <|code_start|> User.objects.create_user(**data) raw_pwd = data.pop('password') self.assertTrue(User.objects.filter(**data).exists()) user = User.objects.all()[0] self.assertTrue(user.check_password(raw_pwd)) def test_create_superuser(se...
self.assertEqual(user_picture_upload_to(user, 'wat.png'), expected)
Continue the code snippet: <|code_start|> urlpatterns = ( # Project Search url(r'^busca/$', ProjectSearch.as_view(), name='project_search'), # Project List url(r'^$', ProjectList.as_view(), name='project_list'), # Project Details url(r'^(?P<slug>[\w-]+)/$', ProjectDet...
ProjectApply.as_view(), name='project_apply'),
Predict the next line for this snippet: <|code_start|> urlpatterns = ( # Project Search url(r'^busca/$', ProjectSearch.as_view(), name='project_search'), # Project List url(r'^$', ProjectList.as_view(), name='project_list'), # Project Details url(r'^(?P<slug>[\w-]+)/$', <|cod...
ProjectDetails.as_view(), name='project_details'),
Using the snippet: <|code_start|> urlpatterns = ( # Project Search url(r'^busca/$', ProjectSearch.as_view(), name='project_search'), # Project List url(r'^$', <|code_end|> , determine the next line of code. You have imports: from django.conf.urls import url from .views import ( ProjectAp...
ProjectList.as_view(), name='project_list'),
Continue the code snippet: <|code_start|> url(r'^cadastro/$', Signup.as_view(), name='signup'), # Edit Dashboard url(r'^editar/$', RedirectView.as_view(pattern_name='accounts:edit_personal_info'), name='edit_dashboard'), # Edit Personal Info url(r'^editar/info-pessoal/$', ...
DeleteUser.as_view(), name='delete_user'),
Here is a snippet: <|code_start|> urlpatterns = ( # User Login url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', <|code_end|> . Write the next line using the current file imports: from django.conf.urls import url from django.views.generic import RedirectView from .views ...
logout, name='logout'),
Predict the next line after this snippet: <|code_start|> urlpatterns = ( # User Login url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', <|code_end|> using the current file's imports: from...
password_reset, name='password_reset'),
Predict the next line after this snippet: <|code_start|> urlpatterns = ( # User Login url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', password_reset, name='password_reset'), ...
password_reset_confirm, name='password_reset_confirm'),
Using the snippet: <|code_start|> urlpatterns = ( # User Login url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', password_reset, name='password_reset'), # Password Reset Sent ...
password_reset_sent, name='password_reset_sent'),
Using the snippet: <|code_start|> url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', password_reset, name='password_reset'), # Password Reset Sent url(r'^esqueci-senha/enviado$', ...
EditPersonalInfo.as_view(), name='edit_personal_info'),
Predict the next line for this snippet: <|code_start|> url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', password_reset, name='password_reset'), # Password Reset Sent url(r'^esqueci-senha/enviado$', password_reset_sent, name='password_reset_...
EditProfessionalInfo.as_view(), name='edit_professional_info'),
Predict the next line after this snippet: <|code_start|> urlpatterns = ( # User Login url(r'^login/$', login, name='login'), # User Logout url(r'^logout/$', logout, name='logout'), # Password Reset url(r'^esqueci-senha/$', password_reset, name='password_reset'), ...
Signup.as_view(), name='signup'),
Given snippet: <|code_start|># coding: utf8 from __future__ import unicode_literals User = get_user_model() class ProjectTestCase(TestCase): def _mock_pygeocoder_request(self, plain_json): responses.add( responses.GET, re.compile(Geocoder.GEOCODE_QUERY_URL), body=j...
project = Project(
Using the snippet: <|code_start|> User = get_user_model() class ProjectTestCase(TestCase): def _mock_pygeocoder_request(self, plain_json): responses.add( responses.GET, re.compile(Geocoder.GEOCODE_QUERY_URL), body=json.dumps(plain_json), content_type='appl...
self.assertEqual(project_img_upload_to(project, filename), expected)
Given the code snippet: <|code_start|> class ServicesAPIKeysTestCase(SimpleTestCase): factory = RequestFactory() @override_settings( FACEBOOK_API_KEY='fb-key', GOOGLE_ANALYTICS_ID='ga-key', GOOGLE_API_KEY='g-key') def test_api_keys(self): context = RequestContext(self.fac...
ctx = blog_url(None)
Predict the next line after this snippet: <|code_start|> @override_settings( FACEBOOK_API_KEY='fb-key', GOOGLE_ANALYTICS_ID='ga-key', GOOGLE_API_KEY='g-key') def test_api_keys(self): context = RequestContext(self.factory.get('/')) self.assertEqual(context.get('FACEBOOK_API...
ctx = contact_info(None)
Continue the code snippet: <|code_start|>@python_2_unicode_compatible class ProjectApply(models.Model): volunteer = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='applications', editable=False) project = models.ForeignKey( 'Project', related_name='applications', editable=False) ...
send_template_email(
Given the following code snippet before the placeholder: <|code_start|> self.assertTrue(isinstance(f.fields['username'], EmailField)) class UserAddressFormTestCase(TestCase): fixtures = ['test_cities'] def test_form_should_have_all_fields(self): self.assertEqual(UserAddressForm.Meta.fields, '...
f = DeleteUserForm(user=u, data={'password': 'test'})
Continue the code snippet: <|code_start|># encoding: utf8 from __future__ import unicode_literals User = get_user_model() class LoginFormTestCase(TestCase): def test_username_authenticationform_subclass(self): <|code_end|> . Use current file imports: from django.contrib.auth import get_user_model from djan...
self.assertTrue(issubclass(LoginForm, AuthenticationForm))
Based on the snippet: <|code_start|># encoding: utf8 from __future__ import unicode_literals User = get_user_model() class LoginFormTestCase(TestCase): def test_username_authenticationform_subclass(self): self.assertTrue(issubclass(LoginForm, AuthenticationForm)) def test_username_field_is_emai...
self.assertEqual(UserAddressForm.Meta.fields, '__all__')
Given the code snippet: <|code_start|> @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): formfield_overrides = { models.PointField: {'widget': forms.TextInput}, } <|code_end|> , generate the next line using the imports in this file: from django import forms from django.contrib import a...
@admin.register(ProjectApply)
Using the snippet: <|code_start|> @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): formfield_overrides = { models.PointField: {'widget': forms.TextInput}, } @admin.register(ProjectApply) class ProjectApplyAdmin(admin.ModelAdmin): actions = None date_hierarchy = 'created' l...
admin.site.register(Tag)
Next line prediction: <|code_start|># coding: utf8 from __future__ import unicode_literals class Signup(AnonymousRequiredMixin, CreateView): ''' User Signup ''' <|code_end|> . Use current file imports: (from django.core.urlresolvers import reverse, reverse_lazy from django.contrib.auth import ( au...
form_class = SignupForm
Given snippet: <|code_start|># coding: utf8 from __future__ import unicode_literals class UserAdmin(admin.ModelAdmin): class UserAddressInline(admin.StackedInline): model = UserAddress list_display = ('email', 'full_name', 'username', 'date_joined') list_filter = ('date_joined',) fieldsets...
admin.site.register(User, UserAdmin)
Given snippet: <|code_start|># coding: utf8 from __future__ import unicode_literals class UserAdmin(admin.ModelAdmin): class UserAddressInline(admin.StackedInline): <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib import admin from .models import User, Us...
model = UserAddress
Predict the next line after this snippet: <|code_start|> class BlogRedirectTestCase(TestCase): def test_blog_redirect_with_empty_setting(self): req = RequestFactory().get('/blog') with self.assertRaises(Http404): with self.settings(BLOG_URL=''): <|code_end|> using the current file's ...
resp = blog_redirect(req)
Based on the snippet: <|code_start|> class SetUserInfoFromAuthProviderTestCase(TestCase): def test_should_return_none_if_user_not_found(self): self.assertIsNone(set_user_info_from_auth_provider(None, None, None)) def test_should_register_full_name_and_email_on_user_instance(self): backend = ...
user = User()
Predict the next line after this snippet: <|code_start|> class UIGuidelineView(TemplateView): template_name = 'guideline/ui.html' def get_context_data(self, **kwargs): return dict( super(UIGuidelineView, self).get_context_data(**kwargs), <|code_end|> using the current file's imports: f...
empty_form=ExampleForm(),
Given snippet: <|code_start|> class FilterCityImportTestCase(TestCase): def test_filter_city_import_should_raise_invalid_items_when_not_br(self): items = [None, None, None, None, None, None, None, None, 'NOBR'] <|code_end|> , continue by predicting the next line. Consider current file imports: from dja...
self.assertRaises(InvalidItems, filter_city_import, None, items)
Based on the snippet: <|code_start|> urlpatterns = [ # About url(r'^sobre/$', TemplateView.as_view(template_name='portal/about.html'), name='about'), # How It Works url(r'^como-funciona/$', TemplateView.as_view(template_name='portal/how_it_works.html'), name='how_it_works'), ...
url(r'^blog/$', blog_redirect, name='blog_redirect'),
Next line prediction: <|code_start|># encoding: utf8 from __future__ import unicode_literals User = get_user_model() class SignupTestCase(TestCase): url = reverse('accounts:signup') def test_signup_page_is_accessible(self): response = self.client.get(self.url) self.assertEqual(response....
self.assertTrue(issubclass(Signup, AnonymousRequiredMixin))
Given the code snippet: <|code_start|># encoding: utf8 from __future__ import unicode_literals User = get_user_model() class SignupTestCase(TestCase): url = reverse('accounts:signup') def test_signup_page_is_accessible(self): response = self.client.get(self.url) self.assertEqual(respons...
self.assertTrue(issubclass(Signup, AnonymousRequiredMixin))
Predict the next line for this snippet: <|code_start|> class FeedbackForm(forms.ModelForm): class Meta: fields = [ 'email', 'question_1', 'question_2', 'question_3', 'question_4', 'question_5', 'comments', ] <|cod...
model = Feedback
Using the snippet: <|code_start|> class TestForm(forms.Form): test_field = forms.CharField(max_length=40) class TypeTestCase(TestCase): def test_type_filter_should_return_correct_class_name(self): self.assertEqual(type_([]), 'list') form = TestForm() self.assertEqual(type_(form['tes...
form_field(form['test_field'])['form_id'], form.prefix)
Given snippet: <|code_start|> def test_generate_an_id_from_a_form_without_prefix(self): form = TestForm() self.assertEqual(form_field(form['test_field'])['form_id'], 'testform') def test_render_html_classes_correctly_for_required_field(self): form = TestForm() form.fields['test_f...
form_fieldset(form, fields='test_field')['fields']],
Given the code snippet: <|code_start|> class TestForm(forms.Form): test_field = forms.CharField(max_length=40) class TypeTestCase(TestCase): def test_type_filter_should_return_correct_class_name(self): <|code_end|> , generate the next line using the imports in this file: from django import forms from djan...
self.assertEqual(type_([]), 'list')
Using the snippet: <|code_start|> from_email=None, domain_override=None, request=None, **kwargs): try: user = User.objects.get(email=self.cleaned_data['email']) except User.DoesNotExist: return if not user.has_usable_password(): return if ...
send_template_email(
Continue the code snippet: <|code_start|> context=context) class SignupForm(forms.ModelForm): password = forms.CharField(label='Senha', widget=forms.PasswordInput) class Meta: model = User fields = ('full_name', 'email',) def save(self, **kwargs): # Set password from ...
model = UserAddress
Based on the snippet: <|code_start|> class HomeBannerTestCase(TestCase): def test_image_upload_to(self): banner = HomeBanner.objects.create() self.assertEqual( <|code_end|> , predict the immediate next line with the help of imports: from django.test import TestCase from ..models import ( Hom...
homebanner_image_upload_to(banner, 'whatever.png'),
Given the code snippet: <|code_start|> class HomeBannerTestCase(TestCase): def test_image_upload_to(self): banner = HomeBanner.objects.create() self.assertEqual( homebanner_image_upload_to(banner, 'whatever.png'), 'homebanners/{:%Y-%m-%d}/image.jpeg'.format(banner.created)...
homebanner_video_upload_to(banner, 'whatever.webm'),