Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|> })
assert ua.is_willcom()
res = ua.is_bogus()
assert res == expected, '%s expected, actual %s' % (expected, res)
for ip, expected in (
('210.230.128.224', True),
('61.198.128.0', False),
):
... | class MyWillcomUserAgent(WillcomUserAgent): |
Next line prediction: <|code_start|>
for ip, expected in (
('210.230.128.224', True),
('61.198.128.0', False),
):
yield func, ip, expected
def test_extra_ip():
ctxt1 = Context(extra_willcom_ips=['192.168.0.0/24'])
ua = detect({'HTTP_USER_AGENT': 'Mozilla/3.0(WILLCOM;KYOCERA/... | class MyWillcomUserAgentFactory(WillcomUserAgentFactory): |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class NonMobileUserAgent(UserAgent):
name = 'NonMobile'
carrier = 'NonMobile'
short_carrier = 'N'
serialnumber = None
def get_flash_version(self):
"""
returns Flash Lite version.
"""
return '3.1'
flash_ver... | return Display() |
Based on the snippet: <|code_start|> return DATA[self.model]
except KeyError:
return '2.0'
flash_version = property(get_flash_version)
def supports_cookie(self):
return True
def make_display(self):
"""
create a Display object.
"""
env ... | return Display(width=width, height=height, color=color, depth=depth) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
WILLCOM_RE = re.compile(r'^Mozilla/3\.0\((?:DDIPOCKET|WILLCOM);(.*)\)')
WILLCOM_CACHE_RE = re.compile(r'^[Cc](\d+)')
WINDOWS_CE_RE = re.compile(r'^Mozilla/4\.0 \((.*)\)')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re... | class WillcomUserAgentParser(UserAgentParser): |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class WillcomUserAgent(UserAgent):
name = 'WILLCOM'
carrier = 'WILLCOM'
short_carrier = 'W'
def __init__(self, *args, **kwds):
super(WillcomUserAgent, self).__init__(*args, **kwds)
self.serialnumber = None
self.model_v... | return Display() |
Predict the next line after this snippet: <|code_start|> })
assert ua.is_ezweb()
res = ua.is_bogus()
assert res == expected, '%s expected, actual %s' % (expected, res)
for ip, expected in (
('210.230.128.224', False),
('210.153.84.0', True),
):
... | class MyEZwebUserAgent(EZwebUserAgent): |
Given the code snippet: <|code_start|>
for ip, expected in (
('210.230.128.224', False),
('210.153.84.0', True),
):
yield func, ip, expected
def test_extra_ip():
ctxt1 = Context(extra_ezweb_ips=['192.168.0.0/24'])
ua = detect({'HTTP_USER_AGENT': 'KDDI-HI36 UP.Browser/6.2.0.1... | class MyEZwebUserAgentFactory(EZwebUserAgentFactory): |
Predict the next line after this snippet: <|code_start|>
FOMA_SERIES_4DIGITS_RE = re.compile(r'\d{4}')
FOMA_SERIES_3DIGITS_RE = re.compile(r'(\d{3}i|\d{2}[ABC][23]?)')
DOCOMO_COMMENT_RE = re.compile(r'\((.+?)\)')
DOCOMO_DISPLAY_BYTES_RE = re.compile(r'^W(\d+)H(\d+)$')
DOCOMO_HTML_VERSION_LIST = [
(re.compile(... | class DoCoMoUserAgentParser(UserAgentParser): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
def locate_discontinuity(grid, y, consider, trnsfm=lambda x: x, ntrail=2):
y = np.asarray(y, dtype=np.float64)
dy = np.diff(y)
tg = trnsfm(grid)
dtg = np.diff(tg)
err = np.zeros(y... | est, slc = interpolate_ahead(tg, y, ntrail, d) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
def locate_discontinuity(grid, y, consider, trnsfm=lambda x: x, ntrail=2):
y = np.asarray(y, dtype=np.float64)
dy = np.diff(y)
tg = trnsfm(grid)
dtg = np.diff(tg)
err = np.... | return avg_stddev(points[:, 0], w1) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
def plot_convergence(key, values, cb, metric=None, xstart=0, xstop=2, **kwargs):
if key in kwargs:
raise ValueError("Cannot have key=%s when given in kwargs" % key)
fig, ... | grid, results = adapted_grid(xstart, xstop, cb, metric=metric, **kwargs) |
Next line prediction: <|code_start|>
def test_locate_discontinuity__pool_discontinuity_approx():
for snr in [False, True]:
loc_res = locate_discontinuity(
<|code_end|>
. Use current file imports:
(from .. import adapted_grid
from ..util import locate_discontinuity, pool_discontinuity_approx
from ._common ... | *adapted_grid(0, 10, g3, grid_additions=(16,) * 8, snr=snr), consider=5 |
Given the code snippet: <|code_start|>
def test_locate_discontinuity__pool_discontinuity_approx():
for snr in [False, True]:
loc_res = locate_discontinuity(
*adapted_grid(0, 10, g3, grid_additions=(16,) * 8, snr=snr), consider=5
)
<|code_end|>
, generate the next line using the imports ... | avg, s = pool_discontinuity_approx(loc_res) |
Given snippet: <|code_start|>
def test_locate_discontinuity__pool_discontinuity_approx():
for snr in [False, True]:
loc_res = locate_discontinuity(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .. import adapted_grid
from ..util import locate_discontinuity, pool_... | *adapted_grid(0, 10, g3, grid_additions=(16,) * 8, snr=snr), consider=5 |
Predict the next line for this snippet: <|code_start|> ystart, ystop = 0, 0
for yslc in yslices:
ystop += yslc.stop - yslc.start
nextresults[yslc] = newresults[ystart:ystop]
nexty[yslc] = newy[ystart:ystop]
ystart = ystop
return nextgrid, nextresul... | est, slc = interpolate_ahead(grid, y, ntrail, direction) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: delo
# @Date: 2014-02-17 21:52:20
# @Email: deloeating@gmail.com
# @Last modified by: Sai
# @Last modified time: 2014-03-02 15:35:42
@fixture
def confData(request):
mpconfig.MoePadConfKey = "MoePadConfTest"
<|co... | rs.hmset(mpconfig.MoePadConfKey, |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: delo
# @Date: 2014-02-17 21:36:42
# @Email: deloeating@gmail.com
# @Last modified by: Sai
# @Last modified time: 2014-03-02 15:35:55
def test_subdict():
a = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
... | assert sub_dict(a, keys) == {'k1': 'v1', 'k3': 'v3'} |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: delo
# @Date: 2014-02-17 21:36:42
# @Email: deloeating@gmail.com
# @Last modified by: Sai
# @Last modified time: 2014-03-02 15:35:55
def test_subdict():
a = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
keys = ['k1', 'k3']
... | tlogger = loggerInit("test.log") |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
log = logging.getLogger('moepad')
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save() # new user created
retur... | rs.hmset("MoePadConf", request.POST)
|
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
_dir = os.path.join(os.path.dirname(__file__), os.path.pardir)
logfile = os.path.join(_dir, "MoePad.log")
def showlog():
os.system("tail -20 %s" % logfile)
def show_verifying():
<|code_end|>
using the current file's imports:
im... | verifying_items = rs.zrange(VERIFYING_SET, 0, -1) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
log = logging.getLogger('moepad')
SinaAppKey = MPConf.SinaAppKey
SinaAppSecret = MPConf.SinaAppSecret
MoePadSite = MPConf.Domain
<|code_end|>
with the help of current file imports:
import logging
import redis
import pickle
from django.... | OriWeiboAuth = WeiboAuthInfoRedis("original") |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
log = logging.getLogger('moepad')
SinaAppKey = MPConf.SinaAppKey
SinaAppSecret = MPConf.SinaAppSecret
MoePadSite = MPConf.Domain
OriWeiboAuth = WeiboAuthInfoRedis("original")
RtWeiboAuth = WeiboAuthInfoRedis("retweet")
def authSina(code):
client = weibo... | current_user_type = rs.get("current_user_type") |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: delo
# @Date: 2014-02-17 23:12:19
# @Email: deloeating@gmail.com
# @Last modified by: Sai
# @Last modified time: 2014-03-02 15:36:07
def test_getItemCategories():
possible_categories = ['R-18', 'R18']
real_categor... | rs.sadd(FORBIDDENS, u"神原骏河".encode('utf-8')) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: delo
# @Date: 2014-02-17 23:12:19
# @Email: deloeating@gmail.com
# @Last modified by: Sai
# @Last modified time: 2014-03-02 15:36:07
def test_getItemCategories():
possible_categories = ['R-18', 'R18']
real_ca... | logger.info(str(type(real_categories[0]))) |
Using the snippet: <|code_start|> possible_categories = ['R-18', 'R18']
real_categories = update.getItemCategories(u'Ahe颜')
assert len(set(possible_categories).intersection(set(real_categories)))
real_categories = update.getItemCategories(u'神原骏河')
logger.info(str(type(real_categories[0])))
asser... | _deletePrefix(NEWITEM) |
Here is a snippet: <|code_start|>
def reportinfo(self):
return (
self.fspath.dirpath(),
None,
self.fspath.relto(self.session.fspath),
)
def _prunetraceback(self, excinfo):
# Traceback implements __getitem__, but list implements __getslice__,
#... | actual = compile_file( |
Here is a snippet: <|code_start|> self.fspath.relto(self.session.fspath),
)
def _prunetraceback(self, excinfo):
# Traceback implements __getitem__, but list implements __getslice__,
# which wins in Python 2
excinfo.traceback = excinfo.traceback.cut(__file__)
def runt... | CoreExtension, |
Given snippet: <|code_start|>
def _prunetraceback(self, excinfo):
# Traceback implements __getitem__, but list implements __getslice__,
# which wins in Python 2
excinfo.traceback = excinfo.traceback.cut(__file__)
def runtest(self):
scss_file = Path(str(self.fspath))
css_... | FontsExtension, |
Continue the code snippet: <|code_start|>
root = type(self)(self.combinator, root.tokens)
selector = (root,) + selector[1:]
return tuple(selector)
def merge_into(self, other):
"""Merge two simple selectors together. This is expected to be the
selector being injected into `o... | if token in CSS2_PSEUDO_ELEMENTS or token.startswith('::'): |
Using the snippet: <|code_start|> def __repr__(self):
return "<%s(%s) at 0x%x>" % (type(self).__name__, ', '.join(repr(map) for map in self.maps), id(self))
def __getitem__(self, key):
for map in self.maps:
if key in map:
return map[key]
raise KeyError(key)
... | if isinstance(map[key], Undefined): |
Continue the code snippet: <|code_start|> def _auto_register_function(self, function, name, ignore_args=0):
name = name.replace('_', '-').rstrip('-')
argspec = inspect.getargspec(function)
if argspec.varargs or argspec.keywords:
# Accepts some arbitrary number of arguments
... | if not isinstance(value, Value): |
Continue the code snippet: <|code_start|>
IPC_CREAT = 0o1000
IPC_PRIVATE = 0
IPC_RMID = 0
SHM_RDONLY = 0o10000
SHM_RND = 0o20000
SHM_REMAP = 0o40000
SHM_EXEC = 0o100000
try:
rt = ctypes.CDLL('librt.so', use_errno=True)
shmget = rt.shmget
shmget.argtypes = [ctypes.c_int, ctypes.c_size_t, ctypes.c_int]
... | class ShmPixbuf(PixbufBase): |
Based on the snippet: <|code_start|>
@has_dependencies
class _Graph(Widget):
fixed_upper_bound = False
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import cairo
from zorro import gethub, sleep
from zorro.di import has_dependencies, dependency
from .base import Widget
fro... | theme = dependency(Theme, 'theme') |
Predict the next line for this snippet: <|code_start|>
def __zorro_di_done__(self):
inj = di(self)
for i, scr in enumerate(self.screens):
inj.inject(scr)
self.commander['screen.{}'.format(i)] = scr
def update(self, screens):
# TODO(tailhook) try to guess which on... | self.updated = Event('screen.updated') |
Continue the code snippet: <|code_start|>class Screen(object):
def __init__(self):
self.topbars = []
self.bottombars = []
self.leftslices = []
self.rightslices = []
self.updated = Event('screen.updated')
self.bars_visible = True
self.group_hooks = []
def... | bar.set_bounds(Rectangle(x, y, w, bar.height)) |
Based on the snippet: <|code_start|>
class LayoutMeta(type):
@classmethod
def __prepare__(cls, name, bases):
return OrderedDict()
def __init__(cls, name, bases, dic):
cls.fields = list(dic.keys())
@has_dependencies
class Layout(metaclass=LayoutMeta):
def __init__(self):
s... | self.relayout = Event('layout.relayout') |
Given snippet: <|code_start|>
class BaseStack(object):
"""Single stack for tile layout
It's customized by subclassing, not by instantiating
:var size: size (e.g. width) of stack in pixels, if None weight is used
:var min_size: minimum size of stack to start to ignore pixel sizes
:var weight: th... | self.box = Rectangle(0, 0, 100, 100) |
Using the snippet: <|code_start|> w.show()
start = end
def stackcommand(fun):
@wraps(fun)
def wrapper(self, *args):
try:
win = self.commander['window']
except KeyError:
return
stack = win.lprops.stack
if stack is None:
... | commander = dependency(CommandDispatcher, 'commander') |
Predict the next line after this snippet: <|code_start|> else:
rstart = start = self.box.x
for n, w in enumerate(self.windows, 1):
if self.vertical:
end = rstart + int(floor(n/vc*self.box.height))
w.set_bounds(Rectangle(
self.box... | class Split(Layout): |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
log = logging.getLogger(__name__)
QUERY_URL = 'http://query.yahooapis.com/v1/public/yql'
WEATHER_URL = 'http://weather.yahooapis.com/forecastrss?'
WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
DEFAULT_PIC = 'http://l.yimg.com/a/i/us/nws/weather/... | class YahooWeather(Widget): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
log = logging.getLogger(__name__)
QUERY_URL = 'http://query.yahooapis.com/v1/public/yql'
WEATHER_URL = 'http://weather.yahooapis.com/forecastrss?'
WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
DEFAULT_PIC = 'http://l.yimg.com/a/i/us/nws/weather/gr/{con... | theme = dependency(Theme, 'theme') |
Based on the snippet: <|code_start|> def __zorro_di_done__(self):
bar = self.theme.bar
self.font = bar.font
self.color = bar.text_color_pat
self.padding = bar.text_padding
gethub().do_spawnhelper(self._update_handler)
def _update_handler(self):
try:
wo... | data = fetchurl(img_url) |
Here is a snippet: <|code_start|>
@has_dependencies
class Title(Widget):
dispatcher = dependency(CommandDispatcher, 'commander')
<|code_end|>
. Write the next line using the current file imports:
from zorro.di import di, has_dependencies, dependency
from cairo import SolidPattern
from .base import Widget
from t... | theme = dependency(Theme, 'theme') |
Using the snippet: <|code_start|> def get_file( self, name ):
with open( os.path.join( self.path, name ), 'rt' ) as f:
return f.read().strip()
@property
def charge( self ):
return self._now/self._full
@property
def time_to_full( self ):
return int( ( self._full -... | class Battery(Widget): |
Next line prediction: <|code_start|> return f.read().strip()
@property
def charge( self ):
return self._now/self._full
@property
def time_to_full( self ):
return int( ( self._full - self._now )/self._power*MIN_IN_HOUR )
@property
def time_to_empty( self ):
r... | theme = dependency(Theme, 'theme') |
Here is a snippet: <|code_start|> def setter(win):
win.ignore_hints = True
return setter
def ignore_protocols(*ignore):
def setter(win):
win.ignore_protocols.update(ignore)
win.protocols -= win.ignore_protocols
return setter
def move_to_group_of(prop):
def setter(win):
... | 'match-type': match_type, |
Based on the snippet: <|code_start|>try:
except ImportError:
class Window(object):
def set_bounds(self, rect):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import mock
from unittest import mock # builtin mock in 3.3
from tilenol.xcb import Rectangle
f... | assert isinstance(rect, Rectangle) |
Continue the code snippet: <|code_start|> else:
ln = ln*4+32
if len(buf)-pos < ln:
break
val = buf[pos:pos+2] + buf[pos+8:pos+ln]
pos += ln
self.produce(seq, val)
class Connection(obj... | for auth in read_auth(): |
Given snippet: <|code_start|>
GRAD = pi/180
rotations = {
'up': 0*GRAD,
'upright': 45*GRAD,
'right': 90*GRAD,
'downright': 135*GRAD,
'down': 180*GRAD,
'downleft': -135*GRAD,
'left': -90*GRAD,
'upleft': -45*GRAD,
}
@has_dependencies
<|code_end|>
, continue by predicting the next ... | class Gesture(Widget): |
Here is a snippet: <|code_start|>
GRAD = pi/180
rotations = {
'up': 0*GRAD,
'upright': 45*GRAD,
'right': 90*GRAD,
'downright': 135*GRAD,
'down': 180*GRAD,
'downleft': -135*GRAD,
'left': -90*GRAD,
'upleft': -45*GRAD,
}
@has_dependencies
class Gesture(Widget):
<|code_end|>
. Writ... | theme = dependency(Theme, 'theme') |
Continue the code snippet: <|code_start|>
GRAD = pi/180
rotations = {
'up': 0*GRAD,
'upright': 45*GRAD,
'right': 90*GRAD,
'downright': 135*GRAD,
'down': 180*GRAD,
'downleft': -135*GRAD,
'left': -90*GRAD,
'upleft': -45*GRAD,
}
@has_dependencies
class Gesture(Widget):
theme =... | gestures = dependency(G.Gestures, 'gestures') |
Predict the next line for this snippet: <|code_start|>
route = [
(r"/",Index.index),
(r"/([0-9]+)/?",Img.category),
(r"/addLink/?",Img.addLink),
(r"/addCate/?",VIP.addCate),
(r"/Admin/addviptime/?",Admin.AddVipTime),
(r"/Admin/suggest/?",Admin.AdminSuggest),
(r"/addKeyword/?",Img.addKeyword),
(r"/album/?",Index... | (r"/search/?",Search.search), |
Here is a snippet: <|code_start|>
route = [
(r"/",Index.index),
(r"/([0-9]+)/?",Img.category),
(r"/addLink/?",Img.addLink),
(r"/addCate/?",VIP.addCate),
(r"/Admin/addviptime/?",Admin.AddVipTime),
(r"/Admin/suggest/?",Admin.AdminSuggest),
(r"/addKeyword/?",Img.addKeyword),
(r"/album/?",Index.album),
<|code_end|>... | (r"/clearMessage/?",User.ClearMessage), |
Next line prediction: <|code_start|>
route = [
(r"/",Index.index),
(r"/([0-9]+)/?",Img.category),
(r"/addLink/?",Img.addLink),
(r"/addCate/?",VIP.addCate),
(r"/Admin/addviptime/?",Admin.AddVipTime),
(r"/Admin/suggest/?",Admin.AdminSuggest),
(r"/addKeyword/?",Img.addKeyword),
(r"/album/?",Index.album),
(r"/clea... | (r"/message/?",SomePage.Message), |
Here is a snippet: <|code_start|>
route = [
(r"/",Index.index),
(r"/([0-9]+)/?",Img.category),
(r"/addLink/?",Img.addLink),
(r"/addCate/?",VIP.addCate),
<|code_end|>
. Write the next line using the current file imports:
from handlers import Index
from handlers import Img
from handlers import Search
from handlers i... | (r"/Admin/addviptime/?",Admin.AddVipTime), |
Given the code snippet: <|code_start|>
route = [
(r"/",Index.index),
(r"/([0-9]+)/?",Img.category),
(r"/addLink/?",Img.addLink),
<|code_end|>
, generate the next line using the imports in this file:
from handlers import Index
from handlers import Img
from handlers import Search
from handlers import User
from handle... | (r"/addCate/?",VIP.addCate), |
Next line prediction: <|code_start|>
class TestCuboid(TestCase):
@classmethod
def setUpClass(cls):
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from HierMat.cuboid import Cuboid
import numpy)
and context including class names, function names, or small code snippets from other fil... | cls.cub1 = Cuboid(numpy.array([0]), numpy.array([1])) |
Next line prediction: <|code_start|>
class TestGrid(TestCase):
@classmethod
def setUpClass(cls):
cls.lim1 = 16
cls.lim2 = 4
cls.lim3 = 4
cls.link_num = 2
cls.points1 = [(float(i) / cls.lim1,) for i in xrange(cls.lim1)]
cls.links1 = {p: [cls.points1[l] for l in ... | cls.grid1 = Grid(cls.points1, cls.links1) |
Predict the next line for this snippet: <|code_start|># Author: Alex Ksikes
# TODO:
# - webpy session module is ineficient and makes 5 db calls per urls!
# - because sessions are attached to an app, every user has sessions whether they atually need it or not.
# - login required decorator should save intended user acti... | for k, v in users.get_user_by_email(email).items(): |
Using the snippet: <|code_start|># Author: Alex Ksikes
class refer:
def GET(self, secret_md5):
applicant = applicants.get_by_secret_md5(secret_md5)
if not applicant and secret_md5 == '0' * 32:
applicant = applicants.get_dummy_record()
return view.reference_... | submissions.submit_reference(applicant, f.d) |
Based on the snippet: <|code_start|># Author: Alex Ksikes
resume_dir = 'public/resumes/'
def submit_application(resume, d, simple=False):
# clean up some fields
clean_up_data(d)
# handle the file upload
d.resume_fn = save_resume(resume, d.first_name, d.last_name)
# in simple mode, no reference ... | d.secret_md5 = utils.make_unique_md5() |
Using the snippet: <|code_start|># Author: Alex Ksikes
resume_dir = 'public/resumes/'
def submit_application(resume, d, simple=False):
# clean up some fields
clean_up_data(d)
# handle the file upload
d.resume_fn = save_resume(resume, d.first_name, d.last_name)
# in simple mode, no reference is ... | email_templates.to_applicant_simple(d) |
Predict the next line after this snippet: <|code_start|> '/reject', 'app.controllers.actions.reject',
'/undecide', 'app.controllers.actions.undecide',
'/rate', 'app.controllers.actions.rate',
'/appl... | session.add_sessions_to_app(app) |
Here is a snippet: <|code_start|># Author: Alex Ksikes
class admit:
@session.login_required
def POST(self):
i = web.input(context='', id=[])
if i.id:
<|code_end|>
. Write the next line using the current file imports:
import web
import config
from app.helpers import paging
from ap... | applicants.admit(i.id, session.get_user_id()) |
Given the code snippet: <|code_start|> if i.id:
applicants.reject(i.id, session.get_user_id())
raise web.seeother(web.ctx.environ['HTTP_REFERER'])
class undecide:
@session.login_required
def POST(self):
i = web.input(context='', id=[])
if i.id:
ap... | comments.add_comment(session.get_user_id(), id, i.comment) |
Next line prediction: <|code_start|> if i.id:
applicants.admit(i.id, session.get_user_id())
raise web.seeother(web.ctx.environ['HTTP_REFERER'])
class reject:
@session.login_required
def POST(self):
i = web.input(context='', id=[])
if i.id:
... | votes.add(i.id, score, session.get_user_id()) |
Based on the snippet: <|code_start|># Author: Alex Ksikes
# This is a sample config file. Complete it and rename the file config.py.
# connect to database
db = web.database(dbn='mysql', db='mlss', user='your username', passwd='your password')
# in development debug error messages and reloader
web.config.debug = Tr... | globals = utils.get_all_functions(misc) |
Using the snippet: <|code_start|># Author: Alex Ksikes
# This is a sample config file. Complete it and rename the file config.py.
# connect to database
db = web.database(dbn='mysql', db='mlss', user='your username', passwd='your password')
# in development debug error messages and reloader
web.config.debug = True
... | globals = utils.get_all_functions(misc) |
Given the code snippet: <|code_start|># Author: Alex Ksikes
# TODO:
# - see for a better paging module
# - no need to have two separate login_required_for_reviews and login_required
results_per_page = 50
default_order = 'id'
class list:
@session.login_required_for_reviews
def GET(self, context):
... | pager = web.storage(paging.get_paging(start, num_results, |
Predict the next line for this snippet: <|code_start|># Author: Alex Ksikes
# TODO:
# - see for a better paging module
# - no need to have two separate login_required_for_reviews and login_required
results_per_page = 50
default_order = 'id'
class list:
<|code_end|>
with the help of current file imports:
impor... | @session.login_required_for_reviews |
Given the code snippet: <|code_start|># Author: Alex Ksikes
# TODO:
# - see for a better paging module
# - no need to have two separate login_required_for_reviews and login_required
results_per_page = 50
default_order = 'id'
class list:
@session.login_required_for_reviews
def GET(self, context):
... | results, num_results = applicants.query(query=i.query, context=context, |
Next line prediction: <|code_start|> counts = applicants.get_counts()
user = session.get_session()
stats = applicants.get_stats()
return view.layout(
view.applicants(results, context, pager, i),
user, context, counts, i.query, stats)
cl... | _comments = comments.get_comments(applicant.id) |
Predict the next line after this snippet: <|code_start|> user = session.get_session()
stats = applicants.get_stats()
return view.layout(
view.applicants(results, context, pager, i),
user, context, counts, i.query, stats)
class show:
@session.login_r... | _votes = votes.get_votes(applicant.id) |
Next line prediction: <|code_start|># Author: Alex Ksikes
vemail = form.regexp(r'.+@.+', 'Please enter a valid email address')
login_form = form.Form(
form.Textbox('email',
form.notnull, vemail,
description='Your email:'),
form.Password('password',
form.notnull,
descriptio... | lambda i: users.is_correct_password(i.email, i.password)) |
Predict the next line for this snippet: <|code_start|> form.Textbox('email',
form.notnull, vemail,
form.Validator('There is no record of this email in our database.',
lambda x: not users.is_email_available(x)),
description='Your email:'),
form.Button('submit', t... | session.login(f.d.email) |
Predict the next line after this snippet: <|code_start|> return login_form()
class register:
def GET(self):
return render_account(show='register_only')
def POST(self):
f = self.form()
if not f.validates(web.input(_unicode=False)):
show = web.input(show='all')... | email_templates.resend_password(user) |
Given the following code snippet before the placeholder: <|code_start|>
password_form = form.Form(
form.Password('password',
form.notnull,
form.Validator('Your password must at least 5 characters long.',
lambda x: users.is_valid_password(x)),
description='Your new password:')... | counts = applicants.get_counts() |
Continue the code snippet: <|code_start|># Author: Alex Ksikes
password_form = form.Form(
form.Password('password',
form.notnull,
form.Validator('Your password must at least 5 characters long.',
<|code_end|>
. Use current file imports:
import web
import config
from web import form
from ... | lambda x: users.is_valid_password(x)), |
Here is a snippet: <|code_start|>
password_form = form.Form(
form.Password('password',
form.notnull,
form.Validator('Your password must at least 5 characters long.',
lambda x: users.is_valid_password(x)),
description='Your new password:'),
form.Button('submit', type='submi... | user = session.get_session() |
Given the code snippet: <|code_start|># Author: Alex Ksikes
vemail = form.regexp(r'.+@.+', 'Please enter a valid email address')
vurl = form.regexp('(^\s*$)|(^http://.*$)',
'Please provide a valid website url (eg, http://www.example.com).')
application_form = form.Form(
form.Textbox('first_name',
... | lambda x: submissions.is_email_available(x)), |
Here is a snippet: <|code_start|> def __init__(self, indent=0, quote='', indent_char=' '):
self.indent = indent
self.indent_char = indent_char
self.indent_quote = quote
if self.indent > 0:
self.indent_string = ''.join((
str(quote),
(self.ind... | s = tsplit(s, NEWLINES) |
Using the snippet: <|code_start|> self.path = path
self._exists = False
if path:
self._create()
def __repr__(self):
return '<app-dir: %s>' % (self.path)
def __getattribute__(self, name):
if not name in ('_exists', 'path', '_create', '_raise_if_none'):
... | mkdir_p(self.path) |
Predict the next line after this snippet: <|code_start|> removedirs(fn)
except OSError as why:
if why.errno == errno.ENOENT:
pass
else:
raise why
def read(self, filename, binary=False):
"""Returns contents of given file with Ap... | if is_collection(path): |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
clint.textui.formatters
~~~~~~~~~~~~~~~~~~~~~~~
Core TextUI functionality for text formatting.
"""
from __future__ import absolute_import
NEWLINES = ('\n', '\r', '\r\n')
def min_width(string, cols, padding=' '):
"""Returns ... | is_color = isinstance(string, ColoredString) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
clint.textui.formatters
~~~~~~~~~~~~~~~~~~~~~~~
Core TextUI functionality for text formatting.
"""
from __future__ import absolute_import
NEWLINES = ('\n', '\r', '\r\n')
def min_width(string, cols, padding=' '):
"""Returns given string with ri... | _sub = clean(substring).ljust((cols + 0), padding) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
clint.textui.formatters
~~~~~~~~~~~~~~~~~~~~~~~
Core TextUI functionality for text formatting.
"""
from __future__ import absolute_import
NEWLINES = ('\n', '\r', '\r\n')
def min_width(string, cols, padding=' '):
"""Returns gi... | stack = tsplit(str(string), NEWLINES) |
Based on the snippet: <|code_start|>
if is_color:
offset = 10
string_copy = string._new('')
else:
offset = 0
stack = tsplit(string, NEWLINES)
for i, substring in enumerate(stack):
stack[i] = substring.split()
_stack = []
for row in stack:
_... | chunks = schunk(word, (cols + offset)) |
Next line prediction: <|code_start|> if sys.platform.startswith('win'):
console_width = _find_windows_console_width()
else:
console_width = _find_unix_console_width()
_width = kwargs.get('width', None)
if _width:
console_width = _width
else:
if not console_width:
... | cols[i][0] = max_width(string, width).split('\n') |
Predict the next line after this snippet: <|code_start|>def columns(*cols, **kwargs):
columns = list(cols)
cwidth = console_width(kwargs)
_big_col = None
_total_cols = 0
for i, (string, width) in enumerate(cols):
if width is not None:
_total_cols += (width + 1)
... | cols[i][0][j] = min_width(string, width) |
Continue the code snippet: <|code_start|> _args.append(arg)
break
else:
if x not in arg:
_args.append(arg)
return Args(_args, no_argv=True)
@property
def flags(self):
"""Returns Arg object including... | for path in expand_path(arg): |
Predict the next line after this snippet: <|code_start|> return self.all[i]
except IndexError:
return None
def __contains__(self, x):
return self.first(x) is not None
def get(self, x):
"""Returns argument at given index, else none."""
try:
r... | if is_collection(x): |
Based on the snippet: <|code_start|> """Read angles info from filename
"""
cpp_obj = CppObj()
data = cci_nc.variables['ann_phase'][::]
data = np.squeeze(data)
setattr(cpp_obj, 'cpp_phase', data)
# if hasattr(phase, 'mask'):
# phase_out = np.where(phase.mask, -999, phase.data)
... | cloudproducts = AllImagerData() |
Here is a snippet: <|code_start|>
def read_cci_cma(cci_nc):
"""Read cloudtype and flag info from filename
"""
cma = CmaObj()
# cci_nc.variables['cc_total'][:])
# cci_nc.variables['ls_flag'][:])
# ctype = CtypeObj()
# pps 0 cloudfree 3 cloudfree snow 1: cloudy, 2:cloudy
# cci lsflag 0:se... | cpp_obj = CppObj() |
Given the following code snippet before the placeholder: <|code_start|> cci_nc.variables['lon'].valid_min),
np.less_equal(cci_nc.variables['lon'][::],
cci_nc.variables['lon'].valid_max)),
cci_nc.variables['lon'][::],
cloudproducts.nodata)... | ctth = CtthObj() |
Predict the next line for this snippet: <|code_start|> """
logger.info("Opening file %s", filename)
cci_nc = netCDF4.Dataset(filename, 'r', format='NETCDF4')
cloudproducts = read_cci_geoobj(cci_nc)
logger.debug("Reading ctth ...")
cloudproducts.ctth = read_cci_ctth(cci_nc)
logger.debug("Readi... | cma = CmaObj() |
Based on the snippet: <|code_start|> cloudproducts.instrument = imager
logger.debug("Not reading surface temperature")
logger.debug("Reading cloud phase")
cloudproducts.cpp = read_cci_phase(cci_nc)
logger.debug("Reading LWP")
cloudproducts.cpp = read_cci_lwp(cci_nc, cloudproducts.cpp)
... | my_angle_obj = ImagerAngObj() |
Next line prediction: <|code_start|> cloudproducts.longitude = cci_nc.variables['lon'][::]
cloudproducts.longitude[cci_nc.variables['lon'][::] == in_fillvalue] = cloudproducts.nodata
cloudproducts.latitude = cci_nc.variables['lon'][::]
cloudproducts.latitude[cci_nc.variables['lon'][::] == in_fillvalue] =... | do_some_geo_obj_logging(cloudproducts) |
Here is a snippet: <|code_start|> if atrain_match_name in ["snow_ice_surface_type"]:
atrain_match_name = "nsidc_surface_type"
setattr(data_obj, atrain_match_name, group[dataset][...])
retv.diff_sec_1970 = h5file['diff_sec_1970'][...]
h5file.close()
return r... | write_match_objects(filename, datasets, groups, groups_attrs, SETTINGS=SETTINGS) |
Next line prediction: <|code_start|> ctype.ct_conditions = None
return ctype, cma, ctth
def read_patmosx_angobj(patmosx_nc):
"""Read angles info from filename."""
angle_obj = ImagerAngObj()
angle_obj.satz.data = patmosx_nc.variables['sensor_zenith_angle'][0, :, :].astype(np.float)
angle_obj.sun... | do_some_geo_obj_logging(cloudproducts) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.