Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>
class TestAnalysis(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_get(self, mock_request: unittest.mock):
mock_request.return_value = unittest.mock.MagicMock(status_code=200)
<|code_end|>
, predict the immediate next line with the help of ... | Analysis(token="mock-token").get(1) |
Given the following code snippet before the placeholder: <|code_start|>
class TestLanguage(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_list(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
... | constants.HttpMethod.get.value, |
Predict the next line for this snippet: <|code_start|>
class TestLanguage(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_list(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"langu... | models.Language(name="Abkhaz", code="ab"), |
Continue the code snippet: <|code_start|>
class TestLanguage(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_list(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"languages": [
... | models.Language(name="Abkhaz", code="ab"), |
Next line prediction: <|code_start|>
class MxliffParser(object):
"""
Parse xliff file of Memsource.
"""
def parse(self, resource: {'XML file content as bytes': bytes}):
root = objectify.fromstring(resource)
memsource_namespace = root.nsmap['m']
def to_memsouce_key(s: str) -> s... | def parse_group(self, group: objectify.ObjectifiedElement) -> models.MxliffUnit: |
Here is a snippet: <|code_start|>
class TestAuth(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_login(self, mock_request: unittest.mock):
ms_response = unittest.mock.Mock(status_code=200)
ms_response.json.return_value = {
"user": {
"lastName... | self.assertIsInstance(response, models.Authentication) |
Based on the snippet: <|code_start|>
class TestAuth(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_login(self, mock_request: unittest.mock):
ms_response = unittest.mock.Mock(status_code=200)
ms_response.json.return_value = {
"user": {
"lastN... | response = auth.Auth().login(user_name="mock-user", password="mock-password") |
Given snippet: <|code_start|>
class TestDomain(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_create(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"id": "mock-id",
"n... | constants.HttpMethod.post.value, |
Continue the code snippet: <|code_start|> mock_request.return_value = ms_response
response = Domain(token="mock-token").create("mock-test")
self.assertEqual(response, {
"id": "mock-id",
"name": "mock-test",
})
mock_request.assert_called_with(
c... | self.assertIsInstance(response, models.Domain) |
Using the snippet: <|code_start|>
class TestDomain(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_create(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"id": "mock-id",
... | response = Domain(token="mock-token").create("mock-test") |
Given the code snippet: <|code_start|>
class TestMxliffParser(unittest.TestCase):
def setUp(self):
# Read test.mxliff file from same directory with this file.
file_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(file_dir, 'test.mxliff')) as f:
self.mxlif... | mxliff_units = MxliffParser().parse(self.mxliff_text) |
Given snippet: <|code_start|>
class TestMxliffParser(unittest.TestCase):
def setUp(self):
# Read test.mxliff file from same directory with this file.
file_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(file_dir, 'test.mxliff')) as f:
self.mxliff_text = ... | self.assertIsInstance(mxliff_units[0], models.MxliffUnit) |
Predict the next line after this snippet: <|code_start|>
class TestProject(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_create(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"ui... | response = Project(token="mock-token").create( |
Next line prediction: <|code_start|> "email": "mock-tm@gengo.com",
"userName": "mock-tm",
"uid": "1234",
"lastName": "mock-last-name",
"id": "1",
"firstName": "mock-first-name",
"role": "ADMIN"
},
... | self.assertIsInstance(response, models.Client) |
Based on the snippet: <|code_start|>
class TestClient(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_create(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"id": "mock-id"
... | response = Client().create("mock-test") |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
log = logging.getLogger(__name__)
def test_dals():
test_string = """
This little piggy went to the market.
This little piggy stayed home.
This little piggy had roast ... | assert dals(test_string).count('\n') == 3 |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class TestBase64Encoding(TestCase):
def test_encode(self):
test_str = "Mickey Mouse"
result_str = "TWlja2V5IE1vdXNl".encode('UTF-8')
<|code_end|>
using the current file's imports:
from unittest import TestCase
fro... | self.assertEqual(crypt.as_base64(test_str), |
Continue the code snippet: <|code_start|> # generate new key, and make sure it's different than the last
self.assertNotEqual(crypt.generate_encryption_key(), key)
def test_hashing_secret(self):
secret = 'test secret'
key_hash = crypt.generate_hash_from_secret(secret)
self.ass... | self.assertRaises(AuthenticationError, crypt.aes_decrypt, encryption_key, |
Continue the code snippet: <|code_start|> # hash should always be the same
self.assertEqual(key_hash, crypt.generate_hash_from_secret(secret))
class TestAESEncryption(TestCase):
def test_encrypt_and_decrypt_end_to_end(self):
test_data = u"Mickey & Miννie Μouse"
encryption_key = cry... | encryption_key_encrypted, encrypted_data = encrypt(secret_key, data) |
Given snippet: <|code_start|> self.assertEqual(key_hash, crypt.generate_hash_from_secret(secret))
class TestAESEncryption(TestCase):
def test_encrypt_and_decrypt_end_to_end(self):
test_data = u"Mickey & Miννie Μouse"
encryption_key = crypt.generate_encryption_key()
encrypted_data =... | round_trip = decrypt(secret_key, encryption_key_encrypted, encrypted_data) |
Predict the next line for this snippet: <|code_start|># assert _get_version_from_pkg_info('tests') == test_version
# finally:
# if os.path.exists('.version'):
# os.remove('.version')
#
# def test_is_git_dirty(self):
# result = _is_git_dirty(os.getcwd())
# ... | tag = get_version(os.getcwd()) |
Predict the next line for this snippet: <|code_start|> >>> typify('32.0.0')
'32.0.0'
>>> [typify(x) for x in ('true', 'yes', 'on')]
[True, True, True]
>>> [typify(x) for x in ('no', 'FALSe', 'off')]
[False, False, False]
>>> [typify(x) for x in ('none', 'None', Non... | elif not (type_hint - {bool, NoneType}): |
Predict the next line for this snippet: <|code_start|>"""Collection of functions to coerce conversion of types with an intelligent guess."""
__all__ = ["boolify", "typify", "maybecall", "listify", "numberify"]
BOOLISH_TRUE = ("true", "yes", "on", "y")
BOOLISH_FALSE = ("false", "off", "n", "no", "non", "none", "")
N... | BOOL_COERCEABLE_TYPES = integer_types + (bool, float, complex, list, set, dict, tuple) |
Next line prediction: <|code_start|> Args:
value (Any): Usually a string, not a sequence
type_hint (type or Tuple[type]):
Examples:
>>> typify('32')
32
>>> typify('32', float)
32.0
>>> typify('32.0')
32.0
>>> typify('32.0.0')
'32.0.... | if isiterable(type_hint): |
Next line prediction: <|code_start|> if not (type_hint - NUMBER_TYPES_SET):
return numberify(value)
elif not (type_hint - STRING_TYPES_SET):
return text_type(value)
elif not (type_hint - {bool, NoneType}):
return boolify(value, nullable=True)
elif not (... | return type(value)((k, typify(v, type_hint)) for k, v in iteritems(value)) |
Next line prediction: <|code_start|>"""Collection of functions to coerce conversion of types with an intelligent guess."""
__all__ = ["boolify", "typify", "maybecall", "listify", "numberify"]
BOOLISH_TRUE = ("true", "yes", "on", "y")
BOOLISH_FALSE = ("false", "off", "n", "no", "non", "none", "")
NULL_STRINGS = ("no... | STRING_TYPES_SET = set(string_types) |
Given snippet: <|code_start|>
def boolify(value, nullable=False, return_string=False):
"""Convert a number, string, or sequence type into a pure boolean.
Args:
value (number, string, sequence): pretty much anything
Returns:
bool: boolean representation of the given value
Examples:
... | val = text_type(value).strip().lower().replace('.', '', 1) |
Continue the code snippet: <|code_start|>"""Collection of functions to coerce conversion of types with an intelligent guess."""
__all__ = ["boolify", "typify", "maybecall", "listify", "numberify"]
BOOLISH_TRUE = ("true", "yes", "on", "y")
BOOLISH_FALSE = ("false", "off", "n", "no", "non", "none", "")
NULL_STRINGS =... | @memoizedproperty |
Here is a snippet: <|code_start|>"""Collection of functions to coerce conversion of types with an intelligent guess."""
__all__ = ["boolify", "typify", "maybecall", "listify", "numberify"]
BOOLISH_TRUE = ("true", "yes", "on", "y")
BOOLISH_FALSE = ("false", "off", "n", "no", "non", "none", "")
NULL_STRINGS = ("none"... | class TypeCoercionError(AuxlibError, ValueError): |
Given snippet: <|code_start|> if 'skip_registration' in cls.__dict__ and cls.skip_registration:
pass # we don't even care # pragma: no cover
elif cls.factory is None:
# this must be the base implementation; add a factory object
cls.factory = type(cls.__name__ + 'Fact... | @with_metaclass(FactoryType) |
Given the code snippet: <|code_start|>"""A python implementation of the factory design pattern. It's designed for use as a base class
for various types of data gateways.
"""
from __future__ import absolute_import, division, print_function
__all__ = ['Factory']
class FactoryBase(object):
@classmethod
def i... | raise InitializationError("RecordRepoFactory has not been initialized.") |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
log = getLogger(__name__)
class TestLoggingSetup(TestCase):
def test_basic_stderr(self):
detach_stderr()
<|code_end|>
using the current file's imports:
fro... | assert attach_stderr() |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
log = getLogger(__name__)
class TestLoggingSetup(TestCase):
def test_basic_stderr(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from logging import ge... | detach_stderr() |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
log = getLogger(__name__)
class TestLoggingSetup(TestCase):
def test_basic_stderr(self):
detach_stderr()
assert attach_stderr()
assert not attach_stderr()
a... | initialize_logging() |
Predict the next line after this snippet: <|code_start|>
log = getLogger(__name__)
class TestLoggingSetup(TestCase):
def test_basic_stderr(self):
detach_stderr()
assert attach_stderr()
assert not attach_stderr()
assert detach_stderr()
assert not detach_stderr()
a... | strng = stringify(req) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
log = getLogger(__name__)
class AllTheAnswers(object):
_x = 42
_y = 43
def __init__(self, x, y):
self._x = x
self._y = y
<|code_end|>
, continue by predicting the next ... | @classproperty |
Continue the code snippet: <|code_start|>except ImportError: # pragma: no cover
logging.getLogger(__name__).error('auxlib.crypt is a pycrypto wrapper, '
'which is not installed in the current '
'environment.') # pragma: no cover
log = l... | if isinstance(content, text_type): |
Given the code snippet: <|code_start|> data = data.encode("UTF-8")
aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key)
data = _pad(data)
iv_bytes = os.urandom(AES_BLOCK_SIZE)
cipher = AES.new(aes_key_bytes, mode=AES.MODE_CBC, IV=iv_bytes)
data = iv_bytes + cipher.encrypt(data... | raise AuthenticationError("HMAC authentication failed") |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
"""Common collection classes."""
from __future__ import print_function, division, absolute_import
def make_immutable(value):
# this function is recursive, and if nested data structures fold back on themselves,
# there will like... | elif isiterable(value): |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""Common collection classes."""
from __future__ import print_function, division, absolute_import
def make_immutable(value):
# this function is recursive, and if nested data structures fold back on themselves,
# there will likely be recursion erro... | return frozenodict((k, make_immutable(v)) for k, v in iteritems(value)) |
Predict the next line for this snippet: <|code_start|> return self._dict[key]
def __contains__(self, key):
return key in self._dict
def copy(self, **add_or_replace):
return self.__class__(self, **add_or_replace)
def __iter__(self):
return iter(self._dict)
def __len__(s... | dict_cls = odict |
Based on the snippet: <|code_start|> The optional `key` argument specifies a one-argument predicate function
like that used for `filter()`. The `key` argument, if supplied, must be
in keyword form. For example:
>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4
"""
... | if text_type(e) != "reduce() of empty sequence with no initial value": |
Given snippet: <|code_start|># file: netdevice/forms.py
class RouterForm(forms.ModelForm):
class Meta:
model = router
fields = ('__all__')
class VrfForm(forms.ModelForm):
class Meta:
model = vrf
fields = ('__all__')
class InterfaceForm(forms.ModelForm):
class Meta... | model = interface |
Given snippet: <|code_start|># file: netdevice/forms.py
class RouterForm(forms.ModelForm):
class Meta:
model = router
fields = ('__all__')
class VrfForm(forms.ModelForm):
class Meta:
model = vrf
fields = ('__all__')
class InterfaceForm(forms.ModelForm):
class Meta... | model = logical_interface |
Given the following code snippet before the placeholder: <|code_start|># file: netdevice/forms.py
class RouterForm(forms.ModelForm):
class Meta:
model = router
fields = ('__all__')
class VrfForm(forms.ModelForm):
class Meta:
<|code_end|>
, predict the next line using imports from the cu... | model = vrf |
Using the snippet: <|code_start|># file: netdevice/serializers.py
class LogicalInterfaceSerializer(serializers.ModelSerializer):
class Meta:
model = logical_interface
fields = ('__all__')
class InterfaceSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, determine the next l... | model = interface |
Predict the next line after this snippet: <|code_start|># file: op_webgui/urls.py
app_name = 'op_webgui'
urlpatterns = [
url(
r'^$',
<|code_end|>
using the current file's imports:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from op_webgui import views
and any r... | views.index, |
Based on the snippet: <|code_start|># file: static/forms.py
class IPv6StaticForm(forms.ModelForm):
class Meta:
model = ipv6_static
fields = ('__all__')
class IPv4StaticForm(forms.ModelForm):
class Meta:
<|code_end|>
, predict the immediate next line with the help of imports:
from django... | model = ipv4_static |
Given the code snippet: <|code_start|> def test_index_view_with_no_routers(self):
"""
We want to see an error if there are no routers.
"""
self.client.login(username='test', password='test')
response = self.client.get(reverse('op_webgui:router_list'), follow=True)
self... | router.objects.create( |
Given the following code snippet before the placeholder: <|code_start|>
class WebGUIViewTests(TestCase):
def setUp(self):
self.client.force_login(User.objects.get_or_create(username='testuser')[0])
def test_index_view_with_no_routers(self):
"""
We want to see an error if there are no ro... | nos = network_os.objects.create(name='many-test-os') |
Given the code snippet: <|code_start|># file: op_webgui/tests.py
class WebGUIViewTests(TestCase):
def setUp(self):
self.client.force_login(User.objects.get_or_create(username='testuser')[0])
def test_index_view_with_no_routers(self):
"""
We want to see an error if there are no rout... | test_router = create_router('ios') |
Continue the code snippet: <|code_start|>class WebGUIViewTests(TestCase):
def setUp(self):
self.client.force_login(User.objects.get_or_create(username='testuser')[0])
def test_index_view_with_no_routers(self):
"""
We want to see an error if there are no routers.
"""
self... | local_aut_num = aut_num.objects.create(asn=65000, name='test asn') |
Here is a snippet: <|code_start|># file: api/urls.py
app_name = 'api'
urlpatterns = [
url(
r'^routers/$',
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from api import views
and context f... | views.RouterList.as_view(), |
Based on the snippet: <|code_start|># file: op_webgui/views.py
def index(request):
info = {}
info['router_count'] = router.objects.count()
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from d... | info['asn_count'] = aut_num.objects.count() |
Predict the next line for this snippet: <|code_start|># file: address/urls.py
app_name = 'static'
urlpatterns = [
url(
r'^(?P<router_id>[0-9]+)/create/ipv6_static/$',
<|code_end|>
with the help of current file imports:
from django.conf.urls import url
from django.contrib.auth import views as auth_view... | views.ipv6_static_create, |
Predict the next line for this snippet: <|code_start|>
def create_aut_num(asn):
test_asn = aut_num.objects.create(asn=asn,
name='Test ASN',
contact='test@test.com',
)
return te... | test_router = create_router('ios') |
Continue the code snippet: <|code_start|># file: bgp/tests.py
def create_aut_num(asn):
test_asn = aut_num.objects.create(asn=asn,
name='Test ASN',
contact='test@test.com',
)
r... | test_neighbor = neighbor.objects.create(router=test_router, |
Given the following code snippet before the placeholder: <|code_start|># file: netdevice/serializers.py
class Ipv6StaticSerializer(serializers.ModelSerializer):
class Meta:
model = ipv6_static
fields = ('__all__')
class Ipv4StaticSerializer(serializers.ModelSerializer):
class Meta:
<|code_en... | model = ipv4_static |
Next line prediction: <|code_start|># file: netdevice/urls.py
app_name = 'netdevice'
urlpatterns = [
url(
r'^create/router/$',
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from django.contrib.auth import views as auth_views
from netdevice import views)
and context includi... | views.router_create, |
Given the code snippet: <|code_start|># file: bgp/forms.py
class ASNForm(forms.ModelForm):
class Meta:
model = aut_num
fields = ('__all__')
class NeighborForm(forms.ModelForm):
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
from django import forms
fro... | model = neighbor |
Predict the next line for this snippet: <|code_start|> }
return render(request, 'bgp/asn_list.html', context)
def aut_num_detail(request, aut_num_id):
aut_num_obj = get_object_or_404(aut_num, pk=aut_num_id)
return render(request, 'bgp/aut_num.html', {'aut_num': aut_num_obj})
def aut_num_c... | router_obj = get_object_or_404(router, pk=router_id) |
Based on the snippet: <|code_start|> if form.is_valid():
asn = form.save()
return redirect('bgp:aut_num_detail', aut_num_id=asn.pk)
else:
form = ASNForm()
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def aut_num_edit(request, aut_num_id):
asn ... | neighbor_obj = get_object_or_404(neighbor, pk=neighbor_id) |
Given the following code snippet before the placeholder: <|code_start|>
def asn_list(request):
asns = aut_num.objects.order_by('asn')
asn_count = asns.count()
paginator = Paginator(asns, 20)
page = request.GET.get('page')
try:
asn_list = paginator.page(page)
except PageNotA... | form = ASNForm(request.POST) |
Predict the next line after this snippet: <|code_start|> return render(request, 'bgp/asn_list.html', context)
def aut_num_detail(request, aut_num_id):
aut_num_obj = get_object_or_404(aut_num, pk=aut_num_id)
return render(request, 'bgp/aut_num.html', {'aut_num': aut_num_obj})
def aut_num_create(request):... | form = NeighborForm(request.POST) |
Continue the code snippet: <|code_start|># file: address/forms.py
class IPv6AddressForm(forms.ModelForm):
class Meta:
model = ipv6_address
fields = ('__all__')
class IPv4AddressForm(forms.ModelForm):
class Meta:
<|code_end|>
. Use current file imports:
from django import forms
from addr... | model = ipv4_address |
Based on the snippet: <|code_start|># file: address/serializers.py
class Ipv6AddressSerializer(serializers.ModelSerializer):
class Meta:
model = ipv6_address
fields = ('__all__')
class Ipv4AddressSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, predict the immediate next l... | model = ipv4_address |
Continue the code snippet: <|code_start|>
def create_v4_static(test_router, network):
v4_route = ipv4_static.objects.create(router=test_router,
network=network,
cidr=16,
nex... | test_router = create_router('ios') |
Here is a snippet: <|code_start|># file: static/tests.py
def create_v4_static(test_router, network):
v4_route = ipv4_static.objects.create(router=test_router,
network=network,
cidr=16,
... | v6_route = ipv6_static.objects.create(router=test_router, |
Given the code snippet: <|code_start|># file: bgp/urls.py
app_name = 'bgp'
urlpatterns = [
url(
r'^asn/$',
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from bgp import views
and context (functi... | views.asn_list, |
Based on the snippet: <|code_start|># file: config_gen/views.py
def index(request):
context = {}
return render(request, 'config_gen/index.html', context)
def router_config(request, router_id):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.shortcuts import get_obje... | router_obj = get_object_or_404(router, pk=router_id) |
Predict the next line after this snippet: <|code_start|># file: address/tests.py
def create_v4_address(logical_interface, address):
v4_address = ipv4_address.objects.create(interface=logical_interface,
host=address,
cidr=24... | test_router = create_router('ios') |
Next line prediction: <|code_start|>
def create_v4_address(logical_interface, address):
v4_address = ipv4_address.objects.create(interface=logical_interface,
host=address,
cidr=24,
... | test_interface = create_interface(test_router) |
Predict the next line after this snippet: <|code_start|># file: address/tests.py
def create_v4_address(logical_interface, address):
v4_address = ipv4_address.objects.create(interface=logical_interface,
host=address,
cidr=24... | v6_address = ipv6_address.objects.create(interface=logical_interface, |
Predict the next line after this snippet: <|code_start|># file: bgp/serializers.py
class AutNumSerializer(serializers.ModelSerializer):
class Meta:
model = aut_num
fields = ('__all__')
class NeighborSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
using the current file's i... | model = neighbor |
Predict the next line after this snippet: <|code_start|># file: static/views.py
def ipv6_static_create(request, router_id):
router_obj = get_object_or_404(router, pk=router_id)
if request.method == "POST":
form = IPv6StaticForm(request.POST)
if form.is_valid():
ipv6_static_obj =... | ipv6_static_obj = get_object_or_404(ipv6_static, pk=ipv6_static_id) |
Based on the snippet: <|code_start|># file: static/views.py
def ipv6_static_create(request, router_id):
router_obj = get_object_or_404(router, pk=router_id)
if request.method == "POST":
<|code_end|>
, predict the immediate next line with the help of imports:
from django.shortcuts import get_object_or_404,... | form = IPv6StaticForm(request.POST) |
Here is a snippet: <|code_start|>
def ipv6_static_create(request, router_id):
router_obj = get_object_or_404(router, pk=router_id)
if request.method == "POST":
form = IPv6StaticForm(request.POST)
if form.is_valid():
ipv6_static_obj = form.save()
return redirect('netde... | form = IPv4StaticForm(request.POST) |
Next line prediction: <|code_start|># file: address/urls.py
app_name = 'address'
urlpatterns = [
url(
r'^(?P<logical_interface_id>[0-9]+)/create/ipv6_address/$',
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from django.contrib.auth import views as auth_views
from address im... | views.ipv6_address_create, |
Continue the code snippet: <|code_start|> 'history': r.history,
'content': r.text,
'relme': [],
'url': sourceURL
}
if r.status_code == requests.codes.ok: # pylint: disable=no-member
dom = BeautifulSoup(r.text, _html_parser)
... | profile = normalizeURL(profileURL) |
Based on the snippet: <|code_start|># http://dreev.es -> [301] -> http://ai.eecs.umich.edu/people/dreeves/
# https://twitter.com/dreev -> [rel-me] -> http://t.co/PlBCqLVndT -> [301] -> http://dreev.es -> [301] -> http://ai.eecs.umich.edu/peop... | result['relme'].append(cleanURL(href)) |
Predict the next line after this snippet: <|code_start|># processing stops)
def findMentions(sourceURL, targetURL=None, exclude_domains=None, content=None, test_urls=True, headers=None, timeout=None):
"""Find all <a /> elements in the given html for a post. Only scan html element matching all criteria in look_in.... | URLValidator(message='invalid source URL')(sourceURL) |
Using the snippet: <|code_start|>
def discoverEndpoint(sourceURL, test_urls=True, headers=None, timeout=None, request=None, debug=False):
"""Discover any WebMention endpoint for a given URL.
:param link: URL to discover WebMention endpoint
:param test_urls: optional flag to test URLs for validation
:pa... | linkHeader = parse_link_header(targetRequest.headers['link']) |
Predict the next line after this snippet: <|code_start|># Licensed under the GPLv3 - see LICENSE
class ParserDictSetup:
@staticmethod
def create_parser(index, default):
def parser(words):
return words[index]
return parser
@staticmethod
def get_default(index, default):
... | parsers = ParserDict(cls.create_parser) |
Predict the next line for this snippet: <|code_start|># Licensed under the GPLv3 - see LICENSE
class ParserDictSetup:
@staticmethod
def create_parser(index, default):
def parser(words):
return words[index]
return parser
@staticmethod
def get_default(index, default):
... | class H(HeaderParserBase): |
Predict the next line after this snippet: <|code_start|>
class TestHeaderParserBase(ParserDictSetup):
def setup_class(cls):
cls.hp = {'0': (0, 'default0'),
'1': (1, 'default1')}
class H(HeaderParserBase):
parsers = ParserDict(cls.create_parser)
indices = P... | cls.header_parser = HeaderParser( |
Given the code snippet: <|code_start|> mask : list of int
For each entry in ``pattern`` a bit mask with bits set for
the parts that are invariant.
"""
if invariants is None:
invariants = self.invariants()
if not invariants:
raise ValueErro... | @fixedvalue |
Based on the snippet: <|code_start|># Licensed under the GPLv3 - see LICENSE
class TestRawOffsets:
@pytest.mark.parametrize('frame_nbytes', [0, 10, 100])
def test_plain(self, frame_nbytes):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from ..offsets import RawOffset... | ro = RawOffsets(frame_nbytes=frame_nbytes) |
Using the snippet: <|code_start|>def main(bot, *args, **kwargs):
"""
kot
Stupid cat memes from http://kotomatrix.ru
"""
matricies = json.loads(bot.store.get('kot_matricies').decode() or '[]')
curr_index = int(bot.store.get('kot_index') or 0)
if curr_index >= len(matricies):
respons... | prepare_binary_from_url(matrix), |
Next line prediction: <|code_start|>
async def main(bot, *args, **kwargs):
"""
btc
Get latest bitcoin price
"""
tickers = [
{'name': 'CEX.IO', 'url': 'https://cex.io/api/ticker/BTC/USD', 'field': 'last', 'sign': '$'},
{'name': 'Bitstamp', 'url': 'https://www.bitstamp.net/api/v2/tic... | response_body = await http.perform_request(ticker['url'], 'GET') |
Given snippet: <|code_start|> headers = {'Authorization': 'Basic {}'.format(auth.decode('utf-8'))}
# Cache return response to decrease number of requests to the bing api
if last_query != query:
# TODO: use `params` here, investigate 'Query is not of type String' error from azure
try:
... | photo = file_id if file_id else prepare_binary_from_url(url) |
Given snippet: <|code_start|>
def main(bot, *args, **kwargs):
"""
webm
Return random webm from csgoanime.
See also: img
"""
last_dt = bot.store.get('webm_dt')
if last_dt is not None and float(last_dt.decode()) > time.time() - 60:
return 'Let me get some rest.'
bot.store.set('we... | file_name = download_file(url, headers={'Referer': resp.url}) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class UtilsTestCase(unittest.TestCase):
def test_clean_text_should_remove_inappropriate_chars(self):
line = u'This :;requirement? # !is @only = $necessary %when ^you &place *your (1st ;order |with us, Mr -. а ... | self.assertEqual(text.clean_text(line), expected) |
Here is a snippet: <|code_start|> set(re.findall("/files/thumb/.*?.jpg", response.content.decode('utf-8'))))
matricies = list(
map(lambda x: 'https://picachoo.ru{}'.format(x.replace('/thumb', '')), matricies))
bot.store.set('picachoo_matricies', json.dumps(matricies))
curr... | prepare_binary_from_url(matrix, verify=False), |
Continue the code snippet: <|code_start|>
async def main(bot, *args, **kwargs):
update = kwargs.get('update', {})
message_id = update.get('message', {}).get('message_id')
# message_id is always even for one-to-one chats and odd for group chats, so let's calculate hash instead of returning raw value
rol... | await http.send(bot, chat_id=kwargs.get('chat_id'), text=str(roll_id), data={'reply_to_message_id': message_id}) |
Given the code snippet: <|code_start|>
async def main(bot, *args, **kwargs):
"""
bm
Random news from http://breakingmad.me/
"""
news_id = random.randint(3,9524)
try:
<|code_end|>
, generate the next line using the imports in this file:
import json
import random
import sys
import re
from modul... | response_body = await http.perform_request("http://breakingmad.me/ru/{}.json".format(news_id), 'GET') |
Given snippet: <|code_start|>
async def main(bot, *args, **kwargs):
"""
bash [query]
Search for quote on http://bash.im/
If no query specified, return random quote.
"""
path = 'index' if args else 'random'
params = {'text': ' '.join(args).encode('windows-1251')} if args else {}
url = ... | response_body = await http.perform_request(url, 'GET', params=params) |
Here is a snippet: <|code_start|>
def main(bot, message, update, *args, **kwargs):
chat_id = kwargs.get('chat_id')
message = message.strip()
message_id = update.get('message', {}).get('message_id')
for url in re.findall(r'http.*\.webm', message):
file_id = bot.store.get(url)
data = {... | file_name = download_file(url) |
Given the code snippet: <|code_start|>
async def main(bot, *args, **kwargs):
"""
usd
Get latest USD/RUB quote
"""
try:
url = 'https://ru.investing.com/currencies/usd-rub'
<|code_end|>
, generate the next line using the imports in this file:
from modules.utils import http
from lxml import ht... | response_body = await http.perform_request(url, 'GET') |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class BaseModuleTestCase(unittest.TestCase):
def setUp(self):
self.bot = MagicMock()
class UserCowsayTestCase(BaseModuleTestCase):
@patch('os.popen')
def test_run_module_with_args_should_call_bot_send(self, popen):
... | self.assertEqual(user_date.main(self.bot), '2015-12-14 12:13:14') |
Predict the next line for this snippet: <|code_start|>class UserCowsayTestCase(BaseModuleTestCase):
@patch('os.popen')
def test_run_module_with_args_should_call_bot_send(self, popen):
user_cowsay.main(self.bot, 'test', 'message')
self.assertEqual(self.bot.send.call_count, 1)
def test_run_m... | self.assertEqual(user_g.main(self.bot, 'green', 'apples'), 'hello\ncontent of the result\nhttp://example.com') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.