Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|> Args:
mapped_value (object): mapped value.
Returns:
bytes: byte stream.
Raises:
FoldingError: if the data type definition cannot be folded into
the byte stream.
"""
raise dtfabric_errors.FoldingError(
'Unable to fold to byte stre... | class BinaryDataFormatTest(test_lib.BaseTestCase): |
Based on the snippet: <|code_start|>
class Record(object):
"""Windows (Enhanced) Metafile Format (WMF and EMF) record.
Attributes:
data_offset (int): record data offset.
data_size (int): record data size.
record_type (int): record type.
size (int): record size.
"""
def __init__(self, record... | class EMFFile(data_format.BinaryDataFile): |
Given snippet: <|code_start|> file_object, record_header.record_type, data_size)
return Record(
record_header.record_type,
record_header.record_size, data_offset, data_size)
def _ReadRecordData(self, file_object, record_type, data_size):
"""Reads a record.
Args:
file_obje... | raise errors.ParseError(( |
Given snippet: <|code_start|># coding: utf-8
if __name__ == '__main__':
args_len = len(sys.argv)
if args_len == 3:
print kwl_to_text(sys.argv[1], sys.argv[2])
elif args_len == 2:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from kwl import text_to_kwl, kwl_to_text... | print text_to_kwl(sys.argv[1]) |
Predict the next line after this snippet: <|code_start|># coding: utf-8
if __name__ == '__main__':
args_len = len(sys.argv)
if args_len == 3:
<|code_end|>
using the current file's imports:
from kwl import text_to_kwl, kwl_to_text
import sys
and any relevant context from other files:
# Path: kwl.py
# def tex... | print kwl_to_text(sys.argv[1], sys.argv[2]) |
Next line prediction: <|code_start|> percent_diff = abs((binding_res[ds] - simulated_binding_res[ds])
/ binding_res[ds])
if percent_diff > allowable_relative_difference:
if simulated_binding_res[ds] == 0.0 and binding_res[ds] < 0:
... | boulder_dicts = wrappers._parseMultiRecordBoulderIO(boulder_str) |
Using the snippet: <|code_start|>except: # For Windows compatibility
resource = None
def _getMemUsage():
""" Get current process memory usage in bytes """
return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
@unittest.skipIf(
sys.platform=='win32',
"Windows doesn't support resource ... | binding_tm = bindings.calcTm( |
Given snippet: <|code_start|> return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
@unittest.skipIf(
sys.platform=='win32',
"Windows doesn't support resource module and wrappers")
class TestLowLevelBindings(unittest.TestCase):
def randArgs(self):
self.seq1 = ''.join([random.choice(... | wrapper_tm = wrappers.calcTm( |
Given snippet: <|code_start|> return self._route
else:
instance = MapMyFitness.instance()
route = instance.route.find(self.route_id)
self._route = route
return self._route
@property
def route_id(self):
links = se... | return privacy_enum_to_string(privacy_enum) |
Next line prediction: <|code_start|> self.inflate()
class RouteInflator(BaseInflator):
def inflate(self):
inflated = copy.deepcopy(self.initial_obj)
inflated['starting_location'] = {
'type': 'Point',
'coordinates': [
inflated['points'][0]['lng'],
... | inflated['start_datetime'] = datetime_to_iso_format(inflated['start_datetime']) |
Given snippet: <|code_start|>
class UserObject(BaseObject):
simple_properties = {
'first_name': None, 'last_name': None, 'username': None,
'time_zone': None, 'gender': None, 'location': None,
}
datetime_properties = {
'last_login': None, 'last_login': 'last_login_datetime',
... | raise AttributeNotFoundException |
Here is a snippet: <|code_start|> return int(self.original_dict['_links']['self'][0]['id'])
@property
def birthdate(self):
if 'birthdate' in self.original_dict:
dt = datetime.datetime.strptime(self.original_dict['birthdate'], '%Y-%m-%d')
return dt.date()
@property
... | raise InvalidSizeException('User get_profile_photo size must one of "small", "medium" or "large".') |
Based on the snippet: <|code_start|>
class Deleteable(object):
def delete(self, id):
self.call('delete', '{0}/{1}'.format(self.path, id))
class Searchable(object):
def _search(self, params):
api_resp = self.call('get', self.path + '/', params=params)
objs = []
for obj in api... | raise InvalidSearchArgumentsException(self.validator) |
Given the following code snippet before the placeholder: <|code_start|>
objs = []
for obj in api_resp['_embedded'][self.embedded_name]:
serializer = self.serializer_class(obj)
objs.append(serializer.serialized)
self.total_count = api_resp['total_count']
return obj... | raise InvalidObjectException(self.validator) |
Using the snippet: <|code_start|> def delete(self, id):
self.call('delete', '{0}/{1}'.format(self.path, id))
class Searchable(object):
def _search(self, params):
api_resp = self.call('get', self.path + '/', params=params)
objs = []
for obj in api_resp['_embedded'][self.embedded... | return Paginator(initial_object_list, self.per_page, self.total_count, self, original_kwargs) |
Predict the next line after this snippet: <|code_start|>
class BaseAPI(object):
http_exception_map = {
400: BadRequestException,
<|code_end|>
using the current file's imports:
import datetime
import json
import requests
from ..exceptions import BadRequestException, UnauthorizedException, NotFoundExcept... | 401: UnauthorizedException, |
Given the following code snippet before the placeholder: <|code_start|>
class BaseAPI(object):
http_exception_map = {
400: BadRequestException,
401: UnauthorizedException,
403: ForbiddenException,
<|code_end|>
, predict the next line using imports from the current file:
import datetime
i... | 404: NotFoundException, |
Given the following code snippet before the placeholder: <|code_start|>
class BaseAPI(object):
http_exception_map = {
400: BadRequestException,
401: UnauthorizedException,
403: ForbiddenException,
404: NotFoundException,
<|code_end|>
, predict the next line using imports from the ... | 500: InternalServerErrorException, |
Predict the next line for this snippet: <|code_start|>
class BaseAPI(object):
http_exception_map = {
400: BadRequestException,
401: UnauthorizedException,
<|code_end|>
with the help of current file imports:
import datetime
import json
import requests
from ..exceptions import BadRequestException... | 403: ForbiddenException, |
Next line prediction: <|code_start|> 403: ForbiddenException,
404: NotFoundException,
500: InternalServerErrorException,
}
def __init__(self, api_config, cache_finds):
self.api_config = api_config
self.cache_finds = cache_finds
def call(self, method, path, data=None,... | kwargs['params'][param_key] = datetime_to_iso_format(param_val) |
Given the following code snippet before the placeholder: <|code_start|>
def privacy_enum_to_string(privacy_enum):
#
# From constants:
# PRIVATE = 0
# PUBLIC = 3
# FRIENDS = 1
#
privacy_map = {
0: 'Private',
1: 'Friends',
3: 'Public'
}
return privacy_map[priv... | return datetime.datetime(year, month, day, hour, minute, second, tzinfo=utc) |
Given the following code snippet before the placeholder: <|code_start|>
route = {
'name': 'My Commute',
'description': 'This is a super-simplified route of my commute.',
'city': 'Littleton',
'country': 'US',
'distance': 25749.5,
<|code_end|>
, predict the next line using imports from the current f... | 'privacy': PRIVATE, |
Given the code snippet: <|code_start|>
route = {
'name': 'My Commute',
'description': 'This is a super-simplified route of my commute.',
'city': 'Littleton',
'country': 'US',
'distance': 25749.5,
'privacy': PRIVATE,
'state': 'CO',
'points': [
{'lat': 39.5735, 'lng': -105.0164},... | 'activity_type': BIKE_RIDE, |
Based on the snippet: <|code_start|>
class RouteObject(BaseObject):
simple_properties = {
'name': None, 'description': None, 'distance': None,
'total_ascent': 'ascent', 'total_descent': 'descent',
'min_elevation': None, 'max_elevation': None,
'city': None, 'state': None, 'country': ... | return privacy_enum_to_string(privacy_enum) |
Here is a snippet: <|code_start|>
class Paginator(object):
def __init__(self, initial_object_list, per_page, total_count,
searchable, original_kwargs, orphans=0):
self.initial_object_list = initial_object_list
self.per_page = per_page
self.total_count = total_count
... | raise PageNotAnInteger('That page number is not an integer') |
Continue the code snippet: <|code_start|>
class Paginator(object):
def __init__(self, initial_object_list, per_page, total_count,
searchable, original_kwargs, orphans=0):
self.initial_object_list = initial_object_list
self.per_page = per_page
self.total_count = total_count... | raise EmptyPage('That page number is less than 1') |
Given the following code snippet before the placeholder: <|code_start|>
class MST(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=-7)
def dst(self, dt):
timedelta(0)
mst = MST()
class TimezonesTest(unittest.TestCase):
def test_timezones(self):
mst_date = datetime(2014, 1... | utc_date = mst_date.astimezone(utc) |
Predict the next line for this snippet: <|code_start|>
class BaseValidator(object):
privacy_options = (PUBLIC, PRIVATE, FRIENDS)
def type_or_types_to_str(self, type_or_types):
def repr_to_str(repr):
return repr.split(" '")[1].split("'>")[0]
if isinstance(type_or_types, (list, tuple... | raise ValidatorException('Either create_obj or search_kwargs must be passed when instantiating a validator.') |
Predict the next line after this snippet: <|code_start|>
class BaseObject(object):
def __init__(self, dict_):
self.original_dict = dict_
if hasattr(self, 'simple_properties'):
for property_key, property_name in self.simple_properties.items():
if property_key in self.ori... | setattr(self, property_name, iso_format_to_datetime(self.original_dict[property_key])) |
Given the code snippet: <|code_start|>#from flaskext.mail import Mail
ONLINE_LAST_MINUTES = 5
db = SQLAlchemy()
cache = Cache()
redis = Redis()
#mail = Mail()
login_manager = LoginManager()
def force_int(value,default=1):
try:
return int(value)
except:
return default
class BleepRenderer(HtmlR... | users = User.query.filter(User.id.in_(uids)).all() |
Predict the next line after this snippet: <|code_start|>
ONLINE_LAST_MINUTES = 5
db = SQLAlchemy()
cache = Cache()
redis = Redis()
#mail = Mail()
login_manager = LoginManager()
def force_int(value,default=1):
try:
return int(value)
except:
return default
class BleepRenderer(HtmlRenderer,Smarty... | profiles = Profile.query.filter(Profile.id.in_(uids)).all() |
Next line prediction: <|code_start|>
def force_int(value,default=1):
try:
return int(value)
except:
return default
class BleepRenderer(HtmlRenderer,SmartyPants):
''' code highlight '''
def block_code(self,text,lang):
if not lang:
return '\n<pre><code>%s</code></pre>\... | nodes = Node.query.filter(Node.id.in_(uids)).all() |
Predict the next line for this snippet: <|code_start|># coding: utf-8
bp = Blueprint('notice',__name__)
@bp.route('/create',methods=('GET','POST'))
@admin_required
def create():
form = NoticeForm()
if form.validate_on_submit():
form.save()
else:
flash(('Missing content'),'error')
retur... | notice = Notice.query.get_or_404(uid) |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
bp = Blueprint('notice',__name__)
@bp.route('/create',methods=('GET','POST'))
@admin_required
def create():
<|code_end|>
, predict the next line using imports from the current file:
from flask import Blueprint,render_template,redi... | form = NoticeForm() |
Predict the next line after this snippet: <|code_start|># coding: utf-8
bp = Blueprint('notice',__name__)
@bp.route('/create',methods=('GET','POST'))
@admin_required
def create():
form = NoticeForm()
if form.validate_on_submit():
form.save()
else:
flash(('Missing content'),'error')
ret... | @cache.cached(timeout=86400) |
Using the snippet: <|code_start|>
bp = Blueprint("node",__name__)
@bp.route('/')
def nodes():
nodes = Node.query.order_by(Node.id.desc()).all()
return render_template('node/nodes.html',nodes = nodes)
@bp.route('/<urlname>',methods=('GET','POST'))
@cache.cached(timeout=50)
def view(urlname):
node = Node.que... | page = force_int(request.args.get('page',1),0) |
Given the following code snippet before the placeholder: <|code_start|>
bp = Blueprint("node",__name__)
@bp.route('/')
def nodes():
nodes = Node.query.order_by(Node.id.desc()).all()
return render_template('node/nodes.html',nodes = nodes)
@bp.route('/<urlname>',methods=('GET','POST'))
<|code_end|>
, predict th... | @cache.cached(timeout=50) |
Based on the snippet: <|code_start|>
bp = Blueprint("node",__name__)
@bp.route('/')
def nodes():
<|code_end|>
, predict the immediate next line with the help of imports:
from flask import redirect,render_template,url_for,flash,abort,request,Blueprint
from _helpers import force_int,cache,fill_with_user,fill_with_node
... | nodes = Node.query.order_by(Node.id.desc()).all() |
Next line prediction: <|code_start|>
bp = Blueprint("node",__name__)
@bp.route('/')
def nodes():
nodes = Node.query.order_by(Node.id.desc()).all()
return render_template('node/nodes.html',nodes = nodes)
@bp.route('/<urlname>',methods=('GET','POST'))
@cache.cached(timeout=50)
def view(urlname):
node = Node.... | paginator = Topic.query.filter_by(node_id=node.id).order_by(Topic.id.desc()).paginate(page,10) |
Continue the code snippet: <|code_start|>
bp = Blueprint("focus",__name__)
def nodes_id():
if current_user is not None and current_user.is_authenticated():
user_key = 'user-nodes/%d' % current_user.id
return redis.smembers(user_key)
def getNodes():
nodes = None
uids = nodes_id()
if uid... | nodes = Node.query.filter(Node.id.in_(uids)) |
Predict the next line for this snippet: <|code_start|>
bp = Blueprint("focus",__name__)
def nodes_id():
if current_user is not None and current_user.is_authenticated():
user_key = 'user-nodes/%d' % current_user.id
<|code_end|>
with the help of current file imports:
from flask import Blueprint,redirect,ur... | return redis.smembers(user_key) |
Based on the snippet: <|code_start|>
bp = Blueprint("focus",__name__)
def nodes_id():
if current_user is not None and current_user.is_authenticated():
user_key = 'user-nodes/%d' % current_user.id
return redis.smembers(user_key)
def getNodes():
nodes = None
uids = nodes_id()
if uids:
... | cache.clear() |
Based on the snippet: <|code_start|># coding:utf-8
bp = Blueprint('admin',__name__)
@bp.route('/',methods=['GET','POST'])
@admin_required
def dashboard():
if request.method == 'POST':
save_sidebar_notice(request.form.get('content',None))
return redirect(url_for('.dashboard'))
<|code_end|>
, predic... | page = force_int(request.args.get('page', 1), 0) |
Predict the next line after this snippet: <|code_start|># coding:utf-8
bp = Blueprint('admin',__name__)
@bp.route('/',methods=['GET','POST'])
@admin_required
def dashboard():
if request.method == 'POST':
save_sidebar_notice(request.form.get('content',None))
return redirect(url_for('.dashboard'))
... | paginator.itmes = fill_object(paginator.items,profiles,'avatar') |
Next line prediction: <|code_start|># coding:utf-8
bp = Blueprint('admin',__name__)
@bp.route('/',methods=['GET','POST'])
@admin_required
def dashboard():
if request.method == 'POST':
save_sidebar_notice(request.form.get('content',None))
return redirect(url_for('.dashboard'))
page = force_int(... | paginator = User.query.order_by(User.id.desc()).paginate(page) |
Continue the code snippet: <|code_start|># coding:utf-8
bp = Blueprint('admin',__name__)
@bp.route('/',methods=['GET','POST'])
@admin_required
def dashboard():
if request.method == 'POST':
save_sidebar_notice(request.form.get('content',None))
return redirect(url_for('.dashboard'))
page = force... | profiles = Profile.query.order_by(Profile.id).paginate(page).items |
Predict the next line for this snippet: <|code_start|># coding:utf-8
bp = Blueprint('admin',__name__)
@bp.route('/',methods=['GET','POST'])
@admin_required
def dashboard():
if request.method == 'POST':
save_sidebar_notice(request.form.get('content',None))
return redirect(url_for('.dashboard'))
... | form = NodeForm() |
Based on the snippet: <|code_start|># coding:utf-8
#from _helpers import db,mark_online#,mail
def create_app():
app = Flask(__name__)
app.secret_key = '\x03\xedS\x08d`\xb0\x97_\x960x\xac\x12\x87\x88\x9f@x:n`\xeb\xd5'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['ROOTDIR'] ... | db.init_app(app) |
Continue the code snippet: <|code_start|># coding:utf-8
#from _helpers import db,mark_online#,mail
def create_app():
app = Flask(__name__)
app.secret_key = '\x03\xedS\x08d`\xb0\x97_\x960x\xac\x12\x87\x88\x9f@x:n`\xeb\xd5'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['ROOTD... | cache.init_app(app,config={'CACHE_TYPE': 'simple'}) |
Using the snippet: <|code_start|>
def create_app():
app = Flask(__name__)
app.secret_key = '\x03\xedS\x08d`\xb0\x97_\x960x\xac\x12\x87\x88\x9f@x:n`\xeb\xd5'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['ROOTDIR'] = os.getcwd()
app.config['ONLINEUSERS'] = set()
app.d... | renderer = BleepRenderer() |
Here is a snippet: <|code_start|># coding:utf-8
#from _helpers import db,mark_online#,mail
def create_app():
app = Flask(__name__)
app.secret_key = '\x03\xedS\x08d`\xb0\x97_\x960x\xac\x12\x87\x88\x9f@x:n`\xeb\xd5'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['ROOTDIR'] = o... | login_manager.init_app(app) |
Here is a snippet: <|code_start|># coding:utf-8
#from _helpers import db,mark_online#,mail
def create_app():
app = Flask(__name__)
app.secret_key = '\x03\xedS\x08d`\xb0\x97_\x960x\xac\x12\x87\x88\x9f@x:n`\xeb\xd5'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['ROOTDIR'] = o... | mark_online(current_user.id) |
Given snippet: <|code_start|>
bp = Blueprint('index',__name__)
@bp.route("/")
@bp.route("/index")
@cache.cached(timeout=1000)
def index():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import Blueprint,render_template
from lolipop.models import Notice,Topic
from _helpe... | notices = Notice.query.order_by(Notice.id.desc()) |
Given snippet: <|code_start|>
bp = Blueprint('index',__name__)
@bp.route("/")
@bp.route("/index")
@cache.cached(timeout=1000)
def index():
notices = Notice.query.order_by(Notice.id.desc())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import Blueprint,render_templa... | topics = Topic.query.order_by(Topic.last_post_id.desc()).limit(15) |
Using the snippet: <|code_start|>
bp = Blueprint('index',__name__)
@bp.route("/")
@bp.route("/index")
@cache.cached(timeout=1000)
def index():
notices = Notice.query.order_by(Notice.id.desc())
topics = Topic.query.order_by(Topic.last_post_id.desc()).limit(15)
<|code_end|>
, determine the next line of code. You... | topics = fill_with_node(fill_with_user(topics)) |
Given the following code snippet before the placeholder: <|code_start|>
bp = Blueprint('index',__name__)
@bp.route("/")
@bp.route("/index")
@cache.cached(timeout=1000)
def index():
notices = Notice.query.order_by(Notice.id.desc())
topics = Topic.query.order_by(Topic.last_post_id.desc()).limit(15)
<|code_end|>
... | topics = fill_with_node(fill_with_user(topics)) |
Using the snippet: <|code_start|>
bp = Blueprint('index',__name__)
@bp.route("/")
@bp.route("/index")
<|code_end|>
, determine the next line of code. You have imports:
from flask import Blueprint,render_template
from lolipop.models import Notice,Topic
from _helpers import fill_with_user,fill_with_node,cache
and cont... | @cache.cached(timeout=1000) |
Given snippet: <|code_start|>
async def download_content(ctx, url):
session: ClientSession = ctx['session']
async with session.get(url) as response:
if response.status != 200:
# retry the job with increasing back-off
# delays will be 5s, 10s, 15s, 20s
# after max_trie... | redis = await create_pool(RedisSettings()) |
Given the code snippet: <|code_start|>
async def download_content(ctx, url):
session: ClientSession = ctx['session']
async with session.get(url) as response:
if response.status != 200:
# retry the job with increasing back-off
# delays will be 5s, 10s, 15s, 20s
# after... | raise Retry(defer=ctx['job_try'] * 5) |
Given the code snippet: <|code_start|>
async def download_content(ctx, url):
session: ClientSession = ctx['session']
async with session.get(url) as response:
if response.status != 200:
# retry the job with increasing back-off
# delays will be 5s, 10s, 15s, 20s
# after... | redis = await create_pool(RedisSettings()) |
Given the code snippet: <|code_start|>
async def the_task(ctx):
await asyncio.sleep(5)
async def main():
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
from arq import create_pool
from arq.connections import RedisSettings
and context (functions, classes, or occasionally cod... | redis = await create_pool(RedisSettings()) |
Here is a snippet: <|code_start|>
async def the_task(ctx):
await asyncio.sleep(5)
async def main():
<|code_end|>
. Write the next line using the current file imports:
import asyncio
from arq import create_pool
from arq.connections import RedisSettings
and context from other files:
# Path: arq/connections.py
# ... | redis = await create_pool(RedisSettings()) |
Given snippet: <|code_start|> port=conf.port or 6379,
ssl=conf.scheme == 'rediss',
password=conf.password,
database=int((conf.path or '0').strip('/')),
)
def __repr__(self) -> str:
return 'RedisSettings({})'.format(', '.join(f'{k}={v!r}' for k, v in se... | default_queue_name: str = default_queue_name, |
Here is a snippet: <|code_start|>
async def enqueue_job(
self,
function: str,
*args: Any,
_job_id: Optional[str] = None,
_queue_name: Optional[str] = None,
_defer_until: Optional[datetime] = None,
_defer_by: Union[None, int, float, timedelta] = None,
_... | job_key = job_key_prefix + job_id |
Given snippet: <|code_start|> _defer_by: Union[None, int, float, timedelta] = None,
_expires: Union[None, int, float, timedelta] = None,
_job_try: Optional[int] = None,
**kwargs: Any,
) -> Optional[Job]:
"""
Enqueue a job.
:param function: Name of the function... | if any(await asyncio.gather(pipe.exists(job_key), pipe.exists(result_key_prefix + job_id))): |
Predict the next line for this snippet: <|code_start|> host=conf.hostname or 'localhost',
port=conf.port or 6379,
ssl=conf.scheme == 'rediss',
password=conf.password,
database=int((conf.path or '0').strip('/')),
)
def __repr__(self) -> str:
... | job_deserializer: Optional[Deserializer] = None, |
Based on the snippet: <|code_start|> :param default_queue_name: the default queue name to use, defaults to ``arq.queue``.
:param kwargs: keyword arguments directly passed to ``redis.asyncio.Redis``.
"""
def __init__(
self,
pool_or_conn: Optional[ConnectionPool] = None,
job_serial... | ) -> Optional[Job]: |
Given the following code snippet before the placeholder: <|code_start|> expires_ms = expires_ms or score - enqueue_time_ms + expires_extra_ms
job = serialize_job(function, args, kwargs, _job_try, enqueue_time_ms, serializer=self.job_serializer)
pipe.multi()
pipe.psetex(jo... | async def _get_job_def(self, job_id: bytes, score: int) -> JobDef: |
Predict the next line after this snippet: <|code_start|> defer_by_ms = to_ms(_defer_by)
expires_ms = to_ms(_expires)
async with self.pipeline(transaction=True) as pipe:
await pipe.watch(job_key)
if any(await asyncio.gather(pipe.exists(job_key), pipe.exists(result_key_pref... | async def _get_job_result(self, key: bytes) -> JobResult: |
Given the following code snippet before the placeholder: <|code_start|> return RedisSettings(
host=conf.hostname or 'localhost',
port=conf.port or 6379,
ssl=conf.scheme == 'rediss',
password=conf.password,
database=int((conf.path or '0').strip('/')),
... | job_serializer: Optional[Serializer] = None, |
Predict the next line after this snippet: <|code_start|> job = serialize_job(function, args, kwargs, _job_try, enqueue_time_ms, serializer=self.job_serializer)
pipe.multi()
pipe.psetex(job_key, expires_ms, job)
pipe.zadd(_queue_name, {job_id: score})
try:
... | jd = deserialize_job(v, deserializer=self.job_deserializer) |
Based on the snippet: <|code_start|> :param _expires: if the job still hasn't started after this duration, do not run it
:param _job_try: useful when re-enqueueing jobs within a job
:param kwargs: any keyword arguments to pass to the function
:return: :class:`arq.jobs.Job` instance or ``N... | job = serialize_job(function, args, kwargs, _job_try, enqueue_time_ms, serializer=self.job_serializer) |
Next line prediction: <|code_start|> ) -> Optional[Job]:
"""
Enqueue a job.
:param function: Name of the function to call
:param args: args to pass to the function
:param _job_id: ID of the job, can be used to enforce job uniqueness
:param _queue_name: queue of the jo... | enqueue_time_ms = timestamp_ms() |
Based on the snippet: <|code_start|> function: str,
*args: Any,
_job_id: Optional[str] = None,
_queue_name: Optional[str] = None,
_defer_until: Optional[datetime] = None,
_defer_by: Union[None, int, float, timedelta] = None,
_expires: Union[None, int, float, timede... | defer_by_ms = to_ms(_defer_by) |
Using the snippet: <|code_start|> Enqueue a job.
:param function: Name of the function to call
:param args: args to pass to the function
:param _job_id: ID of the job, can be used to enforce job uniqueness
:param _queue_name: queue of the job, can be used to create job in differe... | score = to_unix_ms(_defer_until) |
Based on the snippet: <|code_start|>
async def foobar(ctx):
return 42
class WorkerSettings:
burst = True
functions = [foobar]
def test_help():
runner = CliRunner()
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from click.testing import CliRunner
from arq.c... | result = runner.invoke(cli, ['--help']) |
Based on the snippet: <|code_start|> """
v = await self._redis.get(result_key_prefix + self.job_id)
if v:
return deserialize_result(v, deserializer=self._deserializer)
else:
return None
async def status(self) -> JobStatus:
"""
Status of the job... | await self._redis.zadd(abort_jobs_ss, {self.job_id: timestamp_ms()}) |
Here is a snippet: <|code_start|> job_try: int
enqueue_time: datetime
score: Optional[int]
def __post_init__(self) -> None:
if isinstance(self.score, float):
self.score = int(self.score)
@dataclass
class JobResult(JobDef):
success: bool
result: Any
start_time: datetime
... | _queue_name: str = default_queue_name, |
Given the code snippet: <|code_start|> async def info(self) -> Optional[JobDef]:
"""
All information on a job, including its result if it's available, does not wait for the result.
"""
info: Optional[JobDef] = await self.result_info()
if not info:
v = await self._r... | elif await self._redis.exists(in_progress_key_prefix + self.job_id): |
Predict the next line after this snippet: <|code_start|>
:param timeout: maximum time to wait for the job result before raising ``TimeoutError``, will wait forever
:param poll_delay: how often to poll redis for the job result
:param pole_delay: deprecated, use poll_delay instead
"""
... | v = await self._redis.get(job_key_prefix + self.job_id) |
Given the code snippet: <|code_start|> info = await self.result_info()
if info:
result = info.result
if info.success:
return result
elif isinstance(result, (Exception, asyncio.CancelledError)):
raise result
... | v = await self._redis.get(result_key_prefix + self.job_id) |
Using the snippet: <|code_start|> 'st': start_ms,
'ft': finished_ms,
'q': queue_name,
}
if serializer is None:
serializer = pickle.dumps
try:
return serializer(data)
except Exception:
logger.warning('error serializing result of %s', ref, exc_info=True)
... | enqueue_time=ms_to_datetime(d['et']), |
Given snippet: <|code_start|>
def __init__(
self,
job_id: str,
redis: Redis,
_queue_name: str = default_queue_name,
_deserializer: Optional[Deserializer] = None,
):
self.job_id = job_id
self._redis = redis
self._queue_name = _queue_name
sel... | async for delay in poll(poll_delay): |
Predict the next line for this snippet: <|code_start|> v = await self._redis.get(job_key_prefix + self.job_id)
if v:
info = deserialize_job(v, deserializer=self._deserializer)
if info:
info.score = await self._redis.zscore(self._queue_name, self.job_id)
... | return JobStatus.deferred if score > timestamp_ms() else JobStatus.queued |
Here is a snippet: <|code_start|> settings = RedisSettings()
settings.host = [('localhost', 6379), ('localhost', 6379)]
settings.sentinel = True
with pytest.raises(ResponseError, match='unknown command `SENTINEL`'):
await create_pool(settings)
async def test_redis_success_log(caplog, create_poo... | await log_redis_info(redis, _log) |
Predict the next line for this snippet: <|code_start|>
@dataclass
class Options:
month: OptionType
day: OptionType
weekday: WeekdayOptionType
hour: OptionType
minute: OptionType
second: OptionType
microsecond: int
def next_cron(
previous_dt: datetime,
*,
month: OptionType = N... | weekday = WEEKDAYS.index(weekday.lower()) |
Predict the next line after this snippet: <|code_start|> def calculate_next(self, prev_run: datetime) -> None:
self.next_run = next_cron(
prev_run,
month=self.month,
day=self.day,
weekday=self.weekday,
hour=self.hour,
minute=self.minute,... | timeout: Optional[SecondsTimedelta] = None, |
Predict the next line for this snippet: <|code_start|>
@dataclass
class Options:
month: OptionType
day: OptionType
<|code_end|>
with the help of current file imports:
import asyncio
import dataclasses
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional, Un... | weekday: WeekdayOptionType |
Given the code snippet: <|code_start|> mismatch = next_v not in v
# print(field, v, next_v, mismatch)
if mismatch:
micro = max(dt_.microsecond - options.microsecond, 0)
if field == 'month':
if dt_.month == 12:
return datetime(dt_.yea... | coroutine: WorkerCoroutine |
Given the following code snippet before the placeholder: <|code_start|>
Workers will enqueue this job at or just after the set times. If ``unique`` is true (the default) the
job will only be run once even if multiple workers are running.
:param coroutine: coroutine function to run
:param name: name of ... | timeout = to_seconds(timeout) |
Based on the snippet: <|code_start|>
autoclass_content = 'both'
autodoc_member_order = 'bysource'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['... | version = f'v{VERSION}' |
Continue the code snippet: <|code_start|>
async def do_stuff(ctx):
print('doing stuff...')
await asyncio.sleep(10)
return 'stuff done'
async def main():
<|code_end|>
. Use current file imports:
import asyncio
from arq import create_pool
from arq.connections import RedisSettings
and context (classes, fu... | redis = await create_pool(RedisSettings()) |
Predict the next line after this snippet: <|code_start|>
async def do_stuff(ctx):
print('doing stuff...')
await asyncio.sleep(10)
return 'stuff done'
async def main():
<|code_end|>
using the current file's imports:
import asyncio
from arq import create_pool
from arq.connections import RedisSettings
an... | redis = await create_pool(RedisSettings()) |
Using the snippet: <|code_start|>
async def the_task(ctx):
return 42
async def main():
<|code_end|>
, determine the next line of code. You have imports:
import asyncio
import msgpack # installable with "pip install msgpack"
from arq import create_pool
from arq.connections import RedisSettings
and context (c... | redis = await create_pool( |
Here is a snippet: <|code_start|>
async def the_task(ctx):
return 42
async def main():
redis = await create_pool(
<|code_end|>
. Write the next line using the current file imports:
import asyncio
import msgpack # installable with "pip install msgpack"
from arq import create_pool
from arq.connections impo... | RedisSettings(), |
Given the following code snippet before the placeholder: <|code_start|>
if TYPE_CHECKING:
burst_help = 'Batch mode: exit once no jobs are found in any queue.'
health_check_help = 'Health Check: run a health check and exit.'
watch_help = 'Watch a directory and reload the worker upon changes.'
verbose_help = 'Enable v... | logging.config.dictConfig(default_log_config(verbose)) |
Given the following code snippet before the placeholder: <|code_start|>
if TYPE_CHECKING:
burst_help = 'Batch mode: exit once no jobs are found in any queue.'
health_check_help = 'Health Check: run a health check and exit.'
watch_help = 'Watch a directory and reload the worker upon changes.'
verbose_help = 'Enable v... | @click.version_option(VERSION, '-V', '--version', prog_name='arq') |
Given the following code snippet before the placeholder: <|code_start|>
if TYPE_CHECKING:
burst_help = 'Batch mode: exit once no jobs are found in any queue.'
health_check_help = 'Health Check: run a health check and exit.'
watch_help = 'Watch a directory and reload the worker upon changes.'
verbose_help = 'Enable v... | exit(check_health(worker_settings_)) |
Predict the next line after this snippet: <|code_start|> Job queues in python with asyncio and redis.
CLI to run the arq worker.
"""
sys.path.append(os.getcwd())
worker_settings_ = cast('WorkerSettingsType', import_string(worker_settings))
logging.config.dictConfig(default_log_config(verbose))
... | worker = create_worker(worker_settings) |
Using the snippet: <|code_start|>burst_help = 'Batch mode: exit once no jobs are found in any queue.'
health_check_help = 'Health Check: run a health check and exit.'
watch_help = 'Watch a directory and reload the worker upon changes.'
verbose_help = 'Enable verbose output.'
@click.command('arq')
@click.version_optio... | run_worker(worker_settings_, **kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.