Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
def get_months_transactions(user):
today = timezone.now()
first_day_of_a_month = datetime(today.year, today.month, 1,
tzinfo=today.tzinfo)
qs = Transaction.objects.filter(created__gte=first_day_of_a_month,
... | return qs |
Continue the code snippet: <|code_start|>
class TransactionFactory(factory.DjangoModelFactory):
title = factory.Sequence(lambda n: 'transaction_%d' % n)
amount = 10
category = models.Transaction.EXPENSE
user = factory.SubFactory(UserFactory)
class Meta:
model = models.Transaction
class ... | amount = 42 |
Based on the snippet: <|code_start|> 5,
amount=factory.Sequence(lambda n: random.randint(1, 10)),
category=factory.Sequence(lambda n: random.choice(categories)),
user=self.admin,
)
# create for last month
DebtLoanFactory.create_batch(
5... | created=factory.Sequence(lambda n: self._get_all_time()), |
Here is a snippet: <|code_start|> category=factory.Sequence(lambda n: random.choice(categories)),
user=self.admin,
)
# create for last month
DebtLoanFactory.create_batch(
5,
amount=factory.Sequence(lambda n: random.randint(1, 10)),
cate... | print("DebtLoans for admin created") |
Given the following code snippet before the placeholder: <|code_start|> )
# create for this year
TransactionFactory.create_batch(
5,
amount=factory.Sequence(lambda n: random.randint(1, 10)),
category=factory.Sequence(lambda n: random.choice(categories)),
... | ) |
Given snippet: <|code_start|> )
# create for last month
TransactionFactory.create_batch(
5,
amount=factory.Sequence(lambda n: random.randint(1, 10)),
category=factory.Sequence(lambda n: random.choice(categories)),
user=self.admin,
creat... | def create_debt_loans(self): |
Continue the code snippet: <|code_start|> category=factory.Sequence(lambda n: random.choice(categories)),
user=self.admin,
)
# create for last month
TransactionFactory.create_batch(
5,
amount=factory.Sequence(lambda n: random.randint(1, 10)),
... | print("Transactions for admin created") |
Here is a snippet: <|code_start|>
class HomePageTests(TestCase):
def setUp(self):
self.user = UserFactory()
def test_home_not_logged_in(self):
c = Client()
response = c.get(reverse('home'))
self.assertRedirects(response, reverse('login'))
<|code_end|>
. Write the next line us... | def test_home_logged_in(self): |
Given snippet: <|code_start|>
class HomePageTests(TestCase):
def setUp(self):
self.user = UserFactory()
def test_home_not_logged_in(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib.auth.models import User
from django.core.management impor... | c = Client() |
Next line prediction: <|code_start|>
urlpatterns = [
# login/logout
url(r'^logout/$', auth_logout, name='logout'),
url(r'^login/$', views.login, name='login'),
url(r'^login_redirect/$', views.login_redirect, name='login_redirect'),
# password reset
url(r'^password-reset/$',
password_r... | password_reset_confirm, |
Continue the code snippet: <|code_start|> ctx = {}
user_id = request.user.id
user = User.objects.get(id=user_id)
user_debt_loans = DebtLoan.objects.filter(user=user, active=True)
user_debt_loans = user_debt_loans.order_by('-created')
ctx['user'] = user
ctx['debt_loans'] = user_debt_loans
... | return render(request, 'debt_loan_create.html', {'form': form}) |
Predict the next line for this snippet: <|code_start|>@login_required
def transaction_list_filter(request):
fltr = request.GET.get('filter', None)
request.session['filter:transaction_list'] = fltr
return redirect(reverse('transaction_list'))
@login_required
def transaction_create(request):
form = form... | return render(request, 'transaction_create.html', {'form': form}) |
Given the code snippet: <|code_start|>
@login_required
def transaction_list(request):
ctx = {}
user_id = request.user.id
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.url... | user = User.objects.get(id=user_id) |
Given snippet: <|code_start|> ctx['fltr'] = fltr
else:
# make 'this_month' filter default
user_transactions = services.get_months_transactions(user)
ctx['fltr'] = 'this_month'
user_transactions = user_transactions.order_by('-created')
ctx['user'] = user
ctx['transactions... | def transaction_create(request): |
Given the following code snippet before the placeholder: <|code_start|>
class LoginTests(TestCase):
def setUp(self):
self.user = UserFactory()
def test_login_get(self):
c = Client()
response = c.get(reverse('login'))
self.assertEqual(200, response.status_code)
def test_lo... | follow=True |
Predict the next line for this snippet: <|code_start|>
urlpatterns = [
# Examples:
url(r'^$', finance_views_home, name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include(accounts_urls)),
url(r'^books/', include(books_urls)),... | urlpatterns.append( |
Predict the next line after this snippet: <|code_start|>
urlpatterns = [
# Examples:
url(r'^$', finance_views_home, name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include(accounts_urls)),
url(r'^books/', include(books_urls)... | url(r'^__debug__/', include(debug_toolbar.urls)), |
Given the code snippet: <|code_start|>
urlpatterns = [
# Examples:
url(r'^$', finance_views_home, name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include(accounts_urls)),
url(r'^books/', include(books_urls)),
] + static(sett... | url(r'^__debug__/', include(debug_toolbar.urls)), |
Next line prediction: <|code_start|> # Three sources: a <- b <-c
# simply test the structure of resulting connectivity measures
b0 = np.array([[0, 0.9, 0], [0, 0, 0.9], [0, 0, 0]])
identity = np.eye(3)
nfft = 5
c = connectivity.Connectivity(b=b0, c=identity, nfft=nfft)
... | self.assertEqual(k(c.pCOH())[0, 2], 0) |
Next line prediction: <|code_start|> self.assertRaises(AttributeError, csp, np.random.randn(3,10), [1,1,0,0] )
# number of class labels does not match number of trials
self.assertRaises(AttributeError, csp, np.random.randn(5,3,10), [1,1,0,0] )
def testInputSafety(self):
... | self.X[self.C == 0, 2, :] *= 5 |
Given the following code snippet before the placeholder: <|code_start|># Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2014 SCoT Development Team
eeglocs = [p.list for p in _eeglocs]
class TestWarpLocations(unittest.TestCase):
def setUp(self):
pass
def... | self.assertEqual(warp_locations(np.eye(3)).shape, (3, 3)) # returns array |
Here is a snippet: <|code_start|> cls.register = Library('test')
def test_register_function1(self):
@self.register.register
def test():
pass
self.assertIs(self.register.get('test'), test)
def test_register_function2(self):
@self.register.register()
d... | register = Library('namespace') |
Next line prediction: <|code_start|>
self.assertEqual(set(plugins.keys()), set(renders.keys()))
class LibraryTests(TestCase):
@classmethod
def setUpClass(cls):
cls.register = Library('test')
def test_register_function1(self):
@self.register.register
def test():
... | def test_register_get_global(self): |
Continue the code snippet: <|code_start|>
class Library(BaseLibrary):
pass
class AchillesRendersTests(TestCase):
def test_achilles_renders(self):
plugins = achilles_plugins()
renders = achilles_renders()
self.assertEqual(set(plugins.keys()), set(renders.keys()))
class LibraryTest... | @classmethod |
Next line prediction: <|code_start|> out = Template(
"{% load achilles %}"
"{% ablock 'message' %}").render(Context())
self.assertEqual(out, '<div data-ablock="message">foo\n</div>')
def test_render_function_block_returning_same_context(self):
@self.register.block(tem... | "{% ablock 'message' %}").render(Context()) |
Predict the next line for this snippet: <|code_start|> 'id': '2',
'args': [2],
},
{
'name': 'action',
'id': '3',
'kwargs': {'param': 33},
},
])
data = actions.render(self.transport)
... | self.assertEqual(data["1"]["error"], 'ValueError') |
Predict the next line for this snippet: <|code_start|>
class ActionsTests(TestCase):
@classmethod
def setupClass(cls):
cls.register = actions.Library()
def setUp(self):
<|code_end|>
with the help of current file imports:
from django.test import RequestFactory
from django.test import TestCase
f... | request = RequestFactory().get('/path') |
Given snippet: <|code_start|>
class ActionsTests(TestCase):
@classmethod
def setupClass(cls):
cls.request_factory = RequestFactory()
def setUp(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import RequestFactory, TestCase
from django... | self.request = self.request_factory.post( |
Predict the next line for this snippet: <|code_start|>
register = blocks.Library('messages')
def render(request):
return [
{
'level': message.level,
'message': message.message,
'tags': message.tags,
'extra_tags': message.extra_tags,
<|code_end|>
with the h... | } |
Based on the snippet: <|code_start|>
register = actions.Library('example')
@register.action
def multiply(transport, a, b):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib import messages
from achilles import actions, blocks, console
and context (classes, functions, some... | messages.info(request, 'Multiplication done') |
Using the snippet: <|code_start|>
register = actions.Library('example')
@register.action
def multiply(transport, a, b):
messages.info(request, 'Multiplication done')
return float(a) * float(b)
@register.action
def divide(transport, a, b):
messages.info(request, 'Division done')
return float(a) / flo... | def log(transport): |
Here is a snippet: <|code_start|>
def endpoint(request):
if request.method != 'POST':
return HttpResponseBadRequest()
<|code_end|>
. Write the next line using the current file imports:
from django.http import HttpResponseBadRequest, HttpResponse
from django.conf import settings
from django.test.client ... | match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE']) |
Predict the next line for this snippet: <|code_start|>
def endpoint(request):
if request.method != 'POST':
return HttpResponseBadRequest()
match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE'])
if match:
charset = match.group(1)
else:
charset = settings.DEFAULT_CHARSET
... | result[namespace] = render(transport) |
Predict the next line for this snippet: <|code_start|>
def endpoint(request):
if request.method != 'POST':
return HttpResponseBadRequest()
match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE'])
if match:
charset = match.group(1)
else:
charset = settings.DEFAULT_CHARSET
... | data = json.loads(request.body.decode(charset)) |
Here is a snippet: <|code_start|>
class NMapParser(Parser):
type = "parsers.NMap"
def __init__(self, collector):
super(NMapParser, self).__init__(collector)
if os.name == 'nt':
self.script_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "nmap_parser.bat")
el... | self.script_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "nmap_parser.sh") |
Using the snippet: <|code_start|>
def select_folder(self, event):
dialog_select_folder = gtk.FileChooserDialog()
dialog_select_folder.set_title("Export To")
dialog_select_folder.set_transient_for(self)
dialog_select_folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
dia... | if not export_raw and not export_compressed and not export_parsed: |
Given snippet: <|code_start|> hbox_okcancel.pack_start(button_export)
frame_exporttype.add(vbox_exporttype)
frame_exportoptions.add(vbox_exportoptions)
frame_exportto.add(hbox_exportto)
vbox.pack_start(frame_exporttype)
vbox.pack_start(frame_exportoptions)
vbox.pac... | dialog_select_folder.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER) |
Next line prediction: <|code_start|> if self.checkbutton_compress_export.get_active():
self.radiobutton_compress_export_format_zip.set_sensitive(True)
self.radiobutton_compress_export_format_tar.set_sensitive(True)
else:
self.radiobutton_compress_export_format_zip.set_... | if not export_base_dir: |
Given the following code snippet before the placeholder: <|code_start|>
class ManualScreenShotParser(Parser):
type = "parsers.ManualScreenShot"
def __init__(self, collector):
super(ManualScreenShotParser, self).__init__(collector)
if os.name == 'nt':
<|code_end|>
, predict the next line using... | self.script_file = os.path.join( |
Given the code snippet: <|code_start|> self.file_re = file_re
def assert_true(self, file):
return re.match(self.file_re, file)
class Parser(object):
def __init__(self, collector):
self.post_conditions = []
self.collector = collector
self.file_or_dir = collector.output_... | self.status = "running" |
Here is a snippet: <|code_start|>
class TSharkParser(Parser):
type = "parsers.TShark"
def __init__(self, collector):
super(TSharkParser, self).__init__(collector)
if os.name == 'nt':
<|code_end|>
. Write the next line using the current file imports:
import os
import subprocess
import gobject
i... | self.script_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tshark_parser.bat") |
Here is a snippet: <|code_start|>
class SnoopyParser(Parser):
type = "parsers.Snoopy"
def __init__(self, collector):
super(SnoopyParser, self).__init__(collector)
if os.name == 'nt':
self.script_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "snoopy_parser.bat")
... | else: |
Given snippet: <|code_start|>
class manualscreenshot(ManualCollector):
def __init__(self, collector_config):
super(manualscreenshot, self).__init__(collector_config)
self.command_description = "Take Screenshot"
def build_commands(self):
self.commands.append("python takeshoot.py")
... | if not os.path.exists(self.output_dir): |
Given the following code snippet before the placeholder: <|code_start|> menu.append(main_application_menu_item)
main_application_menu_item.connect('activate', self.show_main_gui, gui)
#separator
sep0 = gtk.SeparatorMenuItem()
sep0.show()
menu.append(sep0)
for col... | self.stopall_menu_item.set_sensitive(False) |
Next line prediction: <|code_start|>
class PyKeyloggerParser(Parser):
def __init__(self, collector):
super(PyKeyloggerParser, self).__init__(collector)
self.click_dir = os.path.join(self.file_or_dir, "click_images")
self.timed_dir = os.path.join(self.file_or_dir, "timed_screenshots")
... | else: |
Given the code snippet: <|code_start|>
class nmap(AutomaticCollector):
def build_commands(self):
option = self.config.get_collector_custom_data()["interfaces"]["additional options"]
network = self.config.get_collector_custom_data()["interfaces"]["ip range"]
out_file_name = "nmap_" + defin... | self.output_filenames.append(out_file_name) |
Given the code snippet: <|code_start|>
class tshark(AutomaticCollector):
#TODO: need plugin type in configs?
#TODO: Use self.output_filepath?
def build_commands(self):
# get additional options from the config file
mode = self.config.get_collector_custom_data()["interfaces"]["mode"]
... | + "-w " + str(out_file_path) |
Given the following code snippet before the placeholder: <|code_start|>
class SetEnqueueResetReverseDns(BaseReverseDns):
def __init__(self, *args, **kwargs):
try:
self.IPs = kwargs.pop('IPs')
except KeyError:
# IPs parameter is not filled
<|code_end|>
, predict the next line... | self.IPs = [] |
Using the snippet: <|code_start|>#!/usr/bin/env python3
sys.path.insert(1,"..")
############################################
#utilites
############################################
def is_networkfilesystem(dir):
return gmeutils.helpers.is_networkfs(dir)
<|code_end|>
, determine the next line of code. You have import... | def has_app(appname): |
Here is a snippet: <|code_start|>
#######
#_alert
#######
def _alert(self):
if self.alarmfunc:
self.alarmfunc(*self.alarmfuncargs,**self.kwalarmfuncargs)
self.running=False
##############
#_create_timer
##############
def _create_timer(self):
self.alarm=threading.Timer( self.timer,
self._... | return self.running |
Based on the snippet: <|code_start|> #unpackingformats
#################
def unpackingformats(self):
return ["SHAR"]
##################
#uncompresscommand
##################
@_dbg
def uncompresscommand( self,
sourcefile,
directory,
password=None):
cmd=[ self.cmd,
"\"%s\""%sourc... | if y!=txt: |
Using the snippet: <|code_start|>
def __init__(self,parent):
_baseunpacker.__init__(self,parent,chdir=True)
self.cmd=shutil.which("kgb")
#################
#unpackingformats
#################
def unpackingformats(self):
return ["KGB"]
##################
#uncompresscommand
##################
@_dbg
def... | class _LHA(_baseunpacker): |
Given the code snippet: <|code_start|> "SOPHOS"
]
#################
#get_virusscanner
#################
def get_virusscanner(scanner,parent):
scanner=scanner.upper().strip()
try:
if scanner=="AVAST":
s= _AVAST(parent=parent)
if s.cmd and len(s.cmd)>0:
return s
if scanner=="AVG":
s= _AVG(p... | return s |
Next line prediction: <|code_start|> raise NotImplementedError
#######
#_AVAST
#######
class _AVAST(_basevirusscanner):
def __init__(self,parent):
self.cmd=shutil.which("scan")
_basevirusscanner.__init__(self,parent)
@_dbg
def has_virus(self,directory):
cmd=[self.cmd,"-u",directory]
result=False
infor... | virusinfo=found[1][:-1] |
Next line prediction: <|code_start|> "-in",self._filename,
"-out", sourcefile,
"-inkey" , _recipient[2] ]
return cmd
############
#_opensslcmd
############
@_dbg
def _opensslcmd(self,cmd):
result=""
p = subprocess.Popen( cmd.split(" "),
stdin=None,
stdout=subprocess.PIPE,
... | "-text", |
Based on the snippet: <|code_start|> @_dbg
def get_certemailaddresses(self,certfile):
"""returns a list of all e-mail addresses the 'certfile' for which
is valid."""
cmd=[ self.parent._SMIMECMD,
"x509",
"-in",certfile,
"-text",
"-noout"]
cert,returncode=self._opensslcmd(" ".join(cmd))
cert=... | pass |
Using the snippet: <|code_start|> "timezone":"часовои пояс",
"_date":"0:%d.%m.%Y",
"_time":"%H:%M",
},
"SE":{ "appointment":"möte",
"file":"fil",
"content":"innehåll",
"attachment":"bilaga",
"passwordfor":"Lösenord för",
"_date":"0:%Y-%m-%d",
"_time":"%H:%M",
},
"US":{ "_date":"0:%m/%d/%Y",
"_tim... | except: |
Continue the code snippet: <|code_start|> self.push("454 TLS not available due to temporary reason")
self.parent.log("STARTTLS called, but is not active","w",filename=__file__,lineno=inspect.currentframe().f_lineno)
return
if arg:
self.push("501 Syntax error: no arguments allowed")
return
self.pu... | if command in ["TRUE","ON","YES"] : |
Given the following code snippet before the placeholder: <|code_start|> "error decode base64 '%s'"%
sys.exc_info()[1],filename=__file__,lineno=inspect.currentframe().f_lineno)
d=[]
if len(d)<2:
self.push("454 Temporary authentication failure.")
return
while len(d)>2:
del d[0]
us... | self.push("454 Temporary authentication failure.") |
Predict the next line for this snippet: <|code_start|> self._tabledefinition["encryptionmapindex"]=(
"create unique index eindex"
" on encryptionmap (\"user\");")
self._tabledefinition["pgpencryptsubject"]=("create table \"pgpencryptsubject\" ("
"\"user\" varchar (255) not null ,"
"\"encryptsubj... | "\"encryptionkey\");") |
Given the code snippet: <|code_start|> result=list()
for user in self._smimeuser:
result.append(user)
return result
##################
#smimeprivate_keys
##################
@_dbg
def smimeprivate_keys(self):
"returns a list of all available private keys"
result=list()
for user in self._smimeuse... | def set_pdfpassword(self,user,password,autodelete=True): |
Next line prediction: <|code_start|> self._prepare_syslog()
elif logmode=="stderr":
self._LOGGING=self.l_stderr
else:
self._LOGGING=self.l_none
############
#get_logging
############
@_dbg
def get_logging( self):
if self._LOGGING==self.l_syslog:
return "syslog"
elif self._LOGGING==self.l_... | mode='a', |
Using the snippet: <|code_start|> elif l=='stderr':
self._LOGGING=self.l_stderr
else:
self._LOGGING=self.l_none
except:
pass
try:
self._LOGFILE=cfg.get('logging','file')
except:
pass
try:
self._DEBUG=cfg.getboolean('logging','debug')
except:
pass
try:
s=cfg... | if len(e)>0: |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
#License GPL v3
#Author Horst Knorr <gpgmailencrypt@gmx.de>
host="localhost"
port=10025
cl=sys.argv[1:]
try:
host=cl[0]
port=int(cl[1])
<|code_end|>
, predict the next line using imports from the current file:
import sys
f... | except: |
Given snippet: <|code_start|>
#################
#_basespamchecker
#################
class _basespamchecker(_gmechild):
def __init__(self,parent,leveldict):
_gmechild.__init__(self,parent=parent,filename=__file__)
self.cmd=None
@_dbg
def set_leveldict(self,leveldict):
raise NotImplementedError
@_dbg
def i... | class _SPAMASSASSIN(_basespamchecker): |
Here is a snippet: <|code_start|> except:
self.log("Could not convert score to float","e")
if level =="S":
spamlevel=S_SPAM
elif level == "U":
spamlevel=S_MAYBESPAM
return spamlevel,score
################################################################################
####################
#ge... | if _s.is_available(): |
Predict the next line after this snippet: <|code_start|>cookies = cookielib.LWPCookieJar()
handlers = [
urllib2.HTTPHandler(),
urllib2.HTTPCookieProcessor(cookies)
]
opener = urllib2.build_opener(*handlers)
def fetch_raw(url, data=None, content_type='application/json'):
if not data:
req = urllib... | try: |
Here is a snippet: <|code_start|> urllib2.HTTPHandler(),
urllib2.HTTPCookieProcessor(cookies)
]
opener = urllib2.build_opener(*handlers)
def fetch_raw(url, data=None, content_type='application/json'):
if not data:
req = urllib2.Request(url)
else:
data_bytes = json.dumps(data)
r... | except urllib2.HTTPError as he: |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division
try: # pragma: nocoverage
except ImportError: # pragma: nocoverage
class CommandTest:
def setup(self):
self.app = Flask('alchemist')
self.app.config['COMPONENTS'] = ['... | manager = management.Manager(self.app) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class TestSettings:
def test_project(self):
self.app = Flask('alchemist.tests.a')
with settings(self.app):
alchemist.configure(self.app)
<|code_end|>
using the current file's imports:
from alchemist.tes... | assert self.app.config.get('A_SETTING', 1) |
Given snippet: <|code_start|>
with raises(exceptions.ImproperlyConfigured):
db.engine['default']
def test_usage(self):
uri = 'sqlite:///:memory:'
with settings(self.app, DATABASES={'default': uri}):
with contextlib.closing(db.engine.connect()) as connection... | assert db.engine.url.drivername == 'sqlite' |
Given snippet: <|code_start|> self.fail('Set your SHIPPO_API_KEY in your os.environ')
except Exception as inst:
self.fail("Test failed with exception %s" % inst)
def test_list_accessors(self):
try:
address = shippo.Address.create(**DUMMY_ADDRESS)
except sh... | self.fail("Test failed with exception %s" % inst) |
Based on the snippet: <|code_start|> self.assertRaises(shippo.error.APIConnectionError,
shippo.Address.create)
finally:
shippo.config.api_base = api_base
def test_run(self):
try:
address = shippo.Address.create(**DUMMY_ADDRESS)
... | '☃') |
Based on the snippet: <|code_start|> def test_dns_failure(self):
api_base = shippo.config.api_base
try:
shippo.config.api_base = 'https://my-invalid-domain.ireallywontresolve/v1'
self.assertRaises(shippo.error.APIConnectionError,
shippo.Address.cr... | def test_unicode(self): |
Given snippet: <|code_start|> yield (key, value)
def _build_api_url(url, query):
scheme, netloc, path, base_query, fragment = urllib.parse.urlsplit(url)
if base_query:
query = '%s&%s' % (base_query, query)
return urllib.parse.urlunsplit((scheme, netloc, path, query, fragment))
class... | method.lower(), url, params) |
Given the following code snippet before the placeholder: <|code_start|> Unfortunately the interface to OpenSSL doesn't make it easy to check
the certificate before sending potentially sensitive data on the wire.
This approach raises the bar for an attacker significantly."""
if verify_ss... | uri.hostname, der_cert) |
Predict the next line for this snippet: <|code_start|>
def interpret_response(self, rbody, rcode):
try:
if hasattr(rbody, 'decode'):
rbody = rbody.decode('utf-8')
if rbody == '':
rbody = '{"msg": "empty_response"}'
resp = util.json.... | uri = urllib.parse.urlparse(shippo.config.api_base) |
Given snippet: <|code_start|>
def _build_api_url(url, query):
scheme, netloc, path, base_query, fragment = urllib.parse.urlsplit(url)
if base_query:
query = '%s&%s' % (base_query, query)
return urllib.parse.urlunsplit((scheme, netloc, path, query, fragment))
class APIRequestor(object):
_CER... | resp = self.interpret_response(rbody, rcode) |
Here is a snippet: <|code_start|>
def _encode_datetime(dttime):
if dttime.tzinfo and dttime.tzinfo.utcoffset(dttime) is not None:
utc_timestamp = calendar.timegm(dttime.utctimetuple())
else:
utc_timestamp = time.mktime(dttime.timetuple())
return int(utc_timestamp)
def _api_encode(data):... | yield ("%s[]" % (key,), subvalue) |
Predict the next line after this snippet: <|code_start|> # are succeptible to the same and should be updated.
content = result.content
status_code = result.status_code
except Exception as e:
# Would catch just requests.exceptions.RequestException, but can
... | class UrlFetchClient(HTTPClient): |
Using the snippet: <|code_start|>
if id:
self['object_id'] = id
def __setattr__(self, k, v):
if k[0] == '_' or k in self.__dict__:
return super(ShippoObject, self).__setattr__(k, v)
else:
self[k] = v
def __getattr__(self, k):
if k[0] == '_':
... | if not hasattr(self, '_unsaved_values'): |
Here is a snippet: <|code_start|>
def __init__(self, id=None, api_key=None, **params):
super(ShippoObject, self).__init__()
self._unsaved_values = set()
self._transient_values = set()
self._retrieve_params = params
self._previous_metadata = None
object.__setattr__(... | def __setitem__(self, k, v): |
Here is a snippet: <|code_start|>
super(ShippoObject, self).__setitem__(k, v)
# Allows for unpickling in Python 3.x
if not hasattr(self, '_unsaved_values'):
self._unsaved_values = set()
self._unsaved_values.add(k)
def __getitem__(self, k):
try:
retu... | def construct_from(cls, values, api_key): |
Here is a snippet: <|code_start|> def class_name(cls):
if cls == APIResource:
raise NotImplementedError(
'APIResource is an abstract class. You should perform '
'actions on its subclasses (e.g. Address, Parcel)')
return str(urllib.parse.quote_plus(cls.__na... | response, api_key = requestor.request('post', url, params) |
Based on the snippet: <|code_start|> return client.request(method, url, headers, post_data)
def mock_response(self, body, code):
raise NotImplementedError(
'You must implement this in your test subclass')
def mock_error(self, error):
raise NotImplementedError(
'Y... | self.assertEqual('{"status": "ok"}', body) |
Continue the code snippet: <|code_start|>
class APIRequestorTests(TestCase):
def test_oauth_token_auth(self):
mock_client = Mock()
mock_client.name = 'mock_client'
mock_client.request.return_value = ('{"status": "ok"}', 200)
requestor = api_requestor.APIRequestor(
key... | ) |
Predict the next line for this snippet: <|code_start|># coding=utf-8
register_standard_logs('output', __file__)
mod = Model()
country = Country(mod, 'CO')
Household(country, 'HH')
gov = ConsolidatedGovernment(country, 'GOV')
FixedMarginBusiness(country, 'BUS')
Market(country, 'GOOD')
<|code_end|>
with the help of cu... | Market(country, 'LAB') |
Given the following code snippet before the placeholder: <|code_start|>
License/Disclaimer
------------------
Copyright 2017 Brian Romanchuk
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
ht... | It will not overwrite existing files; it is recommended that you clear out your local copy of the examples directory before installing an updated examples set. |
Predict the next line after this snippet: <|code_start|> Household(country, 'HH')
ConsolidatedGovernment(country, 'GOV')
FixedMarginBusiness(country, 'BUS')
Market(country, 'GOOD')
Market(country, 'LAB')
TaxFlow(country, 'TAX', taxrate=.2)
mod.AddExogenous('GOV', 'DEM_GOOD', [15.,]*5 + [gover... | p.DoPlot() |
Predict the next line for this snippet: <|code_start|>
class TestBaseSolver(TestCase):
def test_CsvString(self):
obj = BaseSolver(['x', 'y', 't'])
<|code_end|>
with the help of current file imports:
from unittest import TestCase
from sfc_models.base_solver import BaseSolver
and context from other files... | obj.x = [1., 1., 1.] |
Here is a snippet: <|code_start|>0.498641604188
>>> best_options['c1']
1
>>> best_options['c2']
1
"""
# Import from __future__
from __future__ import absolute_import, print_function, with_statement
# Import standard library
# Import from pyswarms
# Import from package
class GridSearch(SearchBase):
"""Exhaustiv... | ): |
Given snippet: <|code_start|>>>> options = {'c1': [1, 5],
'c2': [6, 10],
'w' : [2, 5],
'k' : [11, 15],
'p' : 1}
>>> g = RandomSearch(LocalBestPSO, n_particles=40, dimensions=20,
options=options, objective_func=sphere, iters=10)
>>> best_scor... | def assertions(self): |
Here is a snippet: <|code_start|>
return obj_with_args_
@pytest.fixture
def obj_without_args(self):
"""Objective function without arguments"""
return rosenbrock
@pytest.mark.parametrize(
"history, expected_shape",
[
("cost_history", (1000,)),
... | def test_ftol_effect(self, options, optimizer): |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Import modules
# Import from pyswarms
np.random.seed(4135157)
class TestVonNeumannTopology(ABCTestTopology):
@pytest.fixture
def topology(self):
return VonNeumann
@pytest.fixture
<|code_end|>
, continue by predicting ... | def options(self): |
Next line prediction: <|code_start|>
# Python 2.7 compat shims
to_bytes_be = lambda x, sz: x.to_bytes(sz, 'big')
try:
to_bytes_be(int(1), 1)
except AttributeError:
to_bytes_be = lambda x, sz: '{:0{}x}'.format(x, sz * 2).decode('hex')
from_bytes_be = lambda x: int.from_bytes(x, 'big')
try:
from_bytes_be(t... | def encrypt(self, raw): |
Given snippet: <|code_start|>
def emit_challenge(self, cmask):
ts128 = clock_getntime(CLOCK_MONOTONIC) << len(DGST_PRIOS)
for ms in cmask:
ts128 |= ms
cryptic = self.ac.encrypt(to_bytes_be(ts128, AES.block_size))
#return cryptic
return cryptic.decode()
def va... | self.nonce = nonce |
Predict the next line after this snippet: <|code_start|>#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOL... | if not 'UaStateDead' in globals(): |
Given the code snippet: <|code_start|># (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN... | return SipAllow(methods = self.methods) |
Predict the next line for this snippet: <|code_start|># this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, B... | ua.expire_timer = None |
Given the following code snippet before the placeholder: <|code_start|>#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the ... | rs = SipRSeq(body = '50') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.