Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>
# compound()
class CompoundMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('compound', self._positive_properties,
self._negative_properties))
def __call__(self, category_list: ... | (self._negative_properties & category_list[index].positive_properties)): |
Given the code snippet: <|code_start|>
class SubtreeMatchRule:
def __init__(self, positive_properties: Iterable[Property],
negative_properties: Iterable[Property]):
self._positive_properties = make_property_set(positive_properties)
self._negative_properties = make_property_set(ne... | @property |
Continue the code snippet: <|code_start|>
class SubtreeMatchRule:
def __init__(self, positive_properties: Iterable[Property],
negative_properties: Iterable[Property]):
self._positive_properties = make_property_set(positive_properties)
self._negative_properties = make_property_set... | raise NotImplementedError() |
Here is a snippet: <|code_start|>
class SubtreeMatchRule:
def __init__(self, positive_properties: Iterable[Property],
negative_properties: Iterable[Property]):
self._positive_properties = make_property_set(positive_properties)
self._negative_properties = make_property_set(negativ... | repr(self._negative_properties) + ")") |
Here is a snippet: <|code_start|> assert case in (CASE_FREE, LOWER_CASE, UPPER_CASE, TITLE_CASE, MIXED_CASE)
super().__init__(category)
self._case = case
self._hash = hash(self._category) ^ hash(self._case)
@property
def case(self) -> Property:
return self._case
def ... | def __str__(self) -> str: |
Next line prediction: <|code_start|> super().__init__(category)
self._case = case
self._hash = hash(self._category) ^ hash(self._case)
@property
def case(self) -> Property:
return self._case
def __hash__(self) -> int:
return self._hash
def __eq__(self, other: 'C... | return self.case + '->' + str(self.category) |
Based on the snippet: <|code_start|>
class CaseRule(LeafRule):
def __init__(self, category: Category, case: Property):
case = Property.get(case)
assert case in (CASE_FREE, LOWER_CASE, UPPER_CASE, TITLE_CASE, MIXED_CASE)
super().__init__(category)
self._case = case
self._has... | self._case == other._case) |
Predict the next line for this snippet: <|code_start|>
class CaseRule(LeafRule):
def __init__(self, category: Category, case: Property):
case = Property.get(case)
assert case in (CASE_FREE, LOWER_CASE, UPPER_CASE, TITLE_CASE, MIXED_CASE)
super().__init__(category)
self._case = case... | return self._hash |
Based on the snippet: <|code_start|>
class CaseRule(LeafRule):
def __init__(self, category: Category, case: Property):
case = Property.get(case)
assert case in (CASE_FREE, LOWER_CASE, UPPER_CASE, TITLE_CASE, MIXED_CASE)
super().__init__(category)
<|code_end|>
, predict the immediate next l... | self._case = case |
Next line prediction: <|code_start|>
class CaseRule(LeafRule):
def __init__(self, category: Category, case: Property):
case = Property.get(case)
assert case in (CASE_FREE, LOWER_CASE, UPPER_CASE, TITLE_CASE, MIXED_CASE)
super().__init__(category)
self._case = case
self._has... | return self._hash |
Based on the snippet: <|code_start|>
class CaseRule(LeafRule):
def __init__(self, category: Category, case: Property):
case = Property.get(case)
assert case in (CASE_FREE, LOWER_CASE, UPPER_CASE, TITLE_CASE, MIXED_CASE)
super().__init__(category)
self._case = case
self._has... | def __hash__(self) -> int: |
Continue the code snippet: <|code_start|>
class CaseRule(LeafRule):
def __init__(self, category: Category, case: Property):
case = Property.get(case)
assert case in (CASE_FREE, LOWER_CASE, UPPER_CASE, TITLE_CASE, MIXED_CASE)
super().__init__(category)
<|code_end|>
. Use current file import... | self._case = case |
Predict the next line after this snippet: <|code_start|> total_weight += weight
return total_score, total_weight
def adjust_score(self, parse_node: 'trees.TreeNodeInterface', target: float) -> None:
if not 0 <= target <= 1:
raise ValueError("Score target must be in the in... | return 0, 0, 0 |
Given the code snippet: <|code_start|>
class SuffixRule(LeafRule):
def __init__(self, category: Category, suffixes: Iterable[str], positive: bool = True):
super().__init__(category)
self._suffixes = frozenset([suffix.lower() for suffix in suffixes])
self._positive = bool(positive)
... | return self._hash |
Based on the snippet: <|code_start|> self._suffixes = frozenset([suffix.lower() for suffix in suffixes])
self._positive = bool(positive)
self._hash = hash(self._category) ^ hash(self._suffixes) ^ hash(self._positive)
def __hash__(self) -> int:
return self._hash
def __eq__(self, ... | def __str__(self) -> str: |
Given snippet: <|code_start|>
# head()
class HeadMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('head', self._positive_properties,
self._negative_properties))
def __call__(self, category_list: Sequence[Category], h... | return ((self._positive_properties <= category_list[head_index].positive_properties) and |
Given the following code snippet before the placeholder: <|code_start|>
# head()
class HeadMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('head', self._positive_properties,
<|code_end|>
, predict the next line using imports from the current file:
from typing im... | self._negative_properties)) |
Using the snippet: <|code_start|>
# head()
class HeadMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('head', self._positive_properties,
<|code_end|>
, determine the next line of code. You have imports:
from typing import Sequence
from pyramids import categorizat... | self._negative_properties)) |
Given the following code snippet before the placeholder: <|code_start|>
# all_terms(),
class AllTermsMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('all_terms', self._positive_properties,
self._negative_properties))
... | if (not (self._positive_properties <= category_list[index].positive_properties) or |
Based on the snippet: <|code_start|>
# all_terms(),
class AllTermsMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('all_terms', self._positive_properties,
<|code_end|>
, predict the immediate next line with the help of imports:
from typing import Sequence
from py... | self._negative_properties)) |
Here is a snippet: <|code_start|>"""Test suite for Cython categorization code (_categorization.pyx)."""
def test_repr_eval():
"""Ensure that alternately calling repr() and eval() on a category gets back the original
category unchanged."""
cat = Category("abc", ["def"], ["ghi"])
serialized = repr(cat)... | if __name__ == '__main__': |
Predict the next line for this snippet: <|code_start|>
# any_term()
class AnyTermMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('any_term', self._positive_properties,
<|code_end|>
with the help of current file imports:
from typing import Sequence
from pyramids... | self._negative_properties)) |
Here is a snippet: <|code_start|>
# any_term()
class AnyTermMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('any_term', self._positive_properties,
self._negative_properties))
def __call__(self, category_list: Sequen... | if ((self._positive_properties <= category_list[index].positive_properties) and |
Next line prediction: <|code_start|>
if TYPE_CHECKING:
class BranchRule(ParseRule, metaclass=ABCMeta):
""""Used by Parser to identify higher-level (composite) structures,
which are the branches in a parse tree."""
@abstractmethod
def __call__(self, parser_state: 'parsing.ParserState', new_node: 'tre... | @abstractmethod |
Given snippet: <|code_start|>class BranchRule(ParseRule, metaclass=ABCMeta):
""""Used by Parser to identify higher-level (composite) structures,
which are the branches in a parse tree."""
@abstractmethod
def __call__(self, parser_state: 'parsing.ParserState', new_node: 'trees.TreeNodeSet',
... | @property |
Predict the next line for this snippet: <|code_start|>
if TYPE_CHECKING:
class BranchRule(ParseRule, metaclass=ABCMeta):
""""Used by Parser to identify higher-level (composite) structures,
which are the branches in a parse tree."""
@abstractmethod
def __call__(self, parser_state: 'parsing.ParserStat... | @abstractmethod |
Using the snippet: <|code_start|>
if TYPE_CHECKING:
class BranchRule(ParseRule, metaclass=ABCMeta):
""""Used by Parser to identify higher-level (composite) structures,
which are the branches in a parse tree."""
@abstractmethod
def __call__(self, parser_state: 'parsing.ParserState', new_node: 'trees.... | @abstractmethod |
Predict the next line after this snippet: <|code_start|>
class PropertyInheritanceRule:
def __init__(self, category: Category, positive_additions: Iterable[Property],
negative_additions: Iterable[Property]):
self._category = category
self._positive_additions = make_property_set(p... | if self._positive_additions: |
Predict the next line after this snippet: <|code_start|>
class PropertyInheritanceRule:
def __init__(self, category: Category, positive_additions: Iterable[Property],
negative_additions: Iterable[Property]):
self._category = category
self._positive_additions = make_property_set(p... | if self._positive_additions: |
Predict the next line for this snippet: <|code_start|>
class PropertyInheritanceRule:
def __init__(self, category: Category, positive_additions: Iterable[Property],
negative_additions: Iterable[Property]):
self._category = category
self._positive_additions = make_property_set(pos... | self.category.negative_properties <= category.negative_properties): |
Continue the code snippet: <|code_start|>
# last_term()
class LastTermMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('last_term', self._positive_properties,
<|code_end|>
. Use current file imports:
from typing import Sequence
from pyramids import categorization... | self._negative_properties)) |
Predict the next line for this snippet: <|code_start|>
# last_term()
class LastTermMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('last_term', self._positive_properties,
self._negative_properties))
def __call__(sel... | not (self._negative_properties & category_list[-1].positive_properties)) |
Based on the snippet: <|code_start|>
# last_term()
class LastTermMatchRule(SubtreeMatchRule):
def __str__(self) -> str:
return str(categorization.Category('last_term', self._positive_properties,
self._negative_properties))
def __call__(self, category_list: ... | not (self._negative_properties & category_list[-1].positive_properties)) |
Based on the snippet: <|code_start|> for link in json_data['links']:
source = link['source']
sink = link['sink']
label = LinkLabel.get(link['label'])
if sink in links[source]:
links[source][sink].add(label)
else:
links[so... | if sink in self._links[source]} |
Predict the next line for this snippet: <|code_start|> phrase_map[index] = phrase
return ['%s: %s' % (self.get_phrase_category(index), phrase_map[index])
for index in sorted(self.find_roots())]
def find_roots(self) -> Set[int]:
roots = set(range(len(self._tokens))... | return len(roots) == 1 and self._is_forest(roots) |
Based on the snippet: <|code_start|>#!/usr/bin/python
sys.path.append("..")
def test_noise():
N = 500
#rate = 1.0
w = noise.white(N)
b = noise.brown(N)
v = noise.violet(N)
p = noise.pink(N)
# check output length
assert len(w) == N
assert len(b) == N
assert len(v) == N
<... | assert len(p) == N |
Continue the code snippet: <|code_start|>
y_WFM_ind= noise.white(num_points= int(2e4), b0=S_y0, fs=2e4)
y_WPM_ind= noise.violet(num_points= int(2e4), b2=S_y0, fs=2e4)
f, S_y_WFM_ind= welch(y_WFM_ind,fs=2e4, nperseg=y_WFM_ind.size, window='hanning')
f, S_y_WPM_ind= welch(y_WPM_ind,fs=2e4, nperseg=y_WPM_i... | (tau, modsigma_WPM_ind)= at.psd2allan(S_y_WPM_ind, kind= 'm') |
Here is a snippet: <|code_start|>#!/usr/bin/python
sys.path.append("..")
def _test( function, data, rate, taus):
(taus2,devs2,errs2,ns2) = function(data, rate=rate, taus=taus)
assert( len(taus2) == len(devs2) )
<|code_end|>
. Write the next line using the current file imports:
import sys
import allantools ... | assert( len(taus2) == len(errs2) ) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
try:
WIKI_WORD_RE = settings.WIKI_WORD_RE
except AttributeError:
WIKI_WORD_RE = r'(?:[A-Z]+[a-z]+){2,}'
wikiword_pattern = re.compile('^' + WIKI_WORD_RE + '$')
class ArticleForm(forms.ModelForm):
summary = forms.CharField(... | content_type = forms.ModelChoiceField( |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
LOG = logging.getLogger(__name__)
__name__ = "mbot"
__author__ = "Michael Kuty"
DATA_PATH = appdirs.user_data_dir(__name__, __author__)
CONFIG_PATH = appdirs.user_config_dir(__name__, __author__)
CONFIG_FORMAT = "yaml"
DEFAULT_CONFIG = """
core:
dat... | middlewares: |
Based on the snippet: <|code_start|># Copyright Contributors to the Numpyro project.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ... | idx_min: int |
Next line prediction: <|code_start|>
def kernel_generator(step_size: float):
return functools.partial(
kernel,
logprob_fn=logprob_fn,
step_size=step_size,
inverse_mass_matrix=inv_mass_matrix,
num_integration_steps=10,
... | target_accept=0.05, |
Continue the code snippet: <|code_start|>
class GaussianEuclideanMetricsTest(chex.TestCase):
def setUp(self):
super().setUp()
self.key = random.PRNGKey(0)
self.dtype = "float32"
@parameterized.named_parameters(
<|code_end|>
. Use current file imports:
import chex
import jax.numpy as ... | {"testcase_name": "0d", "shape": ()}, |
Using the snippet: <|code_start|>""" All things resampling. """
def _resampling_func(func, name, desc="", additional_params="") -> Callable:
# Decorator for resampling function
doc = f"""
{name} resampling. {desc}
Parameters
----------
weights: jnp.ndarray
Weights to resample
k... | PRNGKey to use in resampling |
Continue the code snippet: <|code_start|>r"""Metric space in which the Hamiltonian dynamic is embedded.
An important particular case (and the most used in practice) of metric for the
position space in the Euclidean metric. It is defined by a definite positive
matrix :math:`M` with fixed value so that the kinetic energ... | dynamic is independent of the position and only depends on the momentum |
Continue the code snippet: <|code_start|>r"""Metric space in which the Hamiltonian dynamic is embedded.
An important particular case (and the most used in practice) of metric for the
position space in the Euclidean metric. It is defined by a definite positive
matrix :math:`M` with fixed value so that the kinetic energ... | monte carlo." Bernoulli 23.4A (2017): 2257-2298. |
Predict the next line after this snippet: <|code_start|>r"""Metric space in which the Hamiltonian dynamic is embedded.
An important particular case (and the most used in practice) of metric for the
position space in the Euclidean metric. It is defined by a definite positive
<|code_end|>
using the current file's impor... | matrix :math:`M` with fixed value so that the kinetic energy of the hamiltonian |
Predict the next line after this snippet: <|code_start|>def kernel(
logprior_fn: Callable,
loglikelihood_fn: Callable,
mcmc_kernel_factory: Callable,
make_mcmc_state: Callable,
resampling_fn: Callable,
target_ess: float,
root_solver: Callable = solver.dichotomy,
use_log_ess: bool = True,... | A solver utility to find delta matching the target ESS. Signature is |
Next line prediction: <|code_start|>
__all__ = [
"adaptive_tempered_smc",
"hmc",
"nuts",
"rmh",
<|code_end|>
. Use current file imports:
(from typing import Callable, Dict, Union
from blackjax.base import AdaptationAlgorithm, SamplingAlgorithm
from blackjax.types import Array, PRNGKey, PyTree
import ... | "tempered_smc", |
Given snippet: <|code_start|>
__all__ = [
"adaptive_tempered_smc",
"hmc",
"nuts",
"rmh",
"tempered_smc",
"window_adaptation",
]
# -----------------------------------------------------------------------------
# SEQUENTIAL MONTE CARLO
# -------------------------------... | class adaptive_tempered_smc: |
Predict the next line for this snippet: <|code_start|>
__all__ = [
"adaptive_tempered_smc",
"hmc",
"nuts",
"rmh",
"tempered_smc",
"window_adaptation",
]
# -----------------------------------------------------------------------------
# SEQUENTIAL MONTE CARLO
# ------... | class adaptive_tempered_smc: |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
@pytest.fixture()
def model(request):
model = Model()
return model
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pywr
import pandas
import datetime
import pytest
from pywr.core import (
Model,
Input,... | @pytest.fixture() |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
@pytest.fixture()
def model(request):
model = Model()
return model
<|code_end|>
, determine the next line of code. You have imports:
import pywr
import pandas
import datetime
import pytest
from pywr.core import (
Model,
Input,
Output,
... | @pytest.fixture() |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
@pytest.fixture()
def model(request):
model = Model()
return model
<|code_end|>
. Write the next line using the current file imports:
import pywr
import pandas
import datetime
import pytest
from pywr.core import (
Model,
Input,
Output,
... | @pytest.fixture() |
Next line prediction: <|code_start|>#!/usr/bin/env python
def test_base_license():
with pytest.raises(TypeError):
lic = License()
<|code_end|>
. Use current file imports:
(import pytest
import numpy as np
import pandas
import pandas as pd
import datetime, calendar
from datetime import datetime... | def test_daily_license(simple_linear_model): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
def test_base_license():
with pytest.raises(TypeError):
lic = License()
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import numpy as np
import pandas
import pandas as pd
import datetime, calendar... | def test_daily_license(simple_linear_model): |
Given snippet: <|code_start|>#!/usr/bin/env python
def test_base_license():
with pytest.raises(TypeError):
lic = License()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
import numpy as np
import pandas
import pandas as pd
import datetime, cal... | def test_daily_license(simple_linear_model): |
Given the code snippet: <|code_start|>
class Item:
def __init__(self, name):
self.name = name
@pytest.fixture
def items():
return [
Item("Hello"),
Item("World"),
Item("River Thames"),
]
@pytest.fixture
def iterator(items):
i = NamedIterator()
for item in items:
... | def test_iterator_contains(items, iterator): |
Continue the code snippet: <|code_start|>
def pytest_report_header(config):
headers = []
solver_name = Model().solver.name
headers.append("solver: {}".format(solver_name))
<|code_end|>
. Use current file imports:
import os
from pywr.model import Model
and context (classes, functions, or code) from other ... | return "\n".join(headers) |
Here is a snippet: <|code_start|>
def make_df(freq, start="2015-01-01", end="2015-12-31"):
# Daily time-step
index = pd.period_range(start, end, freq=freq)
series = pd.DataFrame(np.arange(len(index), dtype=np.float64), index=index)
<|code_end|>
. Write the next line using the current file imports:
from py... | return series |
Given the following code snippet before the placeholder: <|code_start|>
def make_df(freq, start="2015-01-01", end="2015-12-31"):
# Daily time-step
index = pd.period_range(start, end, freq=freq)
series = pd.DataFrame(np.arange(len(index), dtype=np.float64), index=index)
return series
def make_model_in... | return pd.period_range(start, end, freq=freq) |
Next line prediction: <|code_start|>
model = simple_linear_model
def test_keys_and_values(model):
expected_names = {"Input", "Link", "Output"}
assert set(model.nodes.keys()) == expected_names
nodes = {node for node in model.nodes}
assert len(nodes) == 3
assert set(model.nodes.values()) == nodes
... | def test_contains(model): |
Given the following code snippet before the placeholder: <|code_start|>
class TestNotification(TestCase):
def setUp(self):
account = AccountFactory.create()
self.user = account.user
def test_access_notification_list(self):
self.client.login(username=self.user.username, password=DEFAUL... | self.assertEqual(response.status_code, 200) |
Given snippet: <|code_start|>
urlpatterns = [
url(r'^$', LinkView.new, name='link_new'),
url(r'^(?P<post_id>[0-9]+)/add/$', LinkView.add, name='link_add'),
url(r'^(?P<post_id>[0-9]+)/react/$', LinkReactionView.react, name='link_react'),
url(r'^(?P<post_id>[0-9]+)/unreact/$', LinkReactionView.unreact, n... | ] |
Next line prediction: <|code_start|>
class NotificationView:
@staticmethod
@login_required
def list(request):
owner = request.user.accounts.first()
notifications = Notification.objects.filter(owner=owner).order_by('-created_at')
Notification.check_as_viewed(owner)
notify_co... | 'notify_count': notify_count}) |
Given the following code snippet before the placeholder: <|code_start|>
class PostFactory(factory.DjangoModelFactory):
class Meta:
model = Post
owner = factory.SubFactory(AccountFactory)
publisher = factory.SubFactory(AccountFactory)
url = 'http://test.tst'
type = 'html'
<|code_end|>
, pr... | title = factory.sequence(lambda n: 'Title Link Test {}'.format(n)) |
Given the code snippet: <|code_start|>
class PostFactory(factory.DjangoModelFactory):
class Meta:
model = Post
owner = factory.SubFactory(AccountFactory)
publisher = factory.SubFactory(AccountFactory)
url = 'http://test.tst'
type = 'html'
title = factory.sequence(lambda n: 'Title Link... | post = factory.SubFactory(PostFactory) |
Predict the next line for this snippet: <|code_start|>
class PostFactory(factory.DjangoModelFactory):
class Meta:
model = Post
owner = factory.SubFactory(AccountFactory)
publisher = factory.SubFactory(AccountFactory)
url = 'http://test.tst'
type = 'html'
title = factory.sequence(lambd... | image_url = factory.sequence(lambda n: 'Summary Link Test {}'.format(n)) |
Continue the code snippet: <|code_start|>
class PostFactory(factory.DjangoModelFactory):
class Meta:
model = Post
owner = factory.SubFactory(AccountFactory)
publisher = factory.SubFactory(AccountFactory)
url = 'http://test.tst'
type = 'html'
title = factory.sequence(lambda n: 'Title L... | summary = factory.sequence(lambda n: 'Summary Link Test {}'.format(n)) |
Predict the next line for this snippet: <|code_start|>
class TestAccount(TestCase):
def setUp(self):
new_user = AccountFactory.build().user
self.account = AccountFactory.create()
self.user = self.account.user
<|code_end|>
with the help of current file imports:
from unittest.mock import... | self.form_login = { |
Predict the next line after this snippet: <|code_start|> def test_settings_update_password(self):
settings_info = {'first_name': self.user.first_name, 'last_name': self.user.last_name,
'password': 'new', 'confirm_password': 'new'}
self.client.login(username=self.user.username... | mock_views_fs.return_value.exists = MagicMock(return_value=True) |
Given snippet: <|code_start|> 'password': 'invalid',
}
response = self.client.post(reverse('account_login'), data=invalid_login)
self.assertFormError(response, 'form', None, errors=None)
def test_login_fails_identity_and_password_empty(self):
response = self.client.post(r... | def test_access_profile_anonymous(self): |
Given the code snippet: <|code_start|>
class Search:
def __init__(self, query, owner=None):
self.owner = owner
self.adv_separator = ':'
self.results = []
self.query_value = query
self.words = query.lower().split(' ')
def process(self):
if self.is_advanced():
... | raise SearchException('Attr not supported! try: user, title or tag') |
Predict the next line after this snippet: <|code_start|>
class Search:
def __init__(self, query, owner=None):
self.owner = owner
self.adv_separator = ':'
self.results = []
self.query_value = query
self.words = query.lower().split(' ')
def process(self):
if self... | attr, word = self.words.pop(0).split(self.adv_separator) |
Here is a snippet: <|code_start|>
class AuthView:
@staticmethod
def signup(request):
form = None
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form_user = form.save(commit=False)
<|code_end|>
. Write the next line usin... | user = User.objects.create_user(username=form_user.username, email=form_user.email, |
Predict the next line for this snippet: <|code_start|> data = form.data
if '@' in data['identity']:
kwargs = {'email': data['identity'].lower()}
else:
kwargs = {'username': data['identity'].lower()}
try:
... | @staticmethod |
Given the code snippet: <|code_start|>
class AuthView:
@staticmethod
def signup(request):
<|code_end|>
, generate the next line using the imports in this file:
import os
from django.shortcuts import redirect, render, get_object_or_404
from django.urls import reverse
from django.contrib.auth import login, lo... | form = None |
Based on the snippet: <|code_start|> user_account = Account.get_by_user(user=user)
request.session['user_avatar'] = user_account.user_avatar
request.session.save()
return redirect(redirect_path)
except User.Do... | if request.user.is_authenticated: |
Predict the next line after this snippet: <|code_start|> user.first_name = form_user.first_name
user.last_name = form_user.last_name
user.save()
account = Account(user=user)
account.save()
return render(request, 'index.html', {'formS... | request.session.save() |
Using the snippet: <|code_start|>class SettingsView:
@staticmethod
@login_required
def settings(request):
user = request.user
form = None
if request.method == 'POST':
form = SettingsForm(request.POST)
if form.is_valid():
data = form.data
... | fs.delete(filename) |
Using the snippet: <|code_start|> @staticmethod
@login_required
def follow(request, username):
if request.method == 'POST':
relationship = Relationship()
relationship.owner = Account.get_by_user(request.user)
relationship.follow = Account.get_by_username(username)
... | if form.is_valid(): |
Here is a snippet: <|code_start|>
DEFAULT_PASSWORD = 'abc@123'
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
username = factory.sequence(lambda n: 'user{}'.format(n))
email = factory.lazy_attribute(lambda n: '{}@test.com'.format(n.username.lower()))
password = fact... | class RelationshipFactory(factory.DjangoModelFactory): |
Given the code snippet: <|code_start|>
DEFAULT_PASSWORD = 'abc@123'
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
username = factory.sequence(lambda n: 'user{}'.format(n))
email = factory.lazy_attribute(lambda n: '{}@test.com'.format(n.username.lower()))
password =... | first_name = factory.sequence(lambda n: 'First User Name {}'.format(n)) |
Predict the next line for this snippet: <|code_start|> return self.tags.split(',')
def add_link(self, user):
new_post = copy.copy(self)
new_post.owner = user
new_post.origin = self
new_post.id = None
new_post.save()
@staticmethod
def feeds(username):
... | is_reacted=models.Exists(queryset=qs_reactions)).annotate( |
Here is a snippet: <|code_start|> page_info = utils.get_page_info(self.url)
self.type = page_info['type']
self.title = page_info['title']
self.summary = page_info['summary']
self.text = page_info['text']
self.image_url = page_info['image']
self.tags = ','.join(page... | models.Q(owner__user__username=username)).annotate( |
Using the snippet: <|code_start|> RelationshipFactory.create(owner=account0, follow=account1)
RelationshipFactory.create(owner=account1, follow=account2)
[PostFactory.create(owner=account0, publisher=account0,
title='Search A', tags='search') for _ in range(2)]
... | search = response.context['search'] |
Next line prediction: <|code_start|> self.assertEqual(len(search.results), 8)
def test_advanced_search_by_user(self):
self.client.login(username=self.user.username, password=DEFAULT_PASSWORD)
response = self.client.get(reverse('search'), {'q': 'user:search'})
search = response.contex... | self.assertEqual(response.status_code, 200) |
Continue the code snippet: <|code_start|> account2 = AccountFactory.create(user__first_name='Search 2')
RelationshipFactory.create(owner=account0, follow=account1)
RelationshipFactory.create(owner=account1, follow=account2)
[PostFactory.create(owner=account0, publisher=account0,
... | response = self.client.get(reverse('search'), {'q': 'user:search', 'anonymous': 1}) |
Using the snippet: <|code_start|> [PostFactory.create(owner=account0, publisher=account0,
title='Search A', tags='search') for _ in range(2)]
[PostFactory.create(owner=account1, publisher=account1,
title='Search B', tags='search') for _ in range(2)]... | self.assertTemplateUsed(response, 'search/list.html') |
Given the code snippet: <|code_start|>
img_url = 'https://test.fleeg/valid-image-link'
self.client.login(username=self.user.username, password=DEFAULT_PASSWORD)
response = self.client.post(reverse('link_new'), data={'url': img_url})
self.assertRedirects(response, reverse('home'))
... | </html> |
Given the following code snippet before the placeholder: <|code_start|>
class TestLink(TestCase):
def setUp(self):
self.other_user = AccountFactory.create()
self.other_user_post = PostFactory.create(owner=self.other_user, publisher=self.other_user)
self.account = AccountFactory.create()
... | self.assertEqual(response.status_code, 200) |
Using the snippet: <|code_start|> self.assertTrue(response.context['posts'].count())
def test_post_new_link_fails_url_empty(self):
self.client.login(username=self.user.username, password=DEFAULT_PASSWORD)
response = self.client.post(reverse('link_new'), data={})
self.assertFormError(... | response = self.client.post(reverse('link_new'), data={'url': url_post}) |
Predict the next line after this snippet: <|code_start|>
class TestLink(TestCase):
def setUp(self):
self.other_user = AccountFactory.create()
self.other_user_post = PostFactory.create(owner=self.other_user, publisher=self.other_user)
self.account = AccountFactory.create()
self.us... | self.assertTemplateUsed(response, 'link/link.html') |
Given snippet: <|code_start|>
class URLForm(forms.ModelForm):
class Meta:
model = Post
fields = ('url',)
class CommentForm(forms.ModelForm):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from link.models import Post, Comment
and con... | class Meta: |
Using the snippet: <|code_start|>
class general_train(datasets_base):
def __init__(self, path, img_size=64, flip=1, crop_to=0, random_brightness=0):
self._paths = glob.glob(path + "/*.jpg")
#self._img_size=img_size
super(general_train, self).__init__(flip=1, resize_to=img_size, crop_to=crop... | def get_example(self, i): |
Here is a snippet: <|code_start|> if img.shape[0] < 64:
return None
return img
def get_example(self, i):
np.random.seed(None)
while True:
img = self.try_get_example()
if not img is None:
break
img = self.do_augmentation(img)... | return len(self._paths) |
Using the snippet: <|code_start|>
class mnist_train(datasets_base):
def __init__(self, path=None, img_size=64):
self.train, _ = chainer.datasets.get_mnist(withlabel=False, ndim=2, scale=255)
super(mnist_train, self).__init__(flip=1, resize_to=img_size, crop_to=0)
def __len__(self):
ret... | img = self.preprocess_image(img) |
Here is a snippet: <|code_start|>
class celeba_train(datasets_base):
def __init__(self, path, img_size=64):
self._paths = glob.glob(path + "/img_align_celeba/*.jpg")
#self._img_size=img_size
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import chainer
import... | super(celeba_train, self).__init__(flip=1, resize_to=img_size, crop_to=0) |
Based on the snippet: <|code_start|> return tags
def get_fake_tag_batch():
xp = gen.xp
batch = rows*cols
tags = xp.zeros((batch, attr_len)).astype("f")
for i in range(batch):
tags[i] = xp.asarray(get_fake_tag())
return tags
def samples_generation(trai... | d_real = xp.zeros((batch_size, img_chan, img_size, img_size)).astype("f") |
Continue the code snippet: <|code_start|>
approach = Group(
murta2014a, pimentel2015a,
_display="no Work flow",
_approach_name="noWorkflow",
_cite=False,
<|code_end|>
. Use current file imports:
from snowballing.approaches import Group
from ..constants import *
from ...work.y2014 import murta2014a... | _meta=[dict( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.