Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>
try:
except ImportError:
__all__ = [
'hmac_sha1',
'derive_key',
'der_pack',
'der_read',
'get_random_bytes'
]
#
# OATH related
#
def hmac_sha1(secret, message):
return HMAC.new(secret, message, digestmod=SHA).digest()
d... | def parse_truncated(resp): |
Next line prediction: <|code_start|>
class CardStatus:
NoCard, InUse, Present = range(3)
class CardWatcher(QtCore.QObject):
status_changed = QtCore.Signal(int)
def __init__(self, reader_name, callback, parent=None):
super(CardWatcher, self).__init__(parent)
self._status = CardStatus.NoCa... | if self.reader_name in reader.name: |
Using the snippet: <|code_start|> self._callback()
del self._callback
class Worker(QtCore.QObject):
_work_signal = QtCore.Signal(tuple)
_work_done_0 = QtCore.Signal()
@default_messages(_Messages)
def __init__(self, window, m):
super(Worker, self).__init__()
self.m = m
... | if isinstance(fn, tuple): |
Using the snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Additional permission under GNU GPL version 3 section 7
#
# If you modify this program, or any covered work, by linking or
# combining it with t... | del self._callback |
Continue the code snippet: <|code_start|>
from __future__ import absolute_import
class _Messages(object):
wait = 'Please wait...'
class _Event(QtCore.QEvent):
EVENT_TYPE = QtCore.QEvent.Type(QtCore.QEvent.registerEventType())
def __init__(self, callback):
super(_Event, self).__init__(_Event.EV... | self._work_signal.connect(self.work) |
Predict the next line for this snippet: <|code_start|># This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have recei... | class LegacyOathCcid(object): |
Next line prediction: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without eve... | 0x38 |
Continue the code snippet: <|code_start|># This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed... | 0x30, |
Based on the snippet: <|code_start|>#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in... | -1, |
Continue the code snippet: <|code_start|># This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of... | class LegacyOathCcid(object): |
Given the code snippet: <|code_start|># This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of th... | class LegacyOathCcid(object): |
Next line prediction: <|code_start|># combining it with the OpenSSL project's OpenSSL library (or a
# modified version of that library), containing parts covered by the
# terms of the OpenSSL or SSLeay licenses, We grant you additional
# permission to convey the resulting work. Corresponding Source for a
# non-source f... | TAG_T_RESPONSE = 0x76 |
Using the snippet: <|code_start|>SCHEME_STANDARD = 0x00
SCHEME_STEAM = 0x01
STEAM_CHAR_TABLE = "23456789BCDFGHJKMNPQRTVWXY"
def format_code_steam(int_data, digits):
chars = []
for i in range(5):
chars.append(STEAM_CHAR_TABLE[int_data % len(STEAM_CHAR_TABLE)])
int_data //= len(STEAM_CHAR_TABLE... | h = hashlib.sha1() |
Here is a snippet: <|code_start|># permission to convey the resulting work. Corresponding Source for a
# non-source form of such a combination shall include the source code
# for the parts of OpenSSL used as well as that of the covered work.
from __future__ import print_function, division
YKOATH_AID = b'\xa0\x00\x00... | TAG_VERSION = 0x79 |
Next line prediction: <|code_start|>STEAM_CHAR_TABLE = "23456789BCDFGHJKMNPQRTVWXY"
def format_code_steam(int_data, digits):
chars = []
for i in range(5):
chars.append(STEAM_CHAR_TABLE[int_data % len(STEAM_CHAR_TABLE)])
int_data //= len(STEAM_CHAR_TABLE)
return ''.join(chars)
def ensure_... | else: |
Based on the snippet: <|code_start|>#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of th... | INS_CALCULATE = 0xa2 |
Given the following code snippet before the placeholder: <|code_start|># permission to convey the resulting work. Corresponding Source for a
# non-source form of such a combination shall include the source code
# for the parts of OpenSSL used as well as that of the covered work.
from __future__ import print_function, ... | TAG_VERSION = 0x79 |
Here is a snippet: <|code_start|>TAG_NAME = 0x71
TAG_NAME_LIST = 0x72
TAG_KEY = 0x73
TAG_CHALLENGE = 0x74
TAG_RESPONSE = 0x75
TAG_T_RESPONSE = 0x76
TAG_NO_RESPONSE = 0x77
TAG_PROPERTY = 0x78
TAG_VERSION = 0x79
TAG_IMF = 0x7a
TAG_ALGO = 0x7b
TAG_TOUCH_RESPONSE = 0x7c
TYPE_MASK = 0xf0
TYPE_HOTP = 0x10
TYPE_TOTP = 0x20
... | def format_code_steam(int_data, digits): |
Here is a snippet: <|code_start|>
YKOATH_AID = b'\xa0\x00\x00\x05\x27\x21\x01\x01'
YKOATH_NO_SPACE = 0x6a84
INS_PUT = 0x01
INS_DELETE = 0x02
INS_SET_CODE = 0x03
INS_RESET = 0x04
INS_LIST = 0xa1
INS_CALCULATE = 0xa2
INS_VALIDATE = 0xa3
INS_CALC_ALL = 0xa4
INS_SEND_REMAINING = 0xa5
RESP_MORE_DATA = 0x61
TAG_NAME = 0x7... | TYPE_HOTP = 0x10 |
Continue the code snippet: <|code_start|># (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details... | INS_LIST = 0xa1 |
Predict the next line for this snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Additional ... | INS_SEND_REMAINING = 0xa5 |
Given snippet: <|code_start|>TAG_T_RESPONSE = 0x76
TAG_NO_RESPONSE = 0x77
TAG_PROPERTY = 0x78
TAG_VERSION = 0x79
TAG_IMF = 0x7a
TAG_ALGO = 0x7b
TAG_TOUCH_RESPONSE = 0x7c
TYPE_MASK = 0xf0
TYPE_HOTP = 0x10
TYPE_TOTP = 0x20
ALG_MASK = 0x0f
ALG_SHA1 = 0x01
ALG_SHA256 = 0x02
PROP_ALWAYS_INC = 0x01
PROP_REQUIRE_TOUCH = 0x... | return ''.join(chars) |
Continue the code snippet: <|code_start|># (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details... | INS_LIST = 0xa1 |
Given the code snippet: <|code_start|>TAG_NAME = 0x71
TAG_NAME_LIST = 0x72
TAG_KEY = 0x73
TAG_CHALLENGE = 0x74
TAG_RESPONSE = 0x75
TAG_T_RESPONSE = 0x76
TAG_NO_RESPONSE = 0x77
TAG_PROPERTY = 0x78
TAG_VERSION = 0x79
TAG_IMF = 0x7a
TAG_ALGO = 0x7b
TAG_TOUCH_RESPONSE = 0x7c
TYPE_MASK = 0xf0
TYPE_HOTP = 0x10
TYPE_TOTP = 0... | def format_code_steam(int_data, digits): |
Here is a snippet: <|code_start|>
class SiteTestCase(TestCase):
pass
class SiteFormTestCase(TestCase):
def test_form_validation_success(self):
domain = 'www.google.com'
form = SiteForm(data={'domain': domain})
if form.is_valid():
site = form.save()
self.assertEqu... | domain = 'https://www.google.com' |
Predict the next line after this snippet: <|code_start|> # for given list of tags.
try:
return self._session.query("name", "c").from_statement(sql).all()
except ResourceClosedError:
return []
else:
# First we get a list of item ids
... | (" join items_tags it{1} on it{1}.item_id=it{0}.item_id " + \ |
Next line prediction: <|code_start|> # DataRef objects are deleted from database, if there are no references to it from other alive Items.
# TODO: Make admin users to be able to delete any files, owned by anybody.
item = self._session.query(db.Item).get(item_id)
if item.user_login != us... | if delete_data_ref and data_ref.user_login != user_login: |
Given the code snippet: <|code_start|> Limit affects only if tag_names is empty. In other cases limit is ignored.
If limit == 0 it means there is no limit.
'''
#TODO This command should return list of tags, related to arbitrary list of selected items.
def __init__(self, tag_names=[], user_logins=... | ORDER BY name |
Continue the code snippet: <|code_start|>
def _defaultFormatObj(row, obj, role):
raise NotImplementedError()
class UnivTableColumn(object):
def __init__(self, columnId, title, formatObjFun=_defaultFormatObj,
delegate=QtGui.QStyledItemDelegate(), setDataFun=None):
self.id = columnId
... | def setData(self, obj, row, value, role): |
Using the snippet: <|code_start|>
def is_image(self):
supported = set([".bmp", ".gif", ".jpg", ".jpeg", ".png", ".pbm", ".pgm",
".ppm", ".xbm", ".xpm"])
if self.type and self.type == "FILE" and not is_none_or_empty(self.url):
_root, ext = os.path.splitext(self.... | self.data_ref_id = None |
Given the code snippet: <|code_start|>t_ignore = ' \t\n\r'
def t_error(t):
raise LexError("Lexical error in '{}'".format(t.value[0]))
def build_lexer():
# TODO: use file for logging
#lex_errorlog = ply.lex.PlyLogger(open(os.path.join(USER_CONFIG_DIR, "lex.log"), "w"))
lex_errorlog = lex.NullLogger(... | and:"tag 2" |
Using the snippet: <|code_start|> raise YaccError("Syntax error in '{}'".format(str(p)))
# TODO: use file for logging
#yacc_errorlog = ply.yacc.PlyLogger(open(os.path.join(USER_CONFIG_DIR, "yacc.log"), "w"))
yacc_errorlog = yacc.NullLogger()
tokens # This line is needed to supress warning that 'tokens is unused'
... | FieldA >= 10 FieldB~2010% and some = sdfsdf |
Predict the next line for this snippet: <|code_start|>yacc_errorlog = yacc.NullLogger()
tokens # This line is needed to supress warning that 'tokens is unused'
lexer = build_lexer()
parsetabPyDir = consts.USER_CONFIG_DIR
parser = yacc.yacc(errorlog=yacc_errorlog,
debug=(1 if consts.DEBUG else 0), #... | (FieldA >= 10) |
Based on the snippet: <|code_start|>yacc_errorlog = yacc.NullLogger()
tokens # This line is needed to supress warning that 'tokens is unused'
lexer = build_lexer()
parsetabPyDir = consts.USER_CONFIG_DIR
parser = yacc.yacc(errorlog=yacc_errorlog,
debug=(1 if consts.DEBUG else 0), # If debug yacc cre... | (FieldA >= 10) |
Given snippet: <|code_start|>yacc_errorlog = yacc.NullLogger()
tokens # This line is needed to supress warning that 'tokens is unused'
lexer = build_lexer()
parsetabPyDir = consts.USER_CONFIG_DIR
parser = yacc.yacc(errorlog=yacc_errorlog,
debug=(1 if consts.DEBUG else 0), # If debug yacc creates pa... | (FieldA >= 10) |
Predict the next line after this snippet: <|code_start|> def test_getNonExistingItem(self):
cmd = cmds.GetExpungedItemCommand(context.nonExistingItem.id)
self.assertRaises(err.NotFoundError, self.uow.executeCommand, (cmd))
def test_passBadIdToGetItem(self):
cmd = cmds.GetExpungedItemComm... | nonExistentUserLogin = "NonExistentUserLogin" |
Given the following code snippet before the placeholder: <|code_start|> p[0] = p[1]
def p_error(p):
raise YaccError("Syntax error in '{}'".format(str(p)))
lexer = build_lexer()
# TODO: use file for logging
#yacc_errorlog = ply.yacc.PlyLogger(open(os.path.join(USER_CONFIG_DIR, "yacc.log"), "w"))
yacc_errorlo... | TAG AND MORE TAGS |
Predict the next line for this snippet: <|code_start|> '''
p[0] = p[1]
def p_error(p):
raise YaccError("Syntax error in '{}'".format(str(p)))
lexer = build_lexer()
# TODO: use file for logging
#yacc_errorlog = ply.yacc.PlyLogger(open(os.path.join(USER_CONFIG_DIR, "yacc.log"), "w"))
yacc_errorlog = yacc.... | user : "asdf" |
Next line prediction: <|code_start|>def p_tag(p):
'''tag : STRING
'''
p[0] = p[1]
def p_error(p):
raise YaccError("Syntax error in '{}'".format(str(p)))
lexer = build_lexer()
# TODO: use file for logging
#yacc_errorlog = ply.yacc.PlyLogger(open(os.path.join(USER_CONFIG_DIR, "yacc.log"), "w"))
yacc_... | Tag1 : "Slash\\:quote\" end" |
Next line prediction: <|code_start|> '''
p[0] = p[1]
def p_error(p):
raise YaccError("Syntax error in '{}'".format(str(p)))
lexer = build_lexer()
# TODO: use file for logging
#yacc_errorlog = ply.yacc.PlyLogger(open(os.path.join(USER_CONFIG_DIR, "yacc.log"), "w"))
yacc_errorlog = yacc.NullLogger()
toke... | user : "asdf" |
Given the code snippet: <|code_start|>
class Tag(QueryExpression):
'''
A syntax tree node, representing a Tag.
'''
def __init__(self, name, is_negative=False):
self.name = name
self.is_negative = is_negative
def negate(self):
self.is_negative = not self.is_negative
... | i.*, |
Continue the code snippet: <|code_start|> This slot is usually connected to the 'exception' signal, emitted from a
worker thread.
'''
self.reject()
def closeEvent(self, close_event):
close_event.ignore() # Disable close button (X) of the dialog.
def set_progress(se... | self.setWordWrapMode(QtGui.QTextOption.NoWrap) |
Next line prediction: <|code_start|>
class TextEdit(QtGui.QTextEdit):
'''Modified QTextEdit, that supports Completer class. When user presses shortcut Ctrl+Space,
it shows a completer (if such exists) that helps user to enter tag/field names.'''
def __init__(self, parent=None, completer=None, completer_e... | def text(self): |
Given the following code snippet before the placeholder: <|code_start|>
sys.path.insert(0, os.path.abspath('../'))
# -- Project information -----------------------------------------------------
_year = datetime.datetime.now().year
project = 'pyconll'
author = 'Matias Grioni'
copyright = '{}, {}'.format(_year, auth... | 'sphinx.ext.autodoc', |
Given snippet: <|code_start|>
__author__ = 'Danyang'
class Plotter(object):
def __init__(self):
pass
def _plot(self, models, dist_metric=EuclideanDistance()):
expr = Experiment(froze_shuffle=True)
for model in models:
cv = expr.experiment(model, threshold_up=1, debug=False... | expr.plot_roc(cv) |
Predict the next line for this snippet: <|code_start|>
__author__ = 'Danyang'
class Plotter(object):
def __init__(self):
pass
def _plot(self, models, dist_metric=EuclideanDistance()):
expr = Experiment(froze_shuffle=True)
for model in models:
cv = expr.experiment(model, th... | def plot_energy(self): |
Predict the next line for this snippet: <|code_start|>
class AbstractFeature(object):
def compute(self, X, y):
raise NotImplementedError("Every AbstractFeature must implement the compute method.")
def extract(self, X):
raise NotImplementedError("Every AbstractFeature must implement the extract... | return self.__class__.__name__ |
Using the snippet: <|code_start|>
__author__ = 'Danyang'
class KPCA(AbstractFeature):
def __init__(self, num_components=50, kernel="poly", degree=3, coef0=0.0, gamma=None):
AbstractFeature.__init__(self)
self._num_components = num_components
self._kernel = kernel
self._degree = deg... | self._kpca = None |
Given snippet: <|code_start|>
__author__ = 'Danyang'
class KPCA(AbstractFeature):
def __init__(self, num_components=50, kernel="poly", degree=3, coef0=0.0, gamma=None):
AbstractFeature.__init__(self)
self._num_components = num_components
self._kernel = kernel
self._degree = degree
... | self._coef0 = coef0 |
Predict the next line for this snippet: <|code_start|># Implements various distance metrics (because my old scipy.spatial.distance module is horrible)
class AbstractDistance(object):
def __init__(self, name):
self._name = name
def __call__(self,p,q):
<|code_end|>
with the help of current fil... | raise NotImplementedError("Every AbstractDistance must implement the __call__ method.") |
Based on the snippet: <|code_start|>from __future__ import absolute_import
# TODO The evaluation of a model should be completely moved to the generic ValidationStrategy. The specific Validation
# implementations should only care about partition the data, which would make a lot sense. Currently it is not
# po... | @TP.setter |
Using the snippet: <|code_start|>
# TODO The evaluation of a model should be completely moved to the generic ValidationStrategy. The specific Validation
# implementations should only care about partition the data, which would make a lot sense. Currently it is not
# possible to calculate the true_negatives and ... | return self.rates[1] |
Predict the next line after this snippet: <|code_start|>
class AbstractClassifier(object):
def compute(self, X, y):
raise NotImplementedError("Every AbstractClassifier must implement the compute method.")
def predict(self, X):
<|code_end|>
using the current file's imports:
from facerec_py.facerec.di... | raise NotImplementedError("Every AbstractClassifier must implement the predict method.") |
Based on the snippet: <|code_start|>
class AbstractClassifier(object):
def compute(self, X, y):
raise NotImplementedError("Every AbstractClassifier must implement the compute method.")
<|code_end|>
, predict the immediate next line with the help of imports:
from facerec_py.facerec.distance import Euclide... | def predict(self, X): |
Given the following code snippet before the placeholder: <|code_start|>
# try to import the PIL Image module
try:
except ImportError:
def create_font(fontname='Tahoma', fontsize=10):
return { 'fontname': fontname, 'fontsize':fontsize }
def plot_gray(X, sz=None, filename=None):
if not sz is None:
X ... | def plot_eigenvectors(eigenvectors, num_components, sz, filename=None, start_component=0, rows = None, cols = None, title="Subplot", color=True): |
Next line prediction: <|code_start|>class AbstractPredictableModel(object):
def compute(self, X, y):
raise NotImplementedError("Every AbstractPredictableModel must implement the compute method.")
def predict(self, X):
raise NotImplementedError("Every AbstractPredictableModel must implement the ... | def __repr__(self): |
Given the following code snippet before the placeholder: <|code_start|> return self.classifier.predict(q)
def __repr__(self):
feature_repr = repr(self.feature)
classifier_repr = repr(self.classifier)
return "%s(feature=%s, classifier=%s)" % (self.__class__.__name__, feature_repr, cla... | for elt in ps: |
Predict the next line for this snippet: <|code_start|>
# Fixtures
@pytest.fixture
def path(tmpdir):
path = tmpdir.mkdir('reports').join('report.csv').strpath
return text_type(path)
@pytest.fixture
def report_writer(path):
return reports.ReportWriter(path)
@pytest.fixture
def tsv_writer(path):
retur... | class TestReportWriter(object): |
Based on the snippet: <|code_start|> config['day_start'] = day_start
assert time_helpers.end_day_to_datetime(end_day, config) == expectation
class TestParseTime(object):
@pytest.mark.parametrize(('time', 'expectation'), [
('18:55', datetime.time(18, 55)),
('18:55:34', datetime.time(... | )) |
Predict the next line for this snippet: <|code_start|># -*- encoding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
class TestGetDayEnd(object):
@pytest.mark.parametrize(('day_start', 'expectation'), [
(datetime.time(0, 0, 0), datetime.time(23, 59, 59)),
(datetime.time(5, 3... | def test_various_day_start_times(self, base_config, day_start, expectation): |
Given snippet: <|code_start|>from __future__ import annotations
_TEnum = TypeVar('_TEnum', bound=Enum)
class _FlavourKeyedEnum(Protocol[_TEnum]):
retail: _TEnum
vanilla_classic: _TEnum
burning_crusade_classic: _TEnum
def __getitem__(self, __key: str) -> _TEnum:
...
class Flavour(StrEnum... | burning_crusade_classic = 'classic' |
Given the code snippet: <|code_start|>def _encode_reveal_secret_str(value: object):
if isinstance(value, BaseModel):
return value.dict()
elif isinstance(value, SecretStr):
return value.get_secret_value()
raise TypeError('Unencodable value', value)
class GlobalConfig(_BaseSettings):
con... | _ensure_dirs( |
Next line prediction: <|code_start|>from __future__ import annotations
class _PathNotWritableDirectoryError(PydanticValueError):
code = 'path.not_writable_directory'
msg_template = '"{path}" is not a writable directory'
def _expand_path(value: Path):
return Path(os.path.abspath(os.path.expanduser(val... | try: |
Using the snippet: <|code_start|> if devStoreKey is None:
if self.request.get('key') != 'kiosk':
logging.error("failed to validate the request parameters")
self.response.headers['Content-Type'] = 'application/javascript'
self.response.out.write(json.dumps(api_utils.build... | if callback is not '': |
Given the code snippet: <|code_start|> # validate the key
devStoreKey = api_utils.validateDevKey(request.get('key'))
if devStoreKey is None:
logging.debug('... illegal developer key %s' % request.get('key'))
api_utils.recordDeveloperRequest(None,api_utils.GETSTOPS,request.query_string,request... | elif radius is not None and radius is not '' and radius > '5000': |
Next line prediction: <|code_start|> stop = memcache.get(key)
if stop is None:
logging.warn('stopLocation cache MISS - going to the datastore (%s)' % stopID)
stop = db.GqlQuery('select * from StopLocation where stopID = :1', stopID).get()
if stop is None:
logging.error('stopLo... | return None |
Next line prediction: <|code_start|> else:
self.response.headers['Content-Type'] = 'application/json'
response = json.dumps(json_response)
stathat.apiStatCount()
self.response.out.write(response)
## end RequestHandler
def getLots(soup, response, class_name):
results... | result = None |
Given snippet: <|code_start|>
class MainHandler(webapp.RequestHandler):
# POST not support by the API
def post(self):
self.response.headers['Content-Type'] = 'application/javascript'
self.response.out.write(json.dumps(api_utils.buildErrorResponse('-1','The API does not support POST requests')... | if result: |
Based on the snippet: <|code_start|> self.response.out.write(response)
except DeadlineExceededError:
self.response.clear()
self.response.set_status(500)
self.response.out.write("This operation could not be completed in time...")
# persist some statistics
# stath... | logging.debug('validating stopID %s routeID %s' % (stopID,routeID)); |
Based on the snippet: <|code_start|> dev_key = self.request.get('key')
stopID = api_utils.conformStopID(self.request.get('stopID'))
routeID = api_utils.conformRouteID(self.request.get('routeID'))
vehicleID = self.request.get('vehicleID')
logging.debug('getarrivals request parameters... sto... | else: |
Given the code snippet: <|code_start|>
GETARRIVALS = "get arrivals"
GETVEHICLES = "get vehicles"
GETSTOPS = "get stops"
GETROUTES = "get routes"
GETNEARBYSTOPS = "get nearby stops"
GETSTOPLOCATION = "get stop location"
def recordDeveloperRequest(devKey,type,terms,ipaddr,error='success'):
# this is too damn expens... | return db.model_to_protobuf(models).Encode() |
Predict the next line after this snippet: <|code_start|>
# review the results for popular stops
reqs = getRequestedStops();
stops_stats = []
keyLookup = []
totalReqs = 0
for key,value in reqs.items():
stops_stats.append({'stopID':key,
'co... | continue; |
Based on the snippet: <|code_start|> for r in routes:
logging.debug('updating route %s with new location' % r.route)
r.stopLocation = stop
r.put()
self.redirect('https://smsmybus.com/labs/displaystops')
## end FixStop
class CollectorHandler(w... | q.with_cursor(cursor) |
Next line prediction: <|code_start|> stops = StopLocationLoader.all()
for s in stops:
# create a new task for each stop
task = Task(url='/gtfs/port/stop/task/',
params={'stopID':s.stopID,
'name':s.name,
... | if len(stopID) == 3: |
Predict the next line after this snippet: <|code_start|> lat = self.request.get('lat')
lon = self.request.get('lon')
direction = self.request.get('direction')
s = StopLocation()
s.stopID = stopID
s.intersection = name.split('(')[0].rstrip()
s.dir... | def main(): |
Predict the next line after this snippet: <|code_start|> lon = self.request.get('lon')
direction = self.request.get('direction')
s = StopLocation()
s.stopID = stopID
s.intersection = name.split('(')[0].rstrip()
s.direction = direction
s.description = des... | logging.getLogger().setLevel(logging.DEBUG) |
Next line prediction: <|code_start|># into routes and destinations
#
# note that order matters. the Stop transformation has to happen first.
#
class RouteTransformationStart(webapp.RequestHandler):
def get(self) :
# shove a task in the queue because we need more time then
# we may be able to get in ... | except Timeout: |
Continue the code snippet: <|code_start|> for s in stops:
# create a new task for each stop
task = Task(url='/gtfs/port/stop/task/',
params={'stopID':s.stopID,
'name':s.name,
'description':s.descriptio... | stopID = "0" + stopID |
Next line prediction: <|code_start|> method='POST'
)
return({'status':'async'})
def http_post(self, path, data):
pdata = urllib.urlencode(data)
req = urllib2.Request(self.URL_BASE + path, pdata)
resp = urllib2.urlopen(req)
r... | memcache.incr(STATHAT_MEMCACHE_REQ_COUNT, 1, None, 0) |
Given the following code snippet before the placeholder: <|code_start|>
def validateDevKey(devKey):
if devKey is None:
return None
else:
devKey = devKey.lower()
storeKey = memcache.get(devKey)
<|code_end|>
, predict the next line using imports from the current file:
import logging
imp... | if storeKey is None: |
Next line prediction: <|code_start|> self.assertEqual(response.content_type, 'application/json')
data = response.json['lots']
hit = False
for lot in data:
if len(lot['specialEvents']) > 0:
hit = True
self.assertTrue(hit)
def test_parking_valid_uw_s... | hitRecord = lot |
Given the following code snippet before the placeholder: <|code_start|> msg_body += dk.developerName + '(%s) : ' % dk.developerKey
msg_body += str(dk.requestCounter)
msg_body += '\n'
# post counter to google doc
updateField(dk.developerKey,dk.requestCounter)
... | channels = json.loads(memcache.get('channels') or '{}') |
Given the code snippet: <|code_start|>
class MainHandler(webapp.RequestHandler):
def get(self):
# validate the request parameters
devStoreKey = validateRequest(self.request)
if devStoreKey is None:
logging.debug("unable to validate the request parameters")
self.re... | return |
Predict the next line after this snippet: <|code_start|> json_response = routeRequest(routeID)
api_utils.recordDeveloperRequest(devStoreKey, api_utils.GETVEHICLES, self.request.query_string, self.request.remote_addr);
else:
logging.error("API: invalid request")
jso... | def routeRequest(routeID): |
Given the following code snippet before the placeholder: <|code_start|> rpc.callback = create_callback(rpc,stopID,r.route,sid,r.direction)
urlfetch.make_fetch_call(rpc, r.scheduleURL)
rpcs.append(rpc)
# all of the schedule URLs have been fetched. now wait for them to finish
... | logging.error("API: Error loading page. route %s, stop %s" % (routeID,stopID)) |
Using the snippet: <|code_start|> # instead of shoving this in the datastore, we're going to shove
# it in a local variable and retrieve it with the sid later
# old implementation --> stop.put()
insert_result(sid,stop)
# create the task that glues all the messages tog... | aggregated_results.append(stop) |
Given snippet: <|code_start|> # <td><a class="adatime" title="12:12 pm">12:12 pm</a></td>
# <td><a class="adatext" title="NTP">NTP</a></td>
# </tr><tr>
# <td><p class="stopLabel">Scheduled time shown</p></td>
# </tr><tr>
# <td><a class="ada" title="Time... | hours += 12 |
Predict the next line after this snippet: <|code_start|> else:
if refresh is True:
json_response = getRoutes(refresh)
# drop it into the memcache again
memcache.set(api_utils.GETROUTES, json_response)
logging.debug('---> storing in memcache');
... | response = json_response |
Given the following code snippet before the placeholder: <|code_start|> # don't run these jobs during "off" hours
json_response = api_utils.buildErrorResponse('-1','The Metro service is not currently running')
else:
if refresh is True:
json_response = getRoutes(refresh)
... | else: |
Given the following code snippet before the placeholder: <|code_start|>
logging.debug('---> datastore lookup starting!')
offset = 0
q = RouteListing.all()
routes = q.fetch(1000)
hits = {}
response_dict = {'status':0,'timestamp':api_utils.getLocalTimestamp()}
while len(routes) > 0:
o... | routeMap[routeID].append(directionLabel) |
Using the snippet: <|code_start|>
class CartSerializerDefault(serializers.ModelSerializer):
class Meta:
model = Cart
fields = '__all__'
<|code_end|>
, determine the next line of code. You have imports:
from rest_framework import serializers
from .models import (
Cart,
Item
)
and con... | class CartSerializerPOST(serializers.ModelSerializer): |
Given the code snippet: <|code_start|>
extra_kwargs = {
'password': {'write_only': True},
}
def create(self, validated_data):
user = CustomerUser(**validated_data)
password = validated_data['password']
user.set_password(password)
user.save()
token... | token = Token.objects.create(credit_card=credit_card) |
Here is a snippet: <|code_start|>class CustomerUserSerializerPOST(serializers.ModelSerializer):
class Meta:
model = CustomerUser
fields = ('pk', 'username', 'first_name', 'last_name',
'email', 'password', 'cellphone', 'phone_number')
extra_kwargs = {
'password'... | 'expire_date', 'provider', 'user') |
Using the snippet: <|code_start|>
urlpatterns = [
url(r'^index/', productIndexView, name='productIndexView'),
url(r'^(?P<product_id>[0-9]+)/details/$', productDetailView,
name='productDetailView'),
url(r'^productFilter/', productFilterView, name='productFilterView'),
url(r'^list/', categoryIndex... | url(r'^(?P<product_id>[0-9]+)/add_to_cart/$', |
Based on the snippet: <|code_start|>
urlpatterns = [
url(r'^index/', productIndexView, name='productIndexView'),
url(r'^(?P<product_id>[0-9]+)/details/$', productDetailView,
name='productDetailView'),
url(r'^productFilter/', productFilterView, name='productFilterView'),
url(r'^list/', categoryIn... | name='addProductToCart') |
Given the following code snippet before the placeholder: <|code_start|>
urlpatterns = [
url(r'^index/', productIndexView, name='productIndexView'),
url(r'^(?P<product_id>[0-9]+)/details/$', productDetailView,
name='productDetailView'),
url(r'^productFilter/', productFilterView, name='productFilterVi... | if settings.DEBUG: |
Using the snippet: <|code_start|>
urlpatterns = [
url(r'^index/', productIndexView, name='productIndexView'),
url(r'^(?P<product_id>[0-9]+)/details/$', productDetailView,
name='productDetailView'),
url(r'^productFilter/', productFilterView, name='productFilterView'),
url(r'^list/', categoryIndex... | if settings.DEBUG: |
Next line prediction: <|code_start|>
urlpatterns = [
url(r'^index/', productIndexView, name='productIndexView'),
url(r'^(?P<product_id>[0-9]+)/details/$', productDetailView,
name='productDetailView'),
url(r'^productFilter/', productFilterView, name='productFilterView'),
url(r'^list/', categoryIn... | name='addProductToCart') |
Given the following code snippet before the placeholder: <|code_start|>
urlpatterns = [
url(r'^index/', productIndexView, name='productIndexView'),
url(r'^(?P<product_id>[0-9]+)/details/$', productDetailView,
name='productDetailView'),
url(r'^productFilter/', productFilterView, name='productFilterVi... | name='addProductToCart') |
Given snippet: <|code_start|>
urlpatterns = [
url(r'^cart_detail/', login_required(cartDetailView),
name='cartDetailView'),
url(r'^(?P<product_id>[0-9]+)/remove_from_cart/$',
login_required(removeFromCartView),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
... | name='removeProductFromCart') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.