Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> self._loaded_plugins[plugin_name] = plugin
return plugin
def list_plugins(self) -> Dict[str, Dict[str, Any]]:
valid_classes = [
'ArchiverPlugin',
'BasePlugin',
'ProviderPlugin',
'WorkerPlugin',
... | 'classes': plugin_classes, |
Next line prediction: <|code_start|> predicate=lambda mem: inspect.isclass(mem)
and issubclass(mem, BasePlugin)
and mem
not in [
ArchiverPlugin,
BasePlugin,
ProviderPlugin,
WorkerPlugin,
Connec... | ) and self._stoq_config.has_section( # pyre-ignore[16] |
Predict the next line for this snippet: <|code_start|> if parse_version(__version__) < parse_version(min_stoq_version):
self.log.warning(
f'Plugin {plugin_name} not compatible with this version of '
'stoQ. Unpredictable results may occur!'
... | if len(plugin_classes) > 1: |
Given snippet: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# http://www.apache.org/... | pass |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# ... | pass |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# http://www.apac... | pass |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# ... | return None |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# http://www.ap... | return None |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# http://www.apac... | return None |
Continue the code snippet: <|code_start|> ) -> None:
if github:
if plugin_path.startswith('git+http'):
pass
elif plugin_path.startswith('stoq:'):
plugin_name = plugin_path.split(':')[1]
plugin_path = f'{StoqPluginInstaller.DEFAULT_REPO}#... | .replace('.git', '') |
Next line prediction: <|code_start|> .split('#')[0]
.replace('.git', '')
.replace('github.com', 'raw.githubusercontent.com')
.replace('@', '/')
)
path = plugin_path.split('subdirectory=')[1]
requirements = f'{url}/{path}/... | subprocess.check_call( |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# http://www... | else: |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# http://www.ap... | else: |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# ... | if any( |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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 L... | for request_payload in request.payloads |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# http://www.apac... | for request_payload in request.payloads |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# http://www.apache.... | ): |
Continue the code snippet: <|code_start|>
class OIDCCallbackView(OIDCAuthenticationCallbackView):
def login_failure(self, msg=''):
if not msg:
msg = ('Login failed. Please make sure that you are '
<|code_end|>
. Use current file imports:
import feedparser
import json
import logging
import ... | 'an accepted Rep or a vouched Mozillian ' |
Predict the next line for this snippet: <|code_start|>
RE_PERIOD = r'period/(?P<period>\w+)/'
RE_START = r'(start/(?P<start>\d{4}\-\d{2}\-\d{2})/)?'
RE_END = r'(end/(?P<end>\d{4}\-\d{2}\-\d{2})/)?'
RE_SEARCH = r'(search/(?P<search>.+?)/)?'
urlpatterns = [
url(r'^new/$', events_views.edit_event, name='events_new_e... | ] |
Based on the snippet: <|code_start|>
LINE_LIMIT = 75
FOLD_SEP = u'\r\n '
COUNTRIES_NAME_TO_CODE = {}
for code, name in product_details.get_regions('en').items():
name = name.lower()
COUNTRIES_NAME_TO_CODE[name] = code
# Yanking filters from Django.
library.filter(strip_tags)
library.filter(defaultfilters... | def thisyear(): |
Given snippet: <|code_start|>
@app.task
def send_remo_mail(subject, recipients_list, sender=None,
message=None, email_template=None, data=None,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from django.conf import settings
from django... | headers=None): |
Given snippet: <|code_start|>
urlpatterns = [
url(r'^$', base_views.main, name='main'),
url(r'^capture-csp-violation$', base_views.capture_csp_violation,
name='capture-csp-violation'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url
... | ] |
Given snippet: <|code_start|>
OPTIONAL_PARAMETER_REGEX = r'(?:/(?P<day>\d+)/(?P<id>\d+))?'
urlpatterns = [
url(r'^(?P<year>\d+)/(?P<month>\w+)%s/$' % OPTIONAL_PARAMETER_REGEX,
views.view_ng_report, name='reports_ng_view_report'),
url(r'^(?P<year>\d+)/(?P<month>\w+)/(?P<day>\d+)/(?P<id>\d+)/edit/$',
... | url(r'^(?P<year>\d+)/(?P<month>\w+)/(?P<day>\d+)/(?P<id>\d+)/delete/$', |
Using the snippet: <|code_start|>
urlpatterns = [
url(r'^$', dashboard_views.dashboard, name='dashboard'),
url(r'^emailmentees/$', dashboard_views.email_mentees, name='email_mentees'),
<|code_end|>
, determine the next line of code. You have imports:
from django.views.generic import RedirectView
from django.c... | url(r'^stats/$', RedirectView.as_view(url='/dashboard/kpi/', permanent=True)), |
Based on the snippet: <|code_start|>
INACTIVE_HIGH = timedelta(weeks=8)
INACTIVE_LOW = timedelta(weeks=4)
@library.filter
<|code_end|>
, predict the immediate next line with the help of imports:
import urlparse
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
fro... | def get_avatar_url(user, size=50): |
Predict the next line after this snippet: <|code_start|>
INACTIVE_HIGH = timedelta(weeks=8)
INACTIVE_LOW = timedelta(weeks=4)
@library.filter
<|code_end|>
using the current file's imports:
import urlparse
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from dja... | def get_avatar_url(user, size=50): |
Using the snippet: <|code_start|>
KPI_WEEKS = 12
# Number of activities
CORE = 4
ACTIVE = 1
CASUAL = 1
INACTIVE = 0
# Activities Thresholds:
# The max period in which we are looking to find reports for a user
# both in past and future, measured in weeks
CASUAL_INACTIVE = 4
ACTIVE_CORE = 2
class UserProfileFilter(d... | jabber = django_filters.CharFilter(name='userprofile__jabber_id') |
Given the following code snippet before the placeholder: <|code_start|>
KPI_WEEKS = 12
# Number of activities
CORE = 4
ACTIVE = 1
CASUAL = 1
INACTIVE = 0
# Activities Thresholds:
# The max period in which we are looking to find reports for a user
# both in past and future, measured in weeks
CASUAL_INACTIVE = 4
ACTI... | functional_areas = django_filters.CharFilter( |
Next line prediction: <|code_start|>
KPI_WEEKS = 12
# Number of activities
CORE = 4
ACTIVE = 1
CASUAL = 1
INACTIVE = 0
# Activities Thresholds:
# The max period in which we are looking to find reports for a user
# both in past and future, measured in weeks
CASUAL_INACTIVE = 4
ACTIVE_CORE = 2
class UserProfileFilter... | irc_name = django_filters.CharFilter(name='userprofile__irc_name') |
Given the code snippet: <|code_start|># Number of activities
CORE = 4
ACTIVE = 1
CASUAL = 1
INACTIVE = 0
# Activities Thresholds:
# The max period in which we are looking to find reports for a user
# both in past and future, measured in weeks
CASUAL_INACTIVE = 4
ACTIVE_CORE = 2
class UserProfileFilter(django_filters.... | linkedin = django_filters.CharFilter(name='userprofile__linkedin_url') |
Given snippet: <|code_start|>
USERNAME_ALGO = getattr(settings, 'OIDC_USERNAME_ALGO', default_username_algo)
@never_cache
@user_passes_test(lambda u: u.groups.filter(Q(name='Rep') | Q(name='Admin')),
login_url=settings.LOGIN_REDIRECT_URL)
@permission_check(permissions=['profiles.can_edit_profiles... | model=UserProfile) |
Here is a snippet: <|code_start|>
EXTEND_VOTING_PERIOD = 48 * 3600 # 48 hours
NOTIFICATION_INTERVAL = 24 * 3600 # 24 hours
ROTM_VOTING_DAYS = 14
<|code_end|>
. Write the next line using the current file imports:
from datetime import date, datetime, timedelta
from operator import or_
from django.conf import set... | def rotm_nomination_end_date(): |
Predict the next line for this snippet: <|code_start|>
USERNAME_ALGO = getattr(settings, 'OIDC_USERNAME_ALGO', default_username_algo)
BOOLEAN_CHOICES = ((True, 'Yes'), (False, 'No'))
# Max period that a user can be unavailable in weeks
MAX_UNAVAILABILITY_PERIOD = 12
# SOP url for leaving the program
LEAVING_SOP_UR... | class InviteUserForm(happyforms.Form): |
Given snippet: <|code_start|> 'getShaders',
'compare',
'consolidate',
]
namedColors = OrderedDict([
("pink", (1, 0.5, 1)), # noqa
("peach", (1, 0.5, 0.5)), # noqa
("red", (1, 0, 0)), # noqa
("darkred", (0.6, 0, 0)), # noqa
... | ("darkblue", (0, 0, 0.4)), # noqa |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import, division, print_function
def mainGroup(create=True, nodes=None):
main = find.mainGroup()
if main:
return main
if create:
# Draw outer arrow shape
main = curve( name='main', d=T... | tagAsMain(main) |
Here is a snippet: <|code_start|>from __future__ import absolute_import, division, print_function
__all__ = [
'autoCropContent',
'identifyContent',
'disperse',
'grab',
<|code_end|>
. Write the next line using the current file imports:
import collections
import math
from ..vendor.Qt import QtGui, Q... | 'grabTable', |
Given the following code snippet before the placeholder: <|code_start|>
PY_2 = sys.version_info[0] == 2 # Crass checking for python 2
try: # python 3 compatibility
long
except NameError:
long = int # long is just an int in py3
try:
except ImportError:
pass
#from pymel.core import optionVar, Callback, c... | 'autoRedistribute', |
Based on the snippet: <|code_start|>
CREDENTIALS = ('test', 'example.com', 'secret')
GARBAGE_LEVEL = 26
class LoginMethodUpgradeTest(stubloader.StubbedTest):
def testUpgrade(self):
p = Portal(IRealm(self.store),
[ICredentialsChecker(self.store)])
<|code_end|>
, predict the immediate... | def loggedIn(xxx_todo_changeme): |
Next line prediction: <|code_start|>
def createDatabase(s):
ls = LoginSystem(store=s)
ls.installOn(s)
acc = ls.addAccount('test', 'example.com', 'asdf')
ss = acc.avatars.open()
gph = GarbageProtocolHandler(store=ss, garbage=7)
gph.installOn(ss)
# ls.addAccount(u'test2', u'example.com', 'ghj... | saveStub(createDatabase) |
Given snippet: <|code_start|>
def createDatabase(s):
ls = LoginSystem(store=s)
ls.installOn(s)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from axiom.userbase import LoginSystem
from axiom.test.test_userbase import GarbageProtocolHandler
from axiom.test.historic.stubloa... | acc = ls.addAccount('test', 'example.com', 'asdf') |
Using the snippet: <|code_start|>class C(object):
__slots__ = ['a', 'b',
'c', 'initialized']
class D:
def activate(self):
self.initialized = 1
self.test = 2
self.a = 3
self.b = 4
self.c = 5
class E(object):
pass
class X(B, A, C, D, E):
pass
cl... | class DecoyDefault(Decoy, DefaultTest): |
Given the following code snippet before the placeholder: <|code_start|>
class A(SlotMachine):
slots = ['a', 'initialized']
class B(SchemaMachine):
test = Attribute()
initialized = SetOnce()
other = SetOnce(default=None)
nondescriptor = 'readable'
method = lambda self: self
class Bsub(B):
... | __slots__ = ['a', 'b', |
Continue the code snippet: <|code_start|>
class A(SlotMachine):
slots = ['a', 'initialized']
class B(SchemaMachine):
test = Attribute()
initialized = SetOnce()
other = SetOnce(default=None)
nondescriptor = 'readable'
method = lambda self: self
class Bsub(B):
pass
class C(object):
__s... | self.a = 3 |
Given the code snippet: <|code_start|> initialized = SetOnce()
other = SetOnce(default=None)
nondescriptor = 'readable'
method = lambda self: self
class Bsub(B):
pass
class C(object):
__slots__ = ['a', 'b',
'c', 'initialized']
class D:
def activate(self):
self.init... | x = 1 |
Given snippet: <|code_start|>
SECRET = 'asdf'
SECRET2 = 'ghjk'
class AccountUpgradeTest(stubloader.StubbedTest):
def testUpgrade(self):
p = Portal(IRealm(self.store),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from twisted.cred.portal import Portal, IRealm
from... | [ICredentialsChecker(self.store)]) |
Using the snippet: <|code_start|>
def createDatabase(s):
ls = LoginSystem(store=s)
installOn(ls, s)
<|code_end|>
, determine the next line of code. You have imports:
from axiom.userbase import LoginSystem
from axiom.dependency import installOn
from axiom.test.historic.stubloader import saveStub
from axiom.tes... | acc = ls.addAccount(u'test', u'example.com', u'asdf') |
Here is a snippet: <|code_start|>
def createDatabase(s):
ls = LoginSystem(store=s)
installOn(ls, s)
acc = ls.addAccount(u'test', u'example.com', u'asdf')
ss = acc.avatars.open()
gph = GarbageProtocolHandler(store=ss, garbage=7)
installOn(gph, ss)
if __name__ == '__main__':
<|code_end|>
. Writ... | saveStub(createDatabase, 0x1240846306fcda3289550cdf9515b2c7111d2bac) |
Given the following code snippet before the placeholder: <|code_start|>
def createDatabase(s):
ls = LoginSystem(store=s)
installOn(ls, s)
acc = ls.addAccount(u'test', u'example.com', u'asdf')
ss = acc.avatars.open()
gph = GarbageProtocolHandler(store=ss, garbage=7)
installOn(gph, ss)
if __nam... | saveStub(createDatabase, 0x1240846306fcda3289550cdf9515b2c7111d2bac) |
Given snippet: <|code_start|># -*- test-case-name: axiom.test.test_attributes,axiom.test.test_reference -*-
hotfix.require('twisted', 'filepath_copyTo')
_NEEDS_FETCH = object() # token indicating that a value was not found
__metaclass__ = type
<|code_end|>
, continue by predicting the next line. C... | class _ComparisonOperatorMuxer: |
Here is a snippet: <|code_start|>
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run
self.calledBack = Deferred()
def dummyRun(cal... | def test_pollingRemoval(self): |
Continue the code snippet: <|code_start|>from __future__ import print_function
def main(storePath, itemID):
assert 'axiom.test.itemtest' not in sys.modules, "Test is invalid."
st = store.Store(filepath.FilePath(storePath))
<|code_end|>
. Use current file imports:
import sys
from axiom import store
from twi... | item = st.getItemByID(itemID) |
Predict the next line after this snippet: <|code_start|> return iter(self._models)
def _sample(self, model, burn=False):
"""
Resample the hyperparameters with burnin if requested."""
if burn:
model = sample(model, self._burn, False, self._rng)[-1]
return sample(mo... | mu = np.mean(mu_, axis=0) |
Predict the next line after this snippet: <|code_start|>
class MCMC(Model):
"""
Model which implements MCMC to produce a posterior over parameterized
models.
"""
def __init__(self, model, n=100, burn=100, rng=None):
self._n = n
self._ndata = 0
self._burn = burn
self.... | self._models = self._sample(model, burn=(self._ndata > 2*nprev)) |
Based on the snippet: <|code_start|> def sample(self, X, size=None, latent=True, rng=None):
rng = rstate(rng)
model = self._models[rng.randint(self._n)]
return model.sample(X, size, latent, rng)
def predict(self, X, grad=False):
# pylint: disable=arguments-differ
parts = ... | parts = [m.get_improvement(f, X, grad) for m in self._models] |
Predict the next line after this snippet: <|code_start|> s = np.tile(s, (size, 1))
return rng.normal(m, s)
def get_logprior(self, theta, grad=False):
logp = np.sum(
- 0.5 * np.log(2 * np.pi * self._s2)
- 0.5 * np.square(theta - self._mu) / self._s2)
if gr... | inner = np.log1p(theta2_inv) |
Based on the snippet: <|code_start|> m = np.tile(m, (size, 1))
s = np.tile(s, (size, 1))
return rng.normal(m, s)
def get_logprior(self, theta, grad=False):
logp = np.sum(
- 0.5 * np.log(2 * np.pi * self._s2)
- 0.5 * np.square(theta - self._mu) / self._... | theta2_inv = (self._scale / theta)**2 |
Continue the code snippet: <|code_start|>
class Horseshoe(Prior):
"""Horseshoe prior where each parameter value is independently distributed
with scale parameter scale[i]."""
bounds = (EPSILON, np.inf)
def __init__(self, scale=1.):
self._scale = np.array(scale, copy=True, ndmin=1)
self... | PRIORS = dict() |
Based on the snippet: <|code_start|>
class TestLogBehaviorClass:
def setup(self):
self.logger = logging.getLogger("charset_normalizer")
self.logger.handlers.clear()
self.logger.addHandler(logging.NullHandler())
self.logger.level = logging.WARNING
def test_explain_true_behavior... | set_logging_handler( |
Here is a snippet: <|code_start|> self.logger.handlers.clear()
self.logger.addHandler(logging.NullHandler())
self.logger.level = logging.WARNING
def test_explain_true_behavior(self, caplog):
test_sequence = b'This is a test sequence of bytes that should be sufficient'
from_by... | set_logging_handler( |
Continue the code snippet: <|code_start|>
class TestLogBehaviorClass:
def setup(self):
self.logger = logging.getLogger("charset_normalizer")
<|code_end|>
. Use current file imports:
import pytest
import logging
from charset_normalizer.utils import set_logging_handler
from charset_normalizer.api import fr... | self.logger.handlers.clear() |
Predict the next line after this snippet: <|code_start|>
try:
except ImportError: # pragma: no cover
PathLike = str # type: ignore
# Will most likely be controversial
# logging.addLevelName(TRACE, "TRACE")
logger = logging.getLogger("charset_normalizer")
explain_handler = logging.StreamHandler()
explain_handler... | sequences: bytes, |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError: # pragma: no cover
PathLike = str # type: ignore
# Will most likely be controversial
# logging.addLevelName(TRACE, "TRACE")
<|code_end|>
with the help of current file imports:
import logging
from os.path import basename, splitext
... | logger = logging.getLogger("charset_normalizer") |
Here is a snippet: <|code_start|>
try:
except ImportError: # pragma: no cover
PathLike = str # type: ignore
# Will most likely be controversial
# logging.addLevelName(TRACE, "TRACE")
logger = logging.getLogger("charset_normalizer")
explain_handler = logging.StreamHandler()
explain_handler.setFormatter(
logg... | chunk_size: int = 512, |
Given the following code snippet before the placeholder: <|code_start|>
try:
except ImportError: # pragma: no cover
PathLike = str # type: ignore
# Will most likely be controversial
# logging.addLevelName(TRACE, "TRACE")
logger = logging.getLogger("charset_normalizer")
explain_handler = logging.StreamHandler()
... | preemptive_behaviour: bool = True, |
Continue the code snippet: <|code_start|>
@pytest.mark.parametrize(
"content, min_expected_ratio, max_expected_ratio",
[
<|code_end|>
. Use current file imports:
import pytest
from charset_normalizer.md import mess_ratio
and context (classes, functions, or code) from other files:
# Path: charset_normalizer/... | ('典肇乎庚辰年十二月廿一,及己丑年二月十九,收各方語言二百五十,合逾七百萬目;二十大卷佔八成,單英文卷亦過二百萬。悉文乃天下有志共筆而成;有意助之,幾網路、隨纂作,大典茁焉。', 0., 0.), |
Continue the code snippet: <|code_start|># Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
try:
HAVE_VOLATILITY = True
rootlogger = logging.getLogger()
# re-use the rootlogger level (so ... | log = logging.getLogger(__name__) |
Given the code snippet: <|code_start|>)
ROOT_URLCONF = 'web.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'web.wsgi.application'
TEMPLATE_DIRS = (
"templates",
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contr... | TEST_RUNNER = 'django.test.runner.DiscoverRunner' |
Continue the code snippet: <|code_start|># Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
log = logging.getLogger(__name__)
BUFSIZE = 16 * 1024
EXTENSIONS = {
<|code_end|>
. Use current file import... | NetlogParser: ".raw", |
Next line prediction: <|code_start|># Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
log = logging.getLogger(__name__)
BUFSIZE = 16 * 1024
EXTENSIONS = {
<|code_end|>
. Use current file imports:
(... | NetlogParser: ".raw", |
Using the snippet: <|code_start|> # Try via chardet.
if not result and HAVE_CHARDET:
result = chardet_enc(s)
# If not possible to convert the input string, try again with
# a replace strategy.
if not result:
result = unicode(s, errors="replace")
return result
def cleanup_value(... | def classlock(f): |
Here is a snippet: <|code_start|>
if sys.version_info >= (3, 8): # pragma: no cover
else: # pragma: no cover
_PortalFactoryType = typing.Callable[
[], typing.ContextManager[anyio.abc.BlockingPortal]
]
# Annotations for `Session.request()`
Cookies = typing.Union[
typing.MutableMapping[str, str], requests... | TimeOut = typing.Union[float, typing.Tuple[float, float]] |
Continue the code snippet: <|code_start|>
if sys.version_info >= (3, 8): # pragma: no cover
else: # pragma: no cover
_PortalFactoryType = typing.Callable[
[], typing.ContextManager[anyio.abc.BlockingPortal]
]
# Annotations for `Session.request()`
Cookies = typing.Union[
typing.MutableMapping[str, str], ... | TimeOut = typing.Union[float, typing.Tuple[float, float]] |
Using the snippet: <|code_start|>if sys.version_info >= (3, 8): # pragma: no cover
else: # pragma: no cover
_PortalFactoryType = typing.Callable[
[], typing.ContextManager[anyio.abc.BlockingPortal]
]
# Annotations for `Session.request()`
Cookies = typing.Union[
typing.MutableMapping[str, str], requests.co... | def get_all(self, key: str, default: str) -> str: |
Here is a snippet: <|code_start|>
if sys.version_info >= (3, 8): # pragma: no cover
else: # pragma: no cover
_PortalFactoryType = typing.Callable[
[], typing.ContextManager[anyio.abc.BlockingPortal]
]
# Annotations for `Session.request()`
Cookies = typing.Union[
typing.MutableMapping[str, str], requests... | Params = typing.Union[bytes, typing.MutableMapping[str, str]] |
Using the snippet: <|code_start|>
if sys.version_info >= (3, 8): # pragma: no cover
else: # pragma: no cover
_PortalFactoryType = typing.Callable[
[], typing.ContextManager[anyio.abc.BlockingPortal]
]
# Annotations for `Session.request()`
Cookies = typing.Union[
typing.MutableMapping[str, str], requests... | typing.Tuple[str, str], |
Based on the snippet: <|code_start|>
class HTTPSRedirectMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
<|code_end|>
, predict the immediate next line with the help of imports:
from starlette.datastruct... | if scope["type"] in ("http", "websocket") and scope["scheme"] in ("http", "ws"): |
Here is a snippet: <|code_start|>
class HTTPSRedirectMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] in ("http", "websocket") and scope["scheme"] in ("http", "ws"):
u... | redirect_scheme = {"http": "https", "ws": "wss"}[url.scheme] |
Predict the next line for this snippet: <|code_start|>
try:
# @contextfunction renamed to @pass_context in Jinja 3.0, to be removed in 3.1
if hasattr(jinja2, "pass_context"):
pass_context = jinja2.pass_context
else: # pragma: nocover
pass_context = jinja2.contextfunction
except ImportErro... | status_code: int = 200, |
Predict the next line after this snippet: <|code_start|>
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future release. "
"Please refer to https://github.com/abersheeran/a2wsgi as a replacement.",
DeprecationWarning,
<|code_end|>
using the current file's imports:
import... | ) |
Given the following code snippet before the placeholder: <|code_start|>
if sys.version_info >= (3, 10): # pragma: no cover
else: # pragma: no cover
P = ParamSpec("P")
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import sys
import typing
from typing import ParamSpec... | class BackgroundTask: |
Based on the snippet: <|code_start|>
class Address(typing.NamedTuple):
host: str
port: int
class URL:
def __init__(
self,
url: str = "",
scope: typing.Optional[Scope] = None,
**components: typing.Any,
) -> None:
if scope is not None:
<|code_end|>
, predict the... | assert not url, 'Cannot set both "url" and "scope".' |
Here is a snippet: <|code_start|> self._url = url
@property
def components(self) -> SplitResult:
if not hasattr(self, "_components"):
self._components = urlsplit(self._url)
return self._components
@property
def scheme(self) -> str:
return self.components.sche... | return self.components.username |
Given snippet: <|code_start|> app = WSGIMiddleware(hello_world)
client = test_client_factory(app)
response = client.get("/")
assert response.status_code == 200
assert response.text == "Hello World!\n"
def test_wsgi_post(test_client_factory):
app = WSGIMiddleware(echo_body)
client = test_cli... | response = client.get("/") |
Based on the snippet: <|code_start|> headers = [
("Content-Type", "text/plain; charset=utf-8"),
("Content-Length", str(len(output))),
]
start_response(status, headers)
return [output]
def raise_exception(environ, start_response):
raise RuntimeError("Something went wrong")
def retu... | assert response.status_code == 200 |
Predict the next line after this snippet: <|code_start|>
class WebSocketState(enum.Enum):
CONNECTING = 0
CONNECTED = 1
DISCONNECTED = 2
class WebSocketDisconnect(Exception):
def __init__(self, code: int = 1000, reason: str = None) -> None:
<|code_end|>
using the current file's imports:
import enum... | self.code = code |
Given the code snippet: <|code_start|>
class WebSocketState(enum.Enum):
CONNECTING = 0
CONNECTED = 1
<|code_end|>
, generate the next line using the imports in this file:
import enum
import json
import typing
from starlette.requests import HTTPConnection
from starlette.types import Message, Receive, Scope, S... | DISCONNECTED = 2 |
Continue the code snippet: <|code_start|>
class WebSocketState(enum.Enum):
CONNECTING = 0
CONNECTED = 1
DISCONNECTED = 2
class WebSocketDisconnect(Exception):
def __init__(self, code: int = 1000, reason: str = None) -> None:
self.code = code
self.reason = reason or ""
class WebSock... | self.client_state = WebSocketState.CONNECTING |
Here is a snippet: <|code_start|>
class WebSocketState(enum.Enum):
CONNECTING = 0
CONNECTED = 1
DISCONNECTED = 2
class WebSocketDisconnect(Exception):
<|code_end|>
. Write the next line using the current file imports:
import enum
import json
import typing
from starlette.requests import HTTPConnection
f... | def __init__(self, code: int = 1000, reason: str = None) -> None: |
Based on the snippet: <|code_start|>
class WebSocketState(enum.Enum):
CONNECTING = 0
CONNECTED = 1
DISCONNECTED = 2
class WebSocketDisconnect(Exception):
def __init__(self, code: int = 1000, reason: str = None) -> None:
self.code = code
<|code_end|>
, predict the immediate next line with the... | self.reason = reason or "" |
Given the code snippet: <|code_start|> result = cursor.fetchall()
return result
@staticmethod
def updateHistory(clauseSentence,**update):
entry = update
sentence = ''
for key in entry.keys():
sentence += ","+key + " = \'" + str(entry[key])+ "\' "
sente... | if sentence != '' and sentence != None: |
Continue the code snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class BaseDialog(QDialog):
def __init__(self, title):
super().__init__()
self.title = title
def initWindow(self):
self.setWindowTitle(self.title)
self.setWindowIcon(IconTool.buildQIcon('icon.p... | self.center() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class ConfigHelper(object):
LOGCATPATH = ""
#以下是配置信息所对应的key
KEY_LOGCATPATH = 'logcatPath'
@staticmethod
<|code_end|>
with the help of current file imports:
import os
from XulDebugTool.ui.widget.model.d... | def initLogConfigPath(): |
Using the snippet: <|code_start|> else:
try:
url = XulDebugServerHelper.HOST + XulDebugServerHelper.__REQUEST_FOCUS + '/' + id
http = urllib3.PoolManager()
STCLogger().i("focusChooseItemUrl = " + url)
r = http.request('GET', url)
... | @staticmethod |
Using the snippet: <|code_start|>
def index(self, row, column, parent=None, *args, **kwargs):
parentItem = self.getItem(parent)
childItem = parentItem.child(row)
if childItem is not None:
return self.createIndex(row, column, childItem)
else:
return QModelInde... | self.items = [] |
Predict the next line for this snippet: <|code_start|> script.setSourceCode(f.read())
script.setInjectionPoint(QWebEngineScript.DocumentReady)
script.setName(name)
script.setWorldId(QWebEngineScript.MainWorld)
page.scripts().insert(script)
@staticmethod
def findNodeById(i... | def getWindowHeight(): |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/11/8 11:17
# @Author : Mrlsm -- starcor
class SettingWindow(BaseWindow):
def __init__(self):
super().__init__()
self.qObject = QObject()
self.initUI()
self.show()
def initUI(self):
... | self.infoSplitter.addWidget(self.infoList) |
Next line prediction: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class ConsoleWindow(QMainWindow):
global textEdit
def __init__(self, parent=None):
super(ConsoleWindow, self).__init__(parent)
self.isConUrl = False
# 上
self.searchButton = QLineEdit()
sel... | self.combo = QComboBox(self); |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class ConsoleWindow(QMainWindow):
global textEdit
def __init__(self, parent=None):
super(ConsoleWindow, self).__init__(parent)
self.isConUrl = False
# 上
self.searchButton = QLi... | self.combo.setCurrentIndex(0) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class ConfigurationDB(QObject):
@staticmethod
def saveConfiguration(key ,value):
if key == None or len(str(key))<1:
<|code_end|>
, generate the next line using the imports in this file:
import sqlite3
from PyQt5.QtCore import QObject
f... | return |
Given the following code snippet before the placeholder: <|code_start|> self.initWindowTitle()
self.initAboutTitle()
self.initProduction()
self.initGitAddress()
self.initCompanyAddress()
self.initVersionNumber()
def initVersionNumber(self):
self.versionNumber ... | def initProduction(self): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.